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

import 'dart:async';
import 'dart:convert';
7
import 'dart:io' as io; // ignore: dart_io_import
8 9

import 'package:file/file.dart';
10
import 'package:flutter_tools/src/base/common.dart';
11 12
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
13
import 'package:flutter_tools/src/base/utils.dart';
14
import 'package:meta/meta.dart';
15
import 'package:process/process.dart';
16 17
import 'package:vm_service/vm_service.dart';
import 'package:vm_service/vm_service_io.dart';
18 19

import '../src/common.dart';
20
import 'test_utils.dart';
21

22 23 24 25 26 27 28 29 30 31
// Set this to true for debugging to get verbose logs written to stdout.
// The logs include the following:
//   <=stdout= data that the flutter tool running in --verbose mode wrote to stdout.
//   <=stderr= data that the flutter tool running in --verbose mode wrote to stderr.
//   =stdin=> data that the test sent to the flutter tool over stdin.
//   =vm=> data that was sent over the VM service channel to the app running on the test device.
//   <=vm= data that was sent from the app on the test device over the VM service channel.
//   Messages regarding what the test is doing.
// If this is false, then only critical errors and logs when things appear to be
// taking a long time are printed to the console.
32
const bool _printDebugOutputToStdOut = false;
33 34 35 36

final DateTime startTime = DateTime.now();

const Duration defaultTimeout = Duration(seconds: 5);
37 38
const Duration appStartTimeout = Duration(seconds: 120);
const Duration quitTimeout = Duration(seconds: 10);
39

