context.dart 9.42 KB
Newer Older
1 2 3 4 5
// 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';
6
import 'dart:io' as io;
7

8
import 'package:flutter_tools/src/android/android_workflow.dart';
9
import 'package:flutter_tools/src/base/config.dart';
10
import 'package:flutter_tools/src/base/context.dart';
11
import 'package:flutter_tools/src/base/file_system.dart';
12
import 'package:flutter_tools/src/base/io.dart';
13
import 'package:flutter_tools/src/base/logger.dart';
14
import 'package:flutter_tools/src/base/os.dart';
15
import 'package:flutter_tools/src/base/terminal.dart';
16
import 'package:flutter_tools/src/cache.dart';
17
import 'package:flutter_tools/src/context_runner.dart';
18
import 'package:flutter_tools/src/device.dart';
19
import 'package:flutter_tools/src/doctor.dart';
20
import 'package:flutter_tools/src/ios/simulators.dart';
21
import 'package:flutter_tools/src/ios/xcodeproj.dart';
22
import 'package:flutter_tools/src/usage.dart';
23
import 'package:flutter_tools/src/version.dart';
24
import 'package:meta/meta.dart';
25
import 'package:mockito/mockito.dart';
26
import 'package:quiver/time.dart';
27

28 29
import 'common.dart';

30 31
export 'package:flutter_tools/src/base/context.dart' show Generator;

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
typedef ContextInitializer = void Function(AppContext testContext);
39

40
@isTest
41 42
void testUsingContext(String description, dynamic testMethod(), {
  Timeout timeout,
43 44
  Map<Type, Generator> overrides = const <Type, Generator>{},
  bool initializeFlutterRoot = true,
45
  String testOn,
46
  bool skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this
47
}) {
48 49 50 51
  // Ensure we don't rely on the default [Config] constructor which will
  // leak a sticky $HOME/.flutter_settings behind!
  Directory configDir;
  tearDown(() {
52 53 54 55
    if (configDir != null) {
      tryToDelete(configDir);
      configDir = null;
    }
56 57
  });
  Config buildConfig(FileSystem fs) {
58
    configDir = fs.systemTempDirectory.createTempSync('flutter_config_dir_test.');
59
    final File settingsFile = fs.file(
60 61
      fs.path.join(configDir.path, '.flutter_settings')
    );
62
    return Config(settingsFile);
63 64
  }

65
  test(description, () async {
66
    await runInContext<dynamic>(() {
67
      return context.run<dynamic>(
68 69 70
        name: 'mocks',
        overrides: <Type, Generator>{
          Config: () => buildConfig(fs),
71 72 73 74
          DeviceManager: () => MockDeviceManager(),
          Doctor: () => MockDoctor(),
          FlutterVersion: () => MockFlutterVersion(),
          HttpClient: () => MockHttpClient(),
75
          IOSSimulatorUtils: () {
76
            final MockIOSSimulatorUtils mock = MockIOSSimulatorUtils();
77 78 79
            when(mock.getAttachedDevices()).thenReturn(<IOSSimulator>[]);
            return mock;
          },
80 81
          OutputPreferences: () => OutputPreferences(showColor: false),
          Logger: () => BufferLogger(),
82 83 84 85
          OperatingSystemUtils: () => MockOperatingSystemUtils(),
          SimControl: () => MockSimControl(),
          Usage: () => MockUsage(),
          XcodeProjectInterpreter: () => MockXcodeProjectInterpreter(),
86
          FileSystem: () => LocalFileSystemBlockingSetCurrentDirectory(),
87 88 89 90
        },
        body: () {
          final String flutterRoot = getFlutterRoot();

91
          return runZoned<Future<dynamic>>(() {
92
            try {
93
              return context.run<dynamic>(
94 95 96 97 98
                // Apply the overrides to the test context in the zone since their
                // instantiation may reference items already stored on the context.
                overrides: overrides,
                name: 'test-specific overrides',
                body: () async {
99 100 101 102 103
                  if (initializeFlutterRoot) {
                    // Provide a sane default for the flutterRoot directory. Individual
                    // tests can override this either in the test or during setup.
                    Cache.flutterRoot ??= flutterRoot;
                  }
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

                  return await testMethod();
                },
              );
            } catch (error) {
              _printBufferedErrors(context);
              rethrow;
            }
          }, onError: (dynamic error, StackTrace stackTrace) {
            io.stdout.writeln(error);
            io.stdout.writeln(stackTrace);
            _printBufferedErrors(context);
            throw error;
          });
        },
      );
    });
121
  }, timeout: timeout != null ? timeout : const Timeout(Duration(seconds: 60)),
122
      testOn: testOn, skip: skip);
123 124
}

