test_driver.dart 26.5 KB
Newer Older
Ian Hickson's avatar
Ian Hickson committed
1
// Copyright 2014 The Flutter Authors. All rights reserved.
2 3 4 5 6 7 8
// 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';

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

import '../src/common.dart';

20 21 22 23 24 25 26 27 28 29
// 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.
30
const bool _printDebugOutputToStdOut = false;
31 32 33 34

final DateTime startTime = DateTime.now();

const Duration defaultTimeout = Duration(seconds: 5);
35 36
const Duration appStartTimeout = Duration(seconds: 120);
const Duration quitTimeout = Duration(seconds: 10);
37

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

44
  final Directory _projectFolder;
45
  final String _logPrefix;
46 47
  Process _process;
  int _processPid;
48 49 50 51
  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();
52
  String _lastResponse;
53
  Uri _vmServiceWsUri;
54
  bool _hasExited = false;
55

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

62 63 64 65 66 67 68 69 70 71 72 73
  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;
74
    }
75
    if (_printDebugOutputToStdOut) {
76
      print('$time$_logPrefix$line');
77
    }
78
  }
79

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

101
    const ProcessManager _processManager = LocalProcessManager();
102 103 104 105 106 107 108
    _process = await _processManager.start(
      <String>[flutterBin]
        .followedBy(arguments)
        .toList(),
      workingDirectory: _projectFolder.path,
      environment: <String, String>{'FLUTTER_TEST': 'true'},
    );
109

110 111
    // This class doesn't use the result of the future. It's made available
    // via a getter for external uses.
112
    unawaited(_process.exitCode.then((int code) {
113 114
      _debugPrint('Process exited ($code)');
      _hasExited = true;
115
    }));
116 117
    transformToLines(_process.stdout).listen((String line) => _stdout.add(line));
    transformToLines(_process.stderr).listen((String line) => _stderr.add(line));
118 119 120 121 122

    // 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.
123 124
    _stdout.stream.listen((String message) => _debugPrint(message, topic: '<=stdout='));
    _stderr.stream.listen((String message) => _debugPrint(message, topic: '<=stderr='));
125 126
  }

127
  Future<void> connectToVmService({ bool pauseOnExceptions = false }) async {
128 129 130
    _vmService = await vmServiceConnectUri('$_vmServiceWsUri');
    _vmService.onSend.listen((String s) => _debugPrint(s, topic: '=vm=>'));
    _vmService.onReceive.listen((String s) => _debugPrint(s, topic: '<=vm='));
131 132

    final Completer<void> isolateStarted = Completer<void>();
133
    _vmService.onIsolateEvent.listen((Event event) {
134 135 136
      if (event.kind == EventKind.kIsolateStart) {
        isolateStarted.complete();
      } else if (event.kind == EventKind.kIsolateExit && event.isolate.id == _flutterIsolateId) {
137 138 139
        // Hot restarts cause all the isolates to exit, so we need to refresh
        // our idea of what the Flutter isolate ID is.
        _flutterIsolateId = null;
140
      }
141 142 143 144 145 146 147
    });

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

148 149 150 151
    if ((await _vmService.getVM()).isolates.isEmpty) {
      await isolateStarted.future;
    }

152 153 154 155 156 157 158
    await waitForPause();
    if (pauseOnExceptions) {
      await _vmService.setExceptionPauseMode(
        await _getFlutterIsolateId(),
        ExceptionPauseMode.kUnhandled,
      );
    }
159 160
  }

161 162
  Future<int> quit() => _killGracefully();

163
  Future<int> _killGracefully() async {
164
    if (_processPid == null) {
165
      return -1;
166
    }
167 168 169 170 171 172
    // 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)
        .catchError((Object e) => _debugPrint('Ignoring failure to resume during shutdown'));

173
    _debugPrint('Sending SIGTERM to $_processPid..');
174
    ProcessSignal.SIGTERM.send(_processPid);
175
    return _process.exitCode.timeout(quitTimeout, onTimeout: _killForcefully);
176 177 178
  }

  Future<int> _killForcefully() {
179
    _debugPrint('Sending SIGKILL to $_processPid..');
180
    ProcessSignal.SIGKILL.send(_processPid);
181
    return _process.exitCode;
182 183
  }

184 185
  String _flutterIsolateId;
  Future<String> _getFlutterIsolateId() async {
186 187
    // Currently these tests only have a single isolate. If this
    // ceases to be the case, this code will need changing.
188 189 190 191 192 193 194 195
    if (_flutterIsolateId == null) {
      final VM vm = await _vmService.getVM();
      _flutterIsolateId = vm.isolates.first.id;
    }
    return _flutterIsolateId;
  }

  Future<Isolate> _getFlutterIsolate() async {
196
    final Isolate isolate = await _vmService.getIsolate(await _getFlutterIsolateId()) as Isolate;
197
    return isolate;
198 199
  }

