drive_test.dart 20.4 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:flutter_tools/src/android/android_device.dart';
9
import 'package:flutter_tools/src/base/common.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
import 'package:flutter_tools/src/base/platform.dart';
13
import 'package:flutter_tools/src/cache.dart';
14 15
import 'package:flutter_tools/src/commands/drive.dart';
import 'package:flutter_tools/src/device.dart';
16
import 'package:flutter_tools/src/build_info.dart';
17
import 'package:mockito/mockito.dart';
yjbanov's avatar
yjbanov committed
18

19 20 21
import '../../src/common.dart';
import '../../src/context.dart';
import '../../src/mocks.dart';
yjbanov's avatar
yjbanov committed
22

23
void main() {
yjbanov's avatar
yjbanov committed
24
  group('drive', () {
25 26
    DriveCommand command;
    Device mockDevice;
27
    Device mockUnsupportedDevice;
28
    MemoryFileSystem fs;
29
    Directory tempDir;
30

31 32 33 34
    setUpAll(() {
      Cache.disableLocking();
    });

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

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

66
    testUsingContext('returns 1 when test file is not found', () async {
67
      testDeviceManager.addDevice(MockDevice());
68

69 70
      final String testApp = fs.path.join(tempDir.path, 'test', 'e2e.dart');
      final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
71
      fs.file(testApp).createSync(recursive: true);
72

73
      final List<String> args = <String>[
yjbanov's avatar
yjbanov committed
74
        'drive',
75
        '--target=$testApp',
76
        '--no-pub',
yjbanov's avatar
yjbanov committed
77
      ];
78 79 80 81 82
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode ?? 1, 1);
83
        expect(e.message, contains('Test file not found: $testFile'));
84
      }
85
    }, overrides: <Type, Generator>{
86
      FileSystem: () => fs,
87
      ProcessManager: () => FakeProcessManager.any(),
yjbanov's avatar
yjbanov committed
88 89 90
    });

    testUsingContext('returns 1 when app fails to run', () async {
91
      testDeviceManager.addDevice(MockDevice());
92
      appStarter = expectAsync1((DriveCommand command) async => null);
yjbanov's avatar
yjbanov committed
93

94 95
      final String testApp = fs.path.join(tempDir.path, 'test_driver', 'e2e.dart');
      final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
yjbanov's avatar
yjbanov committed
96

97
      final MemoryFileSystem memFs = fs;
98 99
      await memFs.file(testApp).writeAsString('main() { }');
      await memFs.file(testFile).writeAsString('main() { }');
yjbanov's avatar
yjbanov committed
100

101
      final List<String> args = <String>[
yjbanov's avatar
yjbanov committed
102 103
        'drive',
        '--target=$testApp',
104
        '--no-pub',
yjbanov's avatar
yjbanov committed
105
      ];
106 107 108 109 110
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode, 1);
111
        expect(e.message, contains('Application failed to start. Will not run test. Quitting.'));
112
      }
113
    }, overrides: <Type, Generator>{
114
      FileSystem: () => fs,
115
      ProcessManager: () => FakeProcessManager.any(),
yjbanov's avatar
yjbanov committed
116 117
    });

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

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

