driver.dart 37.1 KB
Newer Older
1 2 3 4 5
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';
6
import 'dart:convert';
7
import 'dart:io';
8 9

import 'package:file/file.dart' as f;
10
import 'package:fuchsia_remote_debug_protocol/fuchsia_remote_debug_protocol.dart' as fuchsia;
11
import 'package:json_rpc_2/error_code.dart' as error_code;
12
import 'package:json_rpc_2/json_rpc_2.dart' as rpc;
13
import 'package:meta/meta.dart';
14
import 'package:path/path.dart' as p;
15 16
import 'package:vm_service_client/vm_service_client.dart';
import 'package:web_socket_channel/io.dart';
17

18 19 20
import '../common/error.dart';
import '../common/find.dart';
import '../common/frame_sync.dart';
21
import '../common/fuchsia_compat.dart';
22 23 24 25 26 27
import '../common/gesture.dart';
import '../common/health.dart';
import '../common/message.dart';
import '../common/render_tree.dart';
import '../common/request_data.dart';
import '../common/semantics.dart';
28
import '../common/text.dart';
29
import 'common.dart';
30
import 'timeline.dart';
31

32
/// Timeline stream identifier.
33
enum TimelineStream {
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
  /// A meta-identifier that instructs the Dart VM to record all streams.
  all,

  /// Marks events related to calls made via Dart's C API.
  api,

  /// Marks events from the Dart VM's JIT compiler.
  compiler,

  /// Marks events emitted using the `dart:developer` API.
  dart,

  /// Marks events from the Dart VM debugger.
  debugger,

  /// Marks events emitted using the `dart_tools_api.h` C API.
  embedder,

  /// Marks events from the garbage collector.
  gc,

  /// Marks events related to message passing between Dart isolates.
  isolate,

  /// Marks internal VM events.
  vm,
60 61
}

62
const List<TimelineStream> _defaultStreams = <TimelineStream>[TimelineStream.all];
63

64 65 66
/// How long to wait before showing a message saying that
/// things seem to be taking a long time.
const Duration _kUnusuallyLongTimeout = Duration(seconds: 5);
67 68 69

/// The amount of time we wait prior to making the next attempt to connect to
/// the VM service.
70
const Duration _kPauseBetweenReconnectAttempts = Duration(seconds: 1);
71

72
// See https://github.com/dart-lang/sdk/blob/master/runtime/vm/timeline.cc#L32
73
String _timelineStreamsToString(List<TimelineStream> streams) {
74
  final String contents = streams.map<String>((TimelineStream stream) {
75
    switch (stream) {
76 77 78 79 80 81 82 83 84
      case TimelineStream.all: return 'all';
      case TimelineStream.api: return 'API';
      case TimelineStream.compiler: return 'Compiler';
      case TimelineStream.dart: return 'Dart';
      case TimelineStream.debugger: return 'Debugger';
      case TimelineStream.embedder: return 'Embedder';
      case TimelineStream.gc: return 'GC';
      case TimelineStream.isolate: return 'Isolate';
      case TimelineStream.vm: return 'VM';
85
      default:
86
        throw 'Unknown timeline stream $stream';
87 88 89 90 91
    }
  }).join(', ');
  return '[$contents]';
}

92
final Logger _log = Logger('FlutterDriver');
93

94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114
Future<T> _warnIfSlow<T>({
  @required Future<T> future,
  @required Duration timeout,
  @required String message,
}) {
  assert(future != null);
  assert(timeout != null);
  assert(message != null);
  return future..timeout(timeout, onTimeout: () { _log.warning(message); });
}

Duration _maxDuration(Duration a, Duration b) {
  if (a == null)
    return b;
  if (b == null)
    return a;
  if (a > b)
    return a;
  return b;
}

115 116 117 118
/// A convenient accessor to frequently used finders.
///
/// Examples:
///
119
///     driver.tap(find.text('Save'));
120
///     driver.scroll(find.byValueKey(42));
121
const CommonFinders find = CommonFinders._();
122

123 124 125 126 127
/// Computes a value.
///
/// If computation is asynchronous, the function may return a [Future].
///
/// See also [FlutterDriver.waitFor].
128
typedef EvaluatorFunction = dynamic Function();
129