200 201 202 203 204 205 206 207 208 209 210 211 212 213
  /// 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();
  }

214
  Future<void> addBreakpoint(Uri uri, int line) async {
215
    _debugPrint('Sending breakpoint for: $uri:$line');
216
    await _vmService.addBreakpointWithScriptUri(
217 218 219 220
      await _getFlutterIsolateId(),
      uri.toString(),
      line,
    );
221 222
  }

223 224
  // This method isn't racy. If the isolate is already paused,
  // it will immediately return.
225
  Future<Isolate> waitForPause() async {
226 227 228 229 230 231 232 233 234 235 236 237
    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) {
238
            if (!pauseEvent.isCompleted) {
239
              pauseEvent.complete(event);
240
            }
241 242 243 244 245
          });

        // 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.
246
        final Isolate isolate = await _vmService.getIsolate(flutterIsolate) as Isolate;
247 248 249 250 251 252
        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;
        }
253

254 255
        // Cancel the subscription on either of the above.
        await pauseSubscription.cancel();
256

257 258 259 260
        return _getFlutterIsolate();
      },
      task: 'Waiting for isolate to pause',
    );
261
  }
262

263 264
  Future<Isolate> resume({ bool waitForNextPause = false }) => _resume(null, waitForNextPause);
  Future<Isolate> stepOver({ bool waitForNextPause = true }) => _resume(StepOption.kOver, waitForNextPause);
265
  Future<Isolate> stepOverAsync({ bool waitForNextPause = true }) => _resume(StepOption.kOverAsyncSuspension, waitForNextPause);
266 267
  Future<Isolate> stepInto({ bool waitForNextPause = true }) => _resume(StepOption.kInto, waitForNextPause);
  Future<Isolate> stepOut({ bool waitForNextPause = true }) => _resume(StepOption.kOut, waitForNextPause);
268

269 270 271 272 273
  Future<bool> isAtAsyncSuspension() async {
    final Isolate isolate = await _getFlutterIsolate();
    return isolate.pauseEvent.atAsyncSuspension == true;
  }

274
  Future<Isolate> stepOverOrOverAsyncSuspension({ bool waitForNextPause = true }) async {
275
    if (await isAtAsyncSuspension()) {
276
      return await stepOverAsync(waitForNextPause: waitForNextPause);
277
    }
278
    return await stepOver(waitForNextPause: waitForNextPause);
279
  }
280

281 282 283 284 285 286 287
  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;
288 289
  }

290 291
  Future<InstanceRef> evaluateInFrame(String expression) async {
    return _timeoutWithMessages<InstanceRef>(
292
      () async => await _vmService.evaluateInFrame(await _getFlutterIsolateId(), 0, expression) as InstanceRef,
293 294
      task: 'Evaluating expression ($expression)',
    );
295 296
  }

297 298
  Future<InstanceRef> evaluate(String targetId, String expression) async {
    return _timeoutWithMessages<InstanceRef>(
299
      () async => await _vmService.evaluate(await _getFlutterIsolateId(), targetId, expression) as InstanceRef,
300 301
      task: 'Evaluating expression ($expression for $targetId)',
    );
302 303 304 305 306
  }

  Future<Frame> getTopStackFrame() async {
    final String flutterIsolateId = await _getFlutterIsolateId();
    final Stack stack = await _vmService.getStack(flutterIsolateId);
307
    if (stack.frames.isEmpty) {
308
      throw Exception('Stack is empty');
309
    }
310 311 312
    return stack.frames.first;
  }