40
abstract class FlutterTestDriver {
41 42 43 44
  FlutterTestDriver(
    this._projectFolder, {
    String logPrefix,
  }) : _logPrefix = logPrefix != null ? '$logPrefix: ' : '';
45

46
  final Directory _projectFolder;
47
  final String _logPrefix;
48 49
  Process _process;
  int _processPid;
50 51 52 53
  final StreamController<String> _stdout = StreamController<String>.broadcast();
  final StreamController<String> _stderr = StreamController<String>.broadcast();
  final StreamController<String> _allMessages = StreamController<String>.broadcast();
  final StringBuffer _errorBuffer = StringBuffer();
54
  String _lastResponse;
55
  Uri _vmServiceWsUri;
56
  bool _hasExited = false;
57

58
  VmService _vmService;
59
  String get lastErrorInfo => _errorBuffer.toString();
60
  Stream<String> get stdout => _stdout.stream;
61
  int get vmServicePort => _vmServiceWsUri.port;
62
  bool get hasExited => _hasExited;
63

64 65 66 67 68 69 70 71 72 73 74 75
  String lastTime = '';
  void _debugPrint(String message, { String topic = '' }) {
    const int maxLength = 2500;
    final String truncatedMessage = message.length > maxLength ? message.substring(0, maxLength) + '...' : message;
    final String line = '${topic.padRight(10)} $truncatedMessage';
    _allMessages.add(line);
    final int timeInSeconds = DateTime.now().difference(startTime).inSeconds;
    String time = timeInSeconds.toString().padLeft(5) + 's ';
    if (time == lastTime) {
      time = ' ' * time.length;
    } else {
      lastTime = time;
76
    }
77
    if (_printDebugOutputToStdOut) {
78
      print('$time$_logPrefix$line');
79
    }
80
  }
81

82
  Future<void> _setupProcess(
83
    List<String> arguments, {
84
    String script,
85 86
    bool withDebugger = false,
    File pidFile,
87
    bool singleWidgetReloads = false,
88
  }) async {
89
    final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
90
    if (withDebugger) {
91
      arguments.add('--start-paused');
92 93
    }
    if (_printDebugOutputToStdOut) {
94
      arguments.add('--verbose');
95
    }
96
    if (pidFile != null) {
97
      arguments.addAll(<String>['--pid-file', pidFile.path]);
98
    }
99
    if (script != null) {
100
      arguments.add(script);
101
    }
102
    _debugPrint('Spawning flutter $arguments in ${_projectFolder.path}');
103

104
    const ProcessManager _processManager = LocalProcessManager();
105 106 107 108 109
    _process = await _processManager.start(
      <String>[flutterBin]
        .followedBy(arguments)
        .toList(),
      workingDirectory: _projectFolder.path,
110
      // The web environment variable has the same effect as `flutter config --enable-web`.
111 112 113 114 115 116
      environment: <String, String>{
        'FLUTTER_TEST': 'true',
        'FLUTTER_WEB': 'true',
        if (singleWidgetReloads)
          'FLUTTER_SINGLE_WIDGET_RELOAD': 'true',
      },
117
    );
118

119 120
    // This class doesn't use the result of the future. It's made available
    // via a getter for external uses.
121
    unawaited(_process.exitCode.then((int code) {
122 123
      _debugPrint('Process exited ($code)');
      _hasExited = true;
124
    }));
125 126
    transformToLines(_process.stdout).listen(_stdout.add);
    transformToLines(_process.stderr).listen(_stderr.add);
127 128 129 130 131

    // Capture stderr to a buffer so we can show it all if any requests fail.
    _stderr.stream.listen(_errorBuffer.writeln);

    // This is just debug printing to aid running/debugging tests locally.
132 133
    _stdout.stream.listen((String message) => _debugPrint(message, topic: '<=stdout='));
    _stderr.stream.listen((String message) => _debugPrint(message, topic: '<=stderr='));
134 135
  }

136 137
  Future<void> get done => _process.exitCode;

138
  Future<void> connectToVmService({ bool pauseOnExceptions = false }) async {
139 140 141
    _vmService = await vmServiceConnectUri('$_vmServiceWsUri');
    _vmService.onSend.listen((String s) => _debugPrint(s, topic: '=vm=>'));
    _vmService.onReceive.listen((String s) => _debugPrint(s, topic: '<=vm='));
142 143

    final Completer<void> isolateStarted = Completer<void>();
144
    _vmService.onIsolateEvent.listen((Event event) {
145 146 147
      if (event.kind == EventKind.kIsolateStart) {
        isolateStarted.complete();
      } else if (event.kind == EventKind.kIsolateExit && event.isolate.id == _flutterIsolateId) {
148 149 150
        // Hot restarts cause all the isolates to exit, so we need to refresh
        // our idea of what the Flutter isolate ID is.
        _flutterIsolateId = null;
151
      }
152 153 154 155 156 157 158
    });

    await Future.wait(<Future<Success>>[
      _vmService.streamListen('Isolate'),
      _vmService.streamListen('Debug'),
    ]);

159 160 161 162
    if ((await _vmService.getVM()).isolates.isEmpty) {
      await isolateStarted.future;
    }

163 164 165 166 167 168 169
    await waitForPause();
    if (pauseOnExceptions) {
      await _vmService.setExceptionPauseMode(
        await _getFlutterIsolateId(),
        ExceptionPauseMode.kUnhandled,
      );
    }
170 171
  }

172 173
  Future<int> quit() => _killGracefully();

174
  Future<int> _killGracefully() async {
175
    if (_processPid == null) {
176
      return -1;
177
    }
178 179 180 181
    // If we try to kill the process while it's paused, we'll end up terminating
    // it forcefully and it won't terminate child processes, so we need to ensure
    // it's running before terminating.
    await resume().timeout(defaultTimeout)
182 183 184 185
        .catchError((Object e) {
          _debugPrint('Ignoring failure to resume during shutdown');
          return null;
        });
186

187
    _debugPrint('Sending SIGTERM to $_processPid..');
188
    io.Process.killPid(_processPid, io.ProcessSignal.sigterm);
189
    return _process.exitCode.timeout(quitTimeout, onTimeout: _killForcefully);
190 191 192
  }

  Future<int> _killForcefully() {
193
    _debugPrint('Sending SIGKILL to $_processPid..');
194
    ProcessSignal.SIGKILL.send(_processPid);
195
    return _process.exitCode;
196 197
  }

198 199
  String _flutterIsolateId;
  Future<String> _getFlutterIsolateId() async {
200 201
    // Currently these tests only have a single isolate. If this
    // ceases to be the case, this code will need changing.
202 203
    if (_flutterIsolateId == null) {
      final VM vm = await _vmService.getVM();
204
      _flutterIsolateId = vm.isolates.single.id;
205 206 207 208 209
    }
    return _flutterIsolateId;
  }

