drive_test.dart 28.6 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 6
import 'dart:async';

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

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

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

36 37 38 39
    setUpAll(() {
      Cache.disableLocking();
    });

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

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

71 72 73
    void applyDdsMocks(Device device) {
      final MockDartDevelopmentService mockDds = MockDartDevelopmentService();
      when(device.dds).thenReturn(mockDds);
74
      when(mockDds.startDartDevelopmentService(any, any)).thenReturn(null);
75 76
    }

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

80 81 82
      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);
83

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

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

105 106
      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
107

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

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

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

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

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

179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197
      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 {
198 199 200
      final MockAndroidDevice mockDevice = MockAndroidDevice();
      applyDdsMocks(mockDevice);
      testDeviceManager.addDevice(mockDevice);
201

202 203
      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
204

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

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

223
      final List<String> args = <String>[
yjbanov's avatar
yjbanov committed
224 225
        'drive',
        '--target=$testApp',
226
        '--no-pub',
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
    group('findTargetDevice', () {
      testUsingContext('uses specified device', () async {
        testDeviceManager.specifiedDeviceId = '123';
279
        final Device mockDevice = MockDevice();
280
        testDeviceManager.addDevice(mockDevice);
281 282 283
        when(mockDevice.name).thenReturn('specified-device');
        when(mockDevice.id).thenReturn('123');

284
        final Device device = await findTargetDevice(timeout: null);
285
        expect(device.name, 'specified-device');
286
      }, overrides: <Type, Generator>{
287
        FileSystem: () => fs,
288
        ProcessManager: () => FakeProcessManager.any(),
289 290 291
      });
    });

292
    void findTargetDeviceOnOperatingSystem(String operatingSystem) {
293
      Platform platform() => FakePlatform(operatingSystem: operatingSystem);
294 295

      testUsingContext('returns null if no devices found', () async {
296
        expect(await findTargetDevice(timeout: null), isNull);
297
      }, overrides: <Type, Generator>{
298
        FileSystem: () => fs,
299
        ProcessManager: () => FakeProcessManager.any(),
300
        Platform: platform,
301 302 303
      });

      testUsingContext('uses existing Android device', () async {
304
        final Device mockDevice = MockAndroidDevice();
305
        when(mockDevice.name).thenReturn('mock-android-device');
306 307
        testDeviceManager.addDevice(mockDevice);

308
        final Device device = await findTargetDevice(timeout: null);
309 310 311
        expect(device.name, 'mock-android-device');
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
312
        ProcessManager: () => FakeProcessManager.any(),
313 314 315 316
        Platform: platform,
      });

      testUsingContext('skips unsupported device', () async {
317
        final Device mockDevice = MockAndroidDevice();
318 319 320
        mockUnsupportedDevice = MockDevice();
        when(mockUnsupportedDevice.isSupportedForProject(any))
            .thenReturn(false);
321 322 323 324 325 326 327 328 329 330 331
        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);
332 333
        when(mockDevice.isSupportedForProject(any))
            .thenReturn(true);
334 335 336
        when(mockDevice.targetPlatform).thenAnswer((_) => Future<TargetPlatform>(() => TargetPlatform.android_x64));
        when(mockDevice.isLocalEmulator).thenAnswer((_) => Future<bool>(() => false));
        when(mockDevice.sdkNameAndVersion).thenAnswer((_) => Future<String>(() => 'sdk-28'));
337 338
        testDeviceManager.addDevice(mockDevice);
        testDeviceManager.addDevice(mockUnsupportedDevice);
339

340
        final Device device = await findTargetDevice(timeout: null);
341
        expect(device.name, 'mock-android-device');
342
      }, overrides: <Type, Generator>{
343
        FileSystem: () => fs,
344
        ProcessManager: () => FakeProcessManager.any(),
345
        Platform: platform,
346
      });
347 348 349
    }

    group('findTargetDevice on Linux', () {
350
      findTargetDeviceOnOperatingSystem('linux');
351 352 353
    });

    group('findTargetDevice on Windows', () {
354
      findTargetDeviceOnOperatingSystem('windows');
355
    });
356 357 358 359

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

360
      Platform macOsPlatform() => FakePlatform(operatingSystem: 'macos');
361 362

      testUsingContext('uses existing simulator', () async {
363
        final Device mockDevice = MockDevice();
364
        testDeviceManager.addDevice(mockDevice);
365
        when(mockDevice.name).thenReturn('mock-simulator');
366
        when(mockDevice.isLocalEmulator)
367
            .thenAnswer((Invocation invocation) => Future<bool>.value(true));
368

369
        final Device device = await findTargetDevice(timeout: null);
370 371 372
        expect(device.name, 'mock-simulator');
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
373
        ProcessManager: () => FakeProcessManager.any(),
374 375 376
        Platform: macOsPlatform,
      });
    });
377 378 379 380 381 382 383 384

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

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

385 386
      Future<Device> appStarterSetup() async {
        final Device mockDevice = MockDevice();
387
        applyDdsMocks(mockDevice);
388
        testDeviceManager.addDevice(mockDevice);
389

390
        final FakeDeviceLogReader mockDeviceLogReader = FakeDeviceLogReader();
391 392 393 394
        when(mockDevice.getLogReader()).thenReturn(mockDeviceLogReader);
        final MockLaunchResult mockLaunchResult = MockLaunchResult();
        when(mockLaunchResult.started).thenReturn(true);
        when(mockDevice.startApp(
395 396 397 398 399 400 401
          null,
          mainPath: anyNamed('mainPath'),
          route: anyNamed('route'),
          debuggingOptions: anyNamed('debuggingOptions'),
          platformArgs: anyNamed('platformArgs'),
          prebuiltApplication: anyNamed('prebuiltApplication'),
          userIdentifier: anyNamed('userIdentifier'),
402
        )).thenAnswer((_) => Future<LaunchResult>.value(mockLaunchResult));
403 404
        when(mockDevice.isAppInstalled(any, userIdentifier: anyNamed('userIdentifier')))
          .thenAnswer((_) => Future<bool>.value(false));
405

406 407
        testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
        testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
408

409
        testRunner = (List<String> testArgs, Map<String, String> environment) async {
410 411 412 413 414 415 416 417 418 419 420 421
          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() {}');
422
        return mockDevice;
423 424 425
      }

      testUsingContext('does not use pre-built app if no build arg provided', () async {
426
        final Device mockDevice = await appStarterSetup();
427 428 429 430

        final List<String> args = <String>[
          'drive',
          '--target=$testApp',
431
          '--no-pub',
432 433 434 435 436 437 438 439 440 441 442 443 444 445
        ];
        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,
446
                userIdentifier: anyNamed('userIdentifier'),
447 448 449
        ));
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
450
        ProcessManager: () => FakeProcessManager.any(),
451 452 453
      });

      testUsingContext('does not use pre-built app if --build arg provided', () async {
454
        final Device mockDevice = await appStarterSetup();
455 456 457 458 459

        final List<String> args = <String>[
          'drive',
          '--build',
          '--target=$testApp',
460
          '--no-pub',
461 462 463 464 465 466 467 468 469 470 471 472 473 474
        ];
        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,
475
                userIdentifier: anyNamed('userIdentifier'),
476 477 478
        ));
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
479
        ProcessManager: () => FakeProcessManager.any(),
480 481 482
      });

      testUsingContext('uses prebuilt app if --no-build arg provided', () async {
483
        final Device mockDevice = await appStarterSetup();
484 485 486 487 488

        final List<String> args = <String>[
          'drive',
          '--no-build',
          '--target=$testApp',
489
          '--no-pub',
490 491 492 493 494 495 496 497 498 499 500 501 502 503
        ];
        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,
504
                userIdentifier: anyNamed('userIdentifier'),
505 506 507
        ));
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
508
        ProcessManager: () => FakeProcessManager.any(),
509 510
      });
    });
511 512 513 514 515 516 517 518 519 520

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

      String testApp, testFile;

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

521 522
      Future<Device> appStarterSetup() async {
        final Device mockDevice = MockDevice();
523
        applyDdsMocks(mockDevice);
524 525
        testDeviceManager.addDevice(mockDevice);

526
        final FakeDeviceLogReader mockDeviceLogReader = FakeDeviceLogReader();
527 528 529 530 531 532 533 534 535 536
        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'),
537
          userIdentifier: anyNamed('userIdentifier'),
538
        )).thenAnswer((Invocation invocation) async {
539
          debuggingOptions = invocation.namedArguments[#debuggingOptions] as DebuggingOptions;
540 541
          return mockLaunchResult;
        });
542
        when(mockDevice.isAppInstalled(any, userIdentifier: anyNamed('userIdentifier')))
543 544
            .thenAnswer((_) => Future<bool>.value(false));

545 546
        testApp = globals.fs.path.join(tempDir.path, 'test', 'e2e.dart');
        testFile = globals.fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
547

548
        testRunner = (List<String> testArgs, Map<String, String> environment) async {
549 550 551 552 553 554 555 556 557 558 559 560
          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() {}');
561
        return mockDevice;
562 563 564 565 566 567 568 569
      }

      void _testOptionThatDefaultsToFalse(
        String optionName,
        bool setToTrue,
        bool optionValue(),
      ) {
        testUsingContext('$optionName ${setToTrue ? 'works' : 'defaults to false'}', () async {
570
          final Device mockDevice = await appStarterSetup();
571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590

          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,
591
            userIdentifier: anyNamed('userIdentifier'),
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
          ));
          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,
      );
622 623 624 625 626

      testOptionThatDefaultsToFalse(
        '--purge-persistent-cache',
        () => debuggingOptions.purgePersistentCache,
      );
627
    });
628
  });
629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662

  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', () {
663
      const String chromeBinary = 'random-binary';
664 665 666 667 668
      final Map<String, dynamic> expected = <String, dynamic>{
        'acceptInsecureCerts': true,
        'browserName': 'chrome',
        'goog:loggingPrefs': <String, String>{ sync_io.LogType.performance: 'ALL'},
        'chromeOptions': <String, dynamic>{
669
          'binary': chromeBinary,
670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690
          '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'
          }
        }
      };

691
      expect(getDesiredCapabilities(Browser.chrome, false, chromeBinary), expected);
692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766

    });

    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);
    });
767 768 769 770 771 772 773 774 775 776 777 778 779

    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);
    });
780
  });
781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802

  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
803
}
804 805 806

class MockDevice extends Mock implements Device {
  MockDevice() {
807
    when(isSupported()).thenReturn(true);
808 809 810 811
  }
}

class MockAndroidDevice extends Mock implements AndroidDevice { }
812
class MockDartDevelopmentService extends Mock implements DartDevelopmentService { }
813
class MockLaunchResult extends Mock implements LaunchResult { }