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

5 6
// @dart = 2.8

7
import 'package:file/file.dart';
8
import 'package:file/memory.dart';
9
import 'package:flutter_tools/src/android/android_sdk.dart';
10 11
import 'package:flutter_tools/src/android/android_workflow.dart';
import 'package:flutter_tools/src/base/logger.dart';
12
import 'package:flutter_tools/src/device.dart';
13
import 'package:flutter_tools/src/emulator.dart';
14
import 'package:flutter_tools/src/ios/ios_emulators.dart';
15
import 'package:flutter_tools/src/macos/xcode.dart';
16
import 'package:test/fake.dart';
17

18 19
import '../src/common.dart';
import '../src/context.dart';
20
import '../src/fakes.dart';
21

22 23 24 25 26 27 28 29 30 31
const FakeEmulator emulator1 = FakeEmulator('Nexus_5', 'Nexus 5', 'Google');
const FakeEmulator emulator2 = FakeEmulator('Nexus_5X_API_27_x86', 'Nexus 5X', 'Google');
const FakeEmulator emulator3 = FakeEmulator('iOS Simulator', 'iOS Simulator', 'Apple');
const List<Emulator> emulators = <Emulator>[
  emulator1,
  emulator2,
  emulator3,
];

// We have to send a command that fails in order to get the list of valid
32
// system images paths. This is an example of the output to use in the fake.
33 34 35 36 37 38 39 40 41 42 43 44 45
const String fakeCreateFailureOutput =
  'Error: Package path (-k) not specified. Valid system image paths are:\n'
  'system-images;android-27;google_apis;x86\n'
  'system-images;android-P;google_apis;x86\n'
  'system-images;android-27;google_apis_playstore;x86\n'
  'null\n'; // Yep, these really end with null (on dantup's machine at least)

const FakeCommand kListEmulatorsCommand = FakeCommand(
  command: <String>['avdmanager', 'create', 'avd', '-n', 'temp'],
  stderr: fakeCreateFailureOutput,
  exitCode: 1,
);

46
void main() {
47
  FakeProcessManager fakeProcessManager;
48
  FakeAndroidSdk sdk;
49 50
  FileSystem fileSystem;
  Xcode xcode;
51 52

  setUp(() {
53
    fileSystem = MemoryFileSystem.test();
54
    fakeProcessManager = FakeProcessManager.empty();
55
    sdk = FakeAndroidSdk();
56
    xcode = Xcode.test(processManager: fakeProcessManager, fileSystem: fileSystem);
57

58 59 60 61
    sdk
      ..avdManagerPath = 'avdmanager'
      ..emulatorPath = 'emulator'
      ..adbPath = 'adb';
62 63
  });

64
  group('EmulatorManager', () {
65
    // iOS discovery uses context.
66 67
    testUsingContext('getEmulators', () async {
      // Test that EmulatorManager.getEmulators() doesn't throw.
68 69 70 71 72 73 74 75 76
      final EmulatorManager emulatorManager = EmulatorManager(
        fileSystem: MemoryFileSystem.test(),
        logger: BufferLogger.test(),
        processManager: FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['emulator', '-list-avds'],
            stdout: 'existing-avd-1',
          ),
        ]),
77
        androidSdk: sdk,
78
        androidWorkflow: AndroidWorkflow(
79
          androidSdk: sdk,
80
          featureFlags: TestFeatureFlags(),
81
          operatingSystemUtils: FakeOperatingSystemUtils(),
82 83 84
        ),
      );

85
      await expectLater(() async => emulatorManager.getAllAvailableEmulators(),
86 87 88
        returnsNormally);
    });

89 90 91 92 93 94 95 96 97 98 99 100
    testUsingContext('getEmulators with no Android SDK', () async {
      // Test that EmulatorManager.getEmulators() doesn't throw when there's no Android SDK.
      final EmulatorManager emulatorManager = EmulatorManager(
        fileSystem: MemoryFileSystem.test(),
        logger: BufferLogger.test(),
        processManager: FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['emulator', '-list-avds'],
            stdout: 'existing-avd-1',
          ),
        ]),
        androidWorkflow: AndroidWorkflow(
101
          androidSdk: sdk,
102
          featureFlags: TestFeatureFlags(),
103
          operatingSystemUtils: FakeOperatingSystemUtils(),
104 105 106
        ),
      );

107
      await expectLater(() async => emulatorManager.getAllAvailableEmulators(),
108 109 110
        returnsNormally);
    });