  Future<Isolate> _getFlutterIsolate() async {
210
    final Isolate isolate = await _vmService.getIsolate(await _getFlutterIsolateId());
211
    return isolate;
212 213
  }

214 215 216 217 218 219 220 221 222 223 224 225 226 227
  /// Add a breakpoint and wait for it to trip the program execution.
  ///
  /// Only call this when you are absolutely sure that the program under test
  /// will hit the breakpoint _in the future_.
  ///
  /// In particular, do not call this if the program is currently racing to pass
  /// the line of code you are breaking on. Pretend that calling this will take
  /// an hour before setting the breakpoint. Would the code still eventually hit
  /// the breakpoint and stop?
  Future<void> breakAt(Uri uri, int line) async {
    await addBreakpoint(uri, line);
    await waitForPause();
  }

228
  Future<void> addBreakpoint(Uri uri, int line) async {
229
    _debugPrint('Sending breakpoint for: $uri:$line');
230
    await _vmService.addBreakpointWithScriptUri(
231 232 233 234
      await _getFlutterIsolateId(),
      uri.toString(),
      line,
    );
235 236
  }

237 238
  // This method isn't racy. If the isolate is already paused,
  // it will immediately return.
239
  Future<Isolate> waitForPause() async {
240 241 242 243 244 245 246 247 248 249 250 251
    return _timeoutWithMessages<Isolate>(
      () async {
        final String flutterIsolate = await _getFlutterIsolateId();
        final Completer<Event> pauseEvent = Completer<Event>();

        // Start listening for pause events.
        final StreamSubscription<Event> pauseSubscription = _vmService.onDebugEvent
          .where((Event event) {
            return event.isolate.id == flutterIsolate
                && event.kind.startsWith('Pause');
          })
          .listen((Event event) {
252
            if (!pauseEvent.isCompleted) {
253
              pauseEvent.complete(event);
254
            }
255 256 257 258 259
          });

        // But also check if the isolate was already paused (only after we've set
        // up the subscription) to avoid races. If it was paused, we don't need to wait
        // for the event.
260
        final Isolate isolate = await _vmService.getIsolate(flutterIsolate);
261 262 263 264 265 266
        if (isolate.pauseEvent.kind.startsWith('Pause')) {
          _debugPrint('Isolate was already paused (${isolate.pauseEvent.kind}).');
        } else {
          _debugPrint('Isolate is not already paused, waiting for event to arrive...');
          await pauseEvent.future;
        }
267

268 269
        // Cancel the subscription on either of the above.
        await pauseSubscription.cancel();
270

271 272 273 274
        return _getFlutterIsolate();
      },
      task: 'Waiting for isolate to pause',
    );
275
  }
276

277 278
  Future<Isolate> resume({ bool waitForNextPause = false }) => _resume(null, waitForNextPause);
  Future<Isolate> stepOver({ bool waitForNextPause = true }) => _resume(StepOption.kOver, waitForNextPause);
279
  Future<Isolate> stepOverAsync({ bool waitForNextPause = true }) => _resume(StepOption.kOverAsyncSuspension, waitForNextPause);
280 281
  Future<Isolate> stepInto({ bool waitForNextPause = true }) => _resume(StepOption.kInto, waitForNextPause);
  Future<Isolate> stepOut({ bool waitForNextPause = true }) => _resume(StepOption.kOut, waitForNextPause);
282

283 284 285 286 287
  Future<bool> isAtAsyncSuspension() async {
    final Isolate isolate = await _getFlutterIsolate();
    return isolate.pauseEvent.atAsyncSuspension == true;
  }

288
  Future<Isolate> stepOverOrOverAsyncSuspension({ bool waitForNextPause = true }) async {
289
    if (await isAtAsyncSuspension()) {
290
      return await stepOverAsync(waitForNextPause: waitForNextPause);
291
    }
292
    return await stepOver(waitForNextPause: waitForNextPause);
293
  }
294

295 296 297 298 299 300 301
  Future<Isolate> _resume(String step, bool waitForNextPause) async {
    assert(waitForNextPause != null);
    await _timeoutWithMessages<dynamic>(
      () async => _vmService.resume(await _getFlutterIsolateId(), step: step),
      task: 'Resuming isolate (step=$step)',
    );
    return waitForNextPause ? waitForPause() : null;
302 303
  }

304 305 306
  Future<ObjRef> evaluateInFrame(String expression) async {
    return _timeoutWithMessages<ObjRef>(
      () async => await _vmService.evaluateInFrame(await _getFlutterIsolateId(), 0, expression) as ObjRef,
307 308
      task: 'Evaluating expression ($expression)',
    );
309 310
  }

311 312
  Future<InstanceRef> evaluate(String targetId, String expression) async {
    return _timeoutWithMessages<InstanceRef>(
313
      () async => await _vmService.evaluate(await _getFlutterIsolateId(), targetId, expression) as InstanceRef,
314 315
      task: 'Evaluating expression ($expression for $targetId)',
    );
316 317 318 319
  }

