fuchsia_device_test.dart 52.6 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/file_system.dart';
14
import 'package:flutter_tools/src/base/io.dart';
15
import 'package:flutter_tools/src/base/logger.dart';
16
import 'package:flutter_tools/src/base/os.dart';
17
import 'package:flutter_tools/src/base/platform.dart';
18
import 'package:flutter_tools/src/base/time.dart';
19
import 'package:flutter_tools/src/build_info.dart';
20
import 'package:flutter_tools/src/device.dart';
21
import 'package:flutter_tools/src/fuchsia/amber_ctl.dart';
22
import 'package:flutter_tools/src/fuchsia/application_package.dart';
23
import 'package:flutter_tools/src/fuchsia/fuchsia_dev_finder.dart';
24
import 'package:flutter_tools/src/fuchsia/fuchsia_device.dart';
25 26
import 'package:flutter_tools/src/fuchsia/fuchsia_kernel_compiler.dart';
import 'package:flutter_tools/src/fuchsia/fuchsia_pm.dart';
27
import 'package:flutter_tools/src/fuchsia/fuchsia_sdk.dart';
28
import 'package:flutter_tools/src/fuchsia/fuchsia_workflow.dart';
29
import 'package:flutter_tools/src/fuchsia/tiles_ctl.dart';
30
import 'package:flutter_tools/src/globals.dart' as globals;
31 32
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/vmservice.dart';
33 34 35 36
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;
37

38 39
import '../../src/common.dart';
import '../../src/context.dart';
40

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

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

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

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

75 76 77 78
      expect(device.id, deviceId);
      expect(device.name, name);
    });

79 80 81 82 83 84 85 86 87
    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);
88

89 90
      expect(fuchsiaDevices.canListAnything, false);
      expect(await fuchsiaDevices.pollingGetDevices(), isEmpty);
91
    });
92

93 94 95 96 97 98 99 100 101 102 103 104 105
    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';
      });
106

107 108 109 110 111 112 113 114 115 116 117 118 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
      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);
153 154
    });

155 156 157 158 159 160 161 162
    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);
    });

163
    testUsingContext('default capabilities', () async {
164
      final FuchsiaDevice device = FuchsiaDevice('123');
165 166
      globals.fs.directory('fuchsia').createSync(recursive: true);
      globals.fs.file('pubspec.yaml').createSync();
167 168 169

      expect(device.supportsHotReload, true);
      expect(device.supportsHotRestart, false);
170
      expect(device.supportsFlutterExit, false);
171 172 173
      expect(device.isSupportedForProject(FlutterProject.current()), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => memoryFileSystem,
174
      ProcessManager: () => FakeProcessManager.any(),
175
    });
176 177 178

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

180 181
      expect(device.ephemeral, true);
    });
182 183 184

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

188 189 190
      expect(device.isSupportedForProject(FlutterProject.current()), true);
    }, overrides: <Type, Generator>{
      FileSystem: () => memoryFileSystem,
191
      ProcessManager: () => FakeProcessManager.any(),
192 193 194 195
    });

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

198 199 200
      expect(device.isSupportedForProject(FlutterProject.current()), false);
    }, overrides: <Type, Generator>{
      FileSystem: () => memoryFileSystem,
201
      ProcessManager: () => FakeProcessManager.any(),
202
    });
203

204 205
    testUsingContext('targetPlatform does not throw when sshConfig is missing', () async {
      final FuchsiaDevice device = FuchsiaDevice('123');
206

207 208 209 210 211 212 213
      expect(await device.targetPlatform, TargetPlatform.fuchsia_arm64);
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: null),
      FuchsiaSdk: () => MockFuchsiaSdk(),
      ProcessManager: () => MockProcessManager(),
    });

214
    testUsingContext('targetPlatform arm64 works', () async {
Dan Field's avatar
Dan Field committed
215 216
      when(globals.processManager.run(any)).thenAnswer((Invocation _) async {
        return ProcessResult(1, 0, 'aarch64', '');
217 218 219 220 221
      });
      final FuchsiaDevice device = FuchsiaDevice('123');
      expect(await device.targetPlatform, TargetPlatform.fuchsia_arm64);
    }, overrides: <Type, Generator>{
      FuchsiaArtifacts: () => FuchsiaArtifacts(sshConfig: sshConfig),
222
      FuchsiaSdk: () => MockFuchsiaSdk(),
Dan Field's avatar
Dan Field committed
223
      ProcessManager: () => MockProcessManager(),
224 225 226
    });

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

  group('displays friendly error when', () {
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256
    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);
257 258
      when<String>(mockProcessResult.stdout as String).thenReturn('');
      when<String>(mockProcessResult.stderr as String).thenReturn('');
259 260 261 262 263 264 265 266 267 268 269 270
      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);
271 272
      when<String>(emptyStdoutProcessResult.stdout as String).thenReturn('');
      when<String>(emptyStdoutProcessResult.stderr as String).thenReturn('');
273
    });
274 275

    testUsingContext('No vmservices found', () async {
276 277 278 279 280 281 282
      final FuchsiaDevice device = FuchsiaDevice('id');
      ToolExit toolExit;
      try {
        await device.servicePorts();
      } on ToolExit catch (err) {
        toolExit = err;
      }
283 284 285 286
      expect(
          toolExit.message,
          contains(
              'No Dart Observatories found. Are you running a debug build?'));
287
    }, overrides: <Type, Generator>{
288
      ProcessManager: () => emptyStdoutProcessManager,
289
      FuchsiaArtifacts: () => FuchsiaArtifacts(
290 291 292
            sshConfig: mockFile,
            devFinder: mockFile,
          ),
293
      FuchsiaSdk: () => MockFuchsiaSdk(),
294
    });
295 296 297

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

305
  ''';
306 307
      MockProcessManager mockProcessManager;
      MockProcess mockProcess;
308 309 310
      Completer<int> exitCode;
      StreamController<List<int>> stdout;
      StreamController<List<int>> stderr;
311 312
      MockFile devFinder;
      MockFile sshConfig;
313

314
      setUp(() {
315 316
        mockProcessManager = MockProcessManager();
        mockProcess = MockProcess();
317 318 319
        stdout = StreamController<List<int>>(sync: true);
        stderr = StreamController<List<int>>(sync: true);
        exitCode = Completer<int>();
320 321 322 323 324 325 326
        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();
327 328
        when(devFinder.existsSync()).thenReturn(true);
        when(sshConfig.existsSync()).thenReturn(true);
329 330
        when(devFinder.absolute).thenReturn(devFinder);
        when(sshConfig.absolute).thenReturn(sshConfig);
331 332 333 334 335 336 337 338
      });

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

      testUsingContext('can be parsed for an app', () async {
        final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
339
        final DeviceLogReader reader = device.getLogReader(
340
            app: FuchsiaModulePackage(name: 'example_app'));
341
        final List<String> logLines = <String>[];
342 343 344 345 346 347 348
        final Completer<void> lock = Completer<void>();
        reader.logLines.listen((String line) {
          logLines.add(line);
          if (logLines.length == 2) {
            lock.complete();
          }
        });
349 350 351 352
        expect(logLines, isEmpty);

        stdout.add(utf8.encode(exampleUtcLogs));
        await stdout.close();
353
        await lock.future.timeout(const Duration(seconds: 1));
354 355 356 357 358 359 360 361

        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)),
362 363
        FuchsiaArtifacts: () =>
            FuchsiaArtifacts(devFinder: devFinder, sshConfig: sshConfig),
364 365 366 367
      });

      testUsingContext('cuts off prior logs', () async {
        final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
368
        final DeviceLogReader reader = device.getLogReader(
369
            app: FuchsiaModulePackage(name: 'example_app'));
370 371 372 373 374 375 376 377 378 379
        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();
380
        await lock.future.timeout(const Duration(seconds: 1));
381 382 383 384 385 386 387

        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)),
388 389
        FuchsiaArtifacts: () =>
            FuchsiaArtifacts(devFinder: devFinder, sshConfig: sshConfig),
390 391 392 393 394 395
      });

      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>[];
396 397 398 399 400 401 402
        final Completer<void> lock = Completer<void>();
        reader.logLines.listen((String line) {
          logLines.add(line);
          if (logLines.length == 3) {
            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 416

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

Dan Field's avatar
Dan Field committed
423 424
  group('screenshot', () {
    MockProcessManager mockProcessManager;
425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443

    setUp(() {
      mockProcessManager = MockProcessManager();
    });

    test('is supported on posix platforms', () {
      final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
      expect(device.supportsScreenshot, true);
    }, testOn: 'posix');

    testUsingContext('is not supported on Windows', () {
      final FuchsiaDevice device = FuchsiaDevice('id', name: 'tester');
      expect(device.supportsScreenshot, false);
    }, overrides: <Type, Generator>{
      Platform: () => FakePlatform(
        operatingSystem: 'windows',
      ),
    });

444
    test("takeScreenshot throws if file isn't .ppm", () async {
445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533
      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')),
      );
    }, testOn: 'posix');

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

      when(mockProcessManager.run(
        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>{
      ProcessManager: () => mockProcessManager,
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
    }, testOn: 'posix');

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

      when(mockProcessManager.run(
        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, '', ''));

      when(mockProcessManager.run(
        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>'));

       when(mockProcessManager.run(
        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>{
      ProcessManager: () => mockProcessManager,
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
    }, testOn: 'posix');

534
    testUsingContext("takeScreenshot prints error if can't delete file from device", () async {
535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574
      final FuchsiaDevice device = FuchsiaDevice('0.0.0.0', name: 'tester');

      when(mockProcessManager.run(
        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, '', ''));

      when(mockProcessManager.run(
        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, '', ''));

       when(mockProcessManager.run(
        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'));
575
      } on Exception {
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632
        assert(false);
      }
      expect(
        testLogger.errorText,
        contains('Failed to delete screenshot.ppm from the device:\n<error-message>'),
      );
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
      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');

      when(mockProcessManager.run(
        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, '', ''));

      when(mockProcessManager.run(
        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, '', ''));

       when(mockProcessManager.run(
        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, '', ''));

      try {
        await device.takeScreenshot(globals.fs.file('file.ppm'));
633 634
      } on Exception catch (e) {
        fail('Unexpected exception: $e');
635 636 637 638 639 640 641 642 643 644 645 646
      }
    }, overrides: <Type, Generator>{
      ProcessManager: () => mockProcessManager,
      Platform: () => FakePlatform(
        environment: <String, String>{
          'FUCHSIA_SSH_CONFIG': '/fuchsia/out/default/.ssh',
        },
        operatingSystem: 'linux',
      ),
    }, testOn: 'posix');
  });

647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689
  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
690

691
  group('FuchsiaIsolateDiscoveryProtocol', () {
692 693 694 695 696 697
    MockPortForwarder portForwarder;

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

698
    Future<Uri> findUri(List<FlutterView> views, String expectedIsolateName) async {
699 700 701 702 703 704 705 706 707 708 709 710 711
      final FakeVmServiceHost fakeVmServiceHost = FakeVmServiceHost(
        requests: <VmServiceExpectation>[
          FakeVmServiceRequest(
            method: kListViewsMethod,
            jsonResponse: <String, Object>{
              'views': <Object>[
                for (FlutterView view in views)
                  view.toJson()
              ],
            },
          ),
        ],
      );
712
      final MockFuchsiaDevice fuchsiaDevice =
713
        MockFuchsiaDevice('123', portForwarder, false);
714
      final FuchsiaIsolateDiscoveryProtocol discoveryProtocol =
715
        FuchsiaIsolateDiscoveryProtocol(
716 717
        fuchsiaDevice,
        expectedIsolateName,
718
        (Uri uri) async => fakeVmServiceHost.vmService,
719
        true, // only poll once.
720
      );
721

722 723 724 725
      when(fuchsiaDevice.servicePorts())
          .thenAnswer((Invocation invocation) async => <int>[1]);
      when(portForwarder.forward(1))
          .thenAnswer((Invocation invocation) async => 2);
726
      setHttpAddress(Uri.parse('example'), fakeVmServiceHost.vmService);
727
      return await discoveryProtocol.uri;
728
    }
729

730
    testUsingContext('can find flutter view with matching isolate name', () async {
731
      const String expectedIsolateName = 'foobar';
732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750
      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,
          }),
        ),
751
      ], expectedIsolateName);
752

753 754
      expect(
          uri.toString(), 'http://${InternetAddress.loopbackIPv4.address}:0/');
755 756
    });

757
    testUsingContext('can handle flutter view without matching isolate name', () async {
758
      const String expectedIsolateName = 'foobar';
759 760 761 762 763 764 765 766
      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',
        })),
767
      ], expectedIsolateName);
768

769 770 771 772 773
      expect(uri, throwsException);
    });

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

778 779 780
      expect(uri, throwsException);
    });
  });
781

782
  testUsingContext('Correct flutter runner', () async {
783
    expect(globals.artifacts.getArtifactPath(
784 785 786 787 788 789
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.debug,
      ),
      contains('flutter_jit_runner'),
    );
790
    expect(globals.artifacts.getArtifactPath(
791 792 793 794 795 796
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.profile,
      ),
      contains('flutter_aot_runner'),
    );
797
    expect(globals.artifacts.getArtifactPath(
798 799 800 801 802 803
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.release,
      ),
      contains('flutter_aot_product_runner'),
    );
804
    expect(globals.artifacts.getArtifactPath(
805 806 807 808 809 810 811 812 813
        Artifact.fuchsiaFlutterRunner,
        platform: TargetPlatform.fuchsia_x64,
        mode: BuildMode.jitRelease,
      ),
      contains('flutter_jit_product_runner'),
    );
  });

  group('Fuchsia app start and stop: ', () {
814
    MemoryFileSystem memoryFileSystem;
815
    FakeOperatingSystemUtils osUtils;
816
    FakeFuchsiaDeviceTools fuchsiaDeviceTools;
817
    MockFuchsiaSdk fuchsiaSdk;
818 819 820 821 822 823 824 825
    MockFuchsiaArtifacts fuchsiaArtifacts;
    MockArtifacts mockArtifacts;

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

826 827
    setUp(() {
      memoryFileSystem = MemoryFileSystem();
828
      osUtils = FakeOperatingSystemUtils();
829
      fuchsiaDeviceTools = FakeFuchsiaDeviceTools();
830
      fuchsiaSdk = MockFuchsiaSdk();
831 832 833 834 835 836 837 838 839 840 841 842 843 844
      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(
845
        Artifact.platformKernelDill,
846 847 848 849
        platform: anyNamed('platform'),
        mode: anyNamed('mode'),
      )).thenReturn(platformDill.path);
      when(mockArtifacts.getArtifactPath(
850
        Artifact.flutterPatchedSdkPath,
851 852 853 854
        platform: anyNamed('platform'),
        mode: anyNamed('mode'),
      )).thenReturn(patchedSdk.path);
      when(mockArtifacts.getArtifactPath(
855
        Artifact.fuchsiaFlutterRunner,
856 857 858
        platform: anyNamed('platform'),
        mode: anyNamed('mode'),
      )).thenReturn(runner.path);
859 860
    });

861 862 863 864
    Future<LaunchResult> setupAndStartApp({
      @required bool prebuilt,
      @required BuildMode mode,
    }) async {
865
      const String appName = 'app_name';
866
      final FuchsiaDevice device = FuchsiaDeviceWithFakeDiscovery('123');
867 868
      globals.fs.directory('fuchsia').createSync(recursive: true);
      final File pubspecFile = globals.fs.file('pubspec.yaml')..createSync();
869 870
      pubspecFile.writeAsStringSync('name: $appName');

871 872
      FuchsiaApp app;
      if (prebuilt) {
873
        final File far = globals.fs.file('app_name-0.far')..createSync();
874 875
        app = FuchsiaApp.fromPrebuiltApp(far);
      } else {
876
        globals.fs.file(globals.fs.path.join('fuchsia', 'meta', '$appName.cmx'))
877 878
          ..createSync(recursive: true)
          ..writeAsStringSync('{}');
879 880
        globals.fs.file('.packages').createSync();
        globals.fs.file(globals.fs.path.join('lib', 'main.dart')).createSync(recursive: true);
881 882 883
        app = BuildableFuchsiaApp(project: FlutterProject.current().fuchsia);
      }

884
      final DebuggingOptions debuggingOptions = DebuggingOptions.disabled(BuildInfo(mode, null, treeShakeIcons: false));
885 886 887 888 889
      return await device.startApp(
        app,
        prebuiltApplication: prebuilt,
        debuggingOptions: debuggingOptions,
      );
890
    }
891

892 893 894
    testUsingContext('start prebuilt in release mode', () async {
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.release);
895 896 897
      expect(launchResult.started, isTrue);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
898
      Artifacts: () => mockArtifacts,
899
      FileSystem: () => memoryFileSystem,
900
      ProcessManager: () => FakeProcessManager.any(),
901
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
902
      FuchsiaArtifacts: () => fuchsiaArtifacts,
903 904 905 906
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

907
    testUsingContext('start and stop prebuilt in release mode', () async {
908
      const String appName = 'app_name';
909
      final FuchsiaDevice device = FuchsiaDeviceWithFakeDiscovery('123');
910 911
      globals.fs.directory('fuchsia').createSync(recursive: true);
      final File pubspecFile = globals.fs.file('pubspec.yaml')..createSync();
912
      pubspecFile.writeAsStringSync('name: $appName');
913
      final File far = globals.fs.file('app_name-0.far')..createSync();
914 915 916

      final FuchsiaApp app = FuchsiaApp.fromPrebuiltApp(far);
      final DebuggingOptions debuggingOptions =
917
          DebuggingOptions.disabled(const BuildInfo(BuildMode.release, null, treeShakeIcons: false));
918 919 920 921 922 923 924
      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>{
925
      Artifacts: () => mockArtifacts,
926
      FileSystem: () => memoryFileSystem,
927
      ProcessManager: () => FakeProcessManager.any(),
928
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
929
      FuchsiaArtifacts: () => fuchsiaArtifacts,
930 931 932
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });
933 934 935 936 937 938 939

    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>{
940
      Artifacts: () => mockArtifacts,
941
      FileSystem: () => memoryFileSystem,
942
      ProcessManager: () => FakeProcessManager.any(),
943
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
944
      FuchsiaArtifacts: () => fuchsiaArtifacts,
945 946 947 948 949 950 951 952 953 954
      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>{
955
      Artifacts: () => mockArtifacts,
956
      FileSystem: () => memoryFileSystem,
957
      ProcessManager: () => FakeProcessManager.any(),
958
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
959
      FuchsiaArtifacts: () => fuchsiaArtifacts,
960 961 962 963 964 965 966 967 968 969
      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>{
970
      Artifacts: () => mockArtifacts,
971
      FileSystem: () => memoryFileSystem,
972
      ProcessManager: () => FakeProcessManager.any(),
973
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
974
      FuchsiaArtifacts: () => fuchsiaArtifacts,
975 976 977 978
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

979
    testUsingContext('fail with correct LaunchResult when device-finder fails', () async {
980 981 982 983 984
      final LaunchResult launchResult =
          await setupAndStartApp(prebuilt: true, mode: BuildMode.release);
      expect(launchResult.started, isFalse);
      expect(launchResult.hasObservatory, isFalse);
    }, overrides: <Type, Generator>{
985
      Artifacts: () => mockArtifacts,
986
      FileSystem: () => memoryFileSystem,
987
      ProcessManager: () => FakeProcessManager.any(),
988
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
989
      FuchsiaArtifacts: () => fuchsiaArtifacts,
990 991 992 993 994 995 996 997 998 999
      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>{
1000
      Artifacts: () => mockArtifacts,
1001
      FileSystem: () => memoryFileSystem,
1002
      ProcessManager: () => FakeProcessManager.any(),
1003
      FuchsiaDeviceTools: () => fuchsiaDeviceTools,
1004
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
      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>{
1015
      Artifacts: () => mockArtifacts,
1016
      FileSystem: () => memoryFileSystem,
1017
      ProcessManager: () => FakeProcessManager.any(),
1018
      FuchsiaDeviceTools: () => FakeFuchsiaDeviceTools(amber: FailingAmberCtl()),
1019
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1020 1021 1022 1023 1024 1025 1026 1027 1028 1029
      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>{
1030
      Artifacts: () => mockArtifacts,
1031
      FileSystem: () => memoryFileSystem,
1032
      ProcessManager: () => FakeProcessManager.any(),
1033
      FuchsiaDeviceTools: () => FakeFuchsiaDeviceTools(tiles: FailingTilesCtl()),
1034
      FuchsiaArtifacts: () => fuchsiaArtifacts,
1035 1036 1037 1038
      FuchsiaSdk: () => fuchsiaSdk,
      OperatingSystemUtils: () => osUtils,
    });

1039
  });
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051

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

    setUp(() {
      sshConfig = MockFile();
1052
      when(sshConfig.existsSync()).thenReturn(true);
1053 1054 1055 1056 1057 1058 1059
      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);
1060 1061
      when<String>(mockSuccessProcessResult.stdout as String).thenReturn('version');
      when<String>(mockSuccessProcessResult.stderr as String).thenReturn('');
1062 1063 1064 1065 1066 1067

      mockFailureProcessManager = MockProcessManager();
      mockFailureProcessResult = MockProcessResult();
      when(mockFailureProcessManager.run(any)).thenAnswer(
          (Invocation invocation) => Future<ProcessResult>.value(mockFailureProcessResult));
      when(mockFailureProcessResult.exitCode).thenReturn(1);
1068 1069
      when<String>(mockFailureProcessResult.stdout as String).thenReturn('');
      when<String>(mockFailureProcessResult.stderr as String).thenReturn('');
1070 1071 1072 1073 1074 1075

      emptyStdoutProcessManager = MockProcessManager();
      emptyStdoutProcessResult = MockProcessResult();
      when(emptyStdoutProcessManager.run(any)).thenAnswer((Invocation invocation) =>
          Future<ProcessResult>.value(emptyStdoutProcessResult));
      when(emptyStdoutProcessResult.exitCode).thenReturn(0);
1076 1077
      when<String>(emptyStdoutProcessResult.stdout as String).thenReturn('');
      when<String>(emptyStdoutProcessResult.stderr as String).thenReturn('');
1078 1079
    });

1080 1081 1082 1083 1084 1085 1086 1087 1088
    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(),
    });

1089 1090 1091 1092 1093 1094
    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),
1095
      FuchsiaSdk: () => MockFuchsiaSdk(),
1096 1097 1098 1099 1100 1101 1102 1103
    });

    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),
1104
      FuchsiaSdk: () => MockFuchsiaSdk(),
1105 1106 1107 1108 1109 1110 1111 1112
    });

    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),
1113
      FuchsiaSdk: () => MockFuchsiaSdk(),
1114 1115
    });
  });
1116 1117 1118 1119 1120 1121 1122
}

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

  @override
  final String name;
1123
}
1124

1125 1126 1127 1128
class MockArtifacts extends Mock implements Artifacts {}

class MockFuchsiaArtifacts extends Mock implements FuchsiaArtifacts {}

1129 1130
class MockProcessManager extends Mock implements ProcessManager {}

1131 1132 1133 1134
class MockProcessResult extends Mock implements ProcessResult {}

class MockFile extends Mock implements File {}

1135
class MockProcess extends Mock implements Process {}
1136

1137
Process _createMockProcess({
1138 1139 1140 1141 1142
  int exitCode = 0,
  String stdout = '',
  String stderr = '',
  bool persistent = false,
}) {
1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166
  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;
}

1167
class MockFuchsiaDevice extends Mock implements FuchsiaDevice {
1168 1169 1170
  MockFuchsiaDevice(this.id, this.portForwarder, this._ipv6);

  final bool _ipv6;
1171 1172

  @override
1173
  bool get ipv6 => _ipv6;
1174

1175 1176
  @override
  final String id;
1177

1178 1179 1180 1181
  @override
  final DevicePortForwarder portForwarder;

  @override
1182
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.fuchsia_arm64;
1183 1184
}

1185
class MockPortForwarder extends Mock implements DevicePortForwarder {}
1186

1187 1188 1189 1190
class FuchsiaDeviceWithFakeDiscovery extends FuchsiaDevice {
  FuchsiaDeviceWithFakeDiscovery(String id, {String name}) : super(id, name: name);

  @override
1191 1192 1193
  FuchsiaIsolateDiscoveryProtocol getIsolateDiscoveryProtocol(String isolateName) {
    return FakeFuchsiaIsolateDiscoveryProtocol();
  }
1194 1195 1196

  @override
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.fuchsia_arm64;
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207
}

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

  @override
  void dispose() {}
}

class FakeFuchsiaAmberCtl implements FuchsiaAmberCtl {
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
  @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;
  }
1222 1223 1224 1225 1226 1227 1228

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

  @override
1229
  Future<bool> pkgCtlResolve(FuchsiaDevice device, FuchsiaPackageServer server, String packageName) async {
1230 1231 1232 1233 1234 1235 1236
    return true;
  }

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

1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253
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;
  }
1254 1255 1256 1257 1258 1259 1260

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

  @override
1261
  Future<bool> pkgCtlResolve(FuchsiaDevice device, FuchsiaPackageServer server, String packageName) async {
1262 1263 1264 1265 1266 1267 1268
    return false;
  }

  @override
  Future<bool> pkgCtlRepoRemove(FuchsiaDevice device, FuchsiaPackageServer server) async {
    return false;
  }
1269 1270 1271
}

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

1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352
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();

1353
  @override
1354
  final FuchsiaAmberCtl amberCtl;
1355 1356

  @override
1357
  final FuchsiaTilesCtl tilesCtl;
1358 1359
}

1360
class FakeFuchsiaPM implements FuchsiaPM {
1361 1362 1363 1364
  String _appName;

  @override
  Future<bool> init(String buildPath, String appName) async {
1365
    if (!globals.fs.directory(buildPath).existsSync()) {
1366 1367
      return false;
    }
1368 1369
    globals.fs
        .file(globals.fs.path.join(buildPath, 'meta', 'package'))
1370 1371 1372 1373 1374 1375 1376
        .createSync(recursive: true);
    _appName = appName;
    return true;
  }

  @override
  Future<bool> genkey(String buildPath, String outKeyPath) async {
1377
    if (!globals.fs.file(globals.fs.path.join(buildPath, 'meta', 'package')).existsSync()) {
1378 1379
      return false;
    }
1380
    globals.fs.file(outKeyPath).createSync(recursive: true);
1381 1382 1383 1384
    return true;
  }

  @override
1385
  Future<bool> build(String buildPath, String keyPath, String manifestPath) async {
1386 1387 1388
    if (!globals.fs.file(globals.fs.path.join(buildPath, 'meta', 'package')).existsSync() ||
        !globals.fs.file(keyPath).existsSync() ||
        !globals.fs.file(manifestPath).existsSync()) {
1389 1390
      return false;
    }
1391
    globals.fs.file(globals.fs.path.join(buildPath, 'meta.far')).createSync(recursive: true);
1392 1393 1394 1395
    return true;
  }

  @override
1396
  Future<bool> archive(String buildPath, String keyPath, String manifestPath) async {
1397 1398 1399
    if (!globals.fs.file(globals.fs.path.join(buildPath, 'meta', 'package')).existsSync() ||
        !globals.fs.file(keyPath).existsSync() ||
        !globals.fs.file(manifestPath).existsSync()) {
1400 1401 1402 1403 1404
      return false;
    }
    if (_appName == null) {
      return false;
    }
1405 1406
    globals.fs
        .file(globals.fs.path.join(buildPath, '$_appName-0.far'))
1407 1408 1409 1410 1411 1412
        .createSync(recursive: true);
    return true;
  }

  @override
  Future<bool> newrepo(String repoPath) async {
1413
    if (!globals.fs.directory(repoPath).existsSync()) {
1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425
      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 {
1426
    if (!globals.fs.directory(repoPath).existsSync()) {
1427 1428
      return false;
    }
1429
    if (!globals.fs.file(packagePath).existsSync()) {
1430 1431 1432 1433 1434 1435
      return false;
    }
    return true;
  }
}

1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447
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
1448
  Future<bool> build(String buildPath, String keyPath, String manifestPath) async {
1449 1450 1451 1452
    return false;
  }

  @override
1453
  Future<bool> archive(String buildPath, String keyPath, String manifestPath) async {
1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473
    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 {
1474 1475 1476 1477 1478 1479 1480 1481
  @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;
1482 1483
    final String manifestPath = globals.fs.path.join(outDir, '$appName.dilpmanifest');
    globals.fs.file(manifestPath).createSync(recursive: true);
1484 1485 1486
  }
}

1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498
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 {
1499
  @override
1500
  Future<List<String>> list({ Duration timeout }) async {
1501 1502 1503 1504
    return <String>['192.168.42.172 scare-cable-skip-joy'];
  }

  @override
1505
  Future<String> resolve(String deviceName, {bool local = false}) async {
1506 1507 1508 1509
    return '192.168.42.10';
  }
}

1510 1511
class FailingDevFinder implements FuchsiaDevFinder {
  @override
1512
  Future<List<String>> list({ Duration timeout }) async {
1513 1514 1515 1516
    return null;
  }

  @override
1517
  Future<String> resolve(String deviceName, {bool local = false}) async {
1518 1519 1520 1521
    return null;
  }
}

1522
class MockFuchsiaSdk extends Mock implements FuchsiaSdk {
1523 1524 1525 1526 1527 1528 1529 1530
  MockFuchsiaSdk({
    FuchsiaPM pm,
    FuchsiaKernelCompiler compiler,
    FuchsiaDevFinder devFinder,
  }) : fuchsiaPM = pm ?? FakeFuchsiaPM(),
       fuchsiaKernelCompiler = compiler ?? FakeFuchsiaKernelCompiler(),
       fuchsiaDevFinder = devFinder ?? FakeFuchsiaDevFinder();

1531
  @override
1532
  final FuchsiaPM fuchsiaPM;
1533 1534

  @override
1535
  final FuchsiaKernelCompiler fuchsiaKernelCompiler;
1536 1537

  @override
1538
  final FuchsiaDevFinder fuchsiaDevFinder;
1539
}
1540 1541

class MockFuchsiaWorkflow extends Mock implements FuchsiaWorkflow {}