mocks.dart 19.4 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
import 'dart:async';
6
import 'dart:convert';
7
import 'dart:io' as io show IOSink, ProcessSignal, Stdout, StdoutException;
8

9
import 'package:flutter_tools/src/android/android_device.dart';
10
import 'package:flutter_tools/src/android/android_sdk.dart' show AndroidSdk;
11
import 'package:flutter_tools/src/application_package.dart';
12
import 'package:flutter_tools/src/base/context.dart';
13
import 'package:flutter_tools/src/base/file_system.dart' hide IOSink;
14
import 'package:flutter_tools/src/base/io.dart';
15
import 'package:flutter_tools/src/base/platform.dart';
16
import 'package:flutter_tools/src/build_info.dart';
17
import 'package:flutter_tools/src/compile.dart';
18
import 'package:flutter_tools/src/devfs.dart';
19
import 'package:flutter_tools/src/device.dart';
20 21
import 'package:flutter_tools/src/ios/devices.dart';
import 'package:flutter_tools/src/ios/simulators.dart';
22
import 'package:flutter_tools/src/project.dart';
23
import 'package:flutter_tools/src/runner/flutter_command.dart';
24
import 'package:mockito/mockito.dart';
25
import 'package:process/process.dart';
26 27

import 'common.dart';
28

29 30 31 32 33
final Generator kNoColorTerminalPlatform = () {
  return FakePlatform.fromPlatform(
    const LocalPlatform()
  )..stdoutSupportsAnsi = false;
};
34

35 36
class MockApplicationPackageStore extends ApplicationPackageStore {
  MockApplicationPackageStore() : super(
37
    android: AndroidApk(
Adam Barth's avatar
Adam Barth committed
38
      id: 'io.flutter.android.mock',
39
      file: fs.file('/mock/path/to/android/SkyShell.apk'),
40
      versionCode: 1,
41
      launchActivity: 'io.flutter.android.mock.MockActivity',
Adam Barth's avatar
Adam Barth committed
42
    ),
43
    iOS: BuildableIOSApp(MockIosProject(), MockIosProject.bundleId),
44
  );
45 46
}

47 48 49 50 51 52 53 54 55 56 57 58
class MockApplicationPackageFactory extends Mock implements ApplicationPackageFactory {
  final MockApplicationPackageStore _store = MockApplicationPackageStore();

  @override
  Future<ApplicationPackage> getPackageForPlatform(
    TargetPlatform platform, {
    File applicationBinary,
  }) async {
    return _store.getPackageForPlatform(platform);
  }
}