130 131
/// Drives a Flutter Application running in another process.
class FlutterDriver {
132 133 134
  /// Creates a driver that uses a connection provided by the given
  /// [_serviceClient], [_peer] and [_appIsolate].
  @visibleForTesting
135 136 137 138
  FlutterDriver.connectedTo(
    this._serviceClient,
    this._peer,
    this._appIsolate, {
139 140
    bool printCommunication = false,
    bool logCommunicationToFile = true,
141 142 143
  }) : _printCommunication = printCommunication,
       _logCommunicationToFile = logCommunicationToFile,
       _driverId = _nextDriverId++;
144

145 146 147 148
  static const String _flutterExtensionMethodName = 'ext.flutter.driver';
  static const String _setVMTimelineFlagsMethodName = '_setVMTimelineFlags';
  static const String _getVMTimelineMethodName = '_getVMTimeline';
  static const String _clearVMTimelineMethodName = '_clearVMTimeline';
149
  static const String _collectAllGarbageMethodName = '_collectAllGarbage';
150

151 152
  static int _nextDriverId = 0;

153 154 155 156
  /// Connects to a Flutter application.
  ///
  /// Resumes the application if it is currently paused (e.g. at a breakpoint).
  ///
157
  /// `dartVmServiceUrl` is the URL to Dart observatory (a.k.a. VM service). If
158
  /// not specified, the URL specified by the `VM_SERVICE_URL` environment
159
  /// variable is used. One or the other must be specified.
160
  ///
161
  /// `printCommunication` determines whether the command communication between
162 163
  /// the test and the app should be printed to stdout.
  ///
164
  /// `logCommunicationToFile` determines whether the command communication
165
  /// between the test and the app should be logged to `flutter_driver_commands.log`.
166
  ///
167
  /// `isolateNumber` determines the specific isolate to connect to.
168
  /// If this is left as `null`, will connect to the first isolate found
169 170 171 172 173 174 175 176 177 178 179 180
  /// running on `dartVmServiceUrl`.
  ///
  /// `fuchsiaModuleTarget` specifies the pattern for determining which mod to
  /// control. When running on a Fuchsia device, either this or the environment
  /// variable `FUCHSIA_MODULE_TARGET` must be set (the environment variable is
  /// treated as a substring pattern). This field will be ignored if
  /// `isolateNumber` is set, as this is already enough information to connect
  /// to an isolate.
  ///
  /// The return value is a future. This method never times out, though it may
  /// fail (completing with an error). A timeout can be applied by the caller
  /// using [Future.timeout] if necessary.
181 182
  static Future<FlutterDriver> connect({
    String dartVmServiceUrl,
183 184
    bool printCommunication = false,
    bool logCommunicationToFile = true,
185
    int isolateNumber,
186
    Pattern fuchsiaModuleTarget,
187
  }) async {
188
    // If running on a Fuchsia device, connect to the first isolate whose name
189 190 191 192 193
    // matches FUCHSIA_MODULE_TARGET.
    //
    // If the user has already supplied an isolate number/URL to the Dart VM
    // service, then this won't be run as it is unnecessary.
    if (Platform.isFuchsia && isolateNumber == null) {
194 195 196
      // TODO(awdavies): Use something other than print. On fuchsia
      // `stderr`/`stdout` appear to have issues working correctly.
      flutterDriverLog.listen(print);
197 198
      fuchsiaModuleTarget ??= Platform.environment['FUCHSIA_MODULE_TARGET'];
      if (fuchsiaModuleTarget == null) {
199 200 201 202 203
        throw DriverError(
          'No Fuchsia module target has been specified.\n'
          'Please make sure to specify the FUCHSIA_MODULE_TARGET '
          'environment variable.'
        );
204 205 206 207 208 209 210 211 212 213 214 215
      }
      final fuchsia.FuchsiaRemoteConnection fuchsiaConnection =
          await FuchsiaCompat.connect();
      final List<fuchsia.IsolateRef> refs =
          await fuchsiaConnection.getMainIsolatesByPattern(fuchsiaModuleTarget);
      final fuchsia.IsolateRef ref = refs.first;
      isolateNumber = ref.number;
      dartVmServiceUrl = ref.dartVm.uri.toString();
      await fuchsiaConnection.stop();
      FuchsiaCompat.cleanup();
    }

216
    dartVmServiceUrl ??= Platform.environment['VM_SERVICE_URL'];
217 218

    if (dartVmServiceUrl == null) {
219
      throw DriverError(
220 221 222 223
        'Could not determine URL to connect to application.\n'
        'Either the VM_SERVICE_URL environment variable should be set, or an explicit '
        'URL should be provided to the FlutterDriver.connect() method.'
      );
224
    }
225

Josh Soref's avatar
Josh Soref committed
226
    // Connect to Dart VM services
227
    _log.info('Connecting to Flutter application at $dartVmServiceUrl');
228 229
    final VMServiceClientConnection connection =
        await vmServiceConnectFunction(dartVmServiceUrl);
230 231
    final VMServiceClient client = connection.client;
    final VM vm = await client.getVM();
232 233 234 235 236 237
    final VMIsolateRef isolateRef = isolateNumber ==
        null ? vm.isolates.first :
               vm.isolates.firstWhere(
                   (VMIsolateRef isolate) => isolate.number == isolateNumber);
    _log.trace('Isolate found with number: ${isolateRef.number}');

238
    VMIsolate isolate = await isolateRef.loadRunnable();
239

240
    // TODO(yjbanov): vm_service_client does not support "None" pause event yet.
241 242
    // It is currently reported as null, but we cannot rely on it because
    // eventually the event will be reported as a non-null object. For now,
243 244
    // list all the events we know about. Later we'll check for "None" event
    // explicitly.
245
    //
246 247 248 249 250 251 252
    // See: https://github.com/dart-lang/vm_service_client/issues/4
    if (isolate.pauseEvent is! VMPauseStartEvent &&
        isolate.pauseEvent is! VMPauseExitEvent &&
        isolate.pauseEvent is! VMPauseBreakpointEvent &&
        isolate.pauseEvent is! VMPauseExceptionEvent &&
        isolate.pauseEvent is! VMPauseInterruptedEvent &&
        isolate.pauseEvent is! VMResumeEvent) {
253
      isolate = await isolateRef.loadRunnable();
254 255
    }

256
    final FlutterDriver driver = FlutterDriver.connectedTo(
257 258 259
      client, connection.peer, isolate,
      printCommunication: printCommunication,
      logCommunicationToFile: logCommunicationToFile,
260
    );
261 262 263 264

    // Attempts to resume the isolate, but does not crash if it fails because
    // the isolate is already resumed. There could be a race with other tools,
    // such as a debugger, any of which could have resumed the isolate.
Ian Hickson's avatar
Ian Hickson committed
265
    Future<dynamic> resumeLeniently() {
266
      _log.trace('Attempting to resume isolate');
267 268
      return isolate.resume().catchError((dynamic e) {
        const int vmMustBePausedCode = 101;
269 270 271 272 273 274 275 276 277 278 279 280 281 282
        if (e is rpc.RpcException && e.code == vmMustBePausedCode) {
          // No biggie; something else must have resumed the isolate
          _log.warning(
            'Attempted to resume an already resumed isolate. This may happen '
            'when we lose a race with another tool (usually a debugger) that '
            'is connected to the same isolate.'
          );
        } else {
          // Failed to resume due to another reason. Fail hard.
          throw e;
        }
      });
    }

283
    /// Waits for a signal from the VM service that the extension is registered.
284
    /// Returns [_flutterExtensionMethodName]
285 286
    Future<String> waitForServiceExtension() {
      return isolate.onExtensionAdded.firstWhere((String extension) {
287
        return extension == _flutterExtensionMethodName;
288 289 290 291 292 293 294 295 296 297
      });
    }

    /// Tells the Dart VM Service to notify us about "Isolate" events.
    ///
    /// This is a workaround for an issue in package:vm_service_client, which
    /// subscribes to the "Isolate" stream lazily upon subscription, which
    /// results in lost events.
    ///
    /// Details: https://github.com/dart-lang/vm_service_client/issues/17
298
    Future<void> enableIsolateStreams() async {
299 300 301 302 303
      await connection.peer.sendRequest('streamListen', <String, String>{
        'streamId': 'Isolate',
      });
    }

304 305 306 307 308 309 310
    // Attempt to resume isolate if it was paused
    if (isolate.pauseEvent is VMPauseStartEvent) {
      _log.trace('Isolate is paused at start.');

      // If the isolate is paused at the start, e.g. via the --start-paused
      // option, then the VM service extension is not registered yet. Wait for
      // it to be registered.
311
      await enableIsolateStreams();
312
      final Future<String> whenServiceExtensionReady = waitForServiceExtension();
313
      final Future<dynamic> whenResumed = resumeLeniently();
314 315
      await whenResumed;

316 317 318 319 320 321 322 323 324 325 326
      _log.trace('Waiting for service extension');
      // We will never receive the extension event if the user does not
      // register it. If that happens, show a message but continue waiting.
      await _warnIfSlow<String>(
        future: whenServiceExtensionReady,
        timeout: _kUnusuallyLongTimeout,
        message: 'Flutter Driver extension is taking a long time to become available. '
                 'Ensure your test app (often "lib/main.dart") imports '
                 '"package:flutter_driver/driver_extension.dart" and '
                 'calls enableFlutterDriverExtension() as the first call in main().'
      );
327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
    } else if (isolate.pauseEvent is VMPauseExitEvent ||
               isolate.pauseEvent is VMPauseBreakpointEvent ||
               isolate.pauseEvent is VMPauseExceptionEvent ||
               isolate.pauseEvent is VMPauseInterruptedEvent) {
      // If the isolate is paused for any other reason, assume the extension is
      // already there.
      _log.trace('Isolate is paused mid-flight.');
      await resumeLeniently();
    } else if (isolate.pauseEvent is VMResumeEvent) {
      _log.trace('Isolate is not paused. Assuming application is ready.');
    } else {
      _log.warning(
        'Unknown pause event type ${isolate.pauseEvent.runtimeType}. '
        'Assuming application is ready.'
      );
    }

344 345 346 347 348 349 350 351 352 353 354 355 356 357 358
    // Invoked checkHealth and try to fix delays in the registration of Service
    // extensions
    Future<Health> checkHealth() async {
      try {
        // At this point the service extension must be installed. Verify it.
        return await driver.checkHealth();
      } on rpc.RpcException catch (e) {
        if (e.code != error_code.METHOD_NOT_FOUND) {
          rethrow;
        }
        _log.trace(
          'Check Health failed, try to wait for the service extensions to be'
          'registered.'
        );
        await enableIsolateStreams();
359
        await waitForServiceExtension();
360 361 362 363 364
        return driver.checkHealth();
      }
    }

    final Health health = await checkHealth();
365
    if (health.status != HealthStatus.ok) {
366
      await client.close();
367
      throw DriverError('Flutter application health check failed.');
368 369 370 371 372 373
    }

    _log.info('Connected to Flutter application.');
    return driver;
  }

374 375
  /// The unique ID of this driver instance.
  final int _driverId;
376

377 378
  /// Client connected to the Dart VM running the Flutter application
  final VMServiceClient _serviceClient;
379

380 381
  /// JSON-RPC client useful for sending raw JSON requests.
  final rpc.Peer _peer;
382

383
  /// The main isolate hosting the Flutter application
384
  final VMIsolate _appIsolate;
385

386 387
  /// Whether to print communication between host and app to `stdout`.
  final bool _printCommunication;
388

389 390
  /// Whether to log communication between host and app to `flutter_driver_commands.log`.
  final bool _logCommunicationToFile;
391 392

