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

5 6
// @dart = 2.8

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

10 11
import 'package:file/memory.dart';
import 'package:flutter_tools/src/application_package.dart';
12
import 'package:flutter_tools/src/artifacts.dart';
13
import 'package:flutter_tools/src/base/common.dart';
14
import 'package:flutter_tools/src/base/dds.dart';
15
import 'package:flutter_tools/src/base/file_system.dart';
16
import 'package:flutter_tools/src/base/io.dart';
17
import 'package:flutter_tools/src/base/logger.dart';
18
import 'package:flutter_tools/src/base/os.dart';
19
import 'package:flutter_tools/src/base/platform.dart';
20
import 'package:flutter_tools/src/base/time.dart';
21
import 'package:flutter_tools/src/build_info.dart';
22
import 'package:flutter_tools/src/cache.dart';
23
import 'package:flutter_tools/src/device.dart';
24
import 'package:flutter_tools/src/device_port_forwarder.dart';
25
import 'package:flutter_tools/src/fuchsia/amber_ctl.dart';
26
import 'package:flutter_tools/src/fuchsia/application_package.dart';
27
import 'package:flutter_tools/src/fuchsia/fuchsia_dev_finder.dart';
28
import 'package:flutter_tools/src/fuchsia/fuchsia_device.dart';
29
import 'package:flutter_tools/src/fuchsia/fuchsia_ffx.dart';
30 31
import 'package:flutter_tools/src/fuchsia/fuchsia_kernel_compiler.dart';
import 'package:flutter_tools/src/fuchsia/fuchsia_pm.dart';
32
import 'package:flutter_tools/src/fuchsia/fuchsia_sdk.dart';
33
import 'package:flutter_tools/src/fuchsia/fuchsia_workflow.dart';
34
import 'package:flutter_tools/src/fuchsia/tiles_ctl.dart';
35
import 'package:flutter_tools/src/globals_null_migrated.dart' as globals;
36 37
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/vmservice.dart';
38 39 40
import 'package:meta/meta.dart';
import 'package:mockito/mockito.dart';
import 'package:vm_service/vm_service.dart' as vm_service;
41

42 43
import '../../src/common.dart';
import '../../src/context.dart';
44
import '../../src/fake_vm_services.dart';
45
import '../../src/fakes.dart';
46

47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
final vm_service.Isolate fakeIsolate = vm_service.Isolate(
  id: '1',
  pauseEvent: vm_service.Event(
    kind: vm_service.EventKind.kResume,
    timestamp: 0
  ),
  breakpoints: <vm_service.Breakpoint>[],
  exceptionPauseMode: null,
  libraries: <vm_service.LibraryRef>[],
  livePorts: 0,
  name: 'wrong name',
  number: '1',
  pauseOnExit: false,
  runnable: true,
  startTime: 0,
62
  isSystemIsolate: false,
63
  isolateFlags: <vm_service.IsolateFlag>[],
64 65
);