59 60 61
/// An SDK installation with several SDK levels (19, 22, 23).
class MockAndroidSdk extends Mock implements AndroidSdk {
  static Directory createSdkDirectory({
62
    bool withAndroidN = false,
63
    String withNdkDir,
64
    int ndkVersion = 16,
65 66
    bool withNdkSysroot = false,
    bool withSdkManager = true,
67 68
    bool withPlatformTools = true,
    bool withBuildTools = true,
69
  }) {
70
    final Directory dir = fs.systemTempDirectory.createTempSync('flutter_mock_android_sdk.');
71 72
    final String exe = platform.isWindows ? '.exe' : '';
    final String bat = platform.isWindows ? '.bat' : '';
73

74
    _createDir(dir, 'licenses');
75

76 77 78 79 80 81 82 83
    if (withPlatformTools) {
      _createSdkFile(dir, 'platform-tools/adb$exe');
    }

    if (withBuildTools) {
      _createSdkFile(dir, 'build-tools/19.1.0/aapt$exe');
      _createSdkFile(dir, 'build-tools/22.0.1/aapt$exe');
      _createSdkFile(dir, 'build-tools/23.0.2/aapt$exe');
84
      if (withAndroidN) {
85
        _createSdkFile(dir, 'build-tools/24.0.0-preview/aapt$exe');
86
      }
87
    }
88 89 90 91 92 93 94 95

    _createSdkFile(dir, 'platforms/android-22/android.jar');
    _createSdkFile(dir, 'platforms/android-23/android.jar');
    if (withAndroidN) {
      _createSdkFile(dir, 'platforms/android-N/android.jar');
      _createSdkFile(dir, 'platforms/android-N/build.prop', contents: _buildProp);
    }

96
    if (withSdkManager) {
97
      _createSdkFile(dir, 'tools/bin/sdkmanager$bat');
98
    }
99 100

    if (withNdkDir != null) {
101
      final String ndkToolchainBin = fs.path.join(
102 103 104 105 106 107
        'ndk-bundle',
        'toolchains',
        'arm-linux-androideabi-4.9',
        'prebuilt',
        withNdkDir,
        'bin',
108 109 110
      );
      final String ndkCompiler = fs.path.join(
        ndkToolchainBin,
111 112
        'arm-linux-androideabi-gcc',
      );
113 114 115 116
      final String ndkLinker = fs.path.join(
        ndkToolchainBin,
        'arm-linux-androideabi-ld',
      );
117
      _createSdkFile(dir, ndkCompiler);
118 119 120 121 122 123
      _createSdkFile(dir, ndkLinker);
      _createSdkFile(dir, fs.path.join('ndk-bundle', 'source.properties'), contents: '''
Pkg.Desc = Android NDK[]
Pkg.Revision = $ndkVersion.1.5063045

''');
124 125
    }
    if (withNdkSysroot) {
126 127 128 129 130 131
      final String armPlatform = fs.path.join(
        'ndk-bundle',
        'platforms',
        'android-9',
        'arch-arm',
      );
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157
      _createDir(dir, armPlatform);
    }

    return dir;
  }

  static void _createSdkFile(Directory dir, String filePath, { String contents }) {
    final File file = dir.childFile(filePath);
    file.createSync(recursive: true);
    if (contents != null) {
      file.writeAsStringSync(contents, flush: true);
    }
  }

  static void _createDir(Directory dir, String path) {
    final Directory directory = fs.directory(fs.path.join(dir.path, path));
    directory.createSync(recursive: true);
  }

  static const String _buildProp = r'''
ro.build.version.incremental=1624448
ro.build.version.sdk=24
ro.build.version.codename=REL
''';
}

158
/// A strategy for creating Process objects from a list of commands.
159
typedef ProcessFactory = Process Function(List<String> command);
160 161

/// A ProcessManager that starts Processes by delegating to a ProcessFactory.
162
class MockProcessManager extends Mock implements ProcessManager {
163
  ProcessFactory processFactory = (List<String> commands) => MockProcess();
164 165
  bool canRunSucceeds = true;
  bool runSucceeds = true;
166 167
  List<String> commands;

168
  @override
169
  bool canRun(dynamic command, { String workingDirectory }) => canRunSucceeds;
170

171 172 173 174 175
  @override
  Future<Process> start(
    List<dynamic> command, {
    String workingDirectory,
    Map<String, String> environment,
176 177
    bool includeParentEnvironment = true,
    bool runInShell = false,
178
    ProcessStartMode mode = ProcessStartMode.normal,
179
  }) {
180
    final List<String> commands = command.cast<String>();
181
    if (!runSucceeds) {
182 183
      final String executable = commands[0];
      final List<String> arguments = commands.length > 1 ? commands.sublist(1) : <String>[];
184
      throw ProcessException(executable, arguments);
185 186
    }

187 188
    this.commands = commands;
    return Future<Process>.value(processFactory(commands));
189 190 191
  }
}