  Future<Map<String, dynamic>> _sendCommand(Command command) async {
393
    Map<String, dynamic> response;
394
    try {
395
      final Map<String, String> serialized = command.serialize();
396
      _logCommunication('>>> $serialized');
397 398 399 400 401 402 403 404
      final Future<Map<String, dynamic>> future = _appIsolate.invokeExtension(
        _flutterExtensionMethodName,
        serialized,
      ).then<Map<String, dynamic>>((Object value) => value);
      response = await _warnIfSlow<Map<String, dynamic>>(
        future: future,
        timeout: _maxDuration(command.timeout, _kUnusuallyLongTimeout),
        message: '${command.kind} message is taking a long time to complete...',
405
      );
406
      _logCommunication('<<< $response');
407
    } catch (error, stackTrace) {
408
      throw DriverError(
409 410
        'Failed to fulfill ${command.runtimeType} due to remote error',
        error,
411
        stackTrace,
412 413
      );
    }
414
    if (response['isError'])
415
      throw DriverError('Error in Flutter application: ${response['response']}');
416
    return response['response'];
417 418
  }

419 420 421 422
  void _logCommunication(String message)  {
    if (_printCommunication)
      _log.info(message);
    if (_logCommunicationToFile) {
423
      final f.File file = fs.file(p.join(testOutputsDirectory, 'flutter_driver_commands_$_driverId.log'));
424
      file.createSync(recursive: true); // no-op if file exists
425
      file.writeAsStringSync('${DateTime.now()} $message\n', mode: f.FileMode.append, flush: true);
426 427 428
    }
  }

429
  /// Checks the status of the Flutter Driver extension.
430
  Future<Health> checkHealth({Duration timeout}) async {
431
    return Health.fromJson(await _sendCommand(GetHealth(timeout: timeout)));
432 433
  }

434
  /// Returns a dump of the render tree.
435
  Future<RenderTree> getRenderTree({Duration timeout}) async {
436
    return RenderTree.fromJson(await _sendCommand(GetRenderTree(timeout: timeout)));
437 438
  }

439
  /// Taps at the center of the widget located by [finder].
440
  Future<void> tap(SerializableFinder finder, {Duration timeout}) async {
441
    await _sendCommand(Tap(finder, timeout: timeout));
442
  }
443

444
  /// Waits until [finder] locates the target.
445
  Future<void> waitFor(SerializableFinder finder, {Duration timeout}) async {
446
    await _sendCommand(WaitFor(finder, timeout: timeout));
447 448
  }

449
  /// Waits until [finder] can no longer locate the target.
450
  Future<void> waitForAbsent(SerializableFinder finder, {Duration timeout}) async {
451
    await _sendCommand(WaitForAbsent(finder, timeout: timeout));
452 453
  }

454 455 456 457
  /// Waits until there are no more transient callbacks in the queue.
  ///
  /// Use this method when you need to wait for the moment when the application
  /// becomes "stable", for example, prior to taking a [screenshot].
458
  Future<void> waitUntilNoTransientCallbacks({Duration timeout}) async {
459
    await _sendCommand(WaitUntilNoTransientCallbacks(timeout: timeout));
460 461
  }

462 463 464 465 466 467 468 469 470
  /// Tell the driver to perform a scrolling action.
  ///
  /// A scrolling action begins with a "pointer down" event, which commonly maps
  /// to finger press on the touch screen or mouse button press. A series of
  /// "pointer move" events follow. The action is completed by a "pointer up"
  /// event.
  ///
  /// [dx] and [dy] specify the total offset for the entire scrolling action.
  ///
471
  /// [duration] specifies the length of the action.
472 473 474
  ///
  /// The move events are generated at a given [frequency] in Hz (or events per
  /// second). It defaults to 60Hz.
475 476
  Future<void> scroll(SerializableFinder finder, double dx, double dy, Duration duration, { int frequency = 60, Duration timeout }) async {
    await _sendCommand(Scroll(finder, dx, dy, duration, frequency, timeout: timeout));
477 478
  }

479 480
  /// Scrolls the Scrollable ancestor of the widget located by [finder]
  /// until the widget is completely visible.
481 482 483 484 485
  ///
  /// If the widget located by [finder] is contained by a scrolling widget
  /// that lazily creates its children, like [ListView] or [CustomScrollView],
  /// then this method may fail because [finder] doesn't actually exist.
  /// The [scrollUntilVisible] method can be used in this case.
486 487
  Future<void> scrollIntoView(SerializableFinder finder, { double alignment = 0.0, Duration timeout }) async {
    await _sendCommand(ScrollIntoView(finder, alignment: alignment, timeout: timeout));
488 489
  }

490 491 492 493 494
  /// Repeatedly [scroll] the widget located by [scrollable] by [dxScroll] and
  /// [dyScroll] until [item] is visible, and then use [scrollIntoView] to
  /// ensure the item's final position matches [alignment].
  ///
  /// The [scrollable] must locate the scrolling widget that contains [item].
495
  /// Typically `find.byType('ListView')` or `find.byType('CustomScrollView')`.
496
  ///
497
  /// At least one of [dxScroll] and [dyScroll] must be non-zero.
498 499 500 501
  ///
  /// If [item] is below the currently visible items, then specify a negative
  /// value for [dyScroll] that's a small enough increment to expose [item]
  /// without potentially scrolling it up and completely out of view. Similarly
502
  /// if [item] is above, then specify a positive value for [dyScroll].
503
  ///
504
  /// If [item] is to the right of the currently visible items, then
505 506
  /// specify a negative value for [dxScroll] that's a small enough increment to
  /// expose [item] without potentially scrolling it up and completely out of
507
  /// view. Similarly if [item] is to the left, then specify a positive value
508 509 510
  /// for [dyScroll].
  ///
  /// The [timeout] value should be long enough to accommodate as many scrolls
511
  /// as needed to bring an item into view. The default is to not time out.
512
  Future<void> scrollUntilVisible(SerializableFinder scrollable, SerializableFinder item, {
513 514 515
    double alignment = 0.0,
    double dxScroll = 0.0,
    double dyScroll = 0.0,
516
    Duration timeout,
517 518 519 520 521 522 523 524
  }) async {
    assert(scrollable != null);
    assert(item != null);
    assert(alignment != null);
    assert(dxScroll != null);
    assert(dyScroll != null);
    assert(dxScroll != 0.0 || dyScroll != 0.0);

525 526 527 528
    // Kick off an (unawaited) waitFor that will complete when the item we're
    // looking for finally scrolls onscreen. We add an initial pause to give it
    // the chance to complete if the item is already onscreen; if not, scroll
    // repeatedly until we either find the item or time out.
529
    bool isVisible = false;
530 531
    waitFor(item, timeout: timeout).then<void>((_) { isVisible = true; });
    await Future<void>.delayed(const Duration(milliseconds: 500));
532 533
    while (!isVisible) {
      await scroll(scrollable, dxScroll, dyScroll, const Duration(milliseconds: 100));
534
      await Future<void>.delayed(const Duration(milliseconds: 500));
535 536 537 538 539
    }

    return scrollIntoView(item, alignment: alignment);
  }

540
  /// Returns the text in the `Text` widget located by [finder].
541
  Future<String> getText(SerializableFinder finder, { Duration timeout }) async {
542
    return GetTextResult.fromJson(await _sendCommand(GetText(finder, timeout: timeout))).text;
543 544
  }

545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
  /// Enters `text` into the currently focused text input, such as the
  /// [EditableText] widget.
  ///
  /// This method does not use the operating system keyboard to enter text.
  /// Instead it emulates text entry by sending events identical to those sent
  /// by the operating system keyboard (the "TextInputClient.updateEditingState"
  /// method channel call).
  ///
  /// Generally the behavior is dependent on the implementation of the widget
  /// receiving the input. Usually, editable widgets, such as [EditableText] and
  /// those built on top of it would replace the currently entered text with the
  /// provided `text`.
  ///
  /// It is assumed that the widget receiving text input is focused prior to
  /// calling this method. Typically, a test would activate a widget, e.g. using
  /// [tap], then call this method.
  ///
562 563 564
  /// For this method to work, text emulation must be enabled (see
  /// [setTextEntryEmulation]). Text emulation is enabled by default.
  ///
565 566 567 568
  /// Example:
  ///
  /// ```dart
  /// test('enters text in a text field', () async {
569 570 571 572 573 574
  ///   var textField = find.byValueKey('enter-text-field');
  ///   await driver.tap(textField);  // acquire focus
  ///   await driver.enterText('Hello!');  // enter text
  ///   await driver.waitFor(find.text('Hello!'));  // verify text appears on UI
  ///   await driver.enterText('World!');  // enter another piece of text
  ///   await driver.waitFor(find.text('World!'));  // verify new text appears
575 576
  /// });
  /// ```
577
  Future<void> enterText(String text, { Duration timeout }) async {
578
    await _sendCommand(EnterText(text, timeout: timeout));
579 580
  }

581 582
  /// Configures text entry emulation.
  ///
583
  /// If `enabled` is true, enables text entry emulation via [enterText]. If
584 585 586 587 588 589
  /// `enabled` is false, disables it. By default text entry emulation is
  /// enabled.
  ///
  /// When disabled, [enterText] will fail with a [DriverError]. When an
  /// [EditableText] is focused, the operating system's configured keyboard
  /// method is invoked, such as an on-screen keyboard on a phone or a tablet.
590
  ///
591 592
  /// When enabled, the operating system's configured keyboard will not be
  /// invoked when the widget is focused, as the [SystemChannels.textInput]
593
  /// channel will be mocked out.
594
  Future<void> setTextEntryEmulation({ @required bool enabled, Duration timeout }) async {
595
    assert(enabled != null);
596
    await _sendCommand(SetTextEntryEmulation(enabled, timeout: timeout));
597 598
  }

599 600
  /// Sends a string and returns a string.
  ///
601 602 603 604
  /// This enables generic communication between the driver and the application.
  /// It's expected that the application has registered a [DataHandler]
  /// callback in [enableFlutterDriverExtension] that can successfully handle
  /// these requests.
605
  Future<String> requestData(String message, { Duration timeout }) async {
606
    return RequestDataResult.fromJson(await _sendCommand(RequestData(message, timeout: timeout))).message;
607 608
  }

609 610
  /// Turns semantics on or off in the Flutter app under test.
  ///
611
  /// Returns true when the call actually changed the state from on to off or
612
  /// vice versa.
613
  Future<bool> setSemantics(bool enabled, { Duration timeout }) async {
614
    final SetSemanticsResult result = SetSemanticsResult.fromJson(await _sendCommand(SetSemantics(enabled, timeout: timeout)));
615 616 617
    return result.changedState;
  }

618 619
  /// Retrieves the semantics node id for the object returned by `finder`, or
  /// the nearest ancestor with a semantics node.
620
  ///
621 622
  /// Throws an error if `finder` returns multiple elements or a semantics
  /// node is not found.
623
  ///
624 625
  /// Semantics must be enabled to use this method, either using a platform
  /// specific shell command or [setSemantics].
626
  Future<int> getSemanticsId(SerializableFinder finder, { Duration timeout }) async {
627
    final Map<String, dynamic> jsonResponse = await _sendCommand(GetSemanticsId(finder, timeout: timeout));
628 629 630 631
    final GetSemanticsIdResult result = GetSemanticsIdResult.fromJson(jsonResponse);
    return result.id;
  }

632 633 634 635
  /// Take a screenshot.
  ///
  /// The image will be returned as a PNG.
  Future<List<int>> screenshot() async {
636 637 638 639 640 641 642
    // HACK: this artificial delay here is to deal with a race between the
    //       driver script and the GPU thread. The issue is that driver API
    //       synchronizes with the framework based on transient callbacks, which
    //       are out of sync with the GPU thread. Here's the timeline of events
    //       in ASCII art:
    //
    //       -------------------------------------------------------------------
643
    //       Without this delay:
644 645 646 647 648 649 650 651 652 653
    //       -------------------------------------------------------------------
    //       UI    : <-- build -->
    //       GPU   :               <-- rasterize -->
    //       Gap   :              | random |
    //       Driver:                        <-- screenshot -->
    //
    //       In the diagram above, the gap is the time between the last driver
    //       action taken, such as a `tap()`, and the subsequent call to
    //       `screenshot()`. The gap is random because it is determined by the
    //       unpredictable network communication between the driver process and
654 655 656 657
    //       the application. If this gap is too short, which it typically will
    //       be, the screenshot is taken before the GPU thread is done
    //       rasterizing the frame, so the screenshot of the previous frame is
    //       taken, which is wrong.
658 659
    //
    //       -------------------------------------------------------------------
660
    //       With this delay, if we're lucky:
661 662 663 664 665 666 667 668 669
    //       -------------------------------------------------------------------
    //       UI    : <-- build -->
    //       GPU   :               <-- rasterize -->
    //       Gap   :              |    2 seconds or more   |
    //       Driver:                                        <-- screenshot -->
    //
    //       The two-second gap should be long enough for the GPU thread to
    //       finish rasterizing the frame, but not longer than necessary to keep
    //       driver tests as fast a possible.
670 671 672 673 674 675 676 677 678 679 680 681
    //
    //       -------------------------------------------------------------------
    //       With this delay, if we're not lucky:
    //       -------------------------------------------------------------------
    //       UI    : <-- build -->
    //       GPU   :               <-- rasterize randomly slow today -->
    //       Gap   :              |    2 seconds or more   |
    //       Driver:                                        <-- screenshot -->
    //
    //       In practice, sometimes the device gets really busy for a while and
    //       even two seconds isn't enough, which means that this is still racy
    //       and a source of flakes.
682
    await Future<void>.delayed(const Duration(seconds: 2));
683

684
    final Map<String, dynamic> result = await _peer.sendRequest('_flutter.screenshot');
685
    return base64.decode(result['screenshot']);
686 687
  }

688 689
  /// Returns the Flags set in the Dart VM as JSON.
  ///
690 691
  /// See the complete documentation for [the `getFlagList` Dart VM service
  /// method][getFlagList].
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706
  ///
  /// Example return value:
  ///
  ///     [
  ///       {
  ///         "name": "timeline_recorder",
  ///         "comment": "Select the timeline recorder used. Valid values: ring, endless, startup, and systrace.",
  ///         "modified": false,
  ///         "_flagType": "String",
  ///         "valueAsString": "ring"
  ///       },
  ///       ...
  ///     ]
  ///
  /// [getFlagList]: https://github.com/dart-lang/sdk/blob/master/runtime/vm/service/service.md#getflaglist
707 708
  Future<List<Map<String, dynamic>>> getVmFlags() async {
    final Map<String, dynamic> result = await _peer.sendRequest('getFlagList');
709 710 711
    return result['flags'];
  }

712
  /// Starts recording performance traces.
713 714 715 716
  ///
  /// The `timeout` argument causes a warning to be displayed to the user if the
  /// operation exceeds the specified timeout; it does not actually cancel the
  /// operation.
717
  Future<void> startTracing({
718
    List<TimelineStream> streams = _defaultStreams,
719
    Duration timeout = _kUnusuallyLongTimeout,
720
  }) async {
721
    assert(streams != null && streams.isNotEmpty);
722
    assert(timeout != null);
723
    try {
724 725 726 727 728 729 730
      await _warnIfSlow<void>(
        future: _peer.sendRequest(_setVMTimelineFlagsMethodName, <String, String>{
          'recordedStreams': _timelineStreamsToString(streams)
        }),
        timeout: timeout,
        message: 'VM is taking an unusually long time to respond to being told to start tracing...',
      );
731
    } catch (error, stackTrace) {
732
      throw DriverError(
733 734
        'Failed to start tracing due to remote error',
        error,
735
        stackTrace,
736 737 738 739
      );
    }
  }

740
  /// Stops recording performance traces and downloads the timeline.
741 742 743 744 745 746 747 748
  ///
  /// The `timeout` argument causes a warning to be displayed to the user if the
  /// operation exceeds the specified timeout; it does not actually cancel the
  /// operation.
  Future<Timeline> stopTracingAndDownloadTimeline({
    Duration timeout = _kUnusuallyLongTimeout,
  }) async {
    assert(timeout != null);
749
    try {
750 751 752 753 754
      await _warnIfSlow<void>(
        future: _peer.sendRequest(_setVMTimelineFlagsMethodName, <String, String>{'recordedStreams': '[]'}),
        timeout: timeout,
        message: 'VM is taking an unusually long time to respond to being told to stop tracing...',
      );
755
      return Timeline.fromJson(await _peer.sendRequest(_getVMTimelineMethodName));
756
    } catch (error, stackTrace) {
757
      throw DriverError(
758
        'Failed to stop tracing due to remote error',
759
        error,
760
        stackTrace,
761
      );
762 763 764 765 766 767 768 769 770
    }
  }