313 314 315
  Future<SourcePosition> getSourceLocation() async {
    final String flutterIsolateId = await _getFlutterIsolateId();
    final Frame frame = await getTopStackFrame();
316
    final Script script = await _vmService.getObject(flutterIsolateId, frame.location.script.id) as Script;
317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
    return _lookupTokenPos(script.tokenPosTable, frame.location.tokenPos);
  }

  SourcePosition _lookupTokenPos(List<List<int>> table, int tokenPos) {
    for (List<int> row in table) {
      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;
333 334
  }

335 336 337
  Future<Map<String, dynamic>> _waitFor({
    String event,
    int id,
338
    Duration timeout = defaultTimeout,
339 340
    bool ignoreAppStopEvent = false,
  }) async {
341 342 343 344
    assert(timeout != null);
    assert(event != null || id != null);
    assert(event == null || id == null);
    final String interestingOccurrence = event != null ? '$event event' : 'response to request $id';
345
    final Completer<Map<String, dynamic>> response = Completer<Map<String, dynamic>>();
346 347
    StreamSubscription<String> subscription;
    subscription = _stdout.stream.listen((String line) async {
348
      final Map<String, dynamic> json = parseFlutterResponse(line);
349
      _lastResponse = line;
350
      if (json == null) {
351
        return;
352
      }
353
      if ((event != null && json['event'] == event) ||
354
          (id != null && json['id'] == id)) {
355 356
        await subscription.cancel();
        _debugPrint('OK ($interestingOccurrence)');
357
        response.complete(json);
358
      } else if (!ignoreAppStopEvent && json['event'] == 'app.stop') {
359
        await subscription.cancel();
360
        final StringBuffer error = StringBuffer();
361
        error.write('Received app.stop event while waiting for $interestingOccurrence\n\n');
362 363 364 365 366 367 368
        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');
        }
        response.completeError(error.toString());
369 370
      }
    });
371

372 373 374 375 376
    return _timeoutWithMessages(
      () => response.future,
      timeout: timeout,
      task: 'Expecting $interestingOccurrence',
    ).whenComplete(subscription.cancel);
377 378
  }

379 380
  Future<T> _timeoutWithMessages<T>(
    Future<T> Function() callback, {
381 382 383 384 385 386 387 388
    @required String task,
    Duration timeout = defaultTimeout,
  }) {
    assert(task != null);
    assert(timeout != null);

    if (_printDebugOutputToStdOut) {
      _debugPrint('$task...');
389 390
      final Timer longWarning = Timer(timeout, () => _debugPrint('$task is taking longer than usual...'));
      return callback().whenComplete(longWarning.cancel);
391 392 393 394 395 396
    }

    // 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');
397
    final DateTime start = DateTime.now();
398 399
    bool timeoutExpired = false;
    void logMessage(String logLine) {
400
      final int ms = DateTime.now().difference(start).inMilliseconds;
401 402
      final String formattedLine = '[+ ${ms.toString().padLeft(5)}] $logLine';
      messages.writeln(formattedLine);
403
    }
404
    final StreamSubscription<String> subscription = _allMessages.stream.listen(logMessage);
405

406
    final Timer longWarning = Timer(timeout, () {
407
      _debugPrint(messages.toString());
408
      timeoutExpired = true;
409
      _debugPrint('$task is taking longer than usual...');
410
    });
411
    final Future<T> future = callback().whenComplete(longWarning.cancel);
412 413 414 415

    return future.catchError((dynamic error) {
      if (!timeoutExpired) {
        timeoutExpired = true;
416
        _debugPrint(messages.toString());
417 418 419
      }
      throw error;
    }).whenComplete(() => subscription.cancel());
420
  }
421 422 423
}

class FlutterRunTestDriver extends FlutterTestDriver {
424 425 426 427
  FlutterRunTestDriver(
    Directory projectFolder, {
    String logPrefix,
  }) : super(projectFolder, logPrefix: logPrefix);
428 429 430

  String _currentRunningAppId;

431
  Future<void> run({
432
    bool withDebugger = false,
433
    bool startPaused = false,
434 435 436
    bool pauseOnExceptions = false,
    File pidFile,
  }) async {
437 438
    await _setupProcess(
      <String>[
439
        'run',
440
        '--disable-service-auth-codes',
441 442 443
        '--machine',
        '-d',
        'flutter-tester',
444 445 446 447 448 449
      ],
      withDebugger: withDebugger,
      startPaused: startPaused,
      pauseOnExceptions: pauseOnExceptions,
      pidFile: pidFile,
    );
450 451 452 453 454
  }

  Future<void> attach(
    int port, {
    bool withDebugger = false,
455
    bool startPaused = false,
456 457 458
    bool pauseOnExceptions = false,
    File pidFile,
  }) async {
459 460
    await _setupProcess(
      <String>[
461 462 463 464 465 466
        'attach',
        '--machine',
        '-d',
        'flutter-tester',
        '--debug-port',
        '$port',
467 468 469 470 471 472
      ],
      withDebugger: withDebugger,
      startPaused: startPaused,
      pauseOnExceptions: pauseOnExceptions,
      pidFile: pidFile,
    );
473 474 475 476 477
  }