192 193 194
/// A function that generates a process factory that gives processes that fail
/// a given number of times before succeeding. The returned processes will
/// fail after a delay if one is supplied.
195
ProcessFactory flakyProcessFactory({
196 197 198 199 200 201
  int flakes,
  bool Function(List<String> command) filter,
  Duration delay,
  Stream<List<int>> Function() stdout,
  Stream<List<int>> Function() stderr,
}) {
202
  int flakesLeft = flakes;
203 204
  stdout ??= () => const Stream<List<int>>.empty();
  stderr ??= () => const Stream<List<int>>.empty();
205
  return (List<String> command) {
206 207 208
    if (filter != null && !filter(command)) {
      return MockProcess();
    }
209
    if (flakesLeft == 0) {
210 211 212 213 214
      return MockProcess(
        exitCode: Future<int>.value(0),
        stdout: stdout(),
        stderr: stderr(),
      );
215 216 217 218 219 220 221 222
    }
    flakesLeft = flakesLeft - 1;
    Future<int> exitFuture;
    if (delay == null) {
      exitFuture = Future<int>.value(-9);
    } else {
      exitFuture = Future<int>.delayed(delay, () => Future<int>.value(-9));
    }
223 224 225 226 227
    return MockProcess(
      exitCode: exitFuture,
      stdout: stdout(),
      stderr: stderr(),
    );
228 229 230
  };
}

231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
/// Creates a mock process that returns with the given [exitCode], [stdout] and [stderr].
Process createMockProcess({ int exitCode = 0, String stdout = '', String stderr = '' }) {
  final Stream<List<int>> stdoutStream = Stream<List<int>>.fromIterable(<List<int>>[
    utf8.encode(stdout),
  ]);
  final Stream<List<int>> stderrStream = Stream<List<int>>.fromIterable(<List<int>>[
    utf8.encode(stderr),
  ]);
  final Process process = MockBasicProcess();

  when(process.stdout).thenAnswer((_) => stdoutStream);
  when(process.stderr).thenAnswer((_) => stderrStream);
  when(process.exitCode).thenAnswer((_) => Future<int>.value(exitCode));
  return process;
}

class MockBasicProcess extends Mock implements Process {}

249 250 251
/// A process that exits successfully with no output and ignores all input.
class MockProcess extends Mock implements Process {
  MockProcess({
252
    this.pid = 1,
253 254
    Future<int> exitCode,
    Stream<List<int>> stdin,
255 256
    this.stdout = const Stream<List<int>>.empty(),
    this.stderr = const Stream<List<int>>.empty(),
257
  }) : exitCode = exitCode ?? Future<int>.value(0),
258
       stdin = stdin as IOSink ?? MemoryIOSink();
259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275

  @override
  final int pid;

  @override
  final Future<int> exitCode;

  @override
  final io.IOSink stdin;

  @override
  final Stream<List<int>> stdout;

  @override
  final Stream<List<int>> stderr;
}

276
/// A fake process implementation which can be provided all necessary values.
277 278 279 280 281 282 283 284
class FakeProcess implements Process {
  FakeProcess({
    this.pid = 1,
    Future<int> exitCode,
    Stream<List<int>> stdin,
    this.stdout = const Stream<List<int>>.empty(),
    this.stderr = const Stream<List<int>>.empty(),
  }) : exitCode = exitCode ?? Future<int>.value(0),
285
       stdin = stdin as IOSink ?? MemoryIOSink();
286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307

  @override
  final int pid;

  @override
  final Future<int> exitCode;

  @override
  final io.IOSink stdin;

  @override
  final Stream<List<int>> stdout;

  @override
  final Stream<List<int>> stderr;

  @override
  bool kill([io.ProcessSignal signal = io.ProcessSignal.sigterm]) {
    return true;
  }
}

308 309 310
/// A process that prompts the user to proceed, then asynchronously writes
/// some lines to stdout before it exits.
class PromptingProcess implements Process {
311
  Future<void> showPrompt(String prompt, List<String> outputLines) async {
312
    _stdoutController.add(utf8.encode(prompt));
313 314 315
    final List<int> bytesOnStdin = await _stdin.future;
    // Echo stdin to stdout.
    _stdoutController.add(bytesOnStdin);
316
    if (bytesOnStdin[0] == utf8.encode('y')[0]) {
317
      for (final String line in outputLines) {
318
        _stdoutController.add(utf8.encode('$line\n'));
319
      }
320 321 322 323
    }
    await _stdoutController.close();
  }

324 325
  final StreamController<List<int>> _stdoutController = StreamController<List<int>>();
  final CompleterIOSink _stdin = CompleterIOSink();
326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347