125 126 127 128 129 130 131 132 133
void _printBufferedErrors(AppContext testContext) {
  if (testContext[Logger] is BufferLogger) {
    final BufferLogger bufferLogger = testContext[Logger];
    if (bufferLogger.errorText.isNotEmpty)
      print(bufferLogger.errorText);
    bufferLogger.clear();
  }
}

134
class MockDeviceManager implements DeviceManager {
135 136
  List<Device> devices = <Device>[];

137 138 139 140 141 142 143 144 145
  String _specifiedDeviceId;

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

146
  @override
147 148 149
  set specifiedDeviceId(String id) {
    _specifiedDeviceId = id;
  }
150 151

  @override
152 153
  bool get hasSpecifiedDeviceId => specifiedDeviceId != null;

154 155 156 157 158
  @override
  bool get hasSpecifiedAllDevices {
    return _specifiedDeviceId != null && _specifiedDeviceId == 'all';
  }

159
  @override
160
  Stream<Device> getAllConnectedDevices() => Stream<Device>.fromIterable(devices);
161

162
  @override
163
  Stream<Device> getDevicesById(String deviceId) {
164
    return Stream<Device>.fromIterable(
165
        devices.where((Device device) => device.id == deviceId));
166 167
  }

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

  void addDevice(Device device) => devices.add(device);
176 177 178 179 180 181

  @override
  bool get canListAnything => true;

  @override
  Future<List<String>> getDeviceDiagnostics() async => <String>[];
182 183
}

184
class MockAndroidLicenseValidator extends AndroidLicenseValidator {
185 186 187 188
  @override
  Future<LicensesAccepted> get licensesAccepted async => LicensesAccepted.all;
}

189
class MockDoctor extends Doctor {
190 191 192 193
  // True for testing.
  @override
  bool get canListAnything => true;

194
  // True for testing.
195
  @override
196
  bool get canLaunchAnything => true;
197 198 199 200 201 202 203

  @override
  /// Replaces the android workflow with a version that overrides licensesAccepted,
  /// to prevent individual tests from having to mock out the process for
  /// the Doctor.
  List<DoctorValidator> get validators {
    final List<DoctorValidator> superValidators = super.validators;
204
    return superValidators.map<DoctorValidator>((DoctorValidator v) {
205 206
      if (v is AndroidLicenseValidator) {
        return MockAndroidLicenseValidator();
207 208 209 210
      }
      return v;
    }).toList();
  }
211
}
212 213 214

class MockSimControl extends Mock implements SimControl {
  MockSimControl() {
215
    when(getConnectedDevices()).thenReturn(<SimDevice>[]);
216 217 218
  }
}

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

  @override
  String get name => 'fake OS name and version';
225 226 227

  @override
  String get pathVarSeparator => ';';
228
}
229 230

class MockIOSSimulatorUtils extends Mock implements IOSSimulatorUtils {}
231 232 233 234 235

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

236 237 238 239 240 241
  @override
  bool get suppressAnalytics => false;

  @override
  set suppressAnalytics(bool value) { }

242 243 244 245 246 247
  @override
  bool get enabled => true;

  @override
  set enabled(bool value) { }

248 249 250
  @override
  String get clientId => '00000000-0000-4000-0000-000000000000';

251
  @override
252
  void sendCommand(String command, { Map<String, String> parameters }) { }
253 254

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

257
  @override
258
  void sendTiming(String category, String variableName, Duration duration, { String label }) { }
259 260 261 262 263 264 265 266

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

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

  @override
267
  Future<void> ensureAnalyticsSent() => Future<void>.value();
268 269

  @override
270
  void printWelcome() { }
271 272
}

273 274
class MockXcodeProjectInterpreter implements XcodeProjectInterpreter {
  @override
275 276 277 278 279 280 281 282 283 284
  bool get isInstalled => true;

  @override
  String get versionText => 'Xcode 9.2';

  @override
  int get majorVersion => 9;

  @override
  int get minorVersion => 2;
285 286 287 288 289 290 291 292

  @override
  Map<String, String> getBuildSettings(String projectPath, String target) {
    return <String, String>{};
  }

  @override
  XcodeProjectInfo getInfo(String projectPath) {
293
    return XcodeProjectInfo(
294 295 296 297 298 299 300
      <String>['Runner'],
      <String>['Debug', 'Release'],
      <String>['Runner'],
    );
  }
}

301
class MockFlutterVersion extends Mock implements FlutterVersion {}
302 303

class MockClock extends Mock implements Clock {}
304 305

class MockHttpClient extends Mock implements HttpClient {}
306 307 308 309 310 311 312 313 314 315

class LocalFileSystemBlockingSetCurrentDirectory extends LocalFileSystem {
  @override
  set currentDirectory(dynamic value) {
    throw 'fs.currentDirectory should not be set on the local file system during '
          'tests as this can cause race conditions with concurrent tests. '
          'Consider using a MemoryFileSystem for testing if possible or refactor '
          'code to not require setting fs.currentDirectory.';
  }
}