  @override
  Future<void> _setupProcess(
    List<String> args, {
478
    String script,
479
    bool withDebugger = false,
480
    bool startPaused = false,
481 482 483
    bool pauseOnExceptions = false,
    File pidFile,
  }) async {
484
    assert(!startPaused || withDebugger);
485 486
    await super._setupProcess(
      args,
487
      script: script,
488 489 490 491
      withDebugger: withDebugger,
      pidFile: pidFile,
    );

492 493 494 495 496 497 498 499
    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) {
500
        prematureExitGuard.completeError('Process existed prematurely: ${args.join(' ')}: $_errorBuffer');
501 502
      }
    }));
503

504 505 506 507 508 509
    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');
510
        _processPid = connected['params']['pid'] as int;
511 512 513 514 515 516 517

        // 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);
518
          final String wsUriString = debugPort['params']['wsUri'] as String;
519 520 521 522 523 524
          _vmServiceWsUri = Uri.parse(wsUriString);
          await connectToVmService(pauseOnExceptions: pauseOnExceptions);
          if (!startPaused) {
            await resume(waitForNextPause: false);
          }
        }
525

526 527
        // Now await the started event; if it had already happened the future will
        // have already completed.
528
        _currentRunningAppId = (await started)['params']['appId'] as String;
529
        prematureExitGuard.complete();
530
      } catch (error, stackTrace) {
531
        prematureExitGuard.completeError(error, stackTrace);
532
      }
533
    }());
534

535
    return prematureExitGuard.future;
536 537
  }

538
  Future<void> hotRestart({ bool pause = false }) => _restart(fullRestart: true, pause: pause);
539 540
  Future<void> hotReload() => _restart(fullRestart: false);

541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563
  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'},
    );
  }

  Future<void> reloadMethod({ String libraryId, String classId }) async {
    if (_currentRunningAppId == null) {
      throw Exception('App has not started yet');
    }
    final dynamic reloadMethodResponse = await _sendRequest(
      'app.reloadMethod',
      <String, dynamic>{'appId': _currentRunningAppId, 'class': classId, 'library': libraryId},
    );
    if (reloadMethodResponse == null || reloadMethodResponse['code'] != 0) {
      _throwErrorResponse('reloadMethodResponse request failed');
    }
  }

564
  Future<void> _restart({ bool fullRestart = false, bool pause = false }) async {
565
    if (_currentRunningAppId == null) {
566
      throw Exception('App has not started yet');
567
    }
568

569 570 571
    _debugPrint('Performing ${ pause ? "paused " : "" }${ fullRestart ? "hot restart" : "hot reload" }...');
    final dynamic hotReloadResponse = await _sendRequest(
      'app.restart',
572
      <String, dynamic>{'appId': _currentRunningAppId, 'fullRestart': fullRestart, 'pause': pause},
573
    );
574
    _debugPrint('${fullRestart ? "Hot restart" : "Hot reload"} complete.');
575

576
    if (hotReloadResponse == null || hotReloadResponse['code'] != 0) {
577
      _throwErrorResponse('Hot ${fullRestart ? 'restart' : 'reload'} request failed');
578
    }
579 580 581
  }

  Future<int> detach() async {
582 583 584
    if (_process == null) {
      return 0;
    }
585
    if (_vmService != null) {
586
      _debugPrint('Closing VM service...');
587 588 589
      _vmService.dispose();
    }
    if (_currentRunningAppId != null) {
590
      _debugPrint('Detaching from app...');
591
      await Future.any<void>(<Future<void>>[
592
        _process.exitCode,
593 594 595 596 597 598 599 600 601 602
        _sendRequest(
          'app.detach',
          <String, dynamic>{'appId': _currentRunningAppId},
        ),
      ]).timeout(
        quitTimeout,
        onTimeout: () { _debugPrint('app.detach did not return within $quitTimeout'); },
      );
      _currentRunningAppId = null;
    }
603 604
    _debugPrint('Waiting for process to end...');
    return _process.exitCode.timeout(quitTimeout, onTimeout: _killGracefully);
605 606 607 608
  }

  Future<int> stop() async {
    if (_vmService != null) {
609
      _debugPrint('Closing VM service...');
610 611 612
      _vmService.dispose();
    }
    if (_currentRunningAppId != null) {
613
      _debugPrint('Stopping application...');
614
      await Future.any<void>(<Future<void>>[
615
        _process.exitCode,
616 617 618 619 620 621 622 623 624 625
        _sendRequest(
          'app.stop',
          <String, dynamic>{'appId': _currentRunningAppId},
        ),
      ]).timeout(
        quitTimeout,
        onTimeout: () { _debugPrint('app.stop did not return within $quitTimeout'); },
      );
      _currentRunningAppId = null;
    }
626 627 628
    if (_process != null) {
      _debugPrint('Waiting for process to end...');
      return _process.exitCode.timeout(quitTimeout, onTimeout: _killGracefully);
629 630 631 632
    }
    return 0;
  }

