context.dart 7.42 KB
Newer Older
1 2 3 4 5 6
// Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

import 'dart:async';

7
import 'package:flutter_tools/src/artifacts.dart';
8
import 'package:flutter_tools/src/base/config.dart';
9
import 'package:flutter_tools/src/base/context.dart';
10
import 'package:flutter_tools/src/base/file_system.dart';
11
import 'package:flutter_tools/src/base/logger.dart';
12
import 'package:flutter_tools/src/base/os.dart';
13
import 'package:flutter_tools/src/base/platform.dart';
14
import 'package:flutter_tools/src/base/port_scanner.dart';
15
import 'package:flutter_tools/src/base/terminal.dart';
16
import 'package:flutter_tools/src/cache.dart';
17
import 'package:flutter_tools/src/devfs.dart';
18
import 'package:flutter_tools/src/device.dart';
19 20
import 'package:flutter_tools/src/doctor.dart';
import 'package:flutter_tools/src/ios/mac.dart';
21
import 'package:flutter_tools/src/ios/simulators.dart';
22
import 'package:flutter_tools/src/run_hot.dart';
23
import 'package:flutter_tools/src/usage.dart';
24
import 'package:flutter_tools/src/version.dart';
25
import 'package:mockito/mockito.dart';
26
import 'package:process/process.dart';
27
import 'package:quiver/time.dart';
28 29
import 'package:test/test.dart';

30 31
import 'common.dart';

32 33 34
/// Return the test logger. This assumes that the current Logger is a BufferLogger.
BufferLogger get testLogger => context[Logger];

35 36 37
MockDeviceManager get testDeviceManager => context[DeviceManager];
MockDoctor get testDoctor => context[Doctor];

38 39
typedef dynamic Generator();

40 41 42
typedef void ContextInitializer(AppContext testContext);

void _defaultInitializeContext(AppContext testContext) {
43
  testContext
44
    ..putIfAbsent(AnsiTerminal, () => new AnsiTerminal())
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
    ..putIfAbsent(DeviceManager, () => new MockDeviceManager())
    ..putIfAbsent(DevFSConfig, () => new DevFSConfig())
    ..putIfAbsent(Doctor, () => new MockDoctor())
    ..putIfAbsent(HotRunnerConfig, () => new HotRunnerConfig())
    ..putIfAbsent(Cache, () => new Cache())
    ..putIfAbsent(Artifacts, () => new CachedArtifacts())
    ..putIfAbsent(OperatingSystemUtils, () => new MockOperatingSystemUtils())
    ..putIfAbsent(PortScanner, () => new MockPortScanner())
    ..putIfAbsent(Xcode, () => new Xcode())
    ..putIfAbsent(IOSSimulatorUtils, () {
      final MockIOSSimulatorUtils mock = new MockIOSSimulatorUtils();
      when(mock.getAttachedDevices()).thenReturn(<IOSSimulator>[]);
      return mock;
    })
    ..putIfAbsent(SimControl, () => new MockSimControl())
60
    ..putIfAbsent(Usage, () => new MockUsage())
61 62
    ..putIfAbsent(FlutterVersion, () => new MockFlutterVersion())
    ..putIfAbsent(Clock, () => const Clock());
63 64
}

65 66
void testUsingContext(String description, dynamic testMethod(), {
  Timeout timeout,
67
  Map<Type, Generator> overrides: const <Type, Generator>{},
68
  ContextInitializer initializeContext: _defaultInitializeContext,
69
  bool skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this
70
}) {
71
  test(description, () async {
72
    final AppContext testContext = new AppContext();
73

74
    // The context always starts with these value since others depend on them.
75 76 77 78 79 80
    testContext
      ..putIfAbsent(Platform, () => const LocalPlatform())
      ..putIfAbsent(FileSystem, () => const LocalFileSystem())
      ..putIfAbsent(ProcessManager, () => const LocalProcessManager())
      ..putIfAbsent(Logger, () => new BufferLogger())
      ..putIfAbsent(Config, () => new Config());
81

82 83 84 85 86
    // Apply the initializer after seeding the base value above.
    initializeContext(testContext);

    final String flutterRoot = getFlutterRoot();

87
    try {
88
      return await testContext.runInZone(() async {
89 90 91 92 93
        // Apply the overrides to the test context in the zone since their
        // instantiation may reference items already stored on the context.
        overrides.forEach((Type type, dynamic value()) {
          context.setVariable(type, value());
        });
94

95
        // Provide a sane default for the flutterRoot directory. Individual
96 97 98
        // tests can override this either in the test or during setup.
        Cache.flutterRoot ??= flutterRoot;

99 100 101 102
        return await testMethod();
      }, onError: (dynamic error, StackTrace stackTrace) {
        _printBufferedErrors(testContext);
        throw error;
103
      });
104
    } catch (error) {
105
      _printBufferedErrors(testContext);
106
      rethrow;
107 108
    }

109
  }, timeout: timeout, skip: skip);
110 111
}