  Future<Frame> getTopStackFrame() async {
    final String flutterIsolateId = await _getFlutterIsolateId();
320
    final Stack stack = await _vmService.getStack(flutterIsolateId);
321
    if (stack.frames.isEmpty) {
322
      throw Exception('Stack is empty');
323
    }
324 325 326
    return stack.frames.first;
  }

327 328 329
  Future<SourcePosition> getSourceLocation() async {
    final String flutterIsolateId = await _getFlutterIsolateId();
    final Frame frame = await getTopStackFrame();
330
    final Script script = await _vmService.getObject(flutterIsolateId, frame.location.script.id) as Script;
331 332 333 334
    return _lookupTokenPos(script.tokenPosTable, frame.location.tokenPos);
  }

  SourcePosition _lookupTokenPos(List<List<int>> table, int tokenPos) {
335
    for (final List<int> row in table) {
336 337 338 339 340 341 342 343 344 345 346
      final int lineNumber = row[0];
      int index = 1;

      for (index = 1; index < row.length - 1; index += 2) {
        if (row[index] == tokenPos) {
          return SourcePosition(lineNumber, row[index + 1]);
        }
      }
    }

    return null;
347 348
  }

349 350 351
  Future<Map<String, dynamic>> _waitFor({
    String event,
    int id,
352
    Duration timeout = defaultTimeout,
353 354
    bool ignoreAppStopEvent = false,
  }) async {
355 356 357 358
    assert(timeout != null);
    assert(event != null || id != null);
    assert(event == null || id == null);
    final String interestingOccurrence = event != null ? '$event event' : 'response to request $id';
359
    final Completer<Map<String, dynamic>> response = Completer<Map<String, dynamic>>();
360 361
    StreamSubscription<String> subscription;
    subscription = _stdout.stream.listen((String line) async {
362
      final Map<String, dynamic> json = parseFlutterResponse(line);
363
      _lastResponse = line;
364
      if (json == null) {
365
        return;
366
      }
367
      if ((event != null && json['event'] == event) ||
368
          (id != null && json['id'] == id)) {
369 370
        await subscription.cancel();
        _debugPrint('OK ($interestingOccurrence)');
371
        response.complete(json);
372
      } else if (!ignoreAppStopEvent && json['event'] == 'app.stop') {
373
        await subscription.cancel();
374
        final StringBuffer error = StringBuffer();
375
        error.write('Received app.stop event while waiting for $interestingOccurrence\n\n$_errorBuffer');
376 377 378 379 380 381
        if (json['params'] != null && json['params']['error'] != null) {
          error.write('${json['params']['error']}\n\n');
        }
        if (json['params'] != null && json['params']['trace'] != null) {
          error.write('${json['params']['trace']}\n\n');
        }
382
        response.completeError(Exception(error.toString()));
383 384
      }
    });
385

386 387 388 389 390
    return _timeoutWithMessages(
      () => response.future,
      timeout: timeout,
      task: 'Expecting $interestingOccurrence',
    ).whenComplete(subscription.cancel);
391 392
  }

393 394
  Future<T> _timeoutWithMessages<T>(
    Future<T> Function() callback, {
395 396 397 398 399 400 401 402
    @required String task,
    Duration timeout = defaultTimeout,
  }) {
    assert(task != null);
    assert(timeout != null);

    if (_printDebugOutputToStdOut) {
      _debugPrint('$task...');
403 404
      final Timer longWarning = Timer(timeout, () => _debugPrint('$task is taking longer than usual...'));
      return callback().whenComplete(longWarning.cancel);
405 406 407 408 409 410
    }

    // We're not showing all output to the screen, so let's capture the output
    // that we would have printed if we were, and output it if we take longer
    // than the timeout or if we get an error.
    final StringBuffer messages = StringBuffer('$task\n');
411
    final DateTime start = DateTime.now();
412 413
    bool timeoutExpired = false;
    void logMessage(String logLine) {
414
      final int ms = DateTime.now().difference(start).inMilliseconds;
415 416
      final String formattedLine = '[+ ${ms.toString().padLeft(5)}] $logLine';
      messages.writeln(formattedLine);
417
    }
418
    final StreamSubscription<String> subscription = _allMessages.stream.listen(logMessage);
419

420
    final Timer longWarning = Timer(timeout, () {
421
      _debugPrint(messages.toString());
422
      timeoutExpired = true;
423
      _debugPrint('$task is taking longer than usual...');
424
    });
425
    final Future<T> future = callback().whenComplete(longWarning.cancel);
426 427 428 429

    return future.catchError((dynamic error) {
      if (!timeoutExpired) {
        timeoutExpired = true;
430
        _debugPrint(messages.toString());
431 432 433
      }
      throw error;
    }).whenComplete(() => subscription.cancel());
434
  }
435 436 437
}