  /// Runs [action] and outputs a performance trace for it.
  ///
  /// Waits for the `Future` returned by [action] to complete prior to stopping
  /// the trace.
  ///
  /// This is merely a convenience wrapper on top of [startTracing] and
771
  /// [stopTracingAndDownloadTimeline].
772 773 774
  ///
  /// [streams] limits the recorded timeline event streams to only the ones
  /// listed. By default, all streams are recorded.
775 776 777 778 779 780
  ///
  /// If [retainPriorEvents] is true, retains events recorded prior to calling
  /// [action]. Otherwise, prior events are cleared before calling [action]. By
  /// default, prior events are cleared.
  Future<Timeline> traceAction(
    Future<dynamic> action(), {
781 782
    List<TimelineStream> streams = _defaultStreams,
    bool retainPriorEvents = false,
783 784 785 786
  }) async {
    if (!retainPriorEvents) {
      await clearTimeline();
    }
787
    await startTracing(streams: streams);
788
    await action();
789
    return stopTracingAndDownloadTimeline();
790 791
  }

792
  /// Clears all timeline events recorded up until now.
793 794 795 796 797 798 799 800
  ///
  /// The `timeout` argument causes a warning to be displayed to the user if the
  /// operation exceeds the specified timeout; it does not actually cancel the
  /// operation.
  Future<void> clearTimeline({
    Duration timeout = _kUnusuallyLongTimeout
  }) async {
    assert(timeout != null);
801
    try {
802 803 804 805 806
      await _warnIfSlow<void>(
        future: _peer.sendRequest(_clearVMTimelineMethodName, <String, String>{}),
        timeout: timeout,
        message: 'VM is taking an unusually long time to respond to being told to clear its timeline buffer...',
      );
807
    } catch (error, stackTrace) {
808
      throw DriverError(
809 810 811 812 813 814 815
        'Failed to clear event timeline due to remote error',
        error,
        stackTrace,
      );
    }
  }

816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831
  /// [action] will be executed with the frame sync mechanism disabled.
  ///
  /// By default, Flutter Driver waits until there is no pending frame scheduled
  /// in the app under test before executing an action. This mechanism is called
  /// "frame sync". It greatly reduces flakiness because Flutter Driver will not
  /// execute an action while the app under test is undergoing a transition.
  ///
  /// Having said that, sometimes it is necessary to disable the frame sync
  /// mechanism (e.g. if there is an ongoing animation in the app, it will
  /// never reach a state where there are no pending frames scheduled and the
  /// action will time out). For these cases, the sync mechanism can be disabled
  /// by wrapping the actions to be performed by this [runUnsynchronized] method.
  ///
  /// With frame sync disabled, its the responsibility of the test author to
  /// ensure that no action is performed while the app is undergoing a
  /// transition to avoid flakiness.
832
  Future<T> runUnsynchronized<T>(Future<T> action(), { Duration timeout }) async {
833
    await _sendCommand(SetFrameSync(false, timeout: timeout));
834
    T result;
835 836 837
    try {
      result = await action();
    } finally {
838
      await _sendCommand(SetFrameSync(true, timeout: timeout));
839 840 841 842
    }
    return result;
  }

843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858
  /// Force a garbage collection run in the VM.
  Future<void> forceGC() async {
    try {
      await _peer
          .sendRequest(_collectAllGarbageMethodName, <String, String>{
            'isolateId': 'isolates/${_appIsolate.numberAsString}',
          });
    } catch (error, stackTrace) {
      throw DriverError(
        'Failed to force a GC due to remote error',
        error,
        stackTrace,
      );
    }
  }

859 860 861
  /// Closes the underlying connection to the VM service.
  ///
  /// Returns a [Future] that fires once the connection has been closed.
862
  Future<void> close() async {
863
    // Don't leak vm_service_client-specific objects, if any
864 865 866
    await _serviceClient.close();
    await _peer.close();
  }
867
}
yjbanov's avatar
yjbanov committed
868