633 634 635
  int id = 1;
  Future<dynamic> _sendRequest(String method, dynamic params) async {
    final int requestId = id++;
636
    final Map<String, dynamic> request = <String, dynamic>{
637 638
      'id': requestId,
      'method': method,
639
      'params': params,
640
    };
641
    final String jsonEncoded = json.encode(<Map<String, dynamic>>[request]);
642
    _debugPrint(jsonEncoded, topic: '=stdin=>');
643

644
    // Set up the response future before we send the request to avoid any
645
    // races. If the method we're calling is app.stop then we tell _waitFor not
646 647 648 649 650
    // 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',
    );
651
    _process.stdin.writeln(jsonEncoded);
652
    final Map<String, dynamic> response = await responseFuture;
653

654
    if (response['error'] != null || response['result'] == null) {
655
      _throwErrorResponse('Unexpected error response');
656
    }
657

658
    return response['result'];
659 660
  }

661 662
  void _throwErrorResponse(String message) {
    throw '$message\n\n$_lastResponse\n\n${_errorBuffer.toString()}'.trim();
663
  }
664 665
}

666
class FlutterTestTestDriver extends FlutterTestDriver {
667 668
  FlutterTestTestDriver(Directory _projectFolder, {String logPrefix})
    : super(_projectFolder, logPrefix: logPrefix);
669 670 671 672 673 674 675 676 677

  Future<void> test({
    String testFile = 'test/test.dart',
    bool withDebugger = false,
    bool pauseOnExceptions = false,
    File pidFile,
    Future<void> Function() beforeStart,
  }) async {
    await _setupProcess(<String>[
678 679 680 681 682
      'test',
      '--disable-service-auth-codes',
      '--machine',
      '-d',
      'flutter-tester',
683
    ], script: testFile, withDebugger: withDebugger, pauseOnExceptions: pauseOnExceptions, pidFile: pidFile, beforeStart: beforeStart);
684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
  }

  @override
  Future<void> _setupProcess(
    List<String> args, {
    String script,
    bool withDebugger = false,
    bool pauseOnExceptions = false,
    File pidFile,
    Future<void> Function() beforeStart,
  }) async {
    await super._setupProcess(
      args,
      script: script,
      withDebugger: withDebugger,
      pidFile: pidFile,
    );

    // 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();
706
    _processPid = version['pid'] as int;
707 708 709

    if (withDebugger) {
      final Map<String, dynamic> startedProcess = await _waitFor(event: 'test.startedProcess', timeout: appStartTimeout);
710
      final String vmServiceHttpString = startedProcess['params']['observatoryUri'] as String;
711 712 713 714 715 716
      _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();
      }
717
      await resume(waitForNextPause: false);
718 719 720 721
    }
  }

  Future<Map<String, dynamic>> _waitForJson({
722
    Duration timeout = defaultTimeout,
723
  }) async {
724
    assert(timeout != null);
725
    return _timeoutWithMessages<Map<String, dynamic>>(
726 727
      () => _stdout.stream.map<Map<String, dynamic>>(_parseJsonResponse)
          .firstWhere((Map<String, dynamic> output) => output != null),
728
      timeout: timeout,
729
      task: 'Waiting for JSON',
730 731 732 733 734
    );
  }

  Map<String, dynamic> _parseJsonResponse(String line) {
    try {
735
      return castStringKeyedMap(json.decode(line));
736 737 738 739 740 741 742
    } catch (e) {
      // Not valid JSON, so likely some other output.
      return null;
    }
  }
}

743
Stream<String> transformToLines(Stream<List<int>> byteStream) {
744
  return byteStream.transform<String>(utf8.decoder).transform<String>(const LineSplitter());
745
}
746

747 748 749
Map<String, dynamic> parseFlutterResponse(String line) {
  if (line.startsWith('[') && line.endsWith(']')) {
    try {
750
      final Map<String, dynamic> response = castStringKeyedMap(json.decode(line)[0]);
751
      return response;
752 753 754 755 756 757 758 759
    } catch (e) {
      // Not valid JSON, so likely some other output that was surrounded by [brackets]
      return null;
    }
  }
  return null;
}

760 761 762 763 764 765
class SourcePosition {
  SourcePosition(this.line, this.column);

  final int line;
  final int column;
}