fuchsia_device_test.dart 55.9 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 7
import 'dart:async';
import 'dart:convert';

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

40 41
import '../../src/common.dart';
import '../../src/context.dart';
42

43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
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,
);

60 61
void main() {
  group('fuchsia device', () {
62
    MemoryFileSystem memoryFileSystem;
63
    MockFile sshConfig;
Dan Field's avatar
Dan Field committed
64

65 66
    setUp(() {
      memoryFileSystem = MemoryFileSystem();
67
      sshConfig = MockFile();
68
      when(sshConfig.existsSync()).thenReturn(true);
69
      when(sshConfig.absolute).thenReturn(sshConfig);
70 71
    });

72
    testWithoutContext('stores the requested id and name', () {
73 74 75
      const String deviceId = 'e80::0000:a00a:f00f:2002/3';
      const String name = 'halfbaked';
      final FuchsiaDevice device = FuchsiaDevice(deviceId, name: name);
76

77 78 79 80
      expect(device.id, deviceId);
      expect(device.name, name);
    });

81 82 83 84 85 86 87 88 89 90 91
    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);
    });

92 93 94 95 96 97 98 99 100
    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);
101

102 103
      expect(fuchsiaDevices.canListAnything, false);
      expect(await fuchsiaDevices.pollingGetDevices(), isEmpty);
104
    });
105

106 107 108 109 110 111 112 113 114 115 116 117 118
    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'),
        fuchsiaSdk: fuchsiaSdk,
        fuchsiaWorkflow: fuchsiaWorkflow,
        logger: BufferLogger.test(),
      );
      when(fuchsiaWorkflow.canListDevices).thenReturn(true);
      when(fuchsiaSdk.listDevices()).thenAnswer((Invocation invocation) async {
        return '2001:0db8:85a3:0000:0000:8a2e:0370:7334 paper-pulp-bush-angel';
      });
119

120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165
      final Device device = (await fuchsiaDevices.pollingGetDevices()).single;

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

    testWithoutContext('can parse device-finder output for multiple devices', () 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.canListDevices).thenReturn(true);
      when(fuchsiaSdk.listDevices()).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.42.10');
      expect(devices.last.name, 'foo-bar-fiz-buzz');
      expect(devices.last.id, '192.168.42.10');
    });

    testWithoutContext('can parse junk output from the dev-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.canListDevices).thenReturn(true);
      when(fuchsiaSdk.listDevices()).thenAnswer((Invocation invocation) async {
        return 'junk';
      });

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

      expect(devices, isEmpty);
166 167
    });

168 169 170 171 172 173 174 175
    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);
    });

176
    testUsingContext('default capabilities', () async {
177
      final FuchsiaDevice device = FuchsiaDevice('123');
178 179
      globals.fs.directory('fuchsia').createSync(recursive: true);
      globals.fs.file('pubspec.yaml').createSync();
180 181 182

      expect(device.supportsHotReload, true);
      expect(device.supportsHotRestart, false);
183
      expect(device.supportsFlutterExit, false);
184 185 186
      expect(device.isSupportedForProject(FlutterProject.current()), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => memoryFileSystem,
187
      ProcessManager: () => FakeProcessManager.any(),
188
    });
189 190 191

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

193 194
      expect(device.ephemeral, true);
    });
195 196 197

    testUsingContext('supported for project', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
198 199
      globals.fs.directory('fuchsia').createSync(recursive: true);
      globals.fs.file('pubspec.yaml').createSync();
200

201 202 203
      expect(device.isSupportedForProject(FlutterProject.current()), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => memoryFileSystem,
204
      ProcessManager: () => FakeProcessManager.any(),
205 206 207 208
    });

    testUsingContext('not supported for project', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
209
      globals.fs.file('pubspec.yaml').createSync();
210

211 212 213
      expect(device.isSupportedForProject(FlutterProject.current()), false);
    }, overrides: <Type, Generator>{
      FileSystem: () => memoryFileSystem,
214
      ProcessManager: () => FakeProcessManager.any(),
215
    });
216

217 218
    testUsingContext('targetPlatform does not throw when sshConfig is missing', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
219

220 221 222 223 224 225 226
      expect(await device.targetPlatform, TargetPlatform.fuchsia_arm64);
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: null),
      FuchsiaSdk: () => MockFuchsiaSdk(),
      ProcessManager: () => MockProcessManager(),
    });

227
    testUsingContext('targetPlatform arm64 works', () async {
Dan Field's avatar
Dan Field committed
228 229
      when(globals.processManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(1, 0, 'aarch64', '');
230 231 232 233 234
      });
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.targetPlatform, TargetPlatform.fuchsia_arm64);
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
235
      FuchsiaSdk: () => MockFuchsiaSdk(),
Dan Field's avatar
Dan Field committed
236
      ProcessManager: () => MockProcessManager(),
237 238 239
    });

    testUsingContext('targetPlatform x64 works', () async {
Dan Field's avatar
Dan Field committed
240 241
      when(globals.processManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(1, 0, 'x86_64', '');
242 243 244 245 246
      });
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.targetPlatform, TargetPlatform.fuchsia_x64);
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287
      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');
      expect(() async => await device.hostAddress, throwsToolExit());
    }, 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');
      expect(() async => await device.hostAddress, throwsToolExit());
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
288
      FuchsiaSdk: () => MockFuchsiaSdk(),
Dan Field's avatar
Dan Field committed
289
      ProcessManager: () => MockProcessManager(),
290
    });
291 292 293
  });

  group('displays friendly error when', () {
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
    MockProcessManager mockProcessManager;
    MockProcessResult mockProcessResult;
    MockFile mockFile;
    MockProcessManager emptyStdoutProcessManager;
    MockProcessResult emptyStdoutProcessResult;

    setUp(() {
      mockProcessManager = MockProcessManager();
      mockProcessResult = MockProcessResult();
      mockFile = MockFile();
      when(mockProcessManager.run(
        any,
        environment: anyNamed('environment'),
        workingDirectory: anyNamed('workingDirectory'),
      )).thenAnswer((Invocation invocation) =>
          Future<ProcessResult>.value(mockProcessResult));
      when(mockProcessResult.exitCode).thenReturn(1);
311 312
      when<String>(mockProcessResult.stdout as String).thenReturn('');
      when<String>(mockProcessResult.stderr as String).thenReturn('');
313 314 315 316 317 318 319 320 321 322 323 324
      when(mockFile.absolute).thenReturn(mockFile);
      when(mockFile.path).thenReturn('');

      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);
325 326
      when<String>(emptyStdoutProcessResult.stdout as String).thenReturn('');
      when<String>(emptyStdoutProcessResult.stderr as String).thenReturn('');
327
    });
328 329

    testUsingContext('No vmservices found', () async {
330 331 332 333 334 335 336
      final FuchsiaDevice device = FuchsiaDevice('id');
      ToolExit toolExit;
      try {
        await device.servicePorts();
      } on ToolExit catch (err) {
        toolExit = err;
      }
337 338 339 340
      expect(
          toolExit.message,
          contains(
              'No Dart Observatories found. Are you running a debug build?'));
341
    }, overrides: <Type, Generator>{
342
      ProcessManager: () => emptyStdoutProcessManager,
343
      FuchsiaArtifacts: () => FuchsiaArtifacts(
344 345 346
            sshConfig: mockFile,
            devFinder: mockFile,
          ),
347
      FuchsiaSdk: () => MockFuchsiaSdk(),
348
    });
349 350 351

    group('device logs', () {
      const String exampleUtcLogs = '''
352
[2018-11-09 01:27:45][3][297950920][log] INFO: example_app.cmx(flutter): Error doing thing
353 354
[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
355
[2018-11-09 01:29:58][46257][46269][foo] INFO: other_app.cmx(flutter): Do thing
356
[2018-11-09 01:30:02][41175][41187][bar] INFO: Invoking a bar
357
[2018-11-09 01:30:12][52580][52983][log] INFO: example_app.cmx(flutter): Did thing this time
358

359
  ''';
360 361
      MockProcessManager mockProcessManager;
      MockProcess mockProcess;
362 363 364
      Completer<int> exitCode;
      StreamController<List<int>> stdout;
      StreamController<List<int>> stderr;
365 366
      MockFile devFinder;
      MockFile sshConfig;
367

368
      setUp(() {
369 370
        mockProcessManager = MockProcessManager();
        mockProcess = MockProcess();
371 372 373
        stdout = StreamController<List<int>>(sync: true);
        stderr = StreamController<List<int>>(sync: true);
        exitCode = Completer<int>();
374 375 376 377 378 379 380
        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);
        devFinder = MockFile();
        sshConfig = MockFile();
381 382
        when(devFinder.existsSync()).thenReturn(true);
        when(sshConfig.existsSync()).thenReturn(true);
383 384
        when(devFinder.absolute).thenReturn(devFinder);
        when(sshConfig.absolute).thenReturn(sshConfig);
385 386 387 388 389 390 391 392
      });

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

      testUsingContext('can be parsed for an app', () async {
        final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
393
        final DeviceLogReader reader = device.getLogReader(
394
            app: FuchsiaModulePackage(name: 'example_app'));
395
        final List<String> logLines = <String>[];
396 397 398 399 400 401 402
        final Completer<void> lock = Completer<void>();
        reader.logLines.listen((String line) {
          logLines.add(line);
          if (logLines.length == 2) {
            lock.complete();
          }
        });
403 404 405 406
        expect(logLines, isEmpty);

        stdout.add(utf8.encode(exampleUtcLogs));
        await stdout.close();
407
        await lock.future.timeout(const Duration(seconds: 1));
408 409 410 411 412 413 414 415

        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)),
416 417
        FuchsiaArtifacts: () =>
            FuchsiaArtifacts(devFinder: devFinder, sshConfig: sshConfig),
418 419 420 421
      });

      testUsingContext('cuts off prior logs', () async {
        final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
422
        final DeviceLogReader reader = device.getLogReader(
423
            app: FuchsiaModulePackage(name: 'example_app'));
424 425 426 427 428 429 430 431 432 433
        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();
434
        await lock.future.timeout(const Duration(seconds: 1));
435 436 437 438 439 440 441

        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)),
442 443
        FuchsiaArtifacts: () =>
            FuchsiaArtifacts(devFinder: devFinder, sshConfig: sshConfig),
444 445 446 447 448 449
      });

      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>[];
450 451 452 453 454 455 456
        final Completer<void> lock = Completer<void>();
        reader.logLines.listen((String line) {
          logLines.add(line);
          if (logLines.length == 3) {
            lock.complete();
          }
        });
457 458 459 460
        expect(logLines, isEmpty);

        stdout.add(utf8.encode(exampleUtcLogs));
        await stdout.close();
461
        await lock.future.timeout(const Duration(seconds: 1));
462 463 464 465 466 467 468 469 470

        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)),
471 472
        FuchsiaArtifacts: () =>
            FuchsiaArtifacts(devFinder: devFinder, sshConfig: sshConfig),
473 474
      });
    });
475
  });
476

Dan Field's avatar
Dan Field committed
477
  group('screenshot', () {
478
    testUsingContext('is supported on posix platforms', () {
479 480
      final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
      expect(device.supportsScreenshot, true);
481 482 483 484 485
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(
        operatingSystem: 'linux',
      ),
    });
486 487 488

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

490 491 492 493 494 495 496
      expect(device.supportsScreenshot, false);
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(
        operatingSystem: 'windows',
      ),
    });

497
    test("takeScreenshot throws if file isn't .ppm", () async {
498 499 500 501 502
      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')),
      );
503
    });
504 505 506 507

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

508
      when(globals.processManager.run(
509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        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>{
525 526
      ProcessManager: () => MockProcessManager(),
      FileSystem: () => MemoryFileSystem.test(),
527 528 529 530 531 532
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
533
    });
534 535 536 537

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

538
      when(globals.processManager.run(
539 540 541 542 543 544 545 546 547 548 549
        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, '', ''));

550
      when(globals.processManager.run(
551 552 553 554 555 556 557 558 559 560 561
        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>'));

562
       when(globals.processManager.run(
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
        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>{
579 580
      ProcessManager: () => MockProcessManager(),
      FileSystem: () => MemoryFileSystem.test(),
581 582 583 584 585 586
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
587
    });
588

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

592
      when(globals.processManager.run(
593 594 595 596 597 598 599 600 601 602 603
        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, '', ''));

604
      when(globals.processManager.run(
605 606 607 608 609 610 611 612 613 614 615
        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, '', ''));

616
       when(globals.processManager.run(
617 618 619 620 621 622 623 624 625 626 627 628 629
        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'));
630
      } on Exception {
631 632 633 634 635 636 637
        assert(false);
      }
      expect(
        testLogger.errorText,
        contains('Failed to delete screenshot.ppm from the device:\n<error-message>'),
      );
    }, overrides: <Type, Generator>{
638 639
      ProcessManager: () => MockProcessManager(),
      FileSystem: () => MemoryFileSystem.test(),
640 641 642 643 644 645 646 647 648 649 650
      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');

651
      when(globals.processManager.run(
652 653 654 655 656 657 658 659 660 661 662
        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, '', ''));

663
      when(globals.processManager.run(
664 665 666 667 668 669 670 671 672 673 674
        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, '', ''));

675
       when(globals.processManager.run(
676 677 678 679 680 681 682 683 684 685 686
        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, '', ''));

687 688
      expect(() async => await device.takeScreenshot(globals.fs.file('file.ppm')),
        returnsNormally);
689
    }, overrides: <Type, Generator>{
690 691
      ProcessManager: () => MockProcessManager(),
      FileSystem: () => MemoryFileSystem.test(),
692 693 694 695 696 697
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
698
    });
699 700
  });

701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743
  group('portForwarder', () {
    MockProcessManager mockProcessManager;
    MockFile sshConfig;

    setUp(() {
      mockProcessManager = MockProcessManager();

      sshConfig = MockFile();
      when(sshConfig.path).thenReturn('irrelevant');
      when(sshConfig.existsSync()).thenReturn(true);
      when(sshConfig.absolute).thenReturn(sshConfig);
    });

    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',
        'irrelevant',
        '-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
744

745
  group('FuchsiaIsolateDiscoveryProtocol', () {
746 747 748 749 750 751
    MockPortForwarder portForwarder;

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

752
    Future<Uri> findUri(List<FlutterView> views, String expectedIsolateName) async {
753 754 755 756 757 758 759 760 761 762 763 764 765
      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
        requests: <VmServiceExpectation>[
          FakeVmServiceRequest(
            method: kListViewsMethod,
            jsonResponse: <String, Object>{
              'views': <Object>[
                for (FlutterView view in views)
                  view.toJson()
              ],
            },
          ),
        ],
      );
766
      final MockFuchsiaDevice fuchsiaDevice =
767
        MockFuchsiaDevice('123', portForwarder, false);
768
      final FuchsiaIsolateDiscoveryProtocol discoveryProtocol =
769
        FuchsiaIsolateDiscoveryProtocol(
770 771
        fuchsiaDevice,
        expectedIsolateName,
772
        (Uri uri) async => fakeVmServiceHost.vmService,
773
        (Device device, Uri uri, bool enableServiceAuthCodes) => null,
774
        true, // only poll once.
775
      );
776 777 778 779
      final MockDartDevelopmentService mockDds = MockDartDevelopmentService();
      when(fuchsiaDevice.dds).thenReturn(mockDds);
      when(mockDds.startDartDevelopmentService(any, any, any, any)).thenReturn(null);
      when(mockDds.uri).thenReturn(Uri.parse('example'));
780 781 782 783
      when(fuchsiaDevice.servicePorts())
          .thenAnswer((Invocation invocation) async => <int>[1]);
      when(portForwarder.forward(1))
          .thenAnswer((Invocation invocation) async => 2);
784
      setHttpAddress(Uri.parse('example'), fakeVmServiceHost.vmService);
785
      return await discoveryProtocol.uri;
786
    }
787

788
    testUsingContext('can find flutter view with matching isolate name', () async {
789
      const String expectedIsolateName = 'foobar';
790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808
      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,
          }),
        ),
809
      ], expectedIsolateName);
810

811 812
      expect(
          uri.toString(), 'http://${InternetAddress.loopbackIPv4.address}:0/');
813 814
    });

815
    testUsingContext('can handle flutter view without matching isolate name', () async {
816
      const String expectedIsolateName = 'foobar';
817 818 819 820 821 822 823 824
      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',
        })),
825
      ], expectedIsolateName);
826

827 828 829 830 831
      expect(uri, throwsException);
    });

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

836 837 838
      expect(uri, throwsException);
    });
  });
839

840
  testUsingContext('Correct flutter runner', () async {
841 842 843 844 845 846 847 848 849
    final MockCache cache = MockCache();
    final FileSystem fileSystem = MemoryFileSystem.test();
    when(cache.getArtifactDirectory('flutter_runner')).thenReturn(fileSystem.directory('fuchsia'));
    final CachedArtifacts artifacts = CachedArtifacts(
      cache: cache,
      fileSystem: fileSystem,
      platform: FakePlatform(operatingSystem: 'linux'),
    );
    expect(artifacts.getArtifactPath(
850 851 852 853 854 855
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.debug,
      ),
      contains('flutter_jit_runner'),
    );
856
    expect(artifacts.getArtifactPath(
857 858 859 860 861 862
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.profile,
      ),
      contains('flutter_aot_runner'),
    );
863
    expect(artifacts.getArtifactPath(
864 865 866 867 868 869
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.release,
      ),
      contains('flutter_aot_product_runner'),
    );
870
    expect(artifacts.getArtifactPath(
871 872 873 874 875 876 877 878 879
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.jitRelease,
      ),
      contains('flutter_jit_product_runner'),
    );
  });

  group('Fuchsia app start and stop: ', () {
880
    MemoryFileSystem memoryFileSystem;
881
    FakeOperatingSystemUtils osUtils;
882
    FakeFuchsiaDeviceTools fuchsiaDeviceTools;
883
    MockFuchsiaSdk fuchsiaSdk;
884 885 886 887 888 889 890 891
    MockFuchsiaArtifacts fuchsiaArtifacts;
    MockArtifacts mockArtifacts;

    File compilerSnapshot;
    File platformDill;
    File patchedSdk;
    File runner;

892 893
    setUp(() {
      memoryFileSystem = MemoryFileSystem();
894
      osUtils = FakeOperatingSystemUtils();
895
      fuchsiaDeviceTools = FakeFuchsiaDeviceTools();
896
      fuchsiaSdk = MockFuchsiaSdk();
897 898 899 900 901 902 903 904 905 906 907 908 909 910
      fuchsiaArtifacts = MockFuchsiaArtifacts();

      compilerSnapshot = memoryFileSystem.file('kernel_compiler.snapshot')..createSync();
      platformDill = memoryFileSystem.file('platform_strong.dill')..createSync();
      patchedSdk = memoryFileSystem.file('flutter_runner_patched_sdk')..createSync();
      runner = memoryFileSystem.file('flutter_jit_runner')..createSync();

      mockArtifacts = MockArtifacts();
      when(mockArtifacts.getArtifactPath(
        Artifact.fuchsiaKernelCompiler,
        platform: anyNamed('platform'),
        mode: anyNamed('mode'),
      )).thenReturn(compilerSnapshot.path);
      when(mockArtifacts.getArtifactPath(
911
        Artifact.platformKernelDill,
912 913 914 915
        platform: anyNamed('platform'),
        mode: anyNamed('mode'),
      )).thenReturn(platformDill.path);
      when(mockArtifacts.getArtifactPath(
916
        Artifact.flutterPatchedSdkPath,
917 918 919 920
        platform: anyNamed('platform'),
        mode: anyNamed('mode'),
      )).thenReturn(patchedSdk.path);
      when(mockArtifacts.getArtifactPath(
921
        Artifact.fuchsiaFlutterRunner,
922 923 924
        platform: anyNamed('platform'),
        mode: anyNamed('mode'),
      )).thenReturn(runner.path);
925 926
    });

927 928 929 930
    Future<LaunchResult> setupAndStartApp({
      @required bool prebuilt,
      @required BuildMode mode,
    }) async {
931
      const String appName = 'app_name';
932
      final FuchsiaDevice device = FuchsiaDeviceWithFakeDiscovery('123');
933 934
      globals.fs.directory('fuchsia').createSync(recursive: true);
      final File pubspecFile = globals.fs.file('pubspec.yaml')..createSync();
935 936
      pubspecFile.writeAsStringSync('name: $appName');

937 938
      FuchsiaApp app;
      if (prebuilt) {
939
        final File far = globals.fs.file('app_name-0.far')..createSync();
940 941
        app = FuchsiaApp.fromPrebuiltApp(far);
      } else {
942
        globals.fs.file(globals.fs.path.join('fuchsia', 'meta', '$appName.cmx'))
943 944
          ..createSync(recursive: true)
          ..writeAsStringSync('{}');
945 946
        globals.fs.file('.packages').createSync();
        globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
947 948 949
        app = BuildableFuchsiaApp(project: FlutterProject.current().fuchsia);
      }

950
      final DebuggingOptions debuggingOptions = DebuggingOptions.disabled(BuildInfo(mode, null, treeShakeIcons: false));
951 952 953 954 955
      return await device.startApp(
        app,
        prebuiltApplication: prebuilt,
        debuggingOptions: debuggingOptions,
      );
956
    }
957

958 959 960
    testUsingContext('start prebuilt in release mode', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.release);
961 962 963
      expect(launchResult.started, isTrue);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
964
      Artifacts: () => mockArtifacts,
965
      FileSystem: () => memoryFileSystem,
966
      ProcessManager: () => FakeProcessManager.any(),
967
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
968
      FuchsiaArtifacts: () => fuchsiaArtifacts,
969 970 971 972
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

973
    testUsingContext('start and stop prebuilt in release mode', () async {
974
      const String appName = 'app_name';
975
      final FuchsiaDevice device = FuchsiaDeviceWithFakeDiscovery('123');
976 977
      globals.fs.directory('fuchsia').createSync(recursive: true);
      final File pubspecFile = globals.fs.file('pubspec.yaml')..createSync();
978
      pubspecFile.writeAsStringSync('name: $appName');
979
      final File far = globals.fs.file('app_name-0.far')..createSync();
980 981 982

      final FuchsiaApp app = FuchsiaApp.fromPrebuiltApp(far);
      final DebuggingOptions debuggingOptions =
983
          DebuggingOptions.disabled(const BuildInfo(BuildMode.release, null, treeShakeIcons: false));
984 985 986 987 988 989 990
      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>{
991
      Artifacts: () => mockArtifacts,
992
      FileSystem: () => memoryFileSystem,
993
      ProcessManager: () => FakeProcessManager.any(),
994
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
995
      FuchsiaArtifacts: () => fuchsiaArtifacts,
996 997 998
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });
999 1000 1001 1002 1003 1004 1005

    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>{
1006
      Artifacts: () => mockArtifacts,
1007
      FileSystem: () => memoryFileSystem,
1008
      ProcessManager: () => FakeProcessManager.any(),
1009
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1010
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1011 1012 1013 1014 1015 1016 1017 1018 1019 1020
      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>{
1021
      Artifacts: () => mockArtifacts,
1022
      FileSystem: () => memoryFileSystem,
1023
      ProcessManager: () => FakeProcessManager.any(),
1024
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1025
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
      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>{
1036
      Artifacts: () => mockArtifacts,
1037
      FileSystem: () => memoryFileSystem,
1038
      ProcessManager: () => FakeProcessManager.any(),
1039
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1040
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1041 1042 1043 1044
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

1045
    testUsingContext('fail with correct LaunchResult when device-finder fails', () async {
1046 1047 1048 1049 1050
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.release);
      expect(launchResult.started, isFalse);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
1051
      Artifacts: () => mockArtifacts,
1052
      FileSystem: () => memoryFileSystem,
1053
      ProcessManager: () => FakeProcessManager.any(),
1054
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1055
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1056 1057 1058 1059 1060 1061 1062 1063 1064 1065
      FuchsiaSdk: () => MockFuchsiaSdk(devFinder: FailingDevFinder()),
      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>{
1066
      Artifacts: () => mockArtifacts,
1067
      FileSystem: () => memoryFileSystem,
1068
      ProcessManager: () => FakeProcessManager.any(),
1069
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1070
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1071 1072 1073 1074 1075 1076 1077 1078 1079 1080
      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>{
1081
      Artifacts: () => mockArtifacts,
1082
      FileSystem: () => memoryFileSystem,
1083
      ProcessManager: () => FakeProcessManager.any(),
1084
      FuchsiaDeviceTools: () => FakeFuchsiaDeviceTools(amber: FailingAmberCtl()),
1085
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095
      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>{
1096
      Artifacts: () => mockArtifacts,
1097
      FileSystem: () => memoryFileSystem,
1098
      ProcessManager: () => FakeProcessManager.any(),
1099
      FuchsiaDeviceTools: () => FakeFuchsiaDeviceTools(tiles: FailingTilesCtl()),
1100
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1101 1102 1103 1104
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

1105
  });
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117

  group('sdkNameAndVersion: ', () {
    MockFile sshConfig;
    MockProcessManager mockSuccessProcessManager;
    MockProcessResult mockSuccessProcessResult;
    MockProcessManager mockFailureProcessManager;
    MockProcessResult mockFailureProcessResult;
    MockProcessManager emptyStdoutProcessManager;
    MockProcessResult emptyStdoutProcessResult;

    setUp(() {
      sshConfig = MockFile();
1118
      when(sshConfig.existsSync()).thenReturn(true);
1119 1120 1121 1122 1123 1124 1125
      when(sshConfig.absolute).thenReturn(sshConfig);

      mockSuccessProcessManager = MockProcessManager();
      mockSuccessProcessResult = MockProcessResult();
      when(mockSuccessProcessManager.run(any)).thenAnswer(
          (Invocation invocation) => Future<ProcessResult>.value(mockSuccessProcessResult));
      when(mockSuccessProcessResult.exitCode).thenReturn(0);
1126 1127
      when<String>(mockSuccessProcessResult.stdout as String).thenReturn('version');
      when<String>(mockSuccessProcessResult.stderr as String).thenReturn('');
1128 1129 1130 1131 1132 1133

      mockFailureProcessManager = MockProcessManager();
      mockFailureProcessResult = MockProcessResult();
      when(mockFailureProcessManager.run(any)).thenAnswer(
          (Invocation invocation) => Future<ProcessResult>.value(mockFailureProcessResult));
      when(mockFailureProcessResult.exitCode).thenReturn(1);
1134 1135
      when<String>(mockFailureProcessResult.stdout as String).thenReturn('');
      when<String>(mockFailureProcessResult.stderr as String).thenReturn('');
1136 1137 1138 1139 1140 1141

      emptyStdoutProcessManager = MockProcessManager();
      emptyStdoutProcessResult = MockProcessResult();
      when(emptyStdoutProcessManager.run(any)).thenAnswer((Invocation invocation) =>
          Future<ProcessResult>.value(emptyStdoutProcessResult));
      when(emptyStdoutProcessResult.exitCode).thenReturn(0);
1142 1143
      when<String>(emptyStdoutProcessResult.stdout as String).thenReturn('');
      when<String>(emptyStdoutProcessResult.stderr as String).thenReturn('');
1144 1145
    });

1146 1147 1148 1149 1150 1151 1152 1153 1154
    testUsingContext('does not throw on non-existant ssh config', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.sdkNameAndVersion, equals('Fuchsia'));
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockSuccessProcessManager,
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: null),
      FuchsiaSdk: () => MockFuchsiaSdk(),
    });

1155 1156 1157 1158 1159 1160
    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),
1161
      FuchsiaSdk: () => MockFuchsiaSdk(),
1162 1163 1164 1165 1166 1167 1168 1169
    });

    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),
1170
      FuchsiaSdk: () => MockFuchsiaSdk(),
1171 1172 1173 1174 1175 1176 1177 1178
    });

    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),
1179
      FuchsiaSdk: () => MockFuchsiaSdk(),
1180 1181
    });
  });
1182 1183 1184 1185 1186 1187 1188
}

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

  @override
  final String name;
1189
}
1190

1191 1192 1193 1194
class MockArtifacts extends Mock implements Artifacts {}

class MockFuchsiaArtifacts extends Mock implements FuchsiaArtifacts {}

1195 1196
class MockProcessManager extends Mock implements ProcessManager {}

1197 1198 1199 1200
class MockProcessResult extends Mock implements ProcessResult {}

class MockFile extends Mock implements File {}

1201
class MockProcess extends Mock implements Process {}
1202

1203
Process _createMockProcess({
1204 1205 1206 1207 1208
  int exitCode = 0,
  String stdout = '',
  String stderr = '',
  bool persistent = false,
}) {
1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232
  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;
}

1233
class MockFuchsiaDevice extends Mock implements FuchsiaDevice {
1234 1235 1236
  MockFuchsiaDevice(this.id, this.portForwarder, this._ipv6);

  final bool _ipv6;
1237 1238

  @override
1239
  bool get ipv6 => _ipv6;
1240

1241 1242
  @override
  final String id;
1243

1244 1245 1246 1247
  @override
  final DevicePortForwarder portForwarder;

  @override
1248
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.fuchsia_arm64;
1249 1250
}

1251
class MockPortForwarder extends Mock implements DevicePortForwarder {}
1252

1253 1254 1255 1256
class FuchsiaDeviceWithFakeDiscovery extends FuchsiaDevice {
  FuchsiaDeviceWithFakeDiscovery(String id, {String name}) : super(id, name: name);

  @override
1257 1258 1259
  FuchsiaIsolateDiscoveryProtocol getIsolateDiscoveryProtocol(String isolateName) {
    return FakeFuchsiaIsolateDiscoveryProtocol();
  }
1260 1261 1262

  @override
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.fuchsia_arm64;
1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273
}

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

  @override
  void dispose() {}
}

class FakeFuchsiaAmberCtl implements FuchsiaAmberCtl {
1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287
  @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;
  }
1288 1289 1290 1291 1292 1293 1294

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

  @override
1295
  Future<bool> pkgCtlResolve(FuchsiaDevice device, FuchsiaPackageServer server, String packageName) async {
1296 1297 1298 1299 1300 1301 1302
    return true;
  }

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

1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319
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;
  }
1320 1321 1322 1323 1324 1325 1326

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

  @override
1327
  Future<bool> pkgCtlResolve(FuchsiaDevice device, FuchsiaPackageServer server, String packageName) async {
1328 1329 1330 1331 1332 1333 1334
    return false;
  }

  @override
  Future<bool> pkgCtlRepoRemove(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return false;
  }
1335 1336 1337
}

class FakeFuchsiaTilesCtl implements FuchsiaTilesCtl {
1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384
  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;
  }
}

1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418
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();

1419
  @override
1420
  final FuchsiaAmberCtl amberCtl;
1421 1422

  @override
1423
  final FuchsiaTilesCtl tilesCtl;
1424 1425
}

1426
class FakeFuchsiaPM implements FuchsiaPM {
1427 1428 1429 1430
  String _appName;

  @override
  Future<bool> init(String buildPath, String appName) async {
1431
    if (!globals.fs.directory(buildPath).existsSync()) {
1432 1433
      return false;
    }
1434 1435
    globals.fs
        .file(globals.fs.path.join(buildPath, 'meta', 'package'))
1436 1437 1438 1439 1440 1441 1442
        .createSync(recursive: true);
    _appName = appName;
    return true;
  }

  @override
  Future<bool> genkey(String buildPath, String outKeyPath) async {
1443
    if (!globals.fs.file(globals.fs.path.join(buildPath, 'meta', 'package')).existsSync()) {
1444 1445
      return false;
    }
1446
    globals.fs.file(outKeyPath).createSync(recursive: true);
1447 1448 1449 1450
    return true;
  }

  @override
1451
  Future<bool> build(String buildPath, String keyPath, String manifestPath) async {
1452 1453 1454
    if (!globals.fs.file(globals.fs.path.join(buildPath, 'meta', 'package')).existsSync() ||
        !globals.fs.file(keyPath).existsSync() ||
        !globals.fs.file(manifestPath).existsSync()) {
1455 1456
      return false;
    }
1457
    globals.fs.file(globals.fs.path.join(buildPath, 'meta.far')).createSync(recursive: true);
1458 1459 1460 1461
    return true;
  }

  @override
1462
  Future<bool> archive(String buildPath, String keyPath, String manifestPath) async {
1463 1464 1465
    if (!globals.fs.file(globals.fs.path.join(buildPath, 'meta', 'package')).existsSync() ||
        !globals.fs.file(keyPath).existsSync() ||
        !globals.fs.file(manifestPath).existsSync()) {
1466 1467 1468 1469 1470
      return false;
    }
    if (_appName == null) {
      return false;
    }
1471 1472
    globals.fs
        .file(globals.fs.path.join(buildPath, '$_appName-0.far'))
1473 1474 1475 1476 1477 1478
        .createSync(recursive: true);
    return true;
  }

  @override
  Future<bool> newrepo(String repoPath) async {
1479
    if (!globals.fs.directory(repoPath).existsSync()) {
1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491
      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 {
1492
    if (!globals.fs.directory(repoPath).existsSync()) {
1493 1494
      return false;
    }
1495
    if (!globals.fs.file(packagePath).existsSync()) {
1496 1497 1498 1499 1500 1501
      return false;
    }
    return true;
  }
}

1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513
class FailingPM implements FuchsiaPM {
  @override
  Future<bool> init(String buildPath, String appName) async {
    return false;
  }

  @override
  Future<bool> genkey(String buildPath, String outKeyPath) async {
    return false;
  }

  @override
1514
  Future<bool> build(String buildPath, String keyPath, String manifestPath) async {
1515 1516 1517 1518
    return false;
  }

  @override
1519
  Future<bool> archive(String buildPath, String keyPath, String manifestPath) async {
1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539
    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 {
1540 1541 1542 1543 1544 1545 1546 1547
  @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;
1548 1549
    final String manifestPath = globals.fs.path.join(outDir, '$appName.dilpmanifest');
    globals.fs.file(manifestPath).createSync(recursive: true);
1550 1551 1552
  }
}

1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564
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 {
1565
  @override
1566
  Future<List<String>> list({ Duration timeout }) async {
1567 1568 1569 1570
    return <String>['192.168.42.172 scare-cable-skip-joy'];
  }

  @override
1571
  Future<String> resolve(String deviceName, {bool local = false}) async {
1572 1573 1574 1575
    return '192.168.42.10';
  }
}

1576 1577
class FailingDevFinder implements FuchsiaDevFinder {
  @override
1578
  Future<List<String>> list({ Duration timeout }) async {
1579 1580 1581 1582
    return null;
  }

  @override
1583
  Future<String> resolve(String deviceName, {bool local = false}) async {
1584 1585 1586 1587
    return null;
  }
}

1588
class MockFuchsiaSdk extends Mock implements FuchsiaSdk {
1589 1590 1591 1592 1593 1594 1595 1596
  MockFuchsiaSdk({
    FuchsiaPM pm,
    FuchsiaKernelCompiler compiler,
    FuchsiaDevFinder devFinder,
  }) : fuchsiaPM = pm ?? FakeFuchsiaPM(),
       fuchsiaKernelCompiler = compiler ?? FakeFuchsiaKernelCompiler(),
       fuchsiaDevFinder = devFinder ?? FakeFuchsiaDevFinder();

1597
  @override
1598
  final FuchsiaPM fuchsiaPM;
1599 1600

  @override
1601
  final FuchsiaKernelCompiler fuchsiaKernelCompiler;
1602 1603

  @override
1604
  final FuchsiaDevFinder fuchsiaDevFinder;
1605
}
1606

1607
class MockDartDevelopmentService extends Mock implements DartDevelopmentService {}
1608
class MockFuchsiaWorkflow extends Mock implements FuchsiaWorkflow {}
1609
class MockCache extends Mock implements Cache {}