  @override
  Stream<List<int>> get stdout => _stdoutController.stream;

  @override
  Stream<List<int>> get stderr => const Stream<List<int>>.empty();

  @override
  IOSink get stdin => _stdin;

  @override
  Future<int> get exitCode async {
    await _stdoutController.done;
    return 0;
  }

  @override
  dynamic noSuchMethod(Invocation invocation) => null;
}

/// An IOSink that completes a future with the first line written to it.
class CompleterIOSink extends MemoryIOSink {
348
  final Completer<List<int>> _completer = Completer<List<int>>();
349 350 351 352 353

  Future<List<int>> get future => _completer.future;

  @override
  void add(List<int> data) {
354
    if (!_completer.isCompleted) {
355
      _completer.complete(data);
356
    }
357 358 359 360 361 362 363
    super.add(data);
  }
}

/// An IOSink that collects whatever is written to it.
class MemoryIOSink implements IOSink {
  @override
364
  Encoding encoding = utf8;
365 366 367 368 369 370 371 372 373

  final List<List<int>> writes = <List<int>>[];

  @override
  void add(List<int> data) {
    writes.add(data);
  }

  @override
374 375
  Future<void> addStream(Stream<List<int>> stream) {
    final Completer<void> completer = Completer<void>();
376 377
    stream.listen((List<int> data) {
      add(data);
378
    }).onDone(() => completer.complete());
379 380 381 382 383 384 385 386 387 388 389 390 391 392
    return completer.future;
  }

  @override
  void writeCharCode(int charCode) {
    add(<int>[charCode]);
  }

  @override
  void write(Object obj) {
    add(encoding.encode('$obj'));
  }

  @override
393
  void writeln([ Object obj = '' ]) {
394 395 396 397
    add(encoding.encode('$obj\n'));
  }

  @override
398
  void writeAll(Iterable<dynamic> objects, [ String separator = '' ]) {
399 400 401 402 403 404 405 406 407 408 409
    bool addSeparator = false;
    for (dynamic object in objects) {
      if (addSeparator) {
        write(separator);
      }
      write(object);
      addSeparator = true;
    }
  }

  @override
410
  void addError(dynamic error, [ StackTrace stackTrace ]) {
411
    throw UnimplementedError();
412 413 414
  }

  @override
415
  Future<void> get done => close();
416 417

  @override
418
  Future<void> close() async { }
419 420

  @override
421
  Future<void> flush() async { }
422 423
}

424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445
class MemoryStdout extends MemoryIOSink implements io.Stdout {
  @override
  bool get hasTerminal => _hasTerminal;
  set hasTerminal(bool value) {
    assert(value != null);
    _hasTerminal = value;
  }
  bool _hasTerminal = true;

  @override
  io.IOSink get nonBlocking => this;

  @override
  bool get supportsAnsiEscapes => _supportsAnsiEscapes;
  set supportsAnsiEscapes(bool value) {
    assert(value != null);
    _supportsAnsiEscapes = value;
  }
  bool _supportsAnsiEscapes = true;

  @override
  int get terminalColumns {
446
    if (_terminalColumns != null) {
447
      return _terminalColumns;
448
    }
449 450 451 452 453 454 455
    throw const io.StdoutException('unspecified mock value');
  }
  set terminalColumns(int value) => _terminalColumns = value;
  int _terminalColumns;

  @override
  int get terminalLines {
456
    if (_terminalLines != null) {
457
      return _terminalLines;
458
    }
459 460 461 462 463 464
    throw const io.StdoutException('unspecified mock value');
  }
  set terminalLines(int value) => _terminalLines = value;
  int _terminalLines;
}