111 112 113 114 115 116 117 118 119
    testWithoutContext('getEmulatorsById', () async {
      final TestEmulatorManager testEmulatorManager = TestEmulatorManager(emulators);

      expect(await testEmulatorManager.getEmulatorsMatching('Nexus_5'), <Emulator>[emulator1]);
      expect(await testEmulatorManager.getEmulatorsMatching('Nexus_5X'), <Emulator>[emulator2]);
      expect(await testEmulatorManager.getEmulatorsMatching('Nexus_5X_API_27_x86'),  <Emulator>[emulator2]);
      expect(await testEmulatorManager.getEmulatorsMatching('Nexus'), <Emulator>[emulator1, emulator2]);
      expect(await testEmulatorManager.getEmulatorsMatching('iOS Simulator'), <Emulator>[emulator3]);
      expect(await testEmulatorManager.getEmulatorsMatching('ios'),  <Emulator>[emulator3]);
120 121
    });

122
    testUsingContext('create emulator with a missing avdmanager does not crash.', () async {
123
      sdk.avdManagerPath = null;
124 125 126 127 128 129 130 131 132
      final EmulatorManager emulatorManager = EmulatorManager(
        fileSystem: MemoryFileSystem.test(),
        logger: BufferLogger.test(),
        processManager: FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['emulator', '-list-avds'],
            stdout: 'existing-avd-1',
          ),
        ]),
133
        androidSdk: sdk,
134
        androidWorkflow: AndroidWorkflow(
135
          androidSdk: sdk,
136
          featureFlags: TestFeatureFlags(),
137
          operatingSystemUtils: FakeOperatingSystemUtils(),
138 139 140 141 142 143
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator();

      expect(result.success, false);
      expect(result.error, contains('avdmanager is missing from the Android SDK'));
144
    });
145

146
    // iOS discovery uses context.
147
    testUsingContext('create emulator with an empty name does not fail', () async {
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
      final EmulatorManager emulatorManager = EmulatorManager(
        fileSystem: MemoryFileSystem.test(),
        logger: BufferLogger.test(),
        processManager: FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['emulator', '-list-avds'],
            stdout: 'existing-avd-1',
          ),
          const FakeCommand(
            command: <String>['avdmanager', 'list', 'device', '-c'],
            stdout: 'test\ntest2\npixel\npixel-xl\n',
          ),
          kListEmulatorsCommand,
          const FakeCommand(
            command: <String>[
              'avdmanager',
              'create',
              'avd',
              '-n',
              'flutter_emulator',
              '-k',
              'system-images;android-27;google_apis_playstore;x86',
              '-d',
              'pixel',
            ],
          )
        ]),
175
        androidSdk: sdk,
176
        androidWorkflow: AndroidWorkflow(
177
          androidSdk: sdk,
178
          featureFlags: TestFeatureFlags(),
179
          operatingSystemUtils: FakeOperatingSystemUtils(),
180 181 182 183 184
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator();

      expect(result.success, true);
185 186
    });

187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211
    testWithoutContext('create emulator with a unique name does not throw', () async {
      final EmulatorManager emulatorManager = EmulatorManager(
        fileSystem: MemoryFileSystem.test(),
        logger: BufferLogger.test(),
        processManager: FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['avdmanager', 'list', 'device', '-c'],
            stdout: 'test\ntest2\npixel\npixel-xl\n',
          ),
          kListEmulatorsCommand,
          const FakeCommand(
            command: <String>[
              'avdmanager',
              'create',
              'avd',
              // The specified name is given with the -n flag.
              '-n',
              'test',
              '-k',
              'system-images;android-27;google_apis_playstore;x86',
              '-d',
              'pixel',
            ],
          )
        ]),
212
        androidSdk: sdk,
213
        androidWorkflow: AndroidWorkflow(
214
          androidSdk: sdk,
215
          featureFlags: TestFeatureFlags(),
216
          operatingSystemUtils: FakeOperatingSystemUtils(),
217 218 219 220 221
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator(name: 'test');

      expect(result.success, true);
222 223
    });

224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250
    testWithoutContext('create emulator with an existing name errors', () async {
      final EmulatorManager emulatorManager = EmulatorManager(
        fileSystem: MemoryFileSystem.test(),
        logger: BufferLogger.test(),
        processManager: FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['avdmanager', 'list', 'device', '-c'],
            stdout: 'test\ntest2\npixel\npixel-xl\n',
          ),
          kListEmulatorsCommand,
          const FakeCommand(
            command: <String>[
              'avdmanager',
              'create',
              'avd',
              '-n',
              'existing-avd-1',
              '-k',
              'system-images;android-27;google_apis_playstore;x86',
              '-d',
              'pixel',
            ],
            exitCode: 1,
            stderr: "Error: Android Virtual Device 'existing-avd-1' already exists.\n"
              'Use --force if you want to replace it.'
          )
        ]),