yjbanov's avatar
yjbanov committed
165
    testUsingContext('returns 0 when test ends successfully', () async {
166
      testDeviceManager.addDevice(MockDevice());
167

168 169
      final String testApp = fs.path.join(tempDir.path, 'test', 'e2e.dart');
      final String testFile = fs.path.join(tempDir.path, 'test_driver', 'e2e_test.dart');
yjbanov's avatar
yjbanov committed
170

171
      appStarter = expectAsync1((DriveCommand command) async {
172
        return LaunchResult.succeeded();
173
      });
174
      testRunner = expectAsync2((List<String> testArgs, Map<String, String> environment) async {
175
        expect(testArgs, <String>[testFile]);
176 177 178 179 180 181 182 183
        // VM_SERVICE_URL is not set by drive command arguments
        expect(environment, <String, String>{
          'VM_SERVICE_URL': 'null',
          'SELENIUM_PORT': '4567',
          'BROWSER_NAME': 'firefox',
          'BROWSER_DIMENSION': '1024,768',
          'HEADLESS': 'false',
        });
184
        return null;
185
      });
186
      appStopper = expectAsync1((DriveCommand command) async {
187
        return true;
188
      });
yjbanov's avatar
yjbanov committed
189

190
      final MemoryFileSystem memFs = fs;
yjbanov's avatar
yjbanov committed
191 192 193
      await memFs.file(testApp).writeAsString('main() {}');
      await memFs.file(testFile).writeAsString('main() {}');

194
      final List<String> args = <String>[
yjbanov's avatar
yjbanov committed
195 196
        'drive',
        '--target=$testApp',
197
        '--no-pub',
198 199 200 201
        '--no-headless',
        '--driver-port=4567',
        '--browser-name=firefox',
        '--browser-dimension=1024,768',
yjbanov's avatar
yjbanov committed
202
      ];
203 204
      await createTestCommandRunner(command).run(args);
      expect(testLogger.errorText, isEmpty);
205
    }, overrides: <Type, Generator>{
206
      FileSystem: () => fs,
207
      ProcessManager: () => FakeProcessManager.any(),
yjbanov's avatar
yjbanov committed
208
    });
209

210
    testUsingContext('returns exitCode set by test runner', () async {
211
      testDeviceManager.addDevice(MockDevice());
212

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

216
      appStarter = expectAsync1((DriveCommand command) async {
217
        return LaunchResult.succeeded();
218
      });
219
      testRunner = (List<String> testArgs, Map<String, String> environment) async {
220 221
        throwToolExit(null, exitCode: 123);
      };
222
      appStopper = expectAsync1((DriveCommand command) async {
223
        return true;
224 225
      });

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

230
      final List<String> args = <String>[
231 232
        'drive',
        '--target=$testApp',
233
        '--no-pub',
234
      ];
235 236 237 238 239 240 241
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode ?? 1, 123);
        expect(e.message, isNull);
      }
242
    }, overrides: <Type, Generator>{
243
      FileSystem: () => fs,
244
      ProcessManager: () => FakeProcessManager.any(),
245 246
    });

247 248 249
    group('findTargetDevice', () {
      testUsingContext('uses specified device', () async {
        testDeviceManager.specifiedDeviceId = '123';
250 251
        mockDevice = MockDevice();
        testDeviceManager.addDevice(mockDevice);
252 253 254
        when(mockDevice.name).thenReturn('specified-device');
        when(mockDevice.id).thenReturn('123');

255
        final Device device = await findTargetDevice();
256
        expect(device.name, 'specified-device');
257
      }, overrides: <Type, Generator>{
258
        FileSystem: () => fs,
259
        ProcessManager: () => FakeProcessManager.any(),
260 261 262
      });
    });

263
    void findTargetDeviceOnOperatingSystem(String operatingSystem) {
264
      Platform platform() => FakePlatform(operatingSystem: operatingSystem);
265 266 267

      testUsingContext('returns null if no devices found', () async {
        expect(await findTargetDevice(), isNull);
268
      }, overrides: <Type, Generator>{
269
        FileSystem: () => fs,
270
        ProcessManager: () => FakeProcessManager.any(),
271
        Platform: platform,
272 273 274
      });

      testUsingContext('uses existing Android device', () async {
275
        mockDevice = MockAndroidDevice();
276
        when(mockDevice.name).thenReturn('mock-android-device');
277 278 279 280 281 282
        testDeviceManager.addDevice(mockDevice);

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

      testUsingContext('skips unsupported device', () async {
        mockDevice = MockAndroidDevice();
        mockUnsupportedDevice = MockDevice();
        when(mockUnsupportedDevice.isSupportedForProject(any))
            .thenReturn(false);
292 293 294 295 296 297 298 299 300 301 302
        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);
303 304
        when(mockDevice.isSupportedForProject(any))
            .thenReturn(true);
305 306 307
        when(mockDevice.targetPlatform).thenAnswer((_) => Future<TargetPlatform>(() => TargetPlatform.android_x64));
        when(mockDevice.isLocalEmulator).thenAnswer((_) => Future<bool>(() => false));
        when(mockDevice.sdkNameAndVersion).thenAnswer((_) => Future<String>(() => 'sdk-28'));
308 309
        testDeviceManager.addDevice(mockDevice);
        testDeviceManager.addDevice(mockUnsupportedDevice);
310

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

    group('findTargetDevice on Linux', () {
321
      findTargetDeviceOnOperatingSystem('linux');
322 323 324
    });

    group('findTargetDevice on Windows', () {
325
      findTargetDeviceOnOperatingSystem('windows');
326
    });
327 328 329 330

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

331
      Platform macOsPlatform() => FakePlatform(operatingSystem: 'macos');
332 333

      testUsingContext('uses existing simulator', () async {
334
        testDeviceManager.addDevice(mockDevice);
335
        when(mockDevice.name).thenReturn('mock-simulator');
336
        when(mockDevice.isLocalEmulator)
337
            .thenAnswer((Invocation invocation) => Future<bool>.value(true));
338 339 340 341 342

        final Device device = await findTargetDevice();
        expect(device.name, 'mock-simulator');
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
343
        ProcessManager: () => FakeProcessManager.any(),
344 345 346
        Platform: macOsPlatform,
      });
    });
347 348 349 350 351 352 353 354 355

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

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

      Future<void> appStarterSetup() async {
356
        mockDevice = MockDevice();
357
        testDeviceManager.addDevice(mockDevice);
358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375

        final MockDeviceLogReader mockDeviceLogReader = MockDeviceLogReader();
        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'),
        )).thenAnswer((_) => Future<LaunchResult>.value(mockLaunchResult));
        when(mockDevice.isAppInstalled(any)).thenAnswer((_) => Future<bool>.value(false));

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

376
        testRunner = (List<String> testArgs, Map<String, String> environment) async {
377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396
          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() {}');
      }

      testUsingContext('does not use pre-built app if no build arg provided', () async {
        await appStarterSetup();

        final List<String> args = <String>[
          'drive',
          '--target=$testApp',
397
          '--no-pub',
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
        ];
        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,
        ));
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
415
        ProcessManager: () => FakeProcessManager.any(),
416 417 418 419 420 421 422 423 424
      });

      testUsingContext('does not use pre-built app if --build arg provided', () async {
        await appStarterSetup();

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

      testUsingContext('uses prebuilt app if --no-build arg provided', () async {
        await appStarterSetup();

        final List<String> args = <String>[
          'drive',
          '--no-build',
          '--target=$testApp',
453
          '--no-pub',
454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470
        ];
        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,
        ));
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
471
        ProcessManager: () => FakeProcessManager.any(),
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

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

      String testApp, testFile;

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

      Future<void> appStarterSetup() async {
        mockDevice = MockDevice();
        testDeviceManager.addDevice(mockDevice);

        final MockDeviceLogReader mockDeviceLogReader = MockDeviceLogReader();
        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'),
        )).thenAnswer((Invocation invocation) async {
500
          debuggingOptions = invocation.namedArguments[#debuggingOptions] as DebuggingOptions;
501 502 503 504 505 506 507 508
          return mockLaunchResult;
        });
        when(mockDevice.isAppInstalled(any))
            .thenAnswer((_) => Future<bool>.value(false));

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

509
        testRunner = (List<String> testArgs, Map<String, String> environment) async {
510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 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 575 576 577 578 579 580 581
          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() {}');
      }

      void _testOptionThatDefaultsToFalse(
        String optionName,
        bool setToTrue,
        bool optionValue(),
      ) {
        testUsingContext('$optionName ${setToTrue ? 'works' : 'defaults to false'}', () async {
          await appStarterSetup();

          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,
          ));
          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,
      );
    });
582
  });
yjbanov's avatar
yjbanov committed
583
}
584 585 586

class MockDevice extends Mock implements Device {
  MockDevice() {
587
    when(isSupported()).thenReturn(true);
588 589 590 591
  }
}

class MockAndroidDevice extends Mock implements AndroidDevice { }
592 593

class MockLaunchResult extends Mock implements LaunchResult { }