465 466
/// A Stdio that collects stdout and supports simulated stdin.
class MockStdio extends Stdio {
467
  final MemoryStdout _stdout = MemoryStdout();
468
  final MemoryIOSink _stderr = MemoryIOSink();
469
  final StreamController<List<int>> _stdin = StreamController<List<int>>();
470 471

  @override
472
  MemoryStdout get stdout => _stdout;
473

474
  @override
475
  MemoryIOSink get stderr => _stderr;
476

477 478 479 480
  @override
  Stream<List<int>> get stdin => _stdin.stream;

  void simulateStdin(String line) {
481
    _stdin.add(utf8.encode('$line\n'));
482 483
  }

484 485
  List<String> get writtenToStdout => _stdout.writes.map<String>(_stdout.encoding.decode).toList();
  List<String> get writtenToStderr => _stderr.writes.map<String>(_stderr.encoding.decode).toList();
486 487
}

488
class MockPollingDeviceDiscovery extends PollingDeviceDiscovery {
489 490
  MockPollingDeviceDiscovery() : super('mock');

491
  final List<Device> _devices = <Device>[];
492 493
  final StreamController<Device> _onAddedController = StreamController<Device>.broadcast();
  final StreamController<Device> _onRemovedController = StreamController<Device>.broadcast();
494 495

  @override
496
  Future<List<Device>> pollingGetDevices() async => _devices;
497 498 499 500

  @override
  bool get supportsPlatform => true;

501 502 503
  @override
  bool get canListAnything => true;

504 505 506 507 508 509 510
  void addDevice(MockAndroidDevice device) {
    _devices.add(device);

    _onAddedController.add(device);
  }

  @override
511
  Future<List<Device>> get devices async => _devices;
512 513 514 515 516 517 518 519

  @override
  Stream<Device> get onAdded => _onAddedController.stream;

  @override
  Stream<Device> get onRemoved => _onRemovedController.stream;
}

520
class MockIosProject extends Mock implements IosProject {
521 522
  static const String bundleId = 'com.example.test';

523
  @override
524
  Future<String> get productBundleIdentifier async => bundleId;
525 526 527 528 529

  @override
  String get hostAppBundleName => 'Runner.app';
}

530
class MockAndroidDevice extends Mock implements AndroidDevice {
531
  @override
532
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.android_arm;
533 534

  @override
535
  bool isSupported() => true;
536

537 538 539 540 541 542
  @override
  bool get supportsHotRestart => true;

  @override
  bool get supportsFlutterExit => false;

543 544
  @override
  bool isSupportedForProject(FlutterProject flutterProject) => true;
545 546 547
}

class MockIOSDevice extends Mock implements IOSDevice {
548
  @override
549
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios;
550 551

  @override
552
  bool isSupported() => true;
553 554 555

  @override
  bool isSupportedForProject(FlutterProject flutterProject) => true;
556 557 558
}

class MockIOSSimulator extends Mock implements IOSSimulator {
559
  @override
560
  Future<TargetPlatform> get targetPlatform async => TargetPlatform.ios;
561 562

  @override
563
  bool isSupported() => true;
564 565 566

  @override
  bool isSupportedForProject(FlutterProject flutterProject) => true;
567 568
}

569
class MockDeviceLogReader extends DeviceLogReader {
570
  @override
571 572
  String get name => 'MockLogReader';

573 574 575 576 577 578 579 580 581 582 583
  StreamController<String> _cachedLinesController;

