extension.dart 16.3 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6

7
import 'package:flutter/cupertino.dart';
8
import 'package:flutter/foundation.dart';
9
import 'package:flutter/gestures.dart';
10
import 'package:flutter/material.dart';
11
import 'package:flutter/rendering.dart' show RendererBinding;
12
import 'package:flutter/scheduler.dart';
13
import 'package:flutter/semantics.dart';
14
import 'package:flutter/services.dart';
15
import 'package:flutter/widgets.dart';
16
import 'package:flutter_test/flutter_test.dart';
17

18
import '../common/deserialization_factory.dart';
19 20
import '../common/error.dart';
import '../common/find.dart';
21
import '../common/handler_factory.dart';
22
import '../common/message.dart';
23
import '_extension_io.dart' if (dart.library.html) '_extension_web.dart';
24

25
const String _extensionMethodName = 'driver';
26

27 28 29 30
/// Signature for the handler passed to [enableFlutterDriverExtension].
///
/// Messages are described in string form and should return a [Future] which
/// eventually completes to a string response.
31
typedef DataHandler = Future<String> Function(String? message);
32

33
class _DriverBinding extends BindingBase with SchedulerBinding, ServicesBinding, GestureBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding {
34
  _DriverBinding(this._handler, this._silenceErrors, this._enableTextEntryEmulation, this.finders, this.commands);
35

36
  final DataHandler? _handler;
37
  final bool _silenceErrors;
38
  final bool _enableTextEntryEmulation;
39
  final List<FinderExtension>? finders;
40
  final List<CommandExtension>? commands;
41

42 43 44
  @override
  void initServiceExtensions() {
    super.initServiceExtensions();
45
    final FlutterDriverExtension extension = FlutterDriverExtension(_handler, _silenceErrors, _enableTextEntryEmulation, finders: finders ?? const <FinderExtension>[], commands: commands ?? const <CommandExtension>[]);
46 47
    registerServiceExtension(
      name: _extensionMethodName,
48
      callback: extension.call,
49
    );
50 51 52
    if (kIsWeb) {
      registerWebServiceExtension(extension.call);
    }
53
  }
54 55 56 57 58

  @override
  BinaryMessenger createBinaryMessenger() {
    return TestDefaultBinaryMessenger(super.createBinaryMessenger());
  }
59
}
60 61 62 63