class FlutterRunTestDriver extends FlutterTestDriver {
438 439 440
  FlutterRunTestDriver(
    Directory projectFolder, {
    String logPrefix,
441
    this.spawnDdsInstance = true,
442
  }) : super(projectFolder, logPrefix: logPrefix);
443 444 445

  String _currentRunningAppId;

446
  Future<void> run({
447
    bool withDebugger = false,
448
    bool startPaused = false,
449
    bool pauseOnExceptions = false,
450
    bool chrome = false,
451
    bool expressionEvaluation = true,
452
    bool structuredErrors = false,
453
    bool machine = true,
454
    bool singleWidgetReloads = false,
455
    File pidFile,
456
    String script,
457
    List<String> additionalCommandArgs,
458
  }) async {
459 460
    await _setupProcess(
      <String>[
461
        'run',
462 463
        if (!chrome)
          '--disable-service-auth-codes',
464
        if (machine) '--machine',
465
        if (!spawnDdsInstance) '--disable-dds',
466
        ...getLocalEngineArguments(),
467
        '-d',
468
        if (chrome)
469 470 471 472 473
          ...<String>[
            'chrome',
            '--web-run-headless',
            if (!expressionEvaluation) '--no-web-enable-expression-evaluation'
          ]
474 475
        else
          'flutter-tester',
476 477
        if (structuredErrors)
          '--dart-define=flutter.inspector.structuredErrors=true',
478
        ...?additionalCommandArgs,
479 480 481 482 483
      ],
      withDebugger: withDebugger,
      startPaused: startPaused,
      pauseOnExceptions: pauseOnExceptions,
      pidFile: pidFile,
484
      script: script,
485
      singleWidgetReloads: singleWidgetReloads,
486
    );
487 488 489 490 491
  }

  Future<void> attach(
    int port, {
    bool withDebugger = false,
492
    bool startPaused = false,
493 494
    bool pauseOnExceptions = false,
    File pidFile,
495
    bool singleWidgetReloads = false,
496
  }) async {
497 498
    await _setupProcess(
      <String>[
499
        'attach',
500
         ...getLocalEngineArguments(),
501
        '--machine',
502 503
        if (!spawnDdsInstance)
          '--disable-dds',
504 505 506 507
        '-d',
        'flutter-tester',
        '--debug-port',
        '$port',
508 509 510 511 512
      ],
      withDebugger: withDebugger,
      startPaused: startPaused,
      pauseOnExceptions: pauseOnExceptions,
      pidFile: pidFile,
513
      singleWidgetReloads: singleWidgetReloads,
514
    );
515 516 517 518 519
  }