112 113 114 115 116 117 118 119 120
void _printBufferedErrors(AppContext testContext) {
  if (testContext[Logger] is BufferLogger) {
    final BufferLogger bufferLogger = testContext[Logger];
    if (bufferLogger.errorText.isNotEmpty)
      print(bufferLogger.errorText);
    bufferLogger.clear();
  }
}

121 122 123 124 125 126 127 128 129 130
class MockPortScanner extends PortScanner {
  static int _nextAvailablePort = 12345;

  @override
  Future<bool> isPortAvailable(int port) async => true;

  @override
  Future<int> findAvailablePort() async => _nextAvailablePort++;
}

131
class MockDeviceManager implements DeviceManager {
132 133
  List<Device> devices = <Device>[];

134 135 136 137 138 139 140 141 142
  String _specifiedDeviceId;

  @override
  String get specifiedDeviceId {
    if (_specifiedDeviceId == null || _specifiedDeviceId == 'all')
      return null;
    return _specifiedDeviceId;
  }

143
  @override
144 145 146
  set specifiedDeviceId(String id) {
    _specifiedDeviceId = id;
  }
147 148

  @override
149 150
  bool get hasSpecifiedDeviceId => specifiedDeviceId != null;

151 152 153 154 155
  @override
  bool get hasSpecifiedAllDevices {
    return _specifiedDeviceId != null && _specifiedDeviceId == 'all';
  }

156
  @override
157
  Stream<Device> getAllConnectedDevices() => new Stream<Device>.fromIterable(devices);
158

159
  @override
160 161 162
  Stream<Device> getDevicesById(String deviceId) {
    return new Stream<Device>.fromIterable(
        devices.where((Device device) => device.id == deviceId));
163 164
  }

165
  @override
166 167 168 169
  Stream<Device> getDevices() {
    return hasSpecifiedDeviceId
        ? getDevicesById(specifiedDeviceId)
        : getAllConnectedDevices();
170 171 172 173 174 175
  }

  void addDevice(Device device) => devices.add(device);
}

class MockDoctor extends Doctor {
176 177 178 179
  // True for testing.
  @override
  bool get canListAnything => true;

180
  // True for testing.
181
  @override
182
  bool get canLaunchAnything => true;
183
}
184 185 186

class MockSimControl extends Mock implements SimControl {
  MockSimControl() {
187
    when(getConnectedDevices()).thenReturn(<SimDevice>[]);
188 189 190
  }
}

191 192 193
class MockOperatingSystemUtils extends Mock implements OperatingSystemUtils {
  @override
  List<File> whichAll(String execName) => <File>[];
194 195 196

  @override
  String get name => 'fake OS name and version';
197
}
198 199

class MockIOSSimulatorUtils extends Mock implements IOSSimulatorUtils {}
200 201 202 203 204

class MockUsage implements Usage {
  @override
  bool get isFirstRun => false;

205 206 207 208 209 210
  @override
  bool get suppressAnalytics => false;

  @override
  set suppressAnalytics(bool value) { }

211 212 213 214 215 216
  @override
  bool get enabled => true;

  @override
  set enabled(bool value) { }

217 218 219
  @override
  String get clientId => '00000000-0000-4000-0000-000000000000';

220 221 222 223 224 225
  @override
  void sendCommand(String command) { }

  @override
  void sendEvent(String category, String parameter) { }

226
  @override
227
  void sendTiming(String category, String variableName, Duration duration, { String label }) { }
228 229 230 231 232 233 234 235 236

  @override
  void sendException(dynamic exception, StackTrace trace) { }

  @override
  Stream<Map<String, dynamic>> get onSend => null;

  @override
  Future<Null> ensureAnalyticsSent() => new Future<Null>.value();
237 238

  @override
239
  void printWelcome() { }
240 241
}

242
class MockFlutterVersion extends Mock implements FlutterVersion {}
243 244

class MockClock extends Mock implements Clock {}