/// Enables Flutter Driver VM service extension.
///
/// This extension is required for tests that use `package:flutter_driver` to
64 65 66 67 68
/// drive applications from a separate process. In order to allow the driver
/// to interact with the application, this method changes the behavior of the
/// framework in several ways - including keyboard interaction and text
/// editing. Applications intended for release should never include this
/// method.
69 70 71
///
/// Call this function prior to running your application, e.g. before you call
/// `runApp`.
72 73 74
///
/// Optionally you can pass a [DataHandler] callback. It will be called if the
/// test calls [FlutterDriver.requestData].
75
///
Kent Boogaart's avatar
Kent Boogaart committed
76
/// `silenceErrors` will prevent exceptions from being logged. This is useful
77
/// for tests where exceptions are expected. Defaults to false. Any errors
78
/// will still be returned in the `response` field of the result JSON along
79
/// with an `isError` boolean.
80
///
81 82 83 84 85 86
/// The `enableTextEntryEmulation` parameter controls whether the application interacts
/// with the system's text entry methods or a mocked out version used by Flutter Driver.
/// If it is set to false, [FlutterDriver.enterText] will fail,
/// but testing the application with real keyboard input is possible.
/// This value may be updated during a test by calling [FlutterDriver.setTextEntryEmulation].
///
87 88
/// The `finders` and `commands` parameters are optional and used to add custom
/// finders or commands, as in the following example.
89 90 91
///
/// ```dart main
/// void main() {
92 93 94 95
///   enableFlutterDriverExtension(
///     finders: <FinderExtension>[ SomeFinderExtension() ],
///     commands: <CommandExtension>[ SomeCommandExtension() ],
///   );
96 97 98 99 100 101
///
///   app.main();
/// }
/// ```
///
/// ```dart
102 103 104 105 106 107 108 109 110 111
/// driver.sendCommand(SomeCommand(ByValueKey('Button'), 7));
/// ```
///
/// Note: SomeFinder and SomeFinderExtension must be placed in different files
/// to avoid `dart:ui` import issue. Imports relative to `dart:ui` can't be
/// accessed from host runner, where flutter runtime is not accessible.
///
/// ```dart
/// class SomeFinder extends SerializableFinder {
///   const SomeFinder(this.title);
112 113 114 115
///
///   final String title;
///
///   @override
116
///   String get finderType => 'SomeFinder';
117 118 119 120 121 122 123 124 125 126 127
///
///   @override
///   Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
///     'title': title,
///   });
/// }
/// ```
///
/// ```dart
/// class SomeFinderExtension extends FinderExtension {
///
128
///  String get finderType => 'SomeFinder';
129 130
///
///  SerializableFinder deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory) {
131
///    return SomeFinder(json['title']);
132 133
///  }
///
134
///  Finder createFinder(SerializableFinder finder, CreateFinderFactory finderFactory) {
135
///    Some someFinder = finder as SomeFinder;
136 137 138 139 140 141 142 143 144 145 146 147
///
///    return find.byElementPredicate((Element element) {
///      final Widget widget = element.widget;
///      if (element.widget is SomeWidget) {
///        return element.widget.title == someFinder.title;
///      }
///      return false;
///    });
///  }
/// }
/// ```
///
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225
/// Note: SomeCommand, SomeResult and SomeCommandExtension must be placed in
/// different files to avoid `dart:ui` import issue. Imports relative to `dart:ui`
/// can't be accessed from host runner, where flutter runtime is not accessible.
///
/// ```dart
/// class SomeCommand extends CommandWithTarget {
///   SomeCommand(SerializableFinder finder, this.times, {Duration? timeout})
///       : super(finder, timeout: timeout);
///
///   SomeCommand.deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory)
///       : times = int.parse(json['times']!),
///         super.deserialize(json, finderFactory);
///
///   @override
///   Map<String, String> serialize() {
///     return super.serialize()..addAll(<String, String>{'times': '$times'});
///   }
///
///   @override
///   String get kind => 'SomeCommand';
///
///   final int times;
/// }
///```
///
/// ```dart
/// class SomeCommandResult extends Result {
///   const SomeCommandResult(this.resultParam);
///
///   final String resultParam;
///
///   @override
///   Map<String, dynamic> toJson() {
///     return <String, dynamic>{
///       'resultParam': resultParam,
///     };
///   }
/// }
/// ```
///
/// ```dart
/// class SomeCommandExtension extends CommandExtension {
///   @override
///   String get commandKind => 'SomeCommand';
///
///   @override
///   Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async {
///     final SomeCommand someCommand = command as SomeCommand;
///
///     // Deserialize [Finder]:
///     final Finder finder = finderFactory.createFinder(stubCommand.finder);
///
///     // Wait for [Element]:
///     handlerFactory.waitForElement(finder);
///
///     // Alternatively, wait for [Element] absence:
///     handlerFactory.waitForAbsentElement(finder);
///
///     // Submit known [Command]s:
///     for (int index = 0; i < someCommand.times; index++) {
///       await handlerFactory.handleCommand(Tap(someCommand.finder), prober, finderFactory);
///     }
///
///     // Alternatively, use [WidgetController]:
///     for (int index = 0; i < stubCommand.times; index++) {
///       await prober.tap(finder);
///     }
///
///     return const SomeCommandResult('foo bar');
///   }
///
///   @override
///   Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory) {
///     return SomeCommand.deserialize(params, finderFactory);
///   }
/// }
/// ```
///
226
void enableFlutterDriverExtension({ DataHandler? handler, bool silenceErrors = false, bool enableTextEntryEmulation = true, List<FinderExtension>? finders, List<CommandExtension>? commands}) {
227
  assert(WidgetsBinding.instance == null);
228
  _DriverBinding(handler, silenceErrors, enableTextEntryEmulation, finders ?? <FinderExtension>[], commands ?? <CommandExtension>[]);
229
  assert(WidgetsBinding.instance is _DriverBinding);
230 231
}