869
/// Encapsulates connection information to an instance of a Flutter application.
870
@visibleForTesting
871
class VMServiceClientConnection {
872 873 874
  /// Creates an instance of this class given a [client] and a [peer].
  VMServiceClientConnection(this.client, this.peer);

875 876 877 878 879 880 881 882 883 884
  /// Use this for structured access to the VM service's public APIs.
  final VMServiceClient client;

  /// Use this to make arbitrary raw JSON-RPC calls.
  ///
  /// This object allows reaching into private VM service APIs. Use with
  /// caution.
  final rpc.Peer peer;
}

yjbanov's avatar
yjbanov committed
885
/// A function that connects to a Dart VM service given the [url].
886
typedef VMServiceConnectFunction = Future<VMServiceClientConnection> Function(String url);
yjbanov's avatar
yjbanov committed
887 888 889 890 891 892 893 894 895 896 897 898 899 900

/// The connection function used by [FlutterDriver.connect].
///
/// Overwrite this function if you require a custom method for connecting to
/// the VM service.
VMServiceConnectFunction vmServiceConnectFunction = _waitAndConnect;

/// Restores [vmServiceConnectFunction] to its default value.
void restoreVmServiceConnectFunction() {
  vmServiceConnectFunction = _waitAndConnect;
}

/// Waits for a real Dart VM service to become available, then connects using
/// the [VMServiceClient].
901
Future<VMServiceClientConnection> _waitAndConnect(String url) async {
902 903 904 905 906
  Uri uri = Uri.parse(url);
  if (uri.scheme == 'http')
    uri = uri.replace(scheme: 'ws', path: '/ws');
  int attempts = 0;
  while (true) {
907 908 909
    WebSocket ws1;
    WebSocket ws2;
    try {
910 911
      ws1 = await WebSocket.connect(uri.toString());
      ws2 = await WebSocket.connect(uri.toString());
912 913
      return VMServiceClientConnection(
        VMServiceClient(IOWebSocketChannel(ws1).cast()),
914
        rpc.Peer(IOWebSocketChannel(ws2).cast())..listen(),
915
      );
916
    } catch (e) {
917 918
      await ws1?.close();
      await ws2?.close();
919 920 921 922
      if (attempts > 5)
        _log.warning('It is taking an unusually long time to connect to the VM...');
      attempts += 1;
      await Future<void>.delayed(_kPauseBetweenReconnectAttempts);
923
    }
yjbanov's avatar
yjbanov committed
924 925
  }
}
926 927 928 929 930

/// Provides convenient accessors to frequently used finders.
class CommonFinders {
  const CommonFinders._();

931
  /// Finds [Text] and [EditableText] widgets containing string equal to [text].
932
  SerializableFinder text(String text) => ByText(text);
933

934
  /// Finds widgets by [key]. Only [String] and [int] values can be used.
935
  SerializableFinder byValueKey(dynamic key) => ByValueKey(key);
936 937

  /// Finds widgets with a tooltip with the given [message].
938
  SerializableFinder byTooltip(String message) => ByTooltipMessage(message);
939 940

  /// Finds widgets whose class name matches the given string.
941
  SerializableFinder byType(String type) => ByType(type);
942 943 944

  /// Finds the back button on a Material or Cupertino page's scaffold.
  SerializableFinder pageBack() => PageBack();
945
}