251
        androidSdk: sdk,
252
        androidWorkflow: AndroidWorkflow(
253
          androidSdk: sdk,
254
          featureFlags: TestFeatureFlags(),
255
          operatingSystemUtils: FakeOperatingSystemUtils(),
256 257 258 259 260
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator(name: 'existing-avd-1');

      expect(result.success, false);
261 262
    });

263
    // iOS discovery uses context.
264
    testUsingContext('create emulator without a name but when default exists adds a suffix', () async {
265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292
      final EmulatorManager emulatorManager = EmulatorManager(
        fileSystem: MemoryFileSystem.test(),
        logger: BufferLogger.test(),
        processManager: FakeProcessManager.list(<FakeCommand>[
          const FakeCommand(
            command: <String>['emulator', '-list-avds'],
            stdout: 'existing-avd-1\nflutter_emulator',
          ),
          const FakeCommand(
            command: <String>['avdmanager', 'list', 'device', '-c'],
            stdout: 'test\ntest2\npixel\npixel-xl\n',
          ),
          kListEmulatorsCommand,
          const FakeCommand(
            command: <String>[
              'avdmanager',
              'create',
              'avd',
              // a "_2" suffix is added to disambiguate from the existing emulator.
              '-n',
              'flutter_emulator_2',
              '-k',
              'system-images;android-27;google_apis_playstore;x86',
              '-d',
              'pixel',
            ],
          )
        ]),
293
        androidSdk: sdk,
294
        androidWorkflow: AndroidWorkflow(
295
          androidSdk: sdk,
296
          featureFlags: TestFeatureFlags(),
297
          operatingSystemUtils: FakeOperatingSystemUtils(),
298 299 300 301 302 303
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator();

      expect(result.success, true);
      expect(result.emulatorName, 'flutter_emulator_2');
304
    });
305
  });
306 307 308

  group('ios_emulators', () {
    testUsingContext('runs correct launch commands', () async {
309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329
      fileSystem.directory('/fake/Xcode.app/Contents/Developer/Applications/Simulator.app').createSync(recursive: true);
      fakeProcessManager.addCommands(
        <FakeCommand>[
          const FakeCommand(
            command: <String>['/usr/bin/xcode-select', '--print-path'],
            stdout: '/fake/Xcode.app/Contents/Developer',
          ),
          const FakeCommand(command: <String>[
            'open',
            '-n',
            '-a',
            '/fake/Xcode.app/Contents/Developer/Applications/Simulator.app',
          ]),
          const FakeCommand(command: <String>[
            'open',
            '-a',
            '/fake/Xcode.app/Contents/Developer/Applications/Simulator.app',
          ])
        ],
      );

330
      const Emulator emulator = IOSEmulator('ios');
331
      await emulator.launch();
332
      expect(fakeProcessManager.hasRemainingExpectations, isFalse);
333
    }, overrides: <Type, Generator>{
334 335 336
      ProcessManager: () => fakeProcessManager,
      Xcode: () => xcode,
      FileSystem: () => fileSystem,
337 338
    });
  });
339 340 341 342 343
}

class TestEmulatorManager extends EmulatorManager {
  TestEmulatorManager(this.allEmulators);

344 345
  final List<Emulator> allEmulators;

346
  @override
347
  Future<List<Emulator>> getAllAvailableEmulators() {
348
    return Future<List<Emulator>>.value(allEmulators);
349 350 351
  }
}

352 353
class FakeEmulator extends Emulator {
  const FakeEmulator(String id, this.name, this.manufacturer)
354
    : super(id, true);
355 356

  @override
357
  final String name;
358

359 360
  @override
  final String manufacturer;
361

362 363 364 365
  @override
  Category get category => Category.mobile;

  @override
366
  PlatformType get platformType => PlatformType.android;
367

368
  @override
369
  Future<void> launch({bool coldBoot = false}) {
370
    throw UnimplementedError('Not implemented in Mock');
371
  }
372
}
373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

class FakeAndroidSdk extends Fake implements AndroidSdk {
  @override
  String avdManagerPath;

  @override
  String emulatorPath;

  @override
  String adbPath;

  @override
  String getAvdManagerPath() => avdManagerPath;

  @override
  String getAvdPath() => 'avd';

  @override
  Map<String, String> get sdkManagerEnv => <String, String>{};
}