232
/// Signature for functions that handle a command and return a result.
233
typedef CommandHandlerCallback = Future<Result?> Function(Command c);
234

235
/// Signature for functions that deserialize a JSON map to a command object.
236
typedef CommandDeserializerCallback = Command Function(Map<String, String> params);
237

238
/// Used to expand the new [Finder].
239 240 241 242 243 244
abstract class FinderExtension {

  /// Identifies the type of finder to be used by the driver extension.
  String get finderType;

  /// Deserializes the finder from JSON generated by [SerializableFinder.serialize].
245 246 247 248 249
  ///
  /// Use [finderFactory] to deserialize nested [Finder]s.
  ///
  /// See also:
  ///   * [Ancestor], a finder that uses other [Finder]s as parameters.
250 251 252 253
  SerializableFinder deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory);

  /// Signature for functions that run the given finder and return the [Element]
  /// found, if any, or null otherwise.
254 255
  ///
  /// Call [finderFactory] to create known, nested [Finder]s from [SerializableFinder]s.
256
  Finder createFinder(SerializableFinder finder, CreateFinderFactory finderFactory);
257
}
258

259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313
/// Used to expand the new [Command].
///
/// See also:
///   * [CommandWithTarget], a base class for [Command]s with [Finder]s.
abstract class CommandExtension {

  /// Identifies the type of command to be used by the driver extension.
  String get commandKind;

  /// Deserializes the command from JSON generated by [Command.serialize].
  ///
  /// Use [finderFactory] to deserialize nested [Finder]s.
  /// Usually used for [CommandWithTarget]s.
  ///
  /// Call [commandFactory] to deserialize commands specified as parameters.
  ///
  /// See also:
  ///   * [CommandWithTarget], a base class for commands with target finders.
  ///   * [Tap], a command that uses [Finder]s as parameter.
  Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory);

  /// Calls action for given [command].
  /// Returns action [Result].
  /// Invoke [prober] functions to perform widget actions.
  /// Use [finderFactory] to create [Finder]s from [SerializableFinder].
  /// Call [handlerFactory] to invoke other [Command]s or [CommandWithTarget]s.
  ///
  /// The following example shows invoking nested command with [handlerFactory].
  ///
  /// ```dart
  /// @override
  /// Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async {
  ///   final StubNestedCommand stubCommand = command as StubNestedCommand;
  ///   for (int index = 0; i < stubCommand.times; index++) {
  ///     await handlerFactory.handleCommand(Tap(stubCommand.finder), prober, finderFactory);
  ///   }
  ///   return const StubCommandResult('stub response');
  /// }
  /// ```
  ///
  /// Check the example below for direct [WidgetController] usage with [prober]:
  ///
  /// ```dart
  ///   @override
  /// Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async {
  ///   final StubProberCommand stubCommand = command as StubProberCommand;
  ///   for (int index = 0; i < stubCommand.times; index++) {
  ///     await prober.tap(finderFactory.createFinder(stubCommand.finder));
  ///   }
  ///   return const StubCommandResult('stub response');
  /// }
  /// ```
  Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory);
}

