Unverified Commit 14930901 authored by Jonah Williams's avatar Jonah Williams Committed by GitHub

[flutter_tools] remove mocks from run.dart (#83184)

parent e989d6b1
......@@ -18,6 +18,7 @@ import 'package:flutter_tools/src/base/user_messages.dart';
import 'package:flutter_tools/src/build_info.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/run.dart';
import 'package:flutter_tools/src/devfs.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/project.dart';
......@@ -26,7 +27,7 @@ import 'package:flutter_tools/src/resident_runner.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/vmservice.dart';
import 'package:meta/meta.dart';
import 'package:mockito/mockito.dart';
import 'package:test/fake.dart';
import 'package:vm_service/vm_service.dart';
import '../../src/common.dart';
......@@ -37,7 +38,7 @@ import '../../src/test_flutter_command_runner.dart';
void main() {
group('run', () {
MockDeviceManager mockDeviceManager;
FakeDeviceManager mockDeviceManager;
FileSystem fileSystem;
setUpAll(() {
......@@ -45,7 +46,7 @@ void main() {
});
setUp(() {
mockDeviceManager = MockDeviceManager();
mockDeviceManager = FakeDeviceManager();
fileSystem = MemoryFileSystem.test();
});
......@@ -138,42 +139,32 @@ void main() {
group('run app', () {
MemoryFileSystem fs;
Artifacts artifacts;
MockCache mockCache;
TestUsage usage;
Directory tempDir;
setUpAll(() {
Cache.disableLocking();
});
setUp(() {
artifacts = Artifacts.test();
mockCache = MockCache();
usage = TestUsage();
fs = MemoryFileSystem.test();
tempDir = fs.systemTempDirectory.createTempSync('flutter_run_test.');
fs.currentDirectory = tempDir;
tempDir.childFile('pubspec.yaml')
fs.currentDirectory.childFile('pubspec.yaml')
.writeAsStringSync('name: flutter_app');
tempDir.childFile('.packages')
fs.currentDirectory.childFile('.packages')
.writeAsStringSync('# Generated by pub on 2019-11-25 12:38:01.801784.');
final Directory libDir = tempDir.childDirectory('lib');
final Directory libDir = fs.currentDirectory.childDirectory('lib');
libDir.createSync();
final File mainFile = libDir.childFile('main.dart');
mainFile.writeAsStringSync('void main() {}');
when(mockDeviceManager.hasSpecifiedDeviceId).thenReturn(false);
when(mockDeviceManager.hasSpecifiedAllDevices).thenReturn(false);
});
testUsingContext('exits with a user message when no supported devices attached', () async {
final RunCommand command = RunCommand();
const List<Device> noDevices = <Device>[];
when(mockDeviceManager.getDevices()).thenAnswer(
(Invocation invocation) => Future<List<Device>>.value(noDevices)
);
when(mockDeviceManager.findTargetDevices(any, timeout: anyNamed('timeout'))).thenAnswer(
(Invocation invocation) => Future<List<Device>>.value(noDevices)
);
mockDeviceManager
..devices = <Device>[]
..targetDevices = <Device>[];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
......@@ -192,24 +183,18 @@ void main() {
DeviceManager: () => mockDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('fails when targeted device is not Android with --device-user', () async {
globals.fs.file('pubspec.yaml').createSync();
globals.fs.file('.packages').writeAsStringSync('\n');
globals.fs.file('lib/main.dart').createSync(recursive: true);
fs.file('pubspec.yaml').createSync();
fs.file('.packages').writeAsStringSync('\n');
fs.file('lib/main.dart').createSync(recursive: true);
final FakeDevice device = FakeDevice(isLocalEmulator: true);
when(mockDeviceManager.getAllConnectedDevices()).thenAnswer((Invocation invocation) async {
return <Device>[device];
});
when(mockDeviceManager.getDevices()).thenAnswer((Invocation invocation) async {
return <Device>[device];
});
when(mockDeviceManager.findTargetDevices(any, timeout: anyNamed('timeout'))).thenAnswer((Invocation invocation) async {
return <Device>[device];
});
when(mockDeviceManager.hasSpecifiedAllDevices).thenReturn(false);
when(mockDeviceManager.deviceDiscoverers).thenReturn(<DeviceDiscovery>[]);
mockDeviceManager
..devices = <Device>[device]
..targetDevices = <Device>[device];
final RunCommand command = RunCommand();
await expectLater(createTestCommandRunner(command).run(<String>[
......@@ -219,35 +204,19 @@ void main() {
'10',
]), throwsToolExit(message: '--device-user is only supported for Android. At least one Android device is required.'));
}, overrides: <Type, Generator>{
FileSystem: () => MemoryFileSystem.test(),
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
DeviceManager: () => mockDeviceManager,
Stdio: () => FakeStdio(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('shows unsupported devices when no supported devices are found', () async {
final RunCommand command = RunCommand();
final MockDevice mockDevice = MockDevice(TargetPlatform.android_arm);
when(mockDevice.isLocalEmulator).thenAnswer((Invocation invocation) => Future<bool>.value(true));
when(mockDevice.isSupported()).thenAnswer((Invocation invocation) => true);
when(mockDevice.supportsFastStart).thenReturn(true);
when(mockDevice.id).thenReturn('mock-id');
when(mockDevice.name).thenReturn('mock-name');
when(mockDevice.platformType).thenReturn(PlatformType.android);
when(mockDevice.targetPlatformDisplayName)
.thenAnswer((Invocation invocation) async => 'mock-platform');
when(mockDevice.sdkNameAndVersion).thenAnswer((Invocation invocation) => Future<String>.value('api-14'));
when(mockDeviceManager.getDevices()).thenAnswer((Invocation invocation) {
return Future<List<Device>>.value(<Device>[
mockDevice,
]);
});
when(mockDeviceManager.findTargetDevices(any, timeout: anyNamed('timeout'))).thenAnswer(
(Invocation invocation) => Future<List<Device>>.value(<Device>[]),
);
final FakeDevice mockDevice = FakeDevice(targetPlatform: TargetPlatform.android_arm, isLocalEmulator: true, sdkNameAndVersion: 'api-14');
mockDeviceManager
..devices = <Device>[mockDevice]
..targetDevices = <Device>[];
await expectLater(
() => createTestCommandRunner(command).run(<String>[
......@@ -278,88 +247,24 @@ void main() {
DeviceManager: () => mockDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('updates cache before checking for devices', () async {
final RunCommand command = RunCommand();
// Called as part of requiredArtifacts()
when(mockDeviceManager.getDevices()).thenAnswer(
(Invocation invocation) => Future<List<Device>>.value(<Device>[])
);
// No devices are attached, we just want to verify update the cache
// BEFORE checking for devices
const Duration timeout = Duration(seconds: 10);
when(mockDeviceManager.findTargetDevices(any, timeout: timeout)).thenAnswer(
(Invocation invocation) => Future<List<Device>>.value(<Device>[])
);
try {
await createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--device-timeout',
'10',
]);
fail('Exception expected');
} on ToolExit catch (e) {
// We expect a ToolExit because no devices are attached
expect(e.message, null);
} on Exception catch (e) {
fail('ToolExit expected, got $e');
}
verifyInOrder(<void>[
// cache update
mockCache.updateAll(<DevelopmentArtifact>{DevelopmentArtifact.universal}),
// as part of gathering `requiredArtifacts`
mockDeviceManager.getDevices(),
// in validateCommand()
mockDeviceManager.findTargetDevices(any, timeout: anyNamed('timeout')),
]);
}, overrides: <Type, Generator>{
Cache: () => mockCache,
DeviceManager: () => mockDeviceManager,
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
});
testUsingContext('passes device target platform to usage', () async {
final RunCommand command = RunCommand();
final MockDevice mockDevice = MockDevice(TargetPlatform.ios);
when(mockDevice.supportsRuntimeMode(any)).thenAnswer((Invocation invocation) => true);
when(mockDevice.isLocalEmulator).thenAnswer((Invocation invocation) => Future<bool>.value(false));
when(mockDevice.getLogReader(app: anyNamed('app'))).thenReturn(FakeDeviceLogReader());
when(mockDevice.supportsFastStart).thenReturn(true);
when(mockDevice.sdkNameAndVersion).thenAnswer((Invocation invocation) => Future<String>.value('iOS 13'));
// App fails to start because we're only interested in usage
when(mockDevice.startApp(
any,
mainPath: anyNamed('mainPath'),
debuggingOptions: anyNamed('debuggingOptions'),
platformArgs: anyNamed('platformArgs'),
route: anyNamed('route'),
prebuiltApplication: anyNamed('prebuiltApplication'),
ipv6: anyNamed('ipv6'),
userIdentifier: anyNamed('userIdentifier'),
)).thenAnswer((Invocation invocation) => Future<LaunchResult>.value(LaunchResult.failed()));
when(mockDeviceManager.getDevices()).thenAnswer(
(Invocation invocation) => Future<List<Device>>.value(<Device>[mockDevice])
);
final FakeDevice mockDevice = FakeDevice(targetPlatform: TargetPlatform.ios, sdkNameAndVersion: 'iOS 13')
..startAppSuccess = false;
when(mockDeviceManager.findTargetDevices(any, timeout: anyNamed('timeout'))).thenAnswer(
(Invocation invocation) => Future<List<Device>>.value(<Device>[mockDevice])
);
mockDeviceManager
..devices = <Device>[
mockDevice,
]
..targetDevices = <Device>[
mockDevice,
];
final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_run_test.');
tempDir.childDirectory('ios').childFile('AppDelegate.swift').createSync(recursive: true);
tempDir.childFile('.packages').createSync();
tempDir.childDirectory('lib').childFile('main.dart').createSync(recursive: true);
tempDir.childFile('pubspec.yaml')
..createSync()
..writeAsStringSync('# Hello, World');
globals.fs.currentDirectory = tempDir;
// Causes swift to be detected in the analytics.
fs.currentDirectory.childDirectory('ios').childFile('AppDelegate.swift').createSync(recursive: true);
await expectToolExitLater(createTestCommandRunner(command).run(<String>[
'run',
......@@ -384,34 +289,24 @@ void main() {
});
testUsingContext('should only request artifacts corresponding to connected devices', () async {
when(mockDeviceManager.getDevices()).thenAnswer((Invocation invocation) {
return Future<List<Device>>.value(<Device>[
MockDevice(TargetPlatform.android_arm),
]);
});
mockDeviceManager.devices = <Device>[FakeDevice(targetPlatform: TargetPlatform.android_arm)];
expect(await RunCommand().requiredArtifacts, unorderedEquals(<DevelopmentArtifact>{
DevelopmentArtifact.universal,
DevelopmentArtifact.androidGenSnapshot,
}));
when(mockDeviceManager.getDevices()).thenAnswer((Invocation invocation) {
return Future<List<Device>>.value(<Device>[
MockDevice(TargetPlatform.ios),
]);
});
mockDeviceManager.devices = <Device>[FakeDevice(targetPlatform: TargetPlatform.ios)];
expect(await RunCommand().requiredArtifacts, unorderedEquals(<DevelopmentArtifact>{
DevelopmentArtifact.universal,
DevelopmentArtifact.iOS,
}));
when(mockDeviceManager.getDevices()).thenAnswer((Invocation invocation) {
return Future<List<Device>>.value(<Device>[
MockDevice(TargetPlatform.ios),
MockDevice(TargetPlatform.android_arm),
]);
});
mockDeviceManager.devices = <Device>[
FakeDevice(targetPlatform: TargetPlatform.ios),
FakeDevice(targetPlatform: TargetPlatform.android_arm),
];
expect(await RunCommand().requiredArtifacts, unorderedEquals(<DevelopmentArtifact>{
DevelopmentArtifact.universal,
......@@ -419,11 +314,9 @@ void main() {
DevelopmentArtifact.androidGenSnapshot,
}));
when(mockDeviceManager.getDevices()).thenAnswer((Invocation invocation) {
return Future<List<Device>>.value(<Device>[
MockDevice(TargetPlatform.web_javascript),
]);
});
mockDeviceManager.devices = <Device>[
FakeDevice(targetPlatform: TargetPlatform.web_javascript),
];
expect(await RunCommand().requiredArtifacts, unorderedEquals(<DevelopmentArtifact>{
DevelopmentArtifact.universal,
......@@ -431,6 +324,9 @@ void main() {
}));
}, overrides: <Type, Generator>{
DeviceManager: () => mockDeviceManager,
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
});
......@@ -485,6 +381,10 @@ void main() {
'run',
'--no-pub',
]), contains('Lost connection to device.'));
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Flutter run does not catch other RPC errors', () async {
......@@ -497,6 +397,10 @@ void main() {
'run',
'--no-pub',
]), throwsA(isA<RPCError>()));
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Passes sksl bundle info the build options', () async {
......@@ -507,6 +411,10 @@ void main() {
'--no-pub',
'--bundle-sksl-path=foo.json',
]), throwsToolExit(message: 'No SkSL shader bundle found at foo.json'));
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('Configures web connection options to use web sockets by default', () async {
......@@ -521,21 +429,38 @@ void main() {
expect(options.webUseSseForDebugBackend, false);
expect(options.webUseSseForDebugProxy, false);
expect(options.webUseSseForInjectedClient, false);
}, overrides: <Type, Generator>{
Cache: () => Cache.test(processManager: FakeProcessManager.any()),
FileSystem: () => MemoryFileSystem.test(),
ProcessManager: () => FakeProcessManager.any(),
});
}
class MockCache extends Mock implements Cache {}
class FakeDeviceManager extends Fake implements DeviceManager {
List<Device> devices = <Device>[];
List<Device> targetDevices = <Device>[];
class MockDeviceManager extends Mock implements DeviceManager {}
class MockDevice extends Mock implements Device {
MockDevice(this._targetPlatform);
@override
String specifiedDeviceId;
final TargetPlatform _targetPlatform;
@override
bool hasSpecifiedAllDevices = false;
@override
Future<TargetPlatform> get targetPlatform async => Future<TargetPlatform>.value(_targetPlatform);
bool hasSpecifiedDeviceId = false;
@override
Future<List<Device>> getDevices() async {
return devices;
}
@override
Future<List<Device>> findTargetDevices(FlutterProject flutterProject, {Duration timeout}) async {
return targetDevices;
}
}
class TestRunCommand extends RunCommand {
@override
// ignore: must_call_super
......@@ -545,13 +470,19 @@ class TestRunCommand extends RunCommand {
}
class FakeDevice extends Fake implements Device {
FakeDevice({bool isLocalEmulator = false})
: _isLocalEmulator = isLocalEmulator;
FakeDevice({bool isLocalEmulator = false, TargetPlatform targetPlatform = TargetPlatform.ios, String sdkNameAndVersion = ''})
: _isLocalEmulator = isLocalEmulator,
_targetPlatform = targetPlatform,
_sdkNameAndVersion = sdkNameAndVersion;
static const int kSuccess = 1;
static const int kFailure = -1;
final TargetPlatform _targetPlatform = TargetPlatform.ios;
final TargetPlatform _targetPlatform;
final bool _isLocalEmulator;
final String _sdkNameAndVersion;
@override
Category get category => Category.mobile;
@override
String get id => 'fake_device';
......@@ -570,8 +501,20 @@ class FakeDevice extends Fake implements Device {
@override
bool get supportsFastStart => false;
bool supported = true;
@override
bool isSupportedForProject(FlutterProject flutterProject) => true;
@override
bool isSupported() => supported;
@override
Future<String> get sdkNameAndVersion => Future<String>.value(_sdkNameAndVersion);
@override
Future<String> get sdkNameAndVersion => Future<String>.value('');
Future<String> get targetPlatformDisplayName async =>
getNameForTargetPlatform(await targetPlatform);
@override
DeviceLogReader getLogReader({
......@@ -590,6 +533,16 @@ class FakeDevice extends Fake implements Device {
@override
final PlatformType platformType = PlatformType.ios;
bool startAppSuccess = true;
@override
DevFSWriter createDevFSWriter(
covariant ApplicationPackage app,
String userIdentifier,
) {
return null;
}
@override
Future<LaunchResult> startApp(
ApplicationPackage package, {
......@@ -602,6 +555,9 @@ class FakeDevice extends Fake implements Device {
bool ipv6 = false,
String userIdentifier,
}) async {
if (!startAppSuccess) {
return LaunchResult.failed();
}
final String dartFlags = debuggingOptions.dartFlags;
// In release mode, --dart-flags should be set to the empty string and
// provided flags should be dropped. In debug and profile modes,
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment