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

5
import 'package:file/memory.dart';
6
import 'package:file_testing/file_testing.dart';
7
import 'package:flutter_tools/src/android/android_device.dart';
8
import 'package:flutter_tools/src/base/common.dart';
9
import 'package:flutter_tools/src/base/dds.dart';
yjbanov's avatar
yjbanov committed
10
import 'package:flutter_tools/src/base/file_system.dart';
11
import 'package:flutter_tools/src/base/io.dart';
12 13
import 'package:flutter_tools/src/base/platform.dart';
import 'package:flutter_tools/src/build_info.dart';
14
import 'package:flutter_tools/src/cache.dart';
15 16
import 'package:flutter_tools/src/commands/drive.dart';
import 'package:flutter_tools/src/device.dart';
17
import 'package:flutter_tools/src/globals.dart' as globals;
18
import 'package:mockito/mockito.dart';
19
import 'package:webdriver/sync_io.dart' as sync_io;
20
import 'package:flutter_tools/src/vmservice.dart';
yjbanov's avatar
yjbanov committed
21

22 23
import '../../src/common.dart';
import '../../src/context.dart';
24
import '../../src/fakes.dart';
25
import '../../src/mocks.dart';
yjbanov's avatar
yjbanov committed
26

27
void main() {
yjbanov's avatar
yjbanov committed
28
  group('drive', () {
29
    DriveCommand command;
30
    Device mockUnsupportedDevice;
31
    MemoryFileSystem fs;
32
    Directory tempDir;
33

34 35 36 37
    setUpAll(() {
      Cache.disableLocking();
    });

yjbanov's avatar
yjbanov committed
38
    setUp(() {
39
      command = DriveCommand();
40
      applyMocksToCommand(command);
41
      fs = MemoryFileSystem();
42 43
      tempDir = fs.systemTempDirectory.createTempSync('flutter_drive_test.');
      fs.currentDirectory = tempDir;
44 45
      fs.directory('test').createSync();
      fs.directory('test_driver').createSync();
46
      fs.file('pubspec.yaml').createSync();
47
      fs.file('.packages').createSync();
48
      setExitFunctionForTests();
49
      appStarter = (DriveCommand command, Uri webUri) {
50 51
        throw 'Unexpected call to appStarter';
      };
52
      testRunner = (List<String> testArgs, Map<String, String> environment) {
53 54
        throw 'Unexpected call to testRunner';
      };
55
      appStopper = (DriveCommand command) {
56 57
        throw 'Unexpected call to appStopper';
      };
yjbanov's avatar
yjbanov committed
58 59 60
    });

    tearDown(() {
61
      command = null;
62
      restoreExitFunction();
63 64 65
      restoreAppStarter();
      restoreAppStopper();
      restoreTestRunner();
66
      tryToDelete(tempDir);
yjbanov's avatar
yjbanov committed
67 68
    });

69 70 71
    void applyDdsMocks(Device device) {
      final MockDartDevelopmentService mockDds = MockDartDevelopmentService();
      when(device.dds).thenReturn(mockDds);
72 73
      when(mockDds.startDartDevelopmentService(any, any, any, any)).thenReturn(null);
      when(mockDds.uri).thenReturn(Uri.parse('http://localhost:8181'));
74 75
    }

76
    testUsingContext('returns 1 when test file is not found', () async {
77
      testDeviceManager.addDevice(MockDevice());
78

79 80 81
      final String testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
      final String testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
      globals.fs.file(testApp).createSync(recursive: true);
82

83
      final List<String> args = <String>[
yjbanov's avatar
yjbanov committed
84
        'drive',
85
        '--target=$testApp',
86
        '--no-pub',
yjbanov's avatar
yjbanov committed
87
      ];
88 89 90 91 92
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode ?? 1, 1);
93
        expect(e.message, contains('Test file not found: $testFile'));
94
      }
95
    }, overrides: <Type, Generator>{
96
      FileSystem: () => fs,
97
      ProcessManager: () => FakeProcessManager.any(),
yjbanov's avatar
yjbanov committed
98 99 100
    });

    testUsingContext('returns 1 when app fails to run', () async {
101
      testDeviceManager.addDevice(MockDevice());
102
      appStarter = expectAsync2((DriveCommand command, Uri webUri) async => null);
yjbanov's avatar
yjbanov committed
103

104 105
      final String testApp = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e.dart');
      final String testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
yjbanov's avatar
yjbanov committed
106

107
      final MemoryFileSystem memFs = fs;
108 109
      await memFs.file(testApp).writeAsString('main() { }');
      await memFs.file(testFile).writeAsString('main() { }');
yjbanov's avatar
yjbanov committed
110

111
      final List<String> args = <String>[
yjbanov's avatar
yjbanov committed
112 113
        'drive',
        '--target=$testApp',
114
        '--no-pub',
yjbanov's avatar
yjbanov committed
115
      ];
116 117 118 119 120
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode, 1);
121
        expect(e.message, contains('Application failed to start. Will not run test. Quitting.'));
122
      }
123
    }, overrides: <Type, Generator>{
124
      FileSystem: () => fs,
125
      ProcessManager: () => FakeProcessManager.any(),
yjbanov's avatar
yjbanov committed
126 127
    });

128
    testUsingContext('returns 1 when app file is outside package', () async {
129 130
      final String appFile = globals.fs.path.join(tempDir.dirname, 'other_app', 'app.dart');
      globals.fs.file(appFile).createSync(recursive: true);
131
      final List<String> args = <String>[
132
        '--no-wrap',
133 134
        'drive',
        '--target=$appFile',
135
        '--no-pub',
136
      ];
137 138 139 140 141 142
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode ?? 1, 1);
        expect(testLogger.errorText, contains(
143
            'Application file $appFile is outside the package directory ${tempDir.path}',
144
        ));
145
      }
146
    }, overrides: <Type, Generator>{
147
      FileSystem: () => fs,
148
      ProcessManager: () => FakeProcessManager.any(),
149 150 151
    });

    testUsingContext('returns 1 when app file is in the root dir', () async {
152 153
      final String appFile = globals.fs.path.join(tempDir.path, 'main.dart');
      globals.fs.file(appFile).createSync(recursive: true);
154
      final List<String> args = <String>[
155
        '--no-wrap',
156 157
        'drive',
        '--target=$appFile',
158
        '--no-pub',
159
      ];
160 161 162 163 164 165
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode ?? 1, 1);
        expect(testLogger.errorText, contains(
166 167
            'Application file main.dart must reside in one of the '
            'sub-directories of the package structure, not in the root directory.',
168
        ));
169
      }
170
    }, overrides: <Type, Generator>{
171
      FileSystem: () => fs,
172
      ProcessManager: () => FakeProcessManager.any(),
173 174
    });

175
    testUsingContext('returns 1 when targeted device is not Android with --device-user', () async {
176
      testDeviceManager.addDevice(MockDevice());
177

178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196
      final String testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
      globals.fs.file(testApp).createSync(recursive: true);

      final List<String> args = <String>[
        'drive',
        '--target=$testApp',
        '--no-pub',
        '--device-user',
        '10',
      ];

      expect(() async => await createTestCommandRunner(command).run(args),
        throwsToolExit(message: '--device-user is only supported for Android'));
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
      ProcessManager: () => FakeProcessManager.any(),
    });

    testUsingContext('returns 0 when test ends successfully', () async {
197 198 199
      final MockAndroidDevice mockDevice = MockAndroidDevice();
      applyDdsMocks(mockDevice);
      testDeviceManager.addDevice(mockDevice);
200

201 202
      final String testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
      final String testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
yjbanov's avatar
yjbanov committed
203

204
      appStarter = expectAsync2((DriveCommand command, Uri webUri) async {
205
        return LaunchResult.succeeded();
206
      });
207
      testRunner = expectAsync2((List<String> testArgs, Map<String, String> environment) async {
208
        expect(testArgs, <String>['--no-sound-null-safety', testFile]);
209 210 211 212
        // VM_SERVICE_URL is not set by drive command arguments
        expect(environment, <String, String>{
          'VM_SERVICE_URL': 'null',
        });
213
      });
214
      appStopper = expectAsync1((DriveCommand command) async {
215
        return true;
216
      });
yjbanov's avatar
yjbanov committed
217

218
      final MemoryFileSystem memFs = fs;
yjbanov's avatar
yjbanov committed
219 220 221
      await memFs.file(testApp).writeAsString('main() {}');
      await memFs.file(testFile).writeAsString('main() {}');

222
      final List<String> args = <String>[
yjbanov's avatar
yjbanov committed
223 224
        'drive',
        '--target=$testApp',
225
        '--no-pub',
226
        '--disable-dds',
227 228
        '--device-user',
        '10',
yjbanov's avatar
yjbanov committed
229
      ];
230 231
      await createTestCommandRunner(command).run(args);
      expect(testLogger.errorText, isEmpty);
232
    }, overrides: <Type, Generator>{
233
      FileSystem: () => fs,
234
      ProcessManager: () => FakeProcessManager.any(),
yjbanov's avatar
yjbanov committed
235
    });
236

237
    testUsingContext('returns exitCode set by test runner', () async {
238 239 240
      final MockDevice mockDevice = MockDevice();
      applyDdsMocks(mockDevice);
      testDeviceManager.addDevice(mockDevice);
241

242 243
      final String testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
      final String testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
244

245
      appStarter = expectAsync2((DriveCommand command, Uri webUri) async {
246
        return LaunchResult.succeeded();
247
      });
248
      testRunner = (List<String> testArgs, Map<String, String> environment) async {
249 250
        throwToolExit(null, exitCode: 123);
      };
251
      appStopper = expectAsync1((DriveCommand command) async {
252
        return true;
253 254
      });

255
      final MemoryFileSystem memFs = fs;
256 257 258
      await memFs.file(testApp).writeAsString('main() {}');
      await memFs.file(testFile).writeAsString('main() {}');

259
      final List<String> args = <String>[
260 261
        'drive',
        '--target=$testApp',
262
        '--no-pub',
263
      ];
264 265 266 267 268 269 270
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode ?? 1, 123);
        expect(e.message, isNull);
      }
271
    }, overrides: <Type, Generator>{
272
      FileSystem: () => fs,
273
      ProcessManager: () => FakeProcessManager.any(),
274 275
    });

276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359
    testUsingContext('enable experiment', () async {
      final MockAndroidDevice mockDevice = MockAndroidDevice();
      applyDdsMocks(mockDevice);
      testDeviceManager.addDevice(mockDevice);

      final String testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
      final String testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');

      appStarter = expectAsync2((DriveCommand command, Uri webUri) async {
        return LaunchResult.succeeded();
      });
      testRunner = expectAsync2((List<String> testArgs, Map<String, String> environment) async {
        expect(
          testArgs,
          <String>[
            '--enable-experiment=experiment1,experiment2',
            '--no-sound-null-safety',
            testFile,
          ]
        );
      });
      appStopper = expectAsync1((DriveCommand command) async {
        return true;
      });

      final MemoryFileSystem memFs = fs;
      await memFs.file(testApp).writeAsString('main() {}');
      await memFs.file(testFile).writeAsString('main() {}');

      final List<String> args = <String>[
        'drive',
        '--target=$testApp',
        '--no-pub',
        '--enable-experiment=experiment1',
        '--enable-experiment=experiment2',
      ];
      await createTestCommandRunner(command).run(args);
      expect(testLogger.errorText, isEmpty);
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
      ProcessManager: () => FakeProcessManager.any(),
    });

    testUsingContext('sound null safety', () async {
      final MockAndroidDevice mockDevice = MockAndroidDevice();
      applyDdsMocks(mockDevice);
      testDeviceManager.addDevice(mockDevice);

      final String testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
      final String testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');

      appStarter = expectAsync2((DriveCommand command, Uri webUri) async {
        return LaunchResult.succeeded();
      });
      testRunner = expectAsync2((List<String> testArgs, Map<String, String> environment) async {
        expect(
          testArgs,
          <String>[
            '--sound-null-safety',
            testFile,
          ]
        );
      });
      appStopper = expectAsync1((DriveCommand command) async {
        return true;
      });

      final MemoryFileSystem memFs = fs;
      await memFs.file(testApp).writeAsString('main() {}');
      await memFs.file(testFile).writeAsString('main() {}');

      final List<String> args = <String>[
        'drive',
        '--target=$testApp',
        '--no-pub',
        '--sound-null-safety',
      ];
      await createTestCommandRunner(command).run(args);
      expect(testLogger.errorText, isEmpty);
    }, overrides: <Type, Generator>{
      FileSystem: () => fs,
      ProcessManager: () => FakeProcessManager.any(),
    });

360 361 362
    group('findTargetDevice', () {
      testUsingContext('uses specified device', () async {
        testDeviceManager.specifiedDeviceId = '123';
363
        final Device mockDevice = MockDevice();
364
        testDeviceManager.addDevice(mockDevice);
365 366 367
        when(mockDevice.name).thenReturn('specified-device');
        when(mockDevice.id).thenReturn('123');

368
        final Device device = await findTargetDevice(timeout: null);
369
        expect(device.name, 'specified-device');
370
      }, overrides: <Type, Generator>{
371
        FileSystem: () => fs,
372
        ProcessManager: () => FakeProcessManager.any(),
373 374 375
      });
    });

376
    void findTargetDeviceOnOperatingSystem(String operatingSystem) {
377
      Platform platform() => FakePlatform(operatingSystem: operatingSystem);
378 379

      testUsingContext('returns null if no devices found', () async {
380
        expect(await findTargetDevice(timeout: null), isNull);
381
      }, overrides: <Type, Generator>{
382
        FileSystem: () => fs,
383
        ProcessManager: () => FakeProcessManager.any(),
384
        Platform: platform,
385 386 387
      });

      testUsingContext('uses existing Android device', () async {
388
        final Device mockDevice = MockAndroidDevice();
389
        when(mockDevice.name).thenReturn('mock-android-device');
390 391
        testDeviceManager.addDevice(mockDevice);

392
        final Device device = await findTargetDevice(timeout: null);
393 394 395
        expect(device.name, 'mock-android-device');
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
396
        ProcessManager: () => FakeProcessManager.any(),
397 398 399 400
        Platform: platform,
      });

      testUsingContext('skips unsupported device', () async {
401
        final Device mockDevice = MockAndroidDevice();
402 403 404
        mockUnsupportedDevice = MockDevice();
        when(mockUnsupportedDevice.isSupportedForProject(any))
            .thenReturn(false);
405 406 407 408 409 410 411 412 413 414 415
        when(mockUnsupportedDevice.isSupported())
            .thenReturn(false);
        when(mockUnsupportedDevice.name).thenReturn('mock-web');
        when(mockUnsupportedDevice.id).thenReturn('web-1');
        when(mockUnsupportedDevice.targetPlatform).thenAnswer((_) => Future<TargetPlatform>(() => TargetPlatform.web_javascript));
        when(mockUnsupportedDevice.isLocalEmulator).thenAnswer((_) => Future<bool>(() => false));
        when(mockUnsupportedDevice.sdkNameAndVersion).thenAnswer((_) => Future<String>(() => 'html5'));
        when(mockDevice.name).thenReturn('mock-android-device');
        when(mockDevice.id).thenReturn('mad-28');
        when(mockDevice.isSupported())
            .thenReturn(true);
416 417
        when(mockDevice.isSupportedForProject(any))
            .thenReturn(true);
418 419 420
        when(mockDevice.targetPlatform).thenAnswer((_) => Future<TargetPlatform>(() => TargetPlatform.android_x64));
        when(mockDevice.isLocalEmulator).thenAnswer((_) => Future<bool>(() => false));
        when(mockDevice.sdkNameAndVersion).thenAnswer((_) => Future<String>(() => 'sdk-28'));
421 422
        testDeviceManager.addDevice(mockDevice);
        testDeviceManager.addDevice(mockUnsupportedDevice);
423

424
        final Device device = await findTargetDevice(timeout: null);
425
        expect(device.name, 'mock-android-device');
426
      }, overrides: <Type, Generator>{
427
        FileSystem: () => fs,
428
        ProcessManager: () => FakeProcessManager.any(),
429
        Platform: platform,
430
      });
431 432 433
    }

    group('findTargetDevice on Linux', () {
434
      findTargetDeviceOnOperatingSystem('linux');
435 436 437
    });

    group('findTargetDevice on Windows', () {
438
      findTargetDeviceOnOperatingSystem('windows');
439
    });
440 441 442 443

    group('findTargetDevice on macOS', () {
      findTargetDeviceOnOperatingSystem('macos');

444
      Platform macOsPlatform() => FakePlatform(operatingSystem: 'macos');
445 446

      testUsingContext('uses existing simulator', () async {
447
        final Device mockDevice = MockDevice();
448
        testDeviceManager.addDevice(mockDevice);
449
        when(mockDevice.name).thenReturn('mock-simulator');
450
        when(mockDevice.isLocalEmulator)
451
            .thenAnswer((Invocation invocation) => Future<bool>.value(true));
452

453
        final Device device = await findTargetDevice(timeout: null);
454 455 456
        expect(device.name, 'mock-simulator');
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
457
        ProcessManager: () => FakeProcessManager.any(),
458 459 460
        Platform: macOsPlatform,
      });
    });
461 462 463 464 465 466 467 468

    group('build arguments', () {
      String testApp, testFile;

      setUp(() {
        restoreAppStarter();
      });

469 470
      Future<Device> appStarterSetup() async {
        final Device mockDevice = MockDevice();
471
        applyDdsMocks(mockDevice);
472
        testDeviceManager.addDevice(mockDevice);
473

474
        final FakeDeviceLogReader mockDeviceLogReader = FakeDeviceLogReader();
475 476 477 478
        when(mockDevice.getLogReader()).thenReturn(mockDeviceLogReader);
        final MockLaunchResult mockLaunchResult = MockLaunchResult();
        when(mockLaunchResult.started).thenReturn(true);
        when(mockDevice.startApp(
479 480 481 482 483 484 485
          null,
          mainPath: anyNamed('mainPath'),
          route: anyNamed('route'),
          debuggingOptions: anyNamed('debuggingOptions'),
          platformArgs: anyNamed('platformArgs'),
          prebuiltApplication: anyNamed('prebuiltApplication'),
          userIdentifier: anyNamed('userIdentifier'),
486
        )).thenAnswer((_) => Future<LaunchResult>.value(mockLaunchResult));
487 488
        when(mockDevice.isAppInstalled(any, userIdentifier: anyNamed('userIdentifier')))
          .thenAnswer((_) => Future<bool>.value(false));
489

490 491
        testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
        testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
492

493
        testRunner = (List<String> testArgs, Map<String, String> environment) async {
494 495 496 497 498 499 500 501 502 503 504 505
          throwToolExit(null, exitCode: 123);
        };
        appStopper = expectAsync1(
            (DriveCommand command) async {
              return true;
            },
            count: 2,
        );

        final MemoryFileSystem memFs = fs;
        await memFs.file(testApp).writeAsString('main() {}');
        await memFs.file(testFile).writeAsString('main() {}');
506
        return mockDevice;
507 508 509
      }

      testUsingContext('does not use pre-built app if no build arg provided', () async {
510
        final Device mockDevice = await appStarterSetup();
511 512 513 514

        final List<String> args = <String>[
          'drive',
          '--target=$testApp',
515
          '--no-pub',
516 517 518 519 520 521 522 523 524 525 526 527 528 529
        ];
        try {
          await createTestCommandRunner(command).run(args);
        } on ToolExit catch (e) {
          expect(e.exitCode, 123);
          expect(e.message, null);
        }
        verify(mockDevice.startApp(
                null,
                mainPath: anyNamed('mainPath'),
                route: anyNamed('route'),
                debuggingOptions: anyNamed('debuggingOptions'),
                platformArgs: anyNamed('platformArgs'),
                prebuiltApplication: false,
530
                userIdentifier: anyNamed('userIdentifier'),
531 532 533
        ));
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
534
        ProcessManager: () => FakeProcessManager.any(),
535 536 537
      });

      testUsingContext('does not use pre-built app if --build arg provided', () async {
538
        final Device mockDevice = await appStarterSetup();
539 540 541 542 543

        final List<String> args = <String>[
          'drive',
          '--build',
          '--target=$testApp',
544
          '--no-pub',
545 546 547 548 549 550 551 552 553 554 555 556 557 558
        ];
        try {
          await createTestCommandRunner(command).run(args);
        } on ToolExit catch (e) {
          expect(e.exitCode, 123);
          expect(e.message, null);
        }
        verify(mockDevice.startApp(
                null,
                mainPath: anyNamed('mainPath'),
                route: anyNamed('route'),
                debuggingOptions: anyNamed('debuggingOptions'),
                platformArgs: anyNamed('platformArgs'),
                prebuiltApplication: false,
559
                userIdentifier: anyNamed('userIdentifier'),
560 561 562
        ));
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
563
        ProcessManager: () => FakeProcessManager.any(),
564 565 566
      });

      testUsingContext('uses prebuilt app if --no-build arg provided', () async {
567
        final Device mockDevice = await appStarterSetup();
568 569 570 571 572

        final List<String> args = <String>[
          'drive',
          '--no-build',
          '--target=$testApp',
573
          '--no-pub',
574 575 576 577 578 579 580 581 582 583 584 585 586 587
        ];
        try {
          await createTestCommandRunner(command).run(args);
        } on ToolExit catch (e) {
          expect(e.exitCode, 123);
          expect(e.message, null);
        }
        verify(mockDevice.startApp(
                null,
                mainPath: anyNamed('mainPath'),
                route: anyNamed('route'),
                debuggingOptions: anyNamed('debuggingOptions'),
                platformArgs: anyNamed('platformArgs'),
                prebuiltApplication: true,
588
                userIdentifier: anyNamed('userIdentifier'),
589 590 591
        ));
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
592
        ProcessManager: () => FakeProcessManager.any(),
593 594
      });
    });
595 596 597 598 599 600 601 602 603 604

    group('debugging options', () {
      DebuggingOptions debuggingOptions;

      String testApp, testFile;

      setUp(() {
        restoreAppStarter();
      });

605 606
      Future<Device> appStarterSetup() async {
        final Device mockDevice = MockDevice();
607
        applyDdsMocks(mockDevice);
608 609
        testDeviceManager.addDevice(mockDevice);

610
        final FakeDeviceLogReader mockDeviceLogReader = FakeDeviceLogReader();
611 612 613 614 615 616 617 618 619 620
        when(mockDevice.getLogReader()).thenReturn(mockDeviceLogReader);
        final MockLaunchResult mockLaunchResult = MockLaunchResult();
        when(mockLaunchResult.started).thenReturn(true);
        when(mockDevice.startApp(
          null,
          mainPath: anyNamed('mainPath'),
          route: anyNamed('route'),
          debuggingOptions: anyNamed('debuggingOptions'),
          platformArgs: anyNamed('platformArgs'),
          prebuiltApplication: anyNamed('prebuiltApplication'),
621
          userIdentifier: anyNamed('userIdentifier'),
622
        )).thenAnswer((Invocation invocation) async {
623
          debuggingOptions = invocation.namedArguments[#debuggingOptions] as DebuggingOptions;
624 625
          return mockLaunchResult;
        });
626
        when(mockDevice.isAppInstalled(any, userIdentifier: anyNamed('userIdentifier')))
627 628
            .thenAnswer((_) => Future<bool>.value(false));

629 630
        testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
        testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
631

632
        testRunner = (List<String> testArgs, Map<String, String> environment) async {
633 634 635 636 637 638 639 640 641 642 643 644
          throwToolExit(null, exitCode: 123);
        };
        appStopper = expectAsync1(
          (DriveCommand command) async {
            return true;
          },
          count: 2,
        );

        final MemoryFileSystem memFs = fs;
        await memFs.file(testApp).writeAsString('main() {}');
        await memFs.file(testFile).writeAsString('main() {}');
645
        return mockDevice;
646 647 648 649 650 651 652 653
      }

      void _testOptionThatDefaultsToFalse(
        String optionName,
        bool setToTrue,
        bool optionValue(),
      ) {
        testUsingContext('$optionName ${setToTrue ? 'works' : 'defaults to false'}', () async {
654
          final Device mockDevice = await appStarterSetup();
655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674

          final List<String> args = <String>[
            'drive',
            '--target=$testApp',
            if (setToTrue) optionName,
            '--no-pub',
          ];
          try {
            await createTestCommandRunner(command).run(args);
          } on ToolExit catch (e) {
            expect(e.exitCode, 123);
            expect(e.message, null);
          }
          verify(mockDevice.startApp(
            null,
            mainPath: anyNamed('mainPath'),
            route: anyNamed('route'),
            debuggingOptions: anyNamed('debuggingOptions'),
            platformArgs: anyNamed('platformArgs'),
            prebuiltApplication: false,
675
            userIdentifier: anyNamed('userIdentifier'),
676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705
          ));
          expect(optionValue(), setToTrue ? isTrue : isFalse);
        }, overrides: <Type, Generator>{
          FileSystem: () => fs,
          ProcessManager: () => FakeProcessManager.any(),
        });
      }

      void testOptionThatDefaultsToFalse(
        String optionName,
        bool optionValue(),
      ) {
        _testOptionThatDefaultsToFalse(optionName, true, optionValue);
        _testOptionThatDefaultsToFalse(optionName, false, optionValue);
      }

      testOptionThatDefaultsToFalse(
        '--dump-skp-on-shader-compilation',
        () => debuggingOptions.dumpSkpOnShaderCompilation,
      );

      testOptionThatDefaultsToFalse(
        '--verbose-system-logs',
        () => debuggingOptions.verboseSystemLogs,
      );

      testOptionThatDefaultsToFalse(
        '--cache-sksl',
        () => debuggingOptions.cacheSkSL,
      );
706 707 708 709 710

      testOptionThatDefaultsToFalse(
        '--purge-persistent-cache',
        () => debuggingOptions.purgePersistentCache,
      );
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 744 745 746

  group('getDesiredCapabilities', () {
    test('Chrome with headless on', () {
      final Map<String, dynamic> expected = <String, dynamic>{
        'acceptInsecureCerts': true,
        'browserName': 'chrome',
        'goog:loggingPrefs': <String, String>{ sync_io.LogType.performance: 'ALL'},
        'chromeOptions': <String, dynamic>{
          'w3c': false,
          'args': <String>[
            '--bwsi',
            '--disable-background-timer-throttling',
            '--disable-default-apps',
            '--disable-extensions',
            '--disable-popup-blocking',
            '--disable-translate',
            '--no-default-browser-check',
            '--no-sandbox',
            '--no-first-run',
            '--headless'
          ],
          'perfLoggingPrefs': <String, String>{
            'traceCategories':
            'devtools.timeline,'
                'v8,blink.console,benchmark,blink,'
                'blink.user_timing'
          }
        }
      };

      expect(getDesiredCapabilities(Browser.chrome, true), expected);
    });

    test('Chrome with headless off', () {
747
      const String chromeBinary = 'random-binary';
748 749 750 751 752
      final Map<String, dynamic> expected = <String, dynamic>{
        'acceptInsecureCerts': true,
        'browserName': 'chrome',
        'goog:loggingPrefs': <String, String>{ sync_io.LogType.performance: 'ALL'},
        'chromeOptions': <String, dynamic>{
753
          'binary': chromeBinary,
754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774
          'w3c': false,
          'args': <String>[
            '--bwsi',
            '--disable-background-timer-throttling',
            '--disable-default-apps',
            '--disable-extensions',
            '--disable-popup-blocking',
            '--disable-translate',
            '--no-default-browser-check',
            '--no-sandbox',
            '--no-first-run',
          ],
          'perfLoggingPrefs': <String, String>{
            'traceCategories':
            'devtools.timeline,'
                'v8,blink.console,benchmark,blink,'
                'blink.user_timing'
          }
        }
      };

775
      expect(getDesiredCapabilities(Browser.chrome, false, chromeBinary), expected);
776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850

    });

    test('Firefox with headless on', () {
      final Map<String, dynamic> expected = <String, dynamic>{
        'acceptInsecureCerts': true,
        'browserName': 'firefox',
        'moz:firefoxOptions' : <String, dynamic>{
          'args': <String>['-headless'],
          'prefs': <String, dynamic>{
            'dom.file.createInChild': true,
            'dom.timeout.background_throttling_max_budget': -1,
            'media.autoplay.default': 0,
            'media.gmp-manager.url': '',
            'media.gmp-provider.enabled': false,
            'network.captive-portal-service.enabled': false,
            'security.insecure_field_warning.contextual.enabled': false,
            'test.currentTimeOffsetSeconds': 11491200
          },
          'log': <String, String>{'level': 'trace'}
        }
      };

      expect(getDesiredCapabilities(Browser.firefox, true), expected);
    });

    test('Firefox with headless off', () {
      final Map<String, dynamic> expected = <String, dynamic>{
        'acceptInsecureCerts': true,
        'browserName': 'firefox',
        'moz:firefoxOptions' : <String, dynamic>{
          'args': <String>[],
          'prefs': <String, dynamic>{
            'dom.file.createInChild': true,
            'dom.timeout.background_throttling_max_budget': -1,
            'media.autoplay.default': 0,
            'media.gmp-manager.url': '',
            'media.gmp-provider.enabled': false,
            'network.captive-portal-service.enabled': false,
            'security.insecure_field_warning.contextual.enabled': false,
            'test.currentTimeOffsetSeconds': 11491200
          },
          'log': <String, String>{'level': 'trace'}
        }
      };

      expect(getDesiredCapabilities(Browser.firefox, false), expected);
    });

    test('Edge', () {
      final Map<String, dynamic> expected = <String, dynamic>{
        'acceptInsecureCerts': true,
        'browserName': 'edge',
      };

      expect(getDesiredCapabilities(Browser.edge, false), expected);
    });

    test('macOS Safari', () {
      final Map<String, dynamic> expected = <String, dynamic>{
        'browserName': 'safari',
      };

      expect(getDesiredCapabilities(Browser.safari, false), expected);
    });

    test('iOS Safari', () {
      final Map<String, dynamic> expected = <String, dynamic>{
        'platformName': 'ios',
        'browserName': 'safari',
        'safari:useSimulator': true
      };

      expect(getDesiredCapabilities(Browser.iosSafari, false), expected);
    });
851 852 853 854 855 856 857 858 859 860 861 862 863

    test('android chrome', () {
      final Map<String, dynamic> expected = <String, dynamic>{
        'browserName': 'chrome',
        'platformName': 'android',
        'goog:chromeOptions': <String, dynamic>{
          'androidPackage': 'com.android.chrome',
          'args': <String>['--disable-fullscreen']
        },
      };

      expect(getDesiredCapabilities(Browser.androidChrome, false), expected);
    });
864
  });
865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886

  testUsingContext('Can write SkSL file with provided output file', () async {
    final MockDevice device = MockDevice();
    when(device.name).thenReturn('foo');
    when(device.targetPlatform).thenAnswer((Invocation invocation) async {
      return TargetPlatform.android_arm;
    });
    final File outputFile = globals.fs.file('out/foo');

    final String result = await sharedSkSlWriter(
      device,
      <String, Object>{'foo': 'bar'},
      outputFile: outputFile,
    );

    expect(result, 'out/foo');
    expect(outputFile, exists);
    expect(outputFile.readAsStringSync(), '{"platform":"android","name":"foo","engineRevision":null,"data":{"foo":"bar"}}');
  }, overrides: <Type, Generator>{
    FileSystem: () => MemoryFileSystem.test(),
    ProcessManager: () => FakeProcessManager.any(),
  });
yjbanov's avatar
yjbanov committed
887
}
888 889 890

class MockDevice extends Mock implements Device {
  MockDevice() {
891
    when(isSupported()).thenReturn(true);
892 893 894 895
  }
}

class MockAndroidDevice extends Mock implements AndroidDevice { }
896
class MockDartDevelopmentService extends Mock implements DartDevelopmentService { }
897
class MockLaunchResult extends Mock implements LaunchResult { }