  final List<String> _lineQueue = <String>[];
  StreamController<String> get _linesController {
    _cachedLinesController ??= StreamController<String>
      .broadcast(onListen: () {
        _lineQueue.forEach(_linesController.add);
        _lineQueue.clear();
     });
    return _cachedLinesController;
  }
584

585
  @override
Devon Carew's avatar
Devon Carew committed
586
  Stream<String> get logLines => _linesController.stream;
587

588 589 590 591 592 593 594
  void addLine(String line) {
    if (_linesController.hasListener) {
      _linesController.add(line);
    } else {
      _lineQueue.add(line);
    }
  }
595

596
  @override
597 598 599
  Future<void> dispose() async {
    _lineQueue.clear();
    await _linesController.close();
600
  }
601 602
}

603
void applyMocksToCommand(FlutterCommand command) {
604
  command
605
    ..applicationPackages = MockApplicationPackageStore();
606
}
607

608 609
/// Common functionality for tracking mock interaction
class BasicMock {
610
  final List<String> messages = <String>[];
611

612
  void expectMessages(List<String> expectedMessages) {
613
    final List<String> actualMessages = List<String>.from(messages);
614 615 616 617
    messages.clear();
    expect(actualMessages, unorderedEquals(expectedMessages));
  }

618
  bool contains(String match) {
619 620
    print('Checking for `$match` in:');
    print(messages);
621
    final bool result = messages.contains(match);
622 623 624
    messages.clear();
    return result;
  }
625
}
626

627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650
class MockDevFSOperations extends BasicMock implements DevFSOperations {
  Map<Uri, DevFSContent> devicePathToContent = <Uri, DevFSContent>{};

  @override
  Future<Uri> create(String fsName) async {
    messages.add('create $fsName');
    return Uri.parse('file:///$fsName');
  }

  @override
  Future<dynamic> destroy(String fsName) async {
    messages.add('destroy $fsName');
  }

  @override
  Future<dynamic> writeFile(String fsName, Uri deviceUri, DevFSContent content) async {
    String message = 'writeFile $fsName $deviceUri';
    if (content is DevFSFileContent) {
      message += ' ${content.file.path}';
    }
    messages.add(message);
    devicePathToContent[deviceUri] = content;
  }
}
651 652 653

class MockResidentCompiler extends BasicMock implements ResidentCompiler {
  @override
654
  void accept() { }
655 656

  @override
657
  Future<CompilerOutput> reject() async { return null; }
658 659

  @override
660
  void reset() { }
661 662

  @override
663
  Future<dynamic> shutdown() async { }
664 665 666 667 668 669 670 671

  @override
  Future<CompilerOutput> compileExpression(
    String expression,
    List<String> definitions,
    List<String> typeDefinitions,
    String libraryUri,
    String klass,
672
    bool isStatic,
673 674 675 676
  ) async {
    return null;
  }
  @override
677
  Future<CompilerOutput> recompile(String mainPath, List<Uri> invalidatedFiles, { String outputPath, String packagesFilePath }) async {
678 679
    fs.file(outputPath).createSync(recursive: true);
    fs.file(outputPath).writeAsStringSync('compiled_kernel_output');
680
    return CompilerOutput(outputPath, 0, <Uri>[]);
681 682
  }
}
683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703

/// A fake implementation of [ProcessResult].
class FakeProcessResult implements ProcessResult {
  FakeProcessResult({
    this.exitCode = 0,
    this.pid = 1,
    this.stderr,
    this.stdout,
  });

  @override
  final int exitCode;

  @override
  final int pid;

  @override
  final dynamic stderr;

  @override
  final dynamic stdout;
704 705 706

  @override
  String toString() => stdout?.toString() ?? stderr?.toString() ?? runtimeType.toString();
707
}
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729

class MockStdIn extends Mock implements IOSink {
  final StringBuffer stdInWrites = StringBuffer();

  String getAndClear() {
    final String result = stdInWrites.toString();
    stdInWrites.clear();
    return result;
  }

  @override
  void write([ Object o = '' ]) {
    stdInWrites.write(o);
  }

  @override
  void writeln([ Object o = '' ]) {
    stdInWrites.writeln(o);
  }
}

class MockStream extends Mock implements Stream<List<int>> {}