314 315 316 317 318
/// The class that manages communication between a Flutter Driver test and the
/// application being remote-controlled, on the application side.
///
/// This is not normally used directly. It is instantiated automatically when
/// calling [enableFlutterDriverExtension].
319
@visibleForTesting
320
class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory, DeserializeCommandFactory, CommandHandlerFactory {
321
  /// Creates an object to manage a Flutter Driver connection.
322 323
  FlutterDriverExtension(
    this._requestDataHandler,
324 325
    this._silenceErrors,
    this._enableTextEntryEmulation, {
326
    List<FinderExtension> finders = const <FinderExtension>[],
327
    List<CommandExtension> commands = const <CommandExtension>[],
328
  }) : assert(finders != null) {
329 330 331
    if (_enableTextEntryEmulation) {
      registerTextInput();
    }
332

333
    for(final FinderExtension finder in finders) {
334 335
      _finderExtensions[finder.finderType] = finder;
    }
336

337
    for(final CommandExtension command in commands) {
338 339
      _commandExtensions[command.commandKind] = command;
    }
340 341
  }

342
  final WidgetController _prober = LiveWidgetController(WidgetsBinding.instance!);
343

344
  final DataHandler? _requestDataHandler;
345

346
  final bool _silenceErrors;
347

348 349
  final bool _enableTextEntryEmulation;

350 351 352
  void _log(String message) {
    driverLog('FlutterDriverExtension', message);
  }
353

354
  final Map<String, FinderExtension> _finderExtensions = <String, FinderExtension>{};
355
  final Map<String, CommandExtension> _commandExtensions = <String, CommandExtension>{};
356

357 358 359 360 361 362 363 364 365 366
  /// Processes a driver command configured by [params] and returns a result
  /// as an arbitrary JSON object.
  ///
  /// [params] must contain key "command" whose value is a string that
  /// identifies the kind of the command and its corresponding
  /// [CommandDeserializerCallback]. Other keys and values are specific to the
  /// concrete implementation of [Command] and [CommandDeserializerCallback].
  ///
  /// The returned JSON is command specific. Generally the caller deserializes
  /// the result into a subclass of [Result], but that's not strictly required.
367
  @visibleForTesting
368
  Future<Map<String, dynamic>> call(Map<String, String> params) async {
369
    final String commandKind = params['command']!;
370
    try {
371
      final Command command = deserializeCommand(params, this);
372
      assert(WidgetsBinding.instance!.isRootWidgetAttached || !command.requiresRootWidgetAttached,
373
          'No root widget is attached; have you remembered to call runApp()?');
374
      Future<Result?> responseFuture = handleCommand(command, _prober, this);
375
      if (command.timeout != null)
376 377
        responseFuture = responseFuture.timeout(command.timeout ?? Duration.zero);
      final Result? response = await responseFuture;
378
      return _makeResponse(response?.toJson());
379
    } on TimeoutException catch (error, stackTrace) {
380 381 382
      final String message = 'Timeout while executing $commandKind: $error\n$stackTrace';
      _log(message);
      return _makeResponse(message, isError: true);
383
    } catch (error, stackTrace) {
384
      final String message = 'Uncaught extension error while executing $commandKind: $error\n$stackTrace';
385
      if (!_silenceErrors)
386 387
        _log(message);
      return _makeResponse(message, isError: true);
388 389 390
    }
  }

391
  Map<String, dynamic> _makeResponse(dynamic response, { bool isError = false }) {
392 393 394 395 396 397
    return <String, dynamic>{
      'isError': isError,
      'response': response,
    };
  }

398 399 400 401 402
  @override
  SerializableFinder deserializeFinder(Map<String, String> json) {
    final String? finderType = json['finderType'];
    if (_finderExtensions.containsKey(finderType)) {
      return _finderExtensions[finderType]!.deserialize(json, this);
403 404
    }

405
    return super.deserializeFinder(json);
406 407
  }

408 409
  @override
  Finder createFinder(SerializableFinder finder) {
410 411 412
    final String finderType = finder.finderType;
    if (_finderExtensions.containsKey(finderType)) {
      return _finderExtensions[finderType]!.createFinder(finder, this);
413
    }
414 415

    return super.createFinder(finder);
416 417
  }

418 419 420
  @override
  Command deserializeCommand(Map<String, String> params, DeserializeFinderFactory finderFactory) {
    final String? kind = params['command'];
421
    if(_commandExtensions.containsKey(kind)) {
422
      return _commandExtensions[kind]!.deserialize(params, finderFactory, this);
423 424
    }

425
    return super.deserializeCommand(params, finderFactory);
426
  }
427

428 429 430 431
  @override
  @protected
  DataHandler? getDataHandler() {
    return _requestDataHandler;
432 433
  }

434
  @override
435
  Future<Result> handleCommand(Command command, WidgetController prober, CreateFinderFactory finderFactory) {
436
    final String kind = command.kind;
437
    if(_commandExtensions.containsKey(kind)) {
438
      return _commandExtensions[kind]!.call(command, prober, finderFactory, this);
439
    }
440

441
    return super.handleCommand(command, prober, finderFactory);
442
  }
443
}