extension.dart 16.2 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, TestDefaultBinaryMessengerBinding {
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

/// Enables Flutter Driver VM service extension.
///
/// This extension is required for tests that use `package:flutter_driver` to
59 60 61 62 63
/// 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.
64 65 66
///
/// Call this function prior to running your application, e.g. before you call
/// `runApp`.
67 68 69
///
/// Optionally you can pass a [DataHandler] callback. It will be called if the
/// test calls [FlutterDriver.requestData].
70
///
Kent Boogaart's avatar
Kent Boogaart committed
71
/// `silenceErrors` will prevent exceptions from being logged. This is useful
72
/// for tests where exceptions are expected. Defaults to false. Any errors
73
/// will still be returned in the `response` field of the result JSON along
74
/// with an `isError` boolean.
75
///
76 77 78 79 80 81
/// 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].
///
82 83
/// The `finders` and `commands` parameters are optional and used to add custom
/// finders or commands, as in the following example.
84 85 86
///
/// ```dart main
/// void main() {
87 88 89 90
///   enableFlutterDriverExtension(
///     finders: <FinderExtension>[ SomeFinderExtension() ],
///     commands: <CommandExtension>[ SomeCommandExtension() ],
///   );
91 92 93 94 95 96
///
///   app.main();
/// }
/// ```
///
/// ```dart
97 98 99 100 101 102 103 104 105 106
/// 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);
107 108 109 110
///
///   final String title;
///
///   @override
111
///   String get finderType => 'SomeFinder';
112 113 114 115 116 117 118 119 120 121 122
///
///   @override
///   Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
///     'title': title,
///   });
/// }
/// ```
///
/// ```dart
/// class SomeFinderExtension extends FinderExtension {
///
123
///  String get finderType => 'SomeFinder';
124 125
///
///  SerializableFinder deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory) {
126
///    return SomeFinder(json['title']);
127 128
///  }
///
129
///  Finder createFinder(SerializableFinder finder, CreateFinderFactory finderFactory) {
130
///    Some someFinder = finder as SomeFinder;
131 132 133 134 135 136 137 138 139 140 141 142
///
///    return find.byElementPredicate((Element element) {
///      final Widget widget = element.widget;
///      if (element.widget is SomeWidget) {
///        return element.widget.title == someFinder.title;
///      }
///      return false;
///    });
///  }
/// }
/// ```
///
143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
/// 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;
/// }
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
///
/// ```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);
///   }
/// }
/// ```
///
221
void enableFlutterDriverExtension({ DataHandler? handler, bool silenceErrors = false, bool enableTextEntryEmulation = true, List<FinderExtension>? finders, List<CommandExtension>? commands}) {
222
  assert(WidgetsBinding.instance == null);
223
  _DriverBinding(handler, silenceErrors, enableTextEntryEmulation, finders ?? <FinderExtension>[], commands ?? <CommandExtension>[]);
224
  assert(WidgetsBinding.instance is _DriverBinding);
225 226
}

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

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

233
/// Used to expand the new [Finder].
234 235 236 237 238 239
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].
240 241 242 243 244
  ///
  /// Use [finderFactory] to deserialize nested [Finder]s.
  ///
  /// See also:
  ///   * [Ancestor], a finder that uses other [Finder]s as parameters.
245 246 247 248
  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.
249 250
  ///
  /// Call [finderFactory] to create known, nested [Finder]s from [SerializableFinder]s.
251
  Finder createFinder(SerializableFinder finder, CreateFinderFactory finderFactory);
252
}
253

254 255 256 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
/// 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);
}

309 310 311 312 313
/// 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].
314
@visibleForTesting
315
class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory, DeserializeCommandFactory, CommandHandlerFactory {
316
  /// Creates an object to manage a Flutter Driver connection.
317 318
  FlutterDriverExtension(
    this._requestDataHandler,
319 320
    this._silenceErrors,
    this._enableTextEntryEmulation, {
321
    List<FinderExtension> finders = const <FinderExtension>[],
322
    List<CommandExtension> commands = const <CommandExtension>[],
323
  }) : assert(finders != null) {
324 325 326
    if (_enableTextEntryEmulation) {
      registerTextInput();
    }
327

328
    for (final FinderExtension finder in finders) {
329 330
      _finderExtensions[finder.finderType] = finder;
    }
331

332
    for (final CommandExtension command in commands) {
333 334
      _commandExtensions[command.commandKind] = command;
    }
335 336
  }

337
  final WidgetController _prober = LiveWidgetController(WidgetsBinding.instance!);
338

339
  final DataHandler? _requestDataHandler;
340

341
  final bool _silenceErrors;
342

343 344
  final bool _enableTextEntryEmulation;

345 346 347
  void _log(String message) {
    driverLog('FlutterDriverExtension', message);
  }
348

349
  final Map<String, FinderExtension> _finderExtensions = <String, FinderExtension>{};
350
  final Map<String, CommandExtension> _commandExtensions = <String, CommandExtension>{};
351

352 353 354 355 356 357 358 359 360 361
  /// 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.
362
  @visibleForTesting
363
  Future<Map<String, dynamic>> call(Map<String, String> params) async {
364
    final String commandKind = params['command']!;
365
    try {
366
      final Command command = deserializeCommand(params, this);
367
      assert(WidgetsBinding.instance!.isRootWidgetAttached || !command.requiresRootWidgetAttached,
368
          'No root widget is attached; have you remembered to call runApp()?');
369 370 371 372 373 374
      Future<Result> responseFuture = handleCommand(command, _prober, this);
      if (command.timeout != null) {
        responseFuture = responseFuture.timeout(command.timeout!);
      }
      final Result response = await responseFuture;
      return _makeResponse(response.toJson());
375
    } on TimeoutException catch (error, stackTrace) {
376 377 378
      final String message = 'Timeout while executing $commandKind: $error\n$stackTrace';
      _log(message);
      return _makeResponse(message, isError: true);
379
    } catch (error, stackTrace) {
380
      final String message = 'Uncaught extension error while executing $commandKind: $error\n$stackTrace';
381
      if (!_silenceErrors)
382 383
        _log(message);
      return _makeResponse(message, isError: true);
384 385 386
    }
  }

387
  Map<String, dynamic> _makeResponse(dynamic response, { bool isError = false }) {
388 389 390 391 392 393
    return <String, dynamic>{
      'isError': isError,
      'response': response,
    };
  }

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

401
    return super.deserializeFinder(json);
402 403
  }

404 405
  @override
  Finder createFinder(SerializableFinder finder) {
406 407 408
    final String finderType = finder.finderType;
    if (_finderExtensions.containsKey(finderType)) {
      return _finderExtensions[finderType]!.createFinder(finder, this);
409
    }
410 411

    return super.createFinder(finder);
412 413
  }

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

421
    return super.deserializeCommand(params, finderFactory);
422
  }
423

424 425 426 427
  @override
  @protected
  DataHandler? getDataHandler() {
    return _requestDataHandler;
428 429
  }

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

437
    return super.handleCommand(command, prober, finderFactory);
438
  }
439
}