emulator_test.dart 13.1 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 101 102 103
    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',
          ),
        ]),
        androidSdk: null,
        androidWorkflow: AndroidWorkflow(
          androidSdk: null,
          featureFlags: TestFeatureFlags(),
104
          operatingSystemUtils: FakeOperatingSystemUtils(),
105 106 107
        ),
      );

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

112 113 114 115 116 117 118 119 120
    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]);
121 122
    });

123
    testUsingContext('create emulator with a missing avdmanager does not crash.', () async {
124
      sdk.avdManagerPath = null;
125 126 127 128 129 130 131 132 133
      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',
          ),
        ]),
134
        androidSdk: sdk,
135
        androidWorkflow: AndroidWorkflow(
136
          androidSdk: sdk,
137
          featureFlags: TestFeatureFlags(),
138
          operatingSystemUtils: FakeOperatingSystemUtils(),
139 140 141 142 143 144
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator();

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

147
    // iOS discovery uses context.
148
    testUsingContext('create emulator with an empty name does not fail', () async {
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 175
      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',
            ],
          )
        ]),
176
        androidSdk: sdk,
177
        androidWorkflow: AndroidWorkflow(
178
          androidSdk: sdk,
179
          featureFlags: TestFeatureFlags(),
180
          operatingSystemUtils: FakeOperatingSystemUtils(),
181 182 183 184 185
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator();

      expect(result.success, true);
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 212
    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',
            ],
          )
        ]),
213
        androidSdk: sdk,
214
        androidWorkflow: AndroidWorkflow(
215
          androidSdk: sdk,
216
          featureFlags: TestFeatureFlags(),
217
          operatingSystemUtils: FakeOperatingSystemUtils(),
218 219 220 221 222
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator(name: 'test');

      expect(result.success, true);
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 251
    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.'
          )
        ]),
252
        androidSdk: sdk,
253
        androidWorkflow: AndroidWorkflow(
254
          androidSdk: sdk,
255
          featureFlags: TestFeatureFlags(),
256
          operatingSystemUtils: FakeOperatingSystemUtils(),
257 258 259 260 261
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator(name: 'existing-avd-1');

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

264
    // iOS discovery uses context.
265
    testUsingContext('create emulator without a name but when default exists adds a suffix', () async {
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 293
      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',
            ],
          )
        ]),
294
        androidSdk: sdk,
295
        androidWorkflow: AndroidWorkflow(
296
          androidSdk: sdk,
297
          featureFlags: TestFeatureFlags(),
298
          operatingSystemUtils: FakeOperatingSystemUtils(),
299 300 301 302 303 304
        ),
      );
      final CreateEmulatorResult result = await emulatorManager.createEmulator();

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

  group('ios_emulators', () {
    testUsingContext('runs correct launch commands', () async {
310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330
      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',
          ])
        ],
      );

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

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

345 346
  final List<Emulator> allEmulators;

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

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

  @override
358
  final String name;
359

360 361
  @override
  final String manufacturer;
362

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

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

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

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>{};
}