66 67
void main() {
  group('fuchsia device', () {
68
    MemoryFileSystem memoryFileSystem;
69
    File sshConfig;
Dan Field's avatar
Dan Field committed
70

71
    setUp(() {
72 73
      memoryFileSystem = MemoryFileSystem.test();
      sshConfig = memoryFileSystem.file('ssh_config')..writeAsStringSync('\n');
74 75
    });

76
    testWithoutContext('stores the requested id and name', () {
77 78 79
      const String deviceId = 'e80::0000:a00a:f00f:2002/3';
      const String name = 'halfbaked';
      final FuchsiaDevice device = FuchsiaDevice(deviceId, name: name);
80

81 82 83 84
      expect(device.id, deviceId);
      expect(device.name, name);
    });

85 86 87 88 89 90 91 92 93 94 95
    testWithoutContext('supports all runtime modes besides jitRelease', () {
      const String deviceId = 'e80::0000:a00a:f00f:2002/3';
      const String name = 'halfbaked';
      final FuchsiaDevice device = FuchsiaDevice(deviceId, name: name);

      expect(device.supportsRuntimeMode(BuildMode.debug), true);
      expect(device.supportsRuntimeMode(BuildMode.profile), true);
      expect(device.supportsRuntimeMode(BuildMode.release), true);
      expect(device.supportsRuntimeMode(BuildMode.jitRelease), false);
    });

96 97 98 99 100 101 102 103 104
    testWithoutContext('lists nothing when workflow cannot list devices', () async {
      final MockFuchsiaWorkflow fuchsiaWorkflow = MockFuchsiaWorkflow();
      final FuchsiaDevices fuchsiaDevices = FuchsiaDevices(
        platform: FakePlatform(operatingSystem: 'linux'),
        fuchsiaSdk: null,
        fuchsiaWorkflow: fuchsiaWorkflow,
        logger: BufferLogger.test(),
      );
      when(fuchsiaWorkflow.canListDevices).thenReturn(false);
105

106 107
      expect(fuchsiaDevices.canListAnything, false);
      expect(await fuchsiaDevices.pollingGetDevices(), isEmpty);
108
    });
109

110
    testWithoutContext('can parse ffx output for single device', () async {
111 112 113
      final MockFuchsiaWorkflow fuchsiaWorkflow = MockFuchsiaWorkflow();
      final MockFuchsiaSdk fuchsiaSdk = MockFuchsiaSdk();
      final FuchsiaDevices fuchsiaDevices = FuchsiaDevices(
114
        platform: FakePlatform(operatingSystem: 'linux', environment: <String, String>{},),
115 116 117 118
        fuchsiaSdk: fuchsiaSdk,
        fuchsiaWorkflow: fuchsiaWorkflow,
        logger: BufferLogger.test(),
      );
119
      when(fuchsiaWorkflow.shouldUseDeviceFinder).thenReturn(false);
120
      when(fuchsiaWorkflow.canListDevices).thenReturn(true);
121
      when(fuchsiaSdk.listDevices(useDeviceFinder: false)).thenAnswer((Invocation invocation) async {
122 123
        return '2001:0db8:85a3:0000:0000:8a2e:0370:7334 paper-pulp-bush-angel';
      });
124

125 126 127 128 129 130
      final Device device = (await fuchsiaDevices.pollingGetDevices()).single;

      expect(device.name, 'paper-pulp-bush-angel');
      expect(device.id, '192.168.42.10');
    });

131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152
    testWithoutContext('can parse device-finder output for single device', () async {
      final MockFuchsiaWorkflow fuchsiaWorkflow = MockFuchsiaWorkflow();
      final MockFuchsiaSdk fuchsiaSdk = MockFuchsiaSdk();
      final FuchsiaDevices fuchsiaDevices = FuchsiaDevices(
        platform: FakePlatform(operatingSystem: 'linux', environment: <String, String>{'FUCHSIA_DISABLED_ffx_discovery': '1'},),
        fuchsiaSdk: fuchsiaSdk,
        fuchsiaWorkflow: fuchsiaWorkflow,
        logger: BufferLogger.test(),
      );
      when(fuchsiaWorkflow.shouldUseDeviceFinder).thenReturn(true);
      when(fuchsiaWorkflow.canListDevices).thenReturn(true);
      when(fuchsiaSdk.listDevices(useDeviceFinder: true)).thenAnswer((Invocation invocation) async {
        return '2001:0db8:85a3:0000:0000:8a2e:0370:7334 paper-pulp-bush-angel';
      });

      final Device device = (await fuchsiaDevices.pollingGetDevices()).single;

      expect(device.name, 'paper-pulp-bush-angel');
      expect(device.id, '192.168.11.999');
    });

    testWithoutContext('can parse ffx output for multiple devices', () async {
153 154 155 156 157 158 159 160
      final MockFuchsiaWorkflow fuchsiaWorkflow = MockFuchsiaWorkflow();
      final MockFuchsiaSdk fuchsiaSdk = MockFuchsiaSdk();
      final FuchsiaDevices fuchsiaDevices = FuchsiaDevices(
        platform: FakePlatform(operatingSystem: 'linux'),
        fuchsiaSdk: fuchsiaSdk,
        fuchsiaWorkflow: fuchsiaWorkflow,
        logger: BufferLogger.test(),
      );
161
      when(fuchsiaWorkflow.shouldUseDeviceFinder).thenReturn(false);
162
      when(fuchsiaWorkflow.canListDevices).thenReturn(true);
163
      when(fuchsiaSdk.listDevices(useDeviceFinder: false)).thenAnswer((Invocation invocation) async {
164 165 166 167 168 169 170 171 172 173 174 175
        return '2001:0db8:85a3:0000:0000:8a2e:0370:7334 paper-pulp-bush-angel\n'
          '2001:0db8:85a3:0000:0000:8a2e:0370:7335 foo-bar-fiz-buzz';
      });

      final List<Device> devices = await fuchsiaDevices.pollingGetDevices();

      expect(devices.first.name, 'paper-pulp-bush-angel');
      expect(devices.first.id, '192.168.42.10');
      expect(devices.last.name, 'foo-bar-fiz-buzz');
      expect(devices.last.id, '192.168.42.10');
    });

176
    testWithoutContext('can parse device-finder output for multiple devices', () async {
177 178 179 180 181 182 183 184
      final MockFuchsiaWorkflow fuchsiaWorkflow = MockFuchsiaWorkflow();
      final MockFuchsiaSdk fuchsiaSdk = MockFuchsiaSdk();
      final FuchsiaDevices fuchsiaDevices = FuchsiaDevices(
        platform: FakePlatform(operatingSystem: 'linux'),
        fuchsiaSdk: fuchsiaSdk,
        fuchsiaWorkflow: fuchsiaWorkflow,
        logger: BufferLogger.test(),
      );
185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
      when(fuchsiaWorkflow.shouldUseDeviceFinder).thenReturn(true);
      when(fuchsiaWorkflow.canListDevices).thenReturn(true);
      when(fuchsiaSdk.listDevices(useDeviceFinder: true)).thenAnswer((Invocation invocation) async {
        return '2001:0db8:85a3:0000:0000:8a2e:0370:7334 paper-pulp-bush-angel\n'
          '2001:0db8:85a3:0000:0000:8a2e:0370:7335 foo-bar-fiz-buzz';
      });

      final List<Device> devices = await fuchsiaDevices.pollingGetDevices();

      expect(devices.first.name, 'paper-pulp-bush-angel');
      expect(devices.first.id, '192.168.11.999');
      expect(devices.last.name, 'foo-bar-fiz-buzz');
      expect(devices.last.id, '192.168.11.999');
    });

    testWithoutContext('can parse junk output from ffx', () async {
      final MockFuchsiaWorkflow fuchsiaWorkflow = MockFuchsiaWorkflow();
      final MockFuchsiaSdk fuchsiaSdk = MockFuchsiaSdk();
      final FuchsiaDevices fuchsiaDevices = FuchsiaDevices(
        platform: FakePlatform(operatingSystem: 'linux'),
        fuchsiaSdk: fuchsiaSdk,
        fuchsiaWorkflow: fuchsiaWorkflow,
        logger: BufferLogger.test(),
      );
      when(fuchsiaWorkflow.shouldUseDeviceFinder).thenReturn(false);
210 211 212 213 214 215 216 217
      when(fuchsiaWorkflow.canListDevices).thenReturn(true);
      when(fuchsiaSdk.listDevices()).thenAnswer((Invocation invocation) async {
        return 'junk';
      });

      final List<Device> devices = await fuchsiaDevices.pollingGetDevices();

      expect(devices, isEmpty);
218 219
    });

220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239
    testWithoutContext('can parse junk output from device-finder', () async {
      final MockFuchsiaWorkflow fuchsiaWorkflow = MockFuchsiaWorkflow();
      final MockFuchsiaSdk fuchsiaSdk = MockFuchsiaSdk();
      final FuchsiaDevices fuchsiaDevices = FuchsiaDevices(
        platform: FakePlatform(operatingSystem: 'linux'),
        fuchsiaSdk: fuchsiaSdk,
        fuchsiaWorkflow: fuchsiaWorkflow,
        logger: BufferLogger.test(),
      );
      when(fuchsiaWorkflow.shouldUseDeviceFinder).thenReturn(true);
      when(fuchsiaWorkflow.canListDevices).thenReturn(true);
      when(fuchsiaSdk.listDevices(useDeviceFinder: true)).thenAnswer((Invocation invocation) async {
        return 'junk';
      });

      final List<Device> devices = await fuchsiaDevices.pollingGetDevices();

      expect(devices, isEmpty);
    });

240 241 242 243 244 245 246 247
    testUsingContext('disposing device disposes the portForwarder', () async {
      final MockPortForwarder mockPortForwarder = MockPortForwarder();
      final FuchsiaDevice device = FuchsiaDevice('123');
      device.portForwarder = mockPortForwarder;
      await device.dispose();
      verify(mockPortForwarder.dispose()).called(1);
    });

248
    testWithoutContext('default capabilities', () async {
249
      final FuchsiaDevice device = FuchsiaDevice('123');
250 251 252
      final FlutterProject project = FlutterProject.fromDirectoryTest(memoryFileSystem.currentDirectory);
      memoryFileSystem.directory('fuchsia').createSync(recursive: true);
      memoryFileSystem.file('pubspec.yaml').createSync();
253 254 255

      expect(device.supportsHotReload, true);
      expect(device.supportsHotRestart, false);
256
      expect(device.supportsFlutterExit, false);
257
      expect(device.isSupportedForProject(project), true);
258
    });
259 260 261

    test('is ephemeral', () {
      final FuchsiaDevice device = FuchsiaDevice('123');
262

263 264
      expect(device.ephemeral, true);
    });
265

266
    testWithoutContext('supported for project', () async {
267
      final FuchsiaDevice device = FuchsiaDevice('123');
268 269 270
      final FlutterProject project = FlutterProject.fromDirectoryTest(memoryFileSystem.currentDirectory);
      memoryFileSystem.directory('fuchsia').createSync(recursive: true);
      memoryFileSystem.file('pubspec.yaml').createSync();
271

272
      expect(device.isSupportedForProject(project), true);
273 274
    });

275
    testWithoutContext('not supported for project', () async {
276
      final FuchsiaDevice device = FuchsiaDevice('123');
277 278
      final FlutterProject project = FlutterProject.fromDirectoryTest(memoryFileSystem.currentDirectory);
      memoryFileSystem.file('pubspec.yaml').createSync();
279

280
      expect(device.isSupportedForProject(project), false);
281
    });
282

283 284
    testUsingContext('targetPlatform does not throw when sshConfig is missing', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
285

286 287 288 289 290 291 292
      expect(await device.targetPlatform, TargetPlatform.fuchsia_arm64);
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: null),
      FuchsiaSdk: () => MockFuchsiaSdk(),
      ProcessManager: () => MockProcessManager(),
    });

293
    testUsingContext('targetPlatform arm64 works', () async {
Dan Field's avatar
Dan Field committed
294 295
      when(globals.processManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(1, 0, 'aarch64', '');
296 297 298 299 300
      });
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.targetPlatform, TargetPlatform.fuchsia_arm64);
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
301
      FuchsiaSdk: () => MockFuchsiaSdk(),
Dan Field's avatar
Dan Field committed
302
      ProcessManager: () => MockProcessManager(),
303 304 305
    });

    testUsingContext('targetPlatform x64 works', () async {
Dan Field's avatar
Dan Field committed
306 307
      when(globals.processManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(1, 0, 'x86_64', '');
308 309 310 311 312
      });
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.targetPlatform, TargetPlatform.fuchsia_x64);
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338
      FuchsiaSdk: () => MockFuchsiaSdk(),
      ProcessManager: () => MockProcessManager(),
    });

    testUsingContext('hostAddress parsing works', () async {
      when(globals.processManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(
          1,
          0,
          'fe80::8c6c:2fff:fe3d:c5e1%ethp0003 50666 fe80::5054:ff:fe63:5e7a%ethp0003 22',
          '',
        );
      });
      final FuchsiaDevice device = FuchsiaDevice('id');
      expect(await device.hostAddress, 'fe80::8c6c:2fff:fe3d:c5e1%25ethp0003');
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
      FuchsiaSdk: () => MockFuchsiaSdk(),
      ProcessManager: () => MockProcessManager(),
    });

    testUsingContext('hostAddress parsing throws tool error on failure', () async {
      when(globals.processManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(1, 1, '', '');
      });
      final FuchsiaDevice device = FuchsiaDevice('id');
339
      expect(() async => device.hostAddress, throwsToolExit());
340 341 342 343 344 345 346 347 348 349 350
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
      FuchsiaSdk: () => MockFuchsiaSdk(),
      ProcessManager: () => MockProcessManager(),
    });

    testUsingContext('hostAddress parsing throws tool error on empty response', () async {
      when(globals.processManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(1, 0, '', '');
      });
      final FuchsiaDevice device = FuchsiaDevice('id');
351
      expect(() async => device.hostAddress, throwsToolExit());
352 353
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
354
      FuchsiaSdk: () => MockFuchsiaSdk(),
Dan Field's avatar
Dan Field committed
355
      ProcessManager: () => MockProcessManager(),
356
    });
357 358 359
  });

  group('displays friendly error when', () {
360 361
    MockProcessManager mockProcessManager;
    MockProcessResult mockProcessResult;
362
    File artifactFile;
363 364 365 366 367 368
    MockProcessManager emptyStdoutProcessManager;
    MockProcessResult emptyStdoutProcessResult;

    setUp(() {
      mockProcessManager = MockProcessManager();
      mockProcessResult = MockProcessResult();
369
      artifactFile = MemoryFileSystem.test().file('artifact');
370 371 372 373 374 375 376
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((Invocation invocation) =>
          Future<ProcessResult>.value(mockProcessResult));
      when(mockProcessResult.exitCode).thenReturn(1);
377 378
      when<String>(mockProcessResult.stdout as String).thenReturn('');
      when<String>(mockProcessResult.stderr as String).thenReturn('');
379 380 381 382 383 384 385 386 387 388

      emptyStdoutProcessManager = MockProcessManager();
      emptyStdoutProcessResult = MockProcessResult();
      when(emptyStdoutProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((Invocation invocation) =>
          Future<ProcessResult>.value(emptyStdoutProcessResult));
      when(emptyStdoutProcessResult.exitCode).thenReturn(0);
389 390
      when<String>(emptyStdoutProcessResult.stdout as String).thenReturn('');
      when<String>(emptyStdoutProcessResult.stderr as String).thenReturn('');
391
    });
392 393

    testUsingContext('No vmservices found', () async {
394 395 396 397 398 399 400
      final FuchsiaDevice device = FuchsiaDevice('id');
      ToolExit toolExit;
      try {
        await device.servicePorts();
      } on ToolExit catch (err) {
        toolExit = err;
      }
401 402 403 404
      expect(
          toolExit.message,
          contains(
              'No Dart Observatories found. Are you running a debug build?'));
405
    }, overrides: <Type, Generator>{
406
      ProcessManager: () => emptyStdoutProcessManager,
407
      FuchsiaArtifacts: () => FuchsiaArtifacts(
408 409
            sshConfig: artifactFile,
            devFinder: artifactFile,
410
            ffx: artifactFile,
411
          ),
412
      FuchsiaSdk: () => MockFuchsiaSdk(),
413
    });
414 415 416

    group('device logs', () {
      const String exampleUtcLogs = '''
417
[2018-11-09 01:27:45][3][297950920][log] INFO: example_app.cmx(flutter): Error doing thing
418 419
[2018-11-09 01:27:58][46257][46269][foo] INFO: Using a thing
[2018-11-09 01:29:58][46257][46269][foo] INFO: Blah blah blah
420
[2018-11-09 01:29:58][46257][46269][foo] INFO: other_app.cmx(flutter): Do thing
421
[2018-11-09 01:30:02][41175][41187][bar] INFO: Invoking a bar
422
[2018-11-09 01:30:12][52580][52983][log] INFO: example_app.cmx(flutter): Did thing this time
423

424
  ''';
425 426
      MockProcessManager mockProcessManager;
      MockProcess mockProcess;
427 428 429
      Completer<int> exitCode;
      StreamController<List<int>> stdout;
      StreamController<List<int>> stderr;
430
      File devFinder;
431
      File ffx;
432
      File sshConfig;
433

434
      setUp(() {
435 436
        mockProcessManager = MockProcessManager();
        mockProcess = MockProcess();
437 438 439
        stdout = StreamController<List<int>>(sync: true);
        stderr = StreamController<List<int>>(sync: true);
        exitCode = Completer<int>();
440 441 442 443 444
        when(mockProcessManager.start(any))
            .thenAnswer((Invocation _) => Future<Process>.value(mockProcess));
        when(mockProcess.exitCode).thenAnswer((Invocation _) => exitCode.future);
        when(mockProcess.stdout).thenAnswer((Invocation _) => stdout.stream);
        when(mockProcess.stderr).thenAnswer((Invocation _) => stderr.stream);
445 446
        final FileSystem memoryFileSystem = MemoryFileSystem.test();
        devFinder = memoryFileSystem.file('device-finder')..writeAsStringSync('\n');
447
        ffx = memoryFileSystem.file('ffx')..writeAsStringSync('\n');
448
        sshConfig = memoryFileSystem.file('ssh_config')..writeAsStringSync('\n');
449 450 451 452 453 454 455 456
      });

      tearDown(() {
        exitCode.complete(0);
      });

      testUsingContext('can be parsed for an app', () async {
        final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
457
        final DeviceLogReader reader = device.getLogReader(
458
            app: FuchsiaModulePackage(name: 'example_app'));
459
        final List<String> logLines = <String>[];
460 461 462 463 464 465 466
        final Completer<void> lock = Completer<void>();
        reader.logLines.listen((String line) {
          logLines.add(line);
          if (logLines.length == 2) {
            lock.complete();
          }
        });
467 468 469 470
        expect(logLines, isEmpty);

        stdout.add(utf8.encode(exampleUtcLogs));
        await stdout.close();
471
        await lock.future.timeout(const Duration(seconds: 1));
472 473 474 475 476 477 478 479

        expect(logLines, <String>[
          '[2018-11-09 01:27:45.000] Flutter: Error doing thing',
          '[2018-11-09 01:30:12.000] Flutter: Did thing this time',
        ]);
      }, overrides: <Type, Generator>{
        ProcessManager: () => mockProcessManager,
        SystemClock: () => SystemClock.fixed(DateTime(2018, 11, 9, 1, 25, 45)),
480
        FuchsiaArtifacts: () =>
481
            FuchsiaArtifacts(devFinder: devFinder, sshConfig: sshConfig, ffx: ffx),
482 483 484 485
      });

      testUsingContext('cuts off prior logs', () async {
        final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
486
        final DeviceLogReader reader = device.getLogReader(
487
            app: FuchsiaModulePackage(name: 'example_app'));
488 489 490 491 492 493 494 495 496 497
        final List<String> logLines = <String>[];
        final Completer<void> lock = Completer<void>();
        reader.logLines.listen((String line) {
          logLines.add(line);
          lock.complete();
        });
        expect(logLines, isEmpty);

        stdout.add(utf8.encode(exampleUtcLogs));
        await stdout.close();
498
        await lock.future.timeout(const Duration(seconds: 1));
499 500 501 502 503 504 505

        expect(logLines, <String>[
          '[2018-11-09 01:30:12.000] Flutter: Did thing this time',
        ]);
      }, overrides: <Type, Generator>{
        ProcessManager: () => mockProcessManager,
        SystemClock: () => SystemClock.fixed(DateTime(2018, 11, 9, 1, 29, 45)),
506
        FuchsiaArtifacts: () =>
507
            FuchsiaArtifacts(devFinder: devFinder, sshConfig: sshConfig, ffx: ffx),
508 509 510 511 512 513
      });

      testUsingContext('can be parsed for all apps', () async {
        final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
        final DeviceLogReader reader = device.getLogReader();
        final List<String> logLines = <String>[];
514 515 516 517 518 519 520
        final Completer<void> lock = Completer<void>();
        reader.logLines.listen((String line) {
          logLines.add(line);
          if (logLines.length == 3) {
            lock.complete();
          }
        });
521 522 523 524
        expect(logLines, isEmpty);

        stdout.add(utf8.encode(exampleUtcLogs));
        await stdout.close();
525
        await lock.future.timeout(const Duration(seconds: 1));
526 527 528 529 530 531 532 533 534

        expect(logLines, <String>[
          '[2018-11-09 01:27:45.000] Flutter: Error doing thing',
          '[2018-11-09 01:29:58.000] Flutter: Do thing',
          '[2018-11-09 01:30:12.000] Flutter: Did thing this time',
        ]);
      }, overrides: <Type, Generator>{
        ProcessManager: () => mockProcessManager,
        SystemClock: () => SystemClock.fixed(DateTime(2018, 11, 9, 1, 25, 45)),
535
        FuchsiaArtifacts: () =>
536
            FuchsiaArtifacts(devFinder: devFinder, sshConfig: sshConfig, ffx: ffx),
537 538
      });
    });
539
  });
540

Dan Field's avatar
Dan Field committed
541
  group('screenshot', () {
542
    testUsingContext('is supported on posix platforms', () {
543 544
      final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
      expect(device.supportsScreenshot, true);
545 546 547 548 549
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(
        operatingSystem: 'linux',
      ),
    });
550 551 552

    testUsingContext('is not supported on Windows', () {
      final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
553

554 555 556 557 558 559 560
      expect(device.supportsScreenshot, false);
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(
        operatingSystem: 'windows',
      ),
    });

561
    test("takeScreenshot throws if file isn't .ppm", () async {
562 563 564 565 566
      final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
      await expectLater(
        () => device.takeScreenshot(globals.fs.file('file.invalid')),
        throwsA(equals('file.invalid must be a .ppm file')),
      );
567
    });
568 569 570 571

    testUsingContext('takeScreenshot throws if screencap failed', () async {
      final FuchsiaDevice device = FuchsiaDevice('0.0.0.0', name: 'tester');

572
      when(globals.processManager.run(
573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588
        const <String>[
          'ssh',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0',
          'screencap > /tmp/screenshot.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 1, '', '<error-message>'));

      await expectLater(
        () => device.takeScreenshot(globals.fs.file('file.ppm')),
        throwsA(equals('Could not take a screenshot on device tester:\n<error-message>')),
      );
    }, overrides: <Type, Generator>{
589 590
      ProcessManager: () => MockProcessManager(),
      FileSystem: () => MemoryFileSystem.test(),
591 592 593 594 595 596
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
597
    });
598 599 600 601

    testUsingContext('takeScreenshot throws if scp failed', () async {
      final FuchsiaDevice device = FuchsiaDevice('0.0.0.0', name: 'tester');

602
      when(globals.processManager.run(
603 604 605 606 607 608 609 610 611 612 613
        const <String>[
          'ssh',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0',
          'screencap > /tmp/screenshot.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 0, '', ''));

614
      when(globals.processManager.run(
615 616 617 618 619 620 621 622 623 624 625
        const <String>[
          'scp',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0:/tmp/screenshot.ppm',
          'file.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 1, '', '<error-message>'));

626
       when(globals.processManager.run(
627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642
        const <String>[
          'ssh',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0',
          'rm /tmp/screenshot.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 0, '', ''));

      await expectLater(
        () => device.takeScreenshot(globals.fs.file('file.ppm')),
        throwsA(equals('Failed to copy screenshot from device:\n<error-message>')),
      );
    }, overrides: <Type, Generator>{
643 644
      ProcessManager: () => MockProcessManager(),
      FileSystem: () => MemoryFileSystem.test(),
645 646 647 648 649 650
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
651
    });
652

653
    testUsingContext("takeScreenshot prints error if can't delete file from device", () async {
654 655
      final FuchsiaDevice device = FuchsiaDevice('0.0.0.0', name: 'tester');

656
      when(globals.processManager.run(
657 658 659 660 661 662 663 664 665 666 667
        const <String>[
          'ssh',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0',
          'screencap > /tmp/screenshot.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 0, '', ''));

668
      when(globals.processManager.run(
669 670 671 672 673 674 675 676 677 678 679
        const <String>[
          'scp',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0:/tmp/screenshot.ppm',
          'file.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 0, '', ''));

680
       when(globals.processManager.run(
681 682 683 684 685 686 687 688 689 690 691 692 693
        const <String>[
          'ssh',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0',
          'rm /tmp/screenshot.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 1, '', '<error-message>'));

      try {
        await device.takeScreenshot(globals.fs.file('file.ppm'));
694
      } on Exception {
695 696 697 698 699 700 701
        assert(false);
      }
      expect(
        testLogger.errorText,
        contains('Failed to delete screenshot.ppm from the device:\n<error-message>'),
      );
    }, overrides: <Type, Generator>{
702 703
      ProcessManager: () => MockProcessManager(),
      FileSystem: () => MemoryFileSystem.test(),
704 705 706 707 708 709 710 711 712 713 714
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
    }, testOn: 'posix');

    testUsingContext('takeScreenshot returns', () async {
      final FuchsiaDevice device = FuchsiaDevice('0.0.0.0', name: 'tester');

715
      when(globals.processManager.run(
716 717 718 719 720 721 722 723 724 725 726
        const <String>[
          'ssh',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0',
          'screencap > /tmp/screenshot.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 0, '', ''));

727
      when(globals.processManager.run(
728 729 730 731 732 733 734 735 736 737 738
        const <String>[
          'scp',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0:/tmp/screenshot.ppm',
          'file.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 0, '', ''));

739
       when(globals.processManager.run(
740 741 742 743 744 745 746 747 748 749 750
        const <String>[
          'ssh',
          '-F',
          '/fuchsia/out/default/.ssh',
          '0.0.0.0',
          'rm /tmp/screenshot.ppm',
        ],
        workingDirectory: anyNamed('workingDirectory'),
        environment: anyNamed('environment'),
      )).thenAnswer((_) async => ProcessResult(0, 0, '', ''));

751
      expect(() async => device.takeScreenshot(globals.fs.file('file.ppm')),
752
        returnsNormally);
753
    }, overrides: <Type, Generator>{
754 755
      ProcessManager: () => MockProcessManager(),
      FileSystem: () => MemoryFileSystem.test(),
756 757 758 759 760 761
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
762
    });
763 764
  });

765 766
  group('portForwarder', () {
    MockProcessManager mockProcessManager;
767
    File sshConfig;
768 769 770

    setUp(() {
      mockProcessManager = MockProcessManager();
771
      sshConfig = MemoryFileSystem.test().file('irrelevant')..writeAsStringSync('\n');
772 773 774 775 776 777 778 779 780 781 782 783
    });

    testUsingContext('`unforward` prints stdout and stderr if ssh command failed', () async {
      final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');

      final MockProcessResult mockFailureProcessResult = MockProcessResult();
      when(mockFailureProcessResult.exitCode).thenReturn(1);
      when<String>(mockFailureProcessResult.stdout as String).thenReturn('<stdout>');
      when<String>(mockFailureProcessResult.stderr as String).thenReturn('<stderr>');
      when(mockProcessManager.run(<String>[
        'ssh',
        '-F',
784
        sshConfig.absolute.path,
785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803
        '-O',
        'cancel',
        '-vvv',
        '-L',
        '0:127.0.0.1:1',
        'id',
      ])).thenAnswer((Invocation invocation) {
        return Future<ProcessResult>.value(mockFailureProcessResult);
      });
      await expectLater(
        () => device.portForwarder.unforward(ForwardedPort(/*hostPort=*/ 0, /*devicePort=*/ 1)),
        throwsToolExit(message: 'Unforward command failed:\nstdout: <stdout>\nstderr: <stderr>'),
      );
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
    });
  });

Dan Field's avatar
Dan Field committed
804

805
  group('FuchsiaIsolateDiscoveryProtocol', () {
806 807 808 809 810 811
    MockPortForwarder portForwarder;

    setUp(() {
      portForwarder = MockPortForwarder();
    });

812
    Future<Uri> findUri(List<FlutterView> views, String expectedIsolateName) async {
813 814 815 816 817 818 819 820 821 822 823 824
      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
        requests: <VmServiceExpectation>[
          FakeVmServiceRequest(
            method: kListViewsMethod,
            jsonResponse: <String, Object>{
              'views': <Object>[
                for (FlutterView view in views)
                  view.toJson()
              ],
            },
          ),
        ],
825
        httpAddress: Uri.parse('example'),
826
      );
827
      final MockFuchsiaDevice fuchsiaDevice =
828
        MockFuchsiaDevice('123', portForwarder, false);
829
      final FuchsiaIsolateDiscoveryProtocol discoveryProtocol =
830
        FuchsiaIsolateDiscoveryProtocol(
831 832
        fuchsiaDevice,
        expectedIsolateName,
833
        (Uri uri) async => fakeVmServiceHost.vmService,
834
        (Device device, Uri uri, bool enableServiceAuthCodes) => null,
835
        true, // only poll once.
836
      );
837 838
      final MockDartDevelopmentService mockDds = MockDartDevelopmentService();
      when(fuchsiaDevice.dds).thenReturn(mockDds);
839
      when(mockDds.startDartDevelopmentService(any, any, any, any, logger: anyNamed('logger'))).thenReturn(null);
840
      when(mockDds.uri).thenReturn(Uri.parse('example'));
841 842 843 844
      when(fuchsiaDevice.servicePorts())
          .thenAnswer((Invocation invocation) async => <int>[1]);
      when(portForwarder.forward(1))
          .thenAnswer((Invocation invocation) async => 2);
845
      return await discoveryProtocol.uri;
846
    }
847

848
    testUsingContext('can find flutter view with matching isolate name', () async {
849
      const String expectedIsolateName = 'foobar';
850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868
      final Uri uri = await findUri(<FlutterView>[
        // no ui isolate.
        FlutterView(id: '1', uiIsolate: null),
        // wrong name.
        FlutterView(
          id: '2',
          uiIsolate: vm_service.Isolate.parse(<String, dynamic>{
            ...fakeIsolate.toJson(),
            'name': 'Wrong name',
          }),
        ),
        // matching name.
        FlutterView(
          id: '3',
          uiIsolate: vm_service.Isolate.parse(<String, dynamic>{
             ...fakeIsolate.toJson(),
            'name': expectedIsolateName,
          }),
        ),
869
      ], expectedIsolateName);
870

871 872
      expect(
          uri.toString(), 'http://${InternetAddress.loopbackIPv4.address}:0/');
873 874
    });

875
    testUsingContext('can handle flutter view without matching isolate name', () async {
876
      const String expectedIsolateName = 'foobar';
877 878 879 880 881 882 883 884
      final Future<Uri> uri = findUri(<FlutterView>[
        // no ui isolate.
        FlutterView(id: '1', uiIsolate: null),
        // wrong name.
        FlutterView(id: '2', uiIsolate: vm_service.Isolate.parse(<String, Object>{
           ...fakeIsolate.toJson(),
          'name': 'wrong name',
        })),
885
      ], expectedIsolateName);
886

887 888 889 890 891
      expect(uri, throwsException);
    });

    testUsingContext('can handle non flutter view', () async {
      const String expectedIsolateName = 'foobar';
892 893
      final Future<Uri> uri = findUri(<FlutterView>[
        FlutterView(id: '1', uiIsolate: null), // no ui isolate.
894
      ], expectedIsolateName);
895

896 897 898
      expect(uri, throwsException);
    });
  });
899

900
  testUsingContext('Correct flutter runner', () async {
901 902 903
    final Cache cache = Cache.test(
      processManager: FakeProcessManager.any(),
    );
904 905 906 907 908
    final FileSystem fileSystem = MemoryFileSystem.test();
    final CachedArtifacts artifacts = CachedArtifacts(
      cache: cache,
      fileSystem: fileSystem,
      platform: FakePlatform(operatingSystem: 'linux'),
909
      operatingSystemUtils: globals.os,
910 911
    );
    expect(artifacts.getArtifactPath(
912 913 914 915 916 917
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.debug,
      ),
      contains('flutter_jit_runner'),
    );
918
    expect(artifacts.getArtifactPath(
919 920 921 922 923 924
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.profile,
      ),
      contains('flutter_aot_runner'),
    );
925
    expect(artifacts.getArtifactPath(
926 927 928 929 930 931
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.release,
      ),
      contains('flutter_aot_product_runner'),
    );
932
    expect(artifacts.getArtifactPath(
933 934 935 936 937 938 939 940 941
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.jitRelease,
      ),
      contains('flutter_jit_product_runner'),
    );
  });

  group('Fuchsia app start and stop: ', () {
942
    MemoryFileSystem memoryFileSystem;
943
    FakeOperatingSystemUtils osUtils;
944
    FakeFuchsiaDeviceTools fuchsiaDeviceTools;
945
    MockFuchsiaSdk fuchsiaSdk;
946
    Artifacts artifacts;
947 948 949
    FakeProcessManager fakeSuccessfulProcessManager;
    FakeProcessManager fakeFailedProcessManager;
    File sshConfig;
950

951
    setUp(() {
952
      memoryFileSystem = MemoryFileSystem.test();
953
      osUtils = FakeOperatingSystemUtils();
954
      fuchsiaDeviceTools = FakeFuchsiaDeviceTools();
955
      fuchsiaSdk = MockFuchsiaSdk();
956
      sshConfig = MemoryFileSystem.test().file('ssh_config')..writeAsStringSync('\n');
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
      artifacts = Artifacts.test();
      for (final BuildMode mode in <BuildMode>[BuildMode.debug, BuildMode.release]) {
        memoryFileSystem.file(
          artifacts.getArtifactPath(Artifact.fuchsiaKernelCompiler,
              platform: TargetPlatform.fuchsia_arm64, mode: mode),
        ).createSync();

        memoryFileSystem.file(
          artifacts.getArtifactPath(Artifact.platformKernelDill,
              platform: TargetPlatform.fuchsia_arm64, mode: mode),
        ).createSync();

        memoryFileSystem.file(
          artifacts.getArtifactPath(Artifact.flutterPatchedSdkPath,
              platform: TargetPlatform.fuchsia_arm64, mode: mode),
        ).createSync();

        memoryFileSystem.file(
          artifacts.getArtifactPath(Artifact.fuchsiaFlutterRunner,
              platform: TargetPlatform.fuchsia_arm64, mode: mode),
        ).createSync();
      }
979 980 981 982 983 984 985 986 987 988 989 990 991 992
      fakeSuccessfulProcessManager = FakeProcessManager.list(<FakeCommand>[
        FakeCommand(
          command: <String>['ssh', '-F', sshConfig.absolute.path, '123', r'echo $SSH_CONNECTION'],
          stdout: 'fe80::8c6c:2fff:fe3d:c5e1%ethp0003 50666 fe80::5054:ff:fe63:5e7a%ethp0003 22',
        ),
      ]);
      fakeFailedProcessManager = FakeProcessManager.list(<FakeCommand>[
        FakeCommand(
          command: <String>['ssh', '-F', sshConfig.absolute.path, '123', r'echo $SSH_CONNECTION'],
          stdout: '',
          stderr: '',
          exitCode: 1,
        ),
      ]);
993 994
    });

995 996 997 998
    Future<LaunchResult> setupAndStartApp({
      @required bool prebuilt,
      @required BuildMode mode,
    }) async {
999
      const String appName = 'app_name';
1000
      final FuchsiaDevice device = FuchsiaDeviceWithFakeDiscovery('123');
1001 1002
      globals.fs.directory('fuchsia').createSync(recursive: true);
      final File pubspecFile = globals.fs.file('pubspec.yaml')..createSync();
1003 1004
      pubspecFile.writeAsStringSync('name: $appName');

1005 1006
      FuchsiaApp app;
      if (prebuilt) {
1007
        final File far = globals.fs.file('app_name-0.far')..createSync();
1008 1009
        app = FuchsiaApp.fromPrebuiltApp(far);
      } else {
1010
        globals.fs.file(globals.fs.path.join('fuchsia', 'meta', '$appName.cmx'))
1011 1012
          ..createSync(recursive: true)
          ..writeAsStringSync('{}');
1013 1014
        globals.fs.file('.packages').createSync();
        globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
1015
        app = BuildableFuchsiaApp(project: FlutterProject.fromDirectoryTest(globals.fs.currentDirectory).fuchsia);
1016 1017
      }

1018
      final DebuggingOptions debuggingOptions = DebuggingOptions.disabled(BuildInfo(mode, null, treeShakeIcons: false));
1019
      return device.startApp(
1020 1021 1022 1023
        app,
        prebuiltApplication: prebuilt,
        debuggingOptions: debuggingOptions,
      );
1024
    }
1025

1026 1027 1028
    testUsingContext('start prebuilt in release mode', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.release);
1029 1030 1031
      expect(launchResult.started, isTrue);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
1032
      Artifacts: () => artifacts,
1033
      FileSystem: () => memoryFileSystem,
1034
      ProcessManager: () => fakeSuccessfulProcessManager,
1035
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1036
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1037 1038 1039 1040
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

1041
    testUsingContext('start and stop prebuilt in release mode', () async {
1042
      const String appName = 'app_name';
1043
      final FuchsiaDevice device = FuchsiaDeviceWithFakeDiscovery('123');
1044 1045
      globals.fs.directory('fuchsia').createSync(recursive: true);
      final File pubspecFile = globals.fs.file('pubspec.yaml')..createSync();
1046
      pubspecFile.writeAsStringSync('name: $appName');
1047
      final File far = globals.fs.file('app_name-0.far')..createSync();
1048 1049 1050

      final FuchsiaApp app = FuchsiaApp.fromPrebuiltApp(far);
      final DebuggingOptions debuggingOptions =
1051
          DebuggingOptions.disabled(const BuildInfo(BuildMode.release, null, treeShakeIcons: false));
1052 1053 1054 1055 1056 1057 1058
      final LaunchResult launchResult = await device.startApp(app,
          prebuiltApplication: true,
          debuggingOptions: debuggingOptions);
      expect(launchResult.started, isTrue);
      expect(launchResult.hasObservatory, isFalse);
      expect(await device.stopApp(app), isTrue);
    }, overrides: <Type, Generator>{
1059
      Artifacts: () => artifacts,
1060
      FileSystem: () => memoryFileSystem,
1061
      ProcessManager: () => fakeSuccessfulProcessManager,
1062
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1063
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1064 1065 1066
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });
1067 1068 1069 1070 1071 1072 1073

    testUsingContext('start prebuilt in debug mode', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.debug);
      expect(launchResult.started, isTrue);
      expect(launchResult.hasObservatory, isTrue);
    }, overrides: <Type, Generator>{
1074
      Artifacts: () => artifacts,
1075
      FileSystem: () => memoryFileSystem,
1076
      ProcessManager: () => fakeSuccessfulProcessManager,
1077
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1078
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

    testUsingContext('start buildable in release mode', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: false, mode: BuildMode.release);
      expect(launchResult.started, isTrue);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
1089
      Artifacts: () => artifacts,
1090
      FileSystem: () => memoryFileSystem,
1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105
      ProcessManager: () => FakeProcessManager.list(<FakeCommand>[
            const FakeCommand(
              command: <String>[
                'Artifact.genSnapshot.TargetPlatform.fuchsia_arm64.release',
                '--deterministic',
                '--snapshot_kind=app-aot-elf',
                '--elf=build/fuchsia/elf.aotsnapshot',
                'build/fuchsia/app_name.dil'
              ],
            ),
            FakeCommand(
              command: <String>['ssh', '-F', sshConfig.absolute.path, '123', r'echo $SSH_CONNECTION'],
              stdout: 'fe80::8c6c:2fff:fe3d:c5e1%ethp0003 50666 fe80::5054:ff:fe63:5e7a%ethp0003 22',
            ),
          ]),
1106
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1107
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1108 1109 1110 1111 1112 1113 1114 1115 1116 1117
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

    testUsingContext('start buildable in debug mode', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: false, mode: BuildMode.debug);
      expect(launchResult.started, isTrue);
      expect(launchResult.hasObservatory, isTrue);
    }, overrides: <Type, Generator>{
1118
      Artifacts: () => artifacts,
1119
      FileSystem: () => memoryFileSystem,
1120
      ProcessManager: () => fakeSuccessfulProcessManager,
1121
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1122
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1123 1124 1125 1126
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

1127 1128
    testUsingContext('fail when cant get ssh config', () async {
      expect(() async =>
1129
          setupAndStartApp(prebuilt: true, mode: BuildMode.release),
1130 1131
          throwsToolExit(message: 'Cannot interact with device. No ssh config.\n'
                                  'Try setting FUCHSIA_SSH_CONFIG or FUCHSIA_BUILD_DIR.'));
1132
    }, overrides: <Type, Generator>{
1133
      Artifacts: () => artifacts,
1134
      FileSystem: () => memoryFileSystem,
1135
      ProcessManager: () => FakeProcessManager.any(),
1136
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1137 1138 1139 1140 1141 1142
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: null),
      OperatingSystemUtils: () => osUtils,
    });

    testUsingContext('fail when cant get host address', () async {
      expect(() async =>
1143
        setupAndStartApp(prebuilt: true, mode: BuildMode.release),
1144 1145 1146 1147 1148 1149 1150
          throwsToolExit(message: 'Failed to get local address, aborting.'));
    }, overrides: <Type, Generator>{
      Artifacts: () => artifacts,
      FileSystem: () => memoryFileSystem,
      ProcessManager: () => fakeFailedProcessManager,
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1151 1152 1153 1154 1155 1156 1157 1158 1159
      OperatingSystemUtils: () => osUtils,
    });

    testUsingContext('fail with correct LaunchResult when pm fails', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.release);
      expect(launchResult.started, isFalse);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
1160
      Artifacts: () => artifacts,
1161
      FileSystem: () => memoryFileSystem,
1162
      ProcessManager: () => fakeSuccessfulProcessManager,
1163
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1164
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1165 1166 1167 1168 1169 1170 1171 1172 1173 1174
      FuchsiaSdk: () => MockFuchsiaSdk(pm: FailingPM()),
      OperatingSystemUtils: () => osUtils,
    });

    testUsingContext('fail with correct LaunchResult when amber fails', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.release);
      expect(launchResult.started, isFalse);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
1175
      Artifacts: () => artifacts,
1176
      FileSystem: () => memoryFileSystem,
1177
      ProcessManager: () => fakeSuccessfulProcessManager,
1178
      FuchsiaDeviceTools: () => FakeFuchsiaDeviceTools(amber: FailingAmberCtl()),
1179
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1180 1181 1182 1183 1184 1185 1186 1187 1188 1189
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

    testUsingContext('fail with correct LaunchResult when tiles fails', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.release);
      expect(launchResult.started, isFalse);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
1190
      Artifacts: () => artifacts,
1191
      FileSystem: () => memoryFileSystem,
1192
      ProcessManager: () => fakeSuccessfulProcessManager,
1193
      FuchsiaDeviceTools: () => FakeFuchsiaDeviceTools(tiles: FailingTilesCtl()),
1194
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1195 1196 1197 1198
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

1199
  });
1200 1201

  group('sdkNameAndVersion: ', () {
1202
    File sshConfig;
1203 1204 1205 1206 1207 1208 1209 1210
    MockProcessManager mockSuccessProcessManager;
    MockProcessResult mockSuccessProcessResult;
    MockProcessManager mockFailureProcessManager;
    MockProcessResult mockFailureProcessResult;
    MockProcessManager emptyStdoutProcessManager;
    MockProcessResult emptyStdoutProcessResult;

    setUp(() {
1211
      sshConfig = MemoryFileSystem.test().file('ssh_config')..writeAsStringSync('\n');
1212 1213 1214 1215 1216 1217

      mockSuccessProcessManager = MockProcessManager();
      mockSuccessProcessResult = MockProcessResult();
      when(mockSuccessProcessManager.run(any)).thenAnswer(
          (Invocation invocation) => Future<ProcessResult>.value(mockSuccessProcessResult));
      when(mockSuccessProcessResult.exitCode).thenReturn(0);
1218 1219
      when<String>(mockSuccessProcessResult.stdout as String).thenReturn('version');
      when<String>(mockSuccessProcessResult.stderr as String).thenReturn('');
1220 1221 1222 1223 1224 1225

      mockFailureProcessManager = MockProcessManager();
      mockFailureProcessResult = MockProcessResult();
      when(mockFailureProcessManager.run(any)).thenAnswer(
          (Invocation invocation) => Future<ProcessResult>.value(mockFailureProcessResult));
      when(mockFailureProcessResult.exitCode).thenReturn(1);
1226 1227
      when<String>(mockFailureProcessResult.stdout as String).thenReturn('');
      when<String>(mockFailureProcessResult.stderr as String).thenReturn('');
1228 1229 1230 1231 1232 1233

      emptyStdoutProcessManager = MockProcessManager();
      emptyStdoutProcessResult = MockProcessResult();
      when(emptyStdoutProcessManager.run(any)).thenAnswer((Invocation invocation) =>
          Future<ProcessResult>.value(emptyStdoutProcessResult));
      when(emptyStdoutProcessResult.exitCode).thenReturn(0);
1234 1235
      when<String>(emptyStdoutProcessResult.stdout as String).thenReturn('');
      when<String>(emptyStdoutProcessResult.stderr as String).thenReturn('');
1236 1237
    });

1238
    testUsingContext('does not throw on non-existent ssh config', () async {
1239 1240 1241 1242 1243 1244 1245 1246
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.sdkNameAndVersion, equals('Fuchsia'));
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockSuccessProcessManager,
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: null),
      FuchsiaSdk: () => MockFuchsiaSdk(),
    });

1247 1248 1249 1250 1251 1252
    testUsingContext('returns what we get from the device on success', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.sdkNameAndVersion, equals('Fuchsia version'));
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockSuccessProcessManager,
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1253
      FuchsiaSdk: () => MockFuchsiaSdk(),
1254 1255 1256 1257 1258 1259 1260 1261
    });

    testUsingContext('returns "Fuchsia" when device command fails', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.sdkNameAndVersion, equals('Fuchsia'));
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockFailureProcessManager,
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1262
      FuchsiaSdk: () => MockFuchsiaSdk(),
1263 1264 1265 1266 1267 1268 1269 1270
    });

    testUsingContext('returns "Fuchsia" when device gives an empty result', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.sdkNameAndVersion, equals('Fuchsia'));
    }, overrides: <Type, Generator>{
      ProcessManager: () => emptyStdoutProcessManager,
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
1271
      FuchsiaSdk: () => MockFuchsiaSdk(),
1272 1273
    });
  });
1274 1275 1276 1277 1278 1279 1280
}

class FuchsiaModulePackage extends ApplicationPackage {
  FuchsiaModulePackage({@required this.name}) : super(id: name);

  @override
  final String name;
1281
}
1282 1283 1284

class MockProcessManager extends Mock implements ProcessManager {}

1285 1286
class MockProcessResult extends Mock implements ProcessResult {}

1287
class MockProcess extends Mock implements Process {}
1288

1289
Process _createMockProcess({
1290 1291 1292 1293 1294
  int exitCode = 0,
  String stdout = '',
  String stderr = '',
  bool persistent = false,
}) {
1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318
  final Stream<List<int>> stdoutStream = Stream<List<int>>.fromIterable(<List<int>>[
    utf8.encode(stdout),
  ]);
  final Stream<List<int>> stderrStream = Stream<List<int>>.fromIterable(<List<int>>[
    utf8.encode(stderr),
  ]);
  final Process process = MockProcess();

  when(process.stdout).thenAnswer((_) => stdoutStream);
  when(process.stderr).thenAnswer((_) => stderrStream);

  if (persistent) {
    final Completer<int> exitCodeCompleter = Completer<int>();
    when(process.kill()).thenAnswer((_) {
      exitCodeCompleter.complete(-11);
      return true;
    });
    when(process.exitCode).thenAnswer((_) => exitCodeCompleter.future);
  } else {
    when(process.exitCode).thenAnswer((_) => Future<int>.value(exitCode));
  }
  return process;
}

1319
class MockFuchsiaDevice extends Mock implements FuchsiaDevice {
1320 1321 1322
  MockFuchsiaDevice(this.id, this.portForwarder, this._ipv6);

  final bool _ipv6;
1323 1324

  @override
1325
  bool get ipv6 => _ipv6;
1326

1327 1328
  @override
  final String id;
1329

1330 1331 1332 1333
  @override
  final DevicePortForwarder portForwarder;

  @override
1334
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.fuchsia_arm64;
1335 1336
}

1337
class MockPortForwarder extends Mock implements DevicePortForwarder {}
1338

1339 1340 1341 1342
class FuchsiaDeviceWithFakeDiscovery extends FuchsiaDevice {
  FuchsiaDeviceWithFakeDiscovery(String id, {String name}) : super(id, name: name);

  @override
1343 1344 1345
  FuchsiaIsolateDiscoveryProtocol getIsolateDiscoveryProtocol(String isolateName) {
    return FakeFuchsiaIsolateDiscoveryProtocol();
  }
1346 1347 1348

  @override
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.fuchsia_arm64;
1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359
}

class FakeFuchsiaIsolateDiscoveryProtocol implements FuchsiaIsolateDiscoveryProtocol {
  @override
  FutureOr<Uri> get uri => Uri.parse('http://[::1]:37');

  @override
  void dispose() {}
}

class FakeFuchsiaAmberCtl implements FuchsiaAmberCtl {
1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373
  @override
  Future<bool> addSrc(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return true;
  }

  @override
  Future<bool> rmSrc(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return true;
  }

  @override
  Future<bool> getUp(FuchsiaDevice device, String packageName) async {
    return true;
  }
1374 1375 1376 1377 1378 1379 1380

  @override
  Future<bool> addRepoCfg(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return true;
  }

  @override
1381
  Future<bool> pkgCtlResolve(FuchsiaDevice device, FuchsiaPackageServer server, String packageName) async {
1382 1383 1384 1385 1386 1387 1388
    return true;
  }

  @override
  Future<bool> pkgCtlRepoRemove(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return true;
  }
1389 1390
}

1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405
class FailingAmberCtl implements FuchsiaAmberCtl {
  @override
  Future<bool> addSrc(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return false;
  }

  @override
  Future<bool> rmSrc(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return false;
  }

  @override
  Future<bool> getUp(FuchsiaDevice device, String packageName) async {
    return false;
  }
1406 1407 1408 1409 1410 1411 1412

  @override
  Future<bool> addRepoCfg(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return false;
  }

  @override
1413
  Future<bool> pkgCtlResolve(FuchsiaDevice device, FuchsiaPackageServer server, String packageName) async {
1414 1415 1416 1417 1418 1419 1420
    return false;
  }

  @override
  Future<bool> pkgCtlRepoRemove(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return false;
  }
1421 1422 1423
}

class FakeFuchsiaTilesCtl implements FuchsiaTilesCtl {
1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470
  final Map<int, String> _runningApps = <int, String>{};
  bool _started = false;
  int _nextAppId = 1;

  @override
  Future<bool> start(FuchsiaDevice device) async {
    _started = true;
    return true;
  }

  @override
  Future<Map<int, String>> list(FuchsiaDevice device) async {
    if (!_started) {
      return null;
    }
    return _runningApps;
  }

  @override
  Future<bool> add(FuchsiaDevice device, String url, List<String> args) async {
    if (!_started) {
      return false;
    }
    _runningApps[_nextAppId] = url;
    _nextAppId++;
    return true;
  }

  @override
  Future<bool> remove(FuchsiaDevice device, int key) async {
    if (!_started) {
      return false;
    }
    _runningApps.remove(key);
    return true;
  }

  @override
  Future<bool> quit(FuchsiaDevice device) async {
    if (!_started) {
      return false;
    }
    _started = false;
    return true;
  }
}

1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504
class FailingTilesCtl implements FuchsiaTilesCtl {
  @override
  Future<bool> start(FuchsiaDevice device) async {
    return false;
  }

  @override
  Future<Map<int, String>> list(FuchsiaDevice device) async {
    return null;
  }

  @override
  Future<bool> add(FuchsiaDevice device, String url, List<String> args) async {
    return false;
  }

  @override
  Future<bool> remove(FuchsiaDevice device, int key) async {
    return false;
  }

  @override
  Future<bool> quit(FuchsiaDevice device) async {
    return false;
  }
}

class FakeFuchsiaDeviceTools implements FuchsiaDeviceTools {
  FakeFuchsiaDeviceTools({
    FuchsiaAmberCtl amber,
    FuchsiaTilesCtl tiles,
  }) : amberCtl = amber ?? FakeFuchsiaAmberCtl(),
       tilesCtl = tiles ?? FakeFuchsiaTilesCtl();

1505
  @override
1506
  final FuchsiaAmberCtl amberCtl;
1507 1508

  @override
1509
  final FuchsiaTilesCtl tilesCtl;
1510 1511
}

1512
class FakeFuchsiaPM implements FuchsiaPM {
1513 1514 1515 1516
  String _appName;

  @override
  Future<bool> init(String buildPath, String appName) async {
1517
    if (!globals.fs.directory(buildPath).existsSync()) {
1518 1519
      return false;
    }
1520 1521
    globals.fs
        .file(globals.fs.path.join(buildPath, 'meta', 'package'))
1522 1523 1524 1525 1526 1527
        .createSync(recursive: true);
    _appName = appName;
    return true;
  }

  @override
1528
  Future<bool> build(String buildPath, String manifestPath) async {
1529 1530
    if (!globals.fs.file(globals.fs.path.join(buildPath, 'meta', 'package')).existsSync() ||
        !globals.fs.file(manifestPath).existsSync()) {
1531 1532
      return false;
    }
1533
    globals.fs.file(globals.fs.path.join(buildPath, 'meta.far')).createSync(recursive: true);
1534 1535 1536 1537
    return true;
  }

  @override
1538
  Future<bool> archive(String buildPath, String manifestPath) async {
1539 1540
    if (!globals.fs.file(globals.fs.path.join(buildPath, 'meta', 'package')).existsSync() ||
        !globals.fs.file(manifestPath).existsSync()) {
1541 1542 1543 1544 1545
      return false;
    }
    if (_appName == null) {
      return false;
    }
1546 1547
    globals.fs
        .file(globals.fs.path.join(buildPath, '$_appName-0.far'))
1548 1549 1550 1551 1552 1553
        .createSync(recursive: true);
    return true;
  }

  @override
  Future<bool> newrepo(String repoPath) async {
1554
    if (!globals.fs.directory(repoPath).existsSync()) {
1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566
      return false;
    }
    return true;
  }

  @override
  Future<Process> serve(String repoPath, String host, int port) async {
    return _createMockProcess(persistent: true);
  }

  @override
  Future<bool> publish(String repoPath, String packagePath) async {
1567
    if (!globals.fs.directory(repoPath).existsSync()) {
1568 1569
      return false;
    }
1570
    if (!globals.fs.file(packagePath).existsSync()) {
1571 1572 1573 1574 1575 1576
      return false;
    }
    return true;
  }
}

1577 1578 1579 1580 1581 1582 1583 1584
class FailingPM implements FuchsiaPM {
  @override
  Future<bool> init(String buildPath, String appName) async {
    return false;
  }


  @override
1585
  Future<bool> build(String buildPath, String manifestPath) async {
1586 1587 1588 1589
    return false;
  }

  @override
1590
  Future<bool> archive(String buildPath, String manifestPath) async {
1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610
    return false;
  }

  @override
  Future<bool> newrepo(String repoPath) async {
    return false;
  }

  @override
  Future<Process> serve(String repoPath, String host, int port) async {
    return _createMockProcess(exitCode: 6);
  }

  @override
  Future<bool> publish(String repoPath, String packagePath) async {
    return false;
  }
}

class FakeFuchsiaKernelCompiler implements FuchsiaKernelCompiler {
1611 1612 1613 1614 1615 1616 1617 1618
  @override
  Future<void> build({
    @required FuchsiaProject fuchsiaProject,
    @required String target, // E.g., lib/main.dart
    BuildInfo buildInfo = BuildInfo.debug,
  }) async {
    final String outDir = getFuchsiaBuildDirectory();
    final String appName = fuchsiaProject.project.manifest.appName;
1619 1620
    final String manifestPath = globals.fs.path.join(outDir, '$appName.dilpmanifest');
    globals.fs.file(manifestPath).createSync(recursive: true);
1621 1622 1623
  }
}

1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635
class FailingKernelCompiler implements FuchsiaKernelCompiler {
  @override
  Future<void> build({
    @required FuchsiaProject fuchsiaProject,
    @required String target, // E.g., lib/main.dart
    BuildInfo buildInfo = BuildInfo.debug,
  }) async {
    throwToolExit('Build process failed');
  }
}

class FakeFuchsiaDevFinder implements FuchsiaDevFinder {
1636
  @override
1637
  Future<List<String>> list({ Duration timeout }) async {
1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650
    return <String>['192.168.11.999 scare-cable-device-finder'];
  }

  @override
  Future<String> resolve(String deviceName) async {
    return '192.168.11.999';
  }
}

class FakeFuchsiaFfx implements FuchsiaFfx {
  @override
  Future<List<String>> list({Duration timeout}) async {
    return <String>['192.168.42.172 scare-cable-skip-ffx'];
1651 1652 1653
  }

  @override
1654
  Future<String> resolve(String deviceName) async {
1655 1656 1657 1658 1659
    return '192.168.42.10';
  }
}

class MockFuchsiaSdk extends Mock implements FuchsiaSdk {
1660 1661 1662 1663
  MockFuchsiaSdk({
    FuchsiaPM pm,
    FuchsiaKernelCompiler compiler,
    FuchsiaDevFinder devFinder,
1664
    FuchsiaFfx ffx,
1665 1666
  }) : fuchsiaPM = pm ?? FakeFuchsiaPM(),
       fuchsiaKernelCompiler = compiler ?? FakeFuchsiaKernelCompiler(),
1667 1668
       fuchsiaDevFinder = devFinder ?? FakeFuchsiaDevFinder(),
       fuchsiaFfx = ffx ?? FakeFuchsiaFfx();
1669

1670
  @override
1671
  final FuchsiaPM fuchsiaPM;
1672 1673

  @override
1674
  final FuchsiaKernelCompiler fuchsiaKernelCompiler;
1675 1676

  @override
1677
  final FuchsiaDevFinder fuchsiaDevFinder;
1678 1679 1680

  @override
  final FuchsiaFfx fuchsiaFfx;
1681
}
1682

1683
class MockDartDevelopmentService extends Mock implements DartDevelopmentService {}
1684
class MockFuchsiaWorkflow extends Mock implements FuchsiaWorkflow {}