context.dart 8.35 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/io.dart';
12
import 'package:flutter_tools/src/base/logger.dart';
13
import 'package:flutter_tools/src/base/os.dart';
14
import 'package:flutter_tools/src/base/platform.dart';
15
import 'package:flutter_tools/src/base/port_scanner.dart';
16
import 'package:flutter_tools/src/base/terminal.dart';
17
import 'package:flutter_tools/src/cache.dart';
18
import 'package:flutter_tools/src/devfs.dart';
19
import 'package:flutter_tools/src/device.dart';
20 21
import 'package:flutter_tools/src/doctor.dart';
import 'package:flutter_tools/src/ios/mac.dart';
22
import 'package:flutter_tools/src/ios/simulators.dart';
23
import 'package:flutter_tools/src/run_hot.dart';
24
import 'package:flutter_tools/src/usage.dart';
25
import 'package:flutter_tools/src/version.dart';
26
import 'package:mockito/mockito.dart';
27
import 'package:process/process.dart';
28
import 'package:quiver/time.dart';
29 30
import 'package:test/test.dart';

31 32
import 'common.dart';

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

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

39 40
typedef dynamic Generator();

41 42 43
typedef void ContextInitializer(AppContext testContext);

void _defaultInitializeContext(AppContext testContext) {
44
  testContext
45
    ..putIfAbsent(AnsiTerminal, () => new AnsiTerminal())
46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
    ..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())
61
    ..putIfAbsent(Usage, () => new MockUsage())
62
    ..putIfAbsent(FlutterVersion, () => new MockFlutterVersion())
63 64
    ..putIfAbsent(Clock, () => const Clock())
    ..putIfAbsent(HttpClient, () => new MockHttpClient());
65 66
}

67 68
void testUsingContext(String description, dynamic testMethod(), {
  Timeout timeout,
69
  Map<Type, Generator> overrides: const <Type, Generator>{},
70
  ContextInitializer initializeContext: _defaultInitializeContext,
71
  String testOn,
72
  bool skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this
73
}) {
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88

  // Ensure we don't rely on the default [Config] constructor which will
  // leak a sticky $HOME/.flutter_settings behind!
  Directory configDir;
  tearDown(() {
    configDir?.deleteSync(recursive: true);
    configDir = null;
  });
  Config buildConfig(FileSystem fs) {
    configDir = fs.systemTempDirectory.createTempSync('config-dir');
    final File settingsFile = fs.file(
        fs.path.join(configDir.path, '.flutter_settings'));
    return new Config(settingsFile);
  }

89
  test(description, () async {
90
    final AppContext testContext = new AppContext();
91

92
    // The context always starts with these value since others depend on them.
93
    testContext
94
      ..putIfAbsent(Stdio, () => const Stdio())
95 96 97 98
      ..putIfAbsent(Platform, () => const LocalPlatform())
      ..putIfAbsent(FileSystem, () => const LocalFileSystem())
      ..putIfAbsent(ProcessManager, () => const LocalProcessManager())
      ..putIfAbsent(Logger, () => new BufferLogger())
99
      ..putIfAbsent(Config, () => buildConfig(testContext[FileSystem]));
100

101 102 103 104 105
    // Apply the initializer after seeding the base value above.
    initializeContext(testContext);

    final String flutterRoot = getFlutterRoot();

106
    try {
107
      return await testContext.runInZone(() async {
108 109 110 111 112
        // 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());
        });
113

114
        // Provide a sane default for the flutterRoot directory. Individual
115 116 117
        // tests can override this either in the test or during setup.
        Cache.flutterRoot ??= flutterRoot;

118 119 120 121
        return await testMethod();
      }, onError: (dynamic error, StackTrace stackTrace) {
        _printBufferedErrors(testContext);
        throw error;
122
      });
123
    } catch (error) {
124
      _printBufferedErrors(testContext);
125
      rethrow;
126 127
    }

128
  }, timeout: timeout, testOn: testOn, skip: skip);
129 130
}

131 132 133 134 135 136 137 138 139
void _printBufferedErrors(AppContext testContext) {
  if (testContext[Logger] is BufferLogger) {
    final BufferLogger bufferLogger = testContext[Logger];
    if (bufferLogger.errorText.isNotEmpty)
      print(bufferLogger.errorText);
    bufferLogger.clear();
  }
}

140 141 142 143 144 145 146 147 148 149
class MockPortScanner extends PortScanner {
  static int _nextAvailablePort = 12345;

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

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

150
class MockDeviceManager implements DeviceManager {
151 152
  List<Device> devices = <Device>[];

153 154 155 156 157 158 159 160 161
  String _specifiedDeviceId;

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

162
  @override
163 164 165
  set specifiedDeviceId(String id) {
    _specifiedDeviceId = id;
  }
166 167

  @override
168 169
  bool get hasSpecifiedDeviceId => specifiedDeviceId != null;

170 171 172 173 174
  @override
  bool get hasSpecifiedAllDevices {
    return _specifiedDeviceId != null && _specifiedDeviceId == 'all';
  }

175
  @override
176
  Stream<Device> getAllConnectedDevices() => new Stream<Device>.fromIterable(devices);
177

178
  @override
179 180 181
  Stream<Device> getDevicesById(String deviceId) {
    return new Stream<Device>.fromIterable(
        devices.where((Device device) => device.id == deviceId));
182 183
  }

184
  @override
185 186 187 188
  Stream<Device> getDevices() {
    return hasSpecifiedDeviceId
        ? getDevicesById(specifiedDeviceId)
        : getAllConnectedDevices();
189 190 191
  }

  void addDevice(Device device) => devices.add(device);
192 193 194 195 196 197

  @override
  bool get canListAnything => true;

  @override
  Future<List<String>> getDeviceDiagnostics() async => <String>[];
198 199 200
}

class MockDoctor extends Doctor {
201 202 203 204
  // True for testing.
  @override
  bool get canListAnything => true;

205
  // True for testing.
206
  @override
207
  bool get canLaunchAnything => true;
208
}
209 210 211

class MockSimControl extends Mock implements SimControl {
  MockSimControl() {
212
    when(getConnectedDevices()).thenReturn(<SimDevice>[]);
213 214 215
  }
}

216 217 218
class MockOperatingSystemUtils extends Mock implements OperatingSystemUtils {
  @override
  List<File> whichAll(String execName) => <File>[];
219 220 221

  @override
  String get name => 'fake OS name and version';
222
}
223 224

class MockIOSSimulatorUtils extends Mock implements IOSSimulatorUtils {}
225 226 227 228 229

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

230 231 232 233 234 235
  @override
  bool get suppressAnalytics => false;

  @override
  set suppressAnalytics(bool value) { }

236 237 238 239 240 241
  @override
  bool get enabled => true;

  @override
  set enabled(bool value) { }

242 243 244
  @override
  String get clientId => '00000000-0000-4000-0000-000000000000';

245
  @override
246
  void sendCommand(String command, { Map<String, String> parameters }) { }
247 248

  @override
249
  void sendEvent(String category, String parameter, { Map<String, String> parameters }) { }
250

251
  @override
252
  void sendTiming(String category, String variableName, Duration duration, { String label }) { }
253 254 255 256 257 258 259 260 261

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

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

  @override
  Future<Null> ensureAnalyticsSent() => new Future<Null>.value();
262 263

  @override
264
  void printWelcome() { }
265 266
}

267
class MockFlutterVersion extends Mock implements FlutterVersion {}
268 269

class MockClock extends Mock implements Clock {}
270 271

class MockHttpClient extends Mock implements HttpClient {}