drive_test.dart 19.9 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, String observatoryUri) {
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, String observatoryUri) async {
175
        expect(testArgs, <String>[testFile]);
176
        return null;
177
      });
178
      appStopper = expectAsync1((DriveCommand command) async {
179
        return true;
180
      });
yjbanov's avatar
yjbanov committed
181

182
      final MemoryFileSystem memFs = fs;
yjbanov's avatar
yjbanov committed
183 184 185
      await memFs.file(testApp).writeAsString('main() {}');
      await memFs.file(testFile).writeAsString('main() {}');

186
      final List<String> args = <String>[
yjbanov's avatar
yjbanov committed
187 188
        'drive',
        '--target=$testApp',
189
        '--no-pub',
yjbanov's avatar
yjbanov committed
190
      ];
191 192
      await createTestCommandRunner(command).run(args);
      expect(testLogger.errorText, isEmpty);
193
    }, overrides: <Type, Generator>{
194
      FileSystem: () => fs,
195
      ProcessManager: () => FakeProcessManager.any(),
yjbanov's avatar
yjbanov committed
196
    });
197

198
    testUsingContext('returns exitCode set by test runner', () async {
199
      testDeviceManager.addDevice(MockDevice());
200

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

204
      appStarter = expectAsync1((DriveCommand command) async {
205
        return LaunchResult.succeeded();
206
      });
207
      testRunner = (List<String> testArgs, String observatoryUri) async {
208 209
        throwToolExit(null, exitCode: 123);
      };
210
      appStopper = expectAsync1((DriveCommand command) async {
211
        return true;
212 213
      });

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

218
      final List<String> args = <String>[
219 220
        'drive',
        '--target=$testApp',
221
        '--no-pub',
222
      ];
223 224 225 226 227 228 229
      try {
        await createTestCommandRunner(command).run(args);
        fail('Expect exception');
      } on ToolExit catch (e) {
        expect(e.exitCode ?? 1, 123);
        expect(e.message, isNull);
      }
230
    }, overrides: <Type, Generator>{
231
      FileSystem: () => fs,
232
      ProcessManager: () => FakeProcessManager.any(),
233 234
    });

235 236 237
    group('findTargetDevice', () {
      testUsingContext('uses specified device', () async {
        testDeviceManager.specifiedDeviceId = '123';
238 239
        mockDevice = MockDevice();
        testDeviceManager.addDevice(mockDevice);
240 241 242
        when(mockDevice.name).thenReturn('specified-device');
        when(mockDevice.id).thenReturn('123');

243
        final Device device = await findTargetDevice();
244
        expect(device.name, 'specified-device');
245
      }, overrides: <Type, Generator>{
246
        FileSystem: () => fs,
247
        ProcessManager: () => FakeProcessManager.any(),
248 249 250
      });
    });

251
    void findTargetDeviceOnOperatingSystem(String operatingSystem) {
252
      Platform platform() => FakePlatform(operatingSystem: operatingSystem);
253 254 255

      testUsingContext('returns null if no devices found', () async {
        expect(await findTargetDevice(), isNull);
256
      }, overrides: <Type, Generator>{
257
        FileSystem: () => fs,
258
        ProcessManager: () => FakeProcessManager.any(),
259
        Platform: platform,
260 261 262
      });

      testUsingContext('uses existing Android device', () async {
263
        mockDevice = MockAndroidDevice();
264
        when(mockDevice.name).thenReturn('mock-android-device');
265 266 267 268 269 270
        testDeviceManager.addDevice(mockDevice);

        final Device device = await findTargetDevice();
        expect(device.name, 'mock-android-device');
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
271
        ProcessManager: () => FakeProcessManager.any(),
272 273 274 275 276 277 278 279
        Platform: platform,
      });

      testUsingContext('skips unsupported device', () async {
        mockDevice = MockAndroidDevice();
        mockUnsupportedDevice = MockDevice();
        when(mockUnsupportedDevice.isSupportedForProject(any))
            .thenReturn(false);
280 281 282 283 284 285 286 287 288 289 290
        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);
291 292
        when(mockDevice.isSupportedForProject(any))
            .thenReturn(true);
293 294 295
        when(mockDevice.targetPlatform).thenAnswer((_) => Future<TargetPlatform>(() => TargetPlatform.android_x64));
        when(mockDevice.isLocalEmulator).thenAnswer((_) => Future<bool>(() => false));
        when(mockDevice.sdkNameAndVersion).thenAnswer((_) => Future<String>(() => 'sdk-28'));
296 297
        testDeviceManager.addDevice(mockDevice);
        testDeviceManager.addDevice(mockUnsupportedDevice);
298

299
        final Device device = await findTargetDevice();
300
        expect(device.name, 'mock-android-device');
301
      }, overrides: <Type, Generator>{
302
        FileSystem: () => fs,
303
        ProcessManager: () => FakeProcessManager.any(),
304
        Platform: platform,
305
      });
306 307 308
    }

    group('findTargetDevice on Linux', () {
309
      findTargetDeviceOnOperatingSystem('linux');
310 311 312
    });

    group('findTargetDevice on Windows', () {
313
      findTargetDeviceOnOperatingSystem('windows');
314
    });
315 316 317 318

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

319
      Platform macOsPlatform() => FakePlatform(operatingSystem: 'macos');
320 321

      testUsingContext('uses existing simulator', () async {
322
        testDeviceManager.addDevice(mockDevice);
323
        when(mockDevice.name).thenReturn('mock-simulator');
324
        when(mockDevice.isLocalEmulator)
325
            .thenAnswer((Invocation invocation) => Future<bool>.value(true));
326 327 328 329 330

        final Device device = await findTargetDevice();
        expect(device.name, 'mock-simulator');
      }, overrides: <Type, Generator>{
        FileSystem: () => fs,
331
        ProcessManager: () => FakeProcessManager.any(),
332 333 334
        Platform: macOsPlatform,
      });
    });
335 336 337 338 339 340 341 342 343

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

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

      Future<void> appStarterSetup() async {
344
        mockDevice = MockDevice();
345
        testDeviceManager.addDevice(mockDevice);
346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384

        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');

        testRunner = (List<String> testArgs, String observatoryUri) async {
          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',
385
          '--no-pub',
386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
        ];
        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,
403
        ProcessManager: () => FakeProcessManager.any(),
404 405 406 407 408 409 410 411 412
      });

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

        final List<String> args = <String>[
          'drive',
          '--build',
          '--target=$testApp',
413
          '--no-pub',
414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430
        ];
        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,
431
        ProcessManager: () => FakeProcessManager.any(),
432 433 434 435 436 437 438 439 440
      });

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

        final List<String> args = <String>[
          'drive',
          '--no-build',
          '--target=$testApp',
441
          '--no-pub',
442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458
        ];
        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,
459
        ProcessManager: () => FakeProcessManager.any(),
460 461
      });
    });
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487

    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 {
488
          debuggingOptions = invocation.namedArguments[#debuggingOptions] as DebuggingOptions;
489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 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
          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');

        testRunner = (List<String> testArgs, String observatoryUri) async {
          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,
      );
    });
570
  });
yjbanov's avatar
yjbanov committed
571
}
572 573 574

class MockDevice extends Mock implements Device {
  MockDevice() {
575
    when(isSupported()).thenReturn(true);
576 577 578 579
  }
}

class MockAndroidDevice extends Mock implements AndroidDevice { }
580 581

class MockLaunchResult extends Mock implements LaunchResult { }