  @override
  Future<void> _setupProcess(
    List<String> args, {
520
    String script,
521
    bool withDebugger = false,
522
    bool startPaused = false,
523
    bool pauseOnExceptions = false,
524
    bool singleWidgetReloads = false,
525 526
    File pidFile,
  }) async {
527
    assert(!startPaused || withDebugger);
528 529
    await super._setupProcess(
      args,
530
      script: script,
531 532
      withDebugger: withDebugger,
      pidFile: pidFile,
533
      singleWidgetReloads: singleWidgetReloads,
534 535
    );

536 537 538 539 540 541 542 543
    final Completer<void> prematureExitGuard = Completer<void>();

    // If the process exits before all of the `await`s below are done, then it
    // exited prematurely. This causes the currently suspended `await` to
    // deadlock until the test times out. Instead, this causes the test to fail
    // fast.
    unawaited(_process.exitCode.then((_) {
      if (!prematureExitGuard.isCompleted) {
544
        prematureExitGuard.completeError(Exception('Process exited prematurely: ${args.join(' ')}: $_errorBuffer'));
545 546
      }
    }));
547

548 549 550 551 552 553
    unawaited(() async {
      try {
        // Stash the PID so that we can terminate the VM more reliably than using
        // _process.kill() (`flutter` is a shell script so _process itself is a
        // shell, not the flutter tool's Dart process).
        final Map<String, dynamic> connected = await _waitFor(event: 'daemon.connected');
554
        _processPid = connected['params']['pid'] as int;
555 556 557 558 559 560 561

        // Set this up now, but we don't wait it yet. We want to make sure we don't
        // miss it while waiting for debugPort below.
        final Future<Map<String, dynamic>> started = _waitFor(event: 'app.started', timeout: appStartTimeout);

        if (withDebugger) {
          final Map<String, dynamic> debugPort = await _waitFor(event: 'app.debugPort', timeout: appStartTimeout);
562
          final String wsUriString = debugPort['params']['wsUri'] as String;
563 564 565 566 567 568
          _vmServiceWsUri = Uri.parse(wsUriString);
          await connectToVmService(pauseOnExceptions: pauseOnExceptions);
          if (!startPaused) {
            await resume(waitForNextPause: false);
          }
        }
569

570 571
        // Now await the started event; if it had already happened the future will
        // have already completed.
572
        _currentRunningAppId = (await started)['params']['appId'] as String;
573
        prematureExitGuard.complete();
574
      } on Exception catch (error, stackTrace) {
575
        prematureExitGuard.completeError(Exception(error.toString()), stackTrace);
576
      }
577
    }());
578

579
    return prematureExitGuard.future;
580 581
  }

582 583 584
  Future<void> hotRestart({ bool pause = false, bool debounce = false}) => _restart(fullRestart: true, pause: pause);
  Future<void> hotReload({ bool debounce = false, int debounceDurationOverrideMs }) =>
      _restart(fullRestart: false, debounce: debounce, debounceDurationOverrideMs: debounceDurationOverrideMs);
585

586 587 588 589 590 591 592 593 594 595
  Future<void> scheduleFrame() async {
    if (_currentRunningAppId == null) {
      throw Exception('App has not started yet');
    }
    await _sendRequest(
      'app.callServiceExtension',
      <String, dynamic>{'appId': _currentRunningAppId, 'methodName': 'ext.ui.window.scheduleFrame'},
    );
  }

596
  Future<void> _restart({ bool fullRestart = false, bool pause = false, bool debounce = false, int debounceDurationOverrideMs }) async {
597
    if (_currentRunningAppId == null) {
598
      throw Exception('App has not started yet');
599
    }
600

601 602 603
    _debugPrint('Performing ${ pause ? "paused " : "" }${ fullRestart ? "hot restart" : "hot reload" }...');
    final dynamic hotReloadResponse = await _sendRequest(
      'app.restart',
604
      <String, dynamic>{'appId': _currentRunningAppId, 'fullRestart': fullRestart, 'pause': pause, 'debounce': debounce, 'debounceDurationOverrideMs': debounceDurationOverrideMs},
605
    );
606
    _debugPrint('${fullRestart ? "Hot restart" : "Hot reload"} complete.');
607

608
    if (hotReloadResponse == null || hotReloadResponse['code'] != 0) {
609
      _throwErrorResponse('Hot ${fullRestart ? 'restart' : 'reload'} request failed');
610
    }
611 612 613
  }

  Future<int> detach() async {
614 615 616
    if (_process == null) {
      return 0;
    }
617
    if (_vmService != null) {
618
      _debugPrint('Closing VM service...');
619 620 621
      _vmService.dispose();
    }
    if (_currentRunningAppId != null) {
622
      _debugPrint('Detaching from app...');
623
      await Future.any<void>(<Future<void>>[
624
        _process.exitCode,
625 626 627 628 629 630 631 632 633 634
        _sendRequest(
          'app.detach',
          <String, dynamic>{'appId': _currentRunningAppId},
        ),
      ]).timeout(
        quitTimeout,
        onTimeout: () { _debugPrint('app.detach did not return within $quitTimeout'); },
      );
      _currentRunningAppId = null;
    }
635 636
    _debugPrint('Waiting for process to end...');
    return _process.exitCode.timeout(quitTimeout, onTimeout: _killGracefully);
637 638 639 640
  }

  Future<int> stop() async {
    if (_vmService != null) {
641
      _debugPrint('Closing VM service...');
642 643 644
      _vmService.dispose();
    }
    if (_currentRunningAppId != null) {
645
      _debugPrint('Stopping application...');
646
      await Future.any<void>(<Future<void>>[
647
        _process.exitCode,
648 649 650 651 652 653 654 655 656 657
        _sendRequest(
          'app.stop',
          <String, dynamic>{'appId': _currentRunningAppId},
        ),
      ]).timeout(
        quitTimeout,
        onTimeout: () { _debugPrint('app.stop did not return within $quitTimeout'); },
      );
      _currentRunningAppId = null;
    }
658 659 660
    if (_process != null) {
      _debugPrint('Waiting for process to end...');
      return _process.exitCode.timeout(quitTimeout, onTimeout: _killGracefully);
661 662 663 664
    }
    return 0;
  }

665 666 667
  int id = 1;
  Future<dynamic> _sendRequest(String method, dynamic params) async {
    final int requestId = id++;
668
    final Map<String, dynamic> request = <String, dynamic>{
669 670
      'id': requestId,
      'method': method,
671
      'params': params,
672
    };
673
    final String jsonEncoded = json.encode(<Map<String, dynamic>>[request]);
674
    _debugPrint(jsonEncoded, topic: '=stdin=>');
675

676
    // Set up the response future before we send the request to avoid any
677
    // races. If the method we're calling is app.stop then we tell _waitFor not
678 679 680 681 682
    // to throw if it sees an app.stop event before the response to this request.
    final Future<Map<String, dynamic>> responseFuture = _waitFor(
      id: requestId,
      ignoreAppStopEvent: method == 'app.stop',
    );
683
    _process.stdin.writeln(jsonEncoded);
684
    final Map<String, dynamic> response = await responseFuture;
685

686
    if (response['error'] != null || response['result'] == null) {
687
      _throwErrorResponse('Unexpected error response');
688
    }
689

690
    return response['result'];
691 692
  }

693 694
  void _throwErrorResponse(String message) {
    throw '$message\n\n$_lastResponse\n\n${_errorBuffer.toString()}'.trim();
695
  }
696 697

  final bool spawnDdsInstance;
698 699
}

700
class FlutterTestTestDriver extends FlutterTestDriver {
701 702
  FlutterTestTestDriver(Directory _projectFolder, {String logPrefix})
    : super(_projectFolder, logPrefix: logPrefix);
703 704 705 706 707

  Future<void> test({
    String testFile = 'test/test.dart',
    bool withDebugger = false,
    bool pauseOnExceptions = false,
708
    bool coverage = false,
709 710 711 712
    File pidFile,
    Future<void> Function() beforeStart,
  }) async {
    await _setupProcess(<String>[
713
      'test',
714
       ...getLocalEngineArguments(),
715 716
      '--disable-service-auth-codes',
      '--machine',
717 718
      if (coverage)
        '--coverage',
719
    ], script: testFile, withDebugger: withDebugger, pauseOnExceptions: pauseOnExceptions, pidFile: pidFile, beforeStart: beforeStart);
720 721 722 723 724 725 726 727 728 729
  }

  @override
  Future<void> _setupProcess(
    List<String> args, {
    String script,
    bool withDebugger = false,
    bool pauseOnExceptions = false,
    File pidFile,
    Future<void> Function() beforeStart,
730
    bool singleWidgetReloads = false,
731 732 733 734 735 736
  }) async {
    await super._setupProcess(
      args,
      script: script,
      withDebugger: withDebugger,
      pidFile: pidFile,
737
      singleWidgetReloads: singleWidgetReloads,
738 739 740 741 742 743
    );

    // Stash the PID so that we can terminate the VM more reliably than using
    // _proc.kill() (because _proc is a shell, because `flutter` is a shell
    // script).
    final Map<String, dynamic> version = await _waitForJson();
744
    _processPid = version['pid'] as int;
745 746 747

    if (withDebugger) {
      final Map<String, dynamic> startedProcess = await _waitFor(event: 'test.startedProcess', timeout: appStartTimeout);
748
      final String vmServiceHttpString = startedProcess['params']['observatoryUri'] as String;
749 750 751 752 753 754
      _vmServiceWsUri = Uri.parse(vmServiceHttpString).replace(scheme: 'ws', path: '/ws');
      await connectToVmService(pauseOnExceptions: pauseOnExceptions);
      // Allow us to run code before we start, eg. to set up breakpoints.
      if (beforeStart != null) {
        await beforeStart();
      }
755
      await resume(waitForNextPause: false);
756 757 758 759
    }
  }

  Future<Map<String, dynamic>> _waitForJson({
760
    Duration timeout = defaultTimeout,
761
  }) async {
762
    assert(timeout != null);
763
    return _timeoutWithMessages<Map<String, dynamic>>(
764 765
      () => _stdout.stream.map<Map<String, dynamic>>(_parseJsonResponse)
          .firstWhere((Map<String, dynamic> output) => output != null),
766
      timeout: timeout,
767
      task: 'Waiting for JSON',
768 769 770 771 772
    );
  }

  Map<String, dynamic> _parseJsonResponse(String line) {
    try {
773
      return castStringKeyedMap(json.decode(line));
774
    } on Exception {
775 776 777 778
      // Not valid JSON, so likely some other output.
      return null;
    }
  }
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801

  Future<void> waitForCompletion() async {
    final Completer<bool> done = Completer<bool>();
    // Waiting for `{"success":true,"type":"done",...}` line indicating
    // end of test run.
    final StreamSubscription<String> subscription = _stdout.stream.listen(
        (String line) async {
          final Map<String, dynamic> json = _parseJsonResponse(line);
          if (json != null && json['type'] != null && json['success'] != null) {
            done.complete(json['type'] == 'done' && json['success'] == true);
          }
        });

    await resume();

    final Future<dynamic> timeoutFuture =
        Future<dynamic>.delayed(defaultTimeout);
    await Future.any<dynamic>(<Future<dynamic>>[done.future, timeoutFuture]);
    await subscription.cancel();
    if (!done.isCompleted) {
      await quit();
    }
  }
802 803
}

804
Stream<String> transformToLines(Stream<List<int>> byteStream) {
805
  return byteStream.transform<String>(utf8.decoder).transform<String>(const LineSplitter());
806
}
807

808
Map<String, dynamic> parseFlutterResponse(String line) {
809
  if (line.startsWith('[') && line.endsWith(']') && line.length > 2) {
810
    try {
811
      final Map<String, dynamic> response = castStringKeyedMap(json.decode(line)[0]);
812
      return response;
813
    } on FormatException {
814 815 816 817 818 819 820
      // Not valid JSON, so likely some other output that was surrounded by [brackets]
      return null;
    }
  }
  return null;
}

821 822 823 824 825 826
class SourcePosition {
  SourcePosition(this.line, this.column);

  final int line;
  final int column;
}
827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843

Future<Isolate> waitForExtension(VmService vmService) async {
  final Completer<void> completer = Completer<void>();
  await vmService.streamListen(EventStreams.kExtension);
  vmService.onExtensionEvent.listen((Event event) {
    if (event.json['extensionKind'] == 'Flutter.FrameworkInitialization') {
      completer.complete();
    }
  });
  final IsolateRef isolateRef = (await vmService.getVM()).isolates.first;
  final Isolate isolate = await vmService.getIsolate(isolateRef.id);
  if (isolate.extensionRPCs.contains('ext.flutter.brightnessOverride')) {
    return isolate;
  }
  await completer.future;
  return isolate;
}