Unverified Commit 8426910a authored by Ian Hickson's avatar Ian Hickson Committed by GitHub

Revert "[O] Remove many timeouts. (#23531)" (#25646)

This reverts commit 76f70810.
parent 76f70810
...@@ -50,22 +50,20 @@ void main() { ...@@ -50,22 +50,20 @@ void main() {
'--verbose', '--verbose',
'-d', '-d',
device.deviceId, device.deviceId,
'lib/commands.dart', 'lib/commands.dart'
], ],
); );
final StreamController<String> stdout = StreamController<String>.broadcast(); final StreamController<String> stdout =
StreamController<String>.broadcast();
transformToLines(run.stdout).listen((String line) { transformToLines(run.stdout).listen((String line) {
print('run:stdout: $line'); print('run:stdout: $line');
stdout.add(line); stdout.add(line);
final dynamic json = parseFlutterResponse(line); final dynamic json = parseFlutterResponse(line);
if (json != null) { if (json != null && json['event'] == 'app.debugPort') {
if (json['event'] == 'app.debugPort') {
vmServicePort = Uri.parse(json['params']['wsUri']).port; vmServicePort = Uri.parse(json['params']['wsUri']).port;
print('service protocol connection available at port $vmServicePort'); print('service protocol connection available at port $vmServicePort');
} else if (json['event'] == 'app.started') { } else if (json != null && json['event'] == 'app.started') {
appId = json['params']['appId']; appId = json['params']['appId'];
print('application identifier is $appId');
}
} }
if (vmServicePort != null && appId != null && !ready.isCompleted) { if (vmServicePort != null && appId != null && !ready.isCompleted) {
print('run: ready!'); print('run: ready!');
...@@ -75,7 +73,6 @@ void main() { ...@@ -75,7 +73,6 @@ void main() {
}); });
transformToLines(run.stderr).listen((String line) { transformToLines(run.stderr).listen((String line) {
stderr.writeln('run:stderr: $line'); stderr.writeln('run:stderr: $line');
ok = false;
}); });
run.exitCode.then<void>((int exitCode) { run.exitCode.then<void>((int exitCode) {
ok = false; ok = false;
...@@ -84,15 +81,17 @@ void main() { ...@@ -84,15 +81,17 @@ void main() {
if (!ok) if (!ok)
throw 'Failed to run test app.'; throw 'Failed to run test app.';
final VMServiceClient client = VMServiceClient.connect( final VMServiceClient client =
'ws://localhost:$vmServicePort/ws' VMServiceClient.connect('ws://localhost:$vmServicePort/ws');
);
int id = 1; int id = 1;
Future<Map<String, dynamic>> sendRequest(String method, dynamic params) async { Future<Map<String, dynamic>> sendRequest(
String method, dynamic params) async {
final int requestId = id++; final int requestId = id++;
final Completer<Map<String, dynamic>> response = Completer<Map<String, dynamic>>(); final Completer<Map<String, dynamic>> response =
final StreamSubscription<String> responseSubscription = stdout.stream.listen((String line) { Completer<Map<String, dynamic>>();
final StreamSubscription<String> responseSubscription =
stdout.stream.listen((String line) {
final Map<String, dynamic> json = parseFlutterResponse(line); final Map<String, dynamic> json = parseFlutterResponse(line);
if (json != null && json['id'] == requestId) if (json != null && json['id'] == requestId)
response.complete(json); response.complete(json);
...@@ -111,35 +110,27 @@ void main() { ...@@ -111,35 +110,27 @@ void main() {
} }
print('test: sending two hot reloads...'); print('test: sending two hot reloads...');
final Future<dynamic> hotReload1 = sendRequest( final Future<dynamic> hotReload1 = sendRequest('app.restart',
'app.restart', <String, dynamic>{'appId': appId, 'fullRestart': false});
<String, dynamic>{'appId': appId, 'fullRestart': false}, final Future<dynamic> hotReload2 = sendRequest('app.restart',
); <String, dynamic>{'appId': appId, 'fullRestart': false});
final Future<dynamic> hotReload2 = sendRequest( final Future<List<dynamic>> reloadRequests =
'app.restart', Future.wait<dynamic>(<Future<dynamic>>[hotReload1, hotReload2]);
<String, dynamic>{'appId': appId, 'fullRestart': false}, final dynamic results = await Future
); .any<dynamic>(<Future<dynamic>>[run.exitCode, reloadRequests]);
final Future<List<dynamic>> reloadRequests = Future.wait<dynamic>(<Future<dynamic>>[
hotReload1,
hotReload2,
]);
final dynamic results = await Future.any<dynamic>(<Future<dynamic>>[
run.exitCode,
reloadRequests,
]);
if (!ok) if (!ok)
throw 'App failed or crashed during hot reloads.'; throw 'App crashed during hot reloads.';
final List<dynamic> responses = results; final List<dynamic> responses = results;
final List<dynamic> errorResponses = responses.where( final List<dynamic> errorResponses =
(dynamic r) => r['error'] != null responses.where((dynamic r) => r['error'] != null).toList();
).toList(); final List<dynamic> successResponses = responses
final List<dynamic> successResponses = responses.where( .where((dynamic r) =>
(dynamic r) => r['error'] == null && r['error'] == null &&
r['result'] != null && r['result'] != null &&
r['result']['code'] == 0 r['result']['code'] == 0)
).toList(); .toList();
if (errorResponses.length != 1) if (errorResponses.length != 1)
throw 'Did not receive the expected (exactly one) hot reload error response.'; throw 'Did not receive the expected (exactly one) hot reload error response.';
...@@ -149,10 +140,8 @@ void main() { ...@@ -149,10 +140,8 @@ void main() {
if (successResponses.length != 1) if (successResponses.length != 1)
throw 'Did not receive the expected (exactly one) successful hot reload response.'; throw 'Did not receive the expected (exactly one) successful hot reload response.';
final dynamic hotReload3 = await sendRequest( final dynamic hotReload3 = await sendRequest('app.restart',
'app.restart', <String, dynamic>{'appId': appId, 'fullRestart': false});
<String, dynamic>{'appId': appId, 'fullRestart': false},
);
if (hotReload3['error'] != null) if (hotReload3['error'] != null)
throw 'Received an error response from a hot reload after all other hot reloads had completed.'; throw 'Received an error response from a hot reload after all other hot reloads had completed.';
...@@ -161,7 +150,7 @@ void main() { ...@@ -161,7 +150,7 @@ void main() {
if (result != 0) if (result != 0)
throw 'Received unexpected exit code $result from run process.'; throw 'Received unexpected exit code $result from run process.';
print('test: validating that the app has in fact closed...'); print('test: validating that the app has in fact closed...');
await client.done; await client.done.timeout(const Duration(seconds: 5));
}); });
return TaskResult.success(null); return TaskResult.success(null);
}); });
......
...@@ -29,7 +29,7 @@ Future<void> main() async { ...@@ -29,7 +29,7 @@ Future<void> main() async {
final SerializableFinder summary = find.byValueKey('summary'); final SerializableFinder summary = find.byValueKey('summary');
// Wait for calibration to complete and fab to appear. // Wait for calibration to complete and fab to appear.
await driver.waitFor(fab); await driver.waitFor(fab, timeout: const Duration(seconds: 40));
final String calibrationResult = await driver.getText(summary); final String calibrationResult = await driver.getText(summary);
final Match matchCalibration = calibrationRegExp.matchAsPrefix(calibrationResult); final Match matchCalibration = calibrationRegExp.matchAsPrefix(calibrationResult);
...@@ -59,7 +59,7 @@ Future<void> main() async { ...@@ -59,7 +59,7 @@ Future<void> main() async {
expect(double.parse(matchFast.group(1)), closeTo(flutterFrameRate * 2.0, 5.0)); expect(double.parse(matchFast.group(1)), closeTo(flutterFrameRate * 2.0, 5.0));
expect(double.parse(matchFast.group(2)), closeTo(flutterFrameRate, 10.0)); expect(double.parse(matchFast.group(2)), closeTo(flutterFrameRate, 10.0));
expect(int.parse(matchFast.group(3)), 1); expect(int.parse(matchFast.group(3)), 1);
}); }, timeout: const Timeout(Duration(minutes: 1)));
tearDownAll(() async { tearDownAll(() async {
driver?.close(); driver?.close();
......
...@@ -9,24 +9,16 @@ import 'package:meta/meta.dart'; ...@@ -9,24 +9,16 @@ import 'package:meta/meta.dart';
abstract class Command { abstract class Command {
/// Abstract const constructor. This constructor enables subclasses to provide /// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions. /// const constructors so that they can be used in const expressions.
const Command({ this.timeout }); const Command({ Duration timeout })
: timeout = timeout ?? const Duration(seconds: 5);
/// Deserializes this command from the value generated by [serialize]. /// Deserializes this command from the value generated by [serialize].
Command.deserialize(Map<String, String> json) Command.deserialize(Map<String, String> json)
: timeout = _parseTimeout(json); : timeout = Duration(milliseconds: int.parse(json['timeout']));
static Duration _parseTimeout(Map<String, String> json) {
final String timeout = json['timeout'];
if (timeout == null)
return null;
return Duration(milliseconds: int.parse(timeout));
}
/// The maximum amount of time to wait for the command to complete. /// The maximum amount of time to wait for the command to complete.
/// ///
/// Defaults to no timeout, because it is common for operations to take oddly /// Defaults to 5 seconds.
/// long in test environments (e.g. because the test host is overloaded), and
/// having timeouts essentially means having race conditions.
final Duration timeout; final Duration timeout;
/// Identifies the type of the command object and of the handler. /// Identifies the type of the command object and of the handler.
...@@ -36,7 +28,7 @@ abstract class Command { ...@@ -36,7 +28,7 @@ abstract class Command {
@mustCallSuper @mustCallSuper
Map<String, String> serialize() => <String, String>{ Map<String, String> serialize() => <String, String>{
'command': kind, 'command': kind,
'timeout': timeout == null ? null : '${timeout.inMilliseconds}', 'timeout': '${timeout.inMilliseconds}',
}; };
} }
......
...@@ -177,10 +177,7 @@ class FlutterDriverExtension { ...@@ -177,10 +177,7 @@ class FlutterDriverExtension {
if (commandHandler == null || commandDeserializer == null) if (commandHandler == null || commandDeserializer == null)
throw 'Extension $_extensionMethod does not support command $commandKind'; throw 'Extension $_extensionMethod does not support command $commandKind';
final Command command = commandDeserializer(params); final Command command = commandDeserializer(params);
Future<Result> responseFuture = commandHandler(command); final Result response = await commandHandler(command).timeout(command.timeout);
if (command.timeout != null)
responseFuture = responseFuture.timeout(command.timeout);
final Result response = await responseFuture;
return _makeResponse(response?.toJson()); return _makeResponse(response?.toJson());
} on TimeoutException catch (error, stackTrace) { } on TimeoutException catch (error, stackTrace) {
final String msg = 'Timeout while executing $commandKind: $error\n$stackTrace'; final String msg = 'Timeout while executing $commandKind: $error\n$stackTrace';
......
...@@ -11,13 +11,13 @@ import 'package:flutter_driver/src/driver/timeline.dart'; ...@@ -11,13 +11,13 @@ import 'package:flutter_driver/src/driver/timeline.dart';
import 'package:json_rpc_2/json_rpc_2.dart' as rpc; import 'package:json_rpc_2/json_rpc_2.dart' as rpc;
import 'package:mockito/mockito.dart'; import 'package:mockito/mockito.dart';
import 'package:vm_service_client/vm_service_client.dart'; import 'package:vm_service_client/vm_service_client.dart';
import 'package:quiver/testing/async.dart';
import 'common.dart'; import 'common.dart';
/// Magical timeout value that's different from the default. /// Magical timeout value that's different from the default.
const Duration _kTestTimeout = Duration(milliseconds: 1234); const Duration _kTestTimeout = Duration(milliseconds: 1234);
const String _kSerializedTestTimeout = '1234'; const String _kSerializedTestTimeout = '1234';
const Duration _kDefaultCommandTimeout = Duration(seconds: 5);
void main() { void main() {
group('FlutterDriver.connect', () { group('FlutterDriver.connect', () {
...@@ -358,19 +358,17 @@ void main() { ...@@ -358,19 +358,17 @@ void main() {
group('sendCommand error conditions', () { group('sendCommand error conditions', () {
test('local timeout', () async { test('local timeout', () async {
final List<String> log = <String>[];
final StreamSubscription<LogRecord> logSub = flutterDriverLog.listen((LogRecord s) => log.add(s.toString()));
when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) { when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) {
// completer never completed to trigger timeout // completer never competed to trigger timeout
return Completer<Map<String, dynamic>>().future; return Completer<Map<String, dynamic>>().future;
}); });
FakeAsync().run((FakeAsync time) { try {
driver.waitFor(find.byTooltip('foo')); await driver.waitFor(find.byTooltip('foo'), timeout: const Duration(milliseconds: 100));
expect(log, <String>[]); fail('expected an exception');
time.elapse(const Duration(hours: 1)); } catch (error) {
}); expect(error is DriverError, isTrue);
expect(log, <String>['[warning] FlutterDriver: waitFor message is taking a long time to complete...']); expect(error.message, 'Failed to fulfill WaitFor: Flutter application not responding');
await logSub.cancel(); }
}); });
test('remote error', () async { test('remote error', () async {
...@@ -391,6 +389,7 @@ void main() { ...@@ -391,6 +389,7 @@ void main() {
}); });
group('FlutterDriver with custom timeout', () { group('FlutterDriver with custom timeout', () {
const double kTestMultiplier = 3.0;
MockVMServiceClient mockClient; MockVMServiceClient mockClient;
MockPeer mockPeer; MockPeer mockPeer;
MockIsolate mockIsolate; MockIsolate mockIsolate;
...@@ -400,21 +399,21 @@ void main() { ...@@ -400,21 +399,21 @@ void main() {
mockClient = MockVMServiceClient(); mockClient = MockVMServiceClient();
mockPeer = MockPeer(); mockPeer = MockPeer();
mockIsolate = MockIsolate(); mockIsolate = MockIsolate();
driver = FlutterDriver.connectedTo(mockClient, mockPeer, mockIsolate); driver = FlutterDriver.connectedTo(mockClient, mockPeer, mockIsolate, timeoutMultiplier: kTestMultiplier);
}); });
test('GetHealth has no default timeout', () async { test('multiplies the timeout', () async {
when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) { when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) {
expect(i.positionalArguments[1], <String, String>{ expect(i.positionalArguments[1], <String, String>{
'command': 'get_health', 'command': 'get_health',
'timeout': null, 'timeout': '${(_kDefaultCommandTimeout * kTestMultiplier).inMilliseconds}',
}); });
return makeMockResponse(<String, dynamic>{'status': 'ok'}); return makeMockResponse(<String, dynamic>{'status': 'ok'});
}); });
await driver.checkHealth(); await driver.checkHealth();
}); });
test('does not interfere with explicit timeouts', () async { test('does not multiply explicit timeouts', () async {
when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) { when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) {
expect(i.positionalArguments[1], <String, String>{ expect(i.positionalArguments[1], <String, String>{
'command': 'get_health', 'command': 'get_health',
......
...@@ -88,13 +88,15 @@ class AndroidDevice extends Device { ...@@ -88,13 +88,15 @@ class AndroidDevice extends Device {
propCommand, propCommand,
stdoutEncoding: latin1, stdoutEncoding: latin1,
stderrEncoding: latin1, stderrEncoding: latin1,
); ).timeout(const Duration(seconds: 5));
if (result.exitCode == 0) { if (result.exitCode == 0) {
_properties = parseAdbDeviceProperties(result.stdout); _properties = parseAdbDeviceProperties(result.stdout);
} else { } else {
printError('Error retrieving device properties for $name:'); printError('Error retrieving device properties for $name:');
printError(result.stderr); printError(result.stderr);
} }
} on TimeoutException catch (_) {
throwToolExit('adb not responding');
} on ProcessException catch (error) { } on ProcessException catch (error) {
printError('Error retrieving device properties for $name: $error'); printError('Error retrieving device properties for $name: $error');
} }
...@@ -277,7 +279,7 @@ class AndroidDevice extends Device { ...@@ -277,7 +279,7 @@ class AndroidDevice extends Device {
if (!await _checkForSupportedAdbVersion() || !await _checkForSupportedAndroidVersion()) if (!await _checkForSupportedAdbVersion() || !await _checkForSupportedAndroidVersion())
return false; return false;
final Status status = logger.startProgress('Installing ${fs.path.relative(apk.file.path)}...', timeout: kSlowOperation); final Status status = logger.startProgress('Installing ${fs.path.relative(apk.file.path)}...', expectSlowOperation: true);
final RunResult installResult = await runAsync(adbCommandForDevice(<String>['install', '-t', '-r', apk.file.path])); final RunResult installResult = await runAsync(adbCommandForDevice(<String>['install', '-t', '-r', apk.file.path]));
status.stop(); status.stop();
// Some versions of adb exit with exit code 0 even on failure :( // Some versions of adb exit with exit code 0 even on failure :(
......
...@@ -51,10 +51,9 @@ class AndroidEmulator extends Emulator { ...@@ -51,10 +51,9 @@ class AndroidEmulator extends Emulator {
throw '${runResult.stdout}\n${runResult.stderr}'.trimRight(); throw '${runResult.stdout}\n${runResult.stderr}'.trimRight();
} }
}); });
// The emulator continues running on a successful launch, so if it hasn't // emulator continues running on a successful launch so if we
// quit within 3 seconds we assume that's a success and just return. This // haven't quit within 3 seconds we assume that's a success and just
// means that on a slow machine, a failure that takes more than three // return.
// seconds won't be recognized as such... :-/
return Future.any<void>(<Future<void>>[ return Future.any<void>(<Future<void>>[
launchResult, launchResult,
Future<void>.delayed(const Duration(seconds: 3)) Future<void>.delayed(const Duration(seconds: 3))
......
...@@ -50,15 +50,9 @@ class AndroidWorkflow implements Workflow { ...@@ -50,15 +50,9 @@ class AndroidWorkflow implements Workflow {
class AndroidValidator extends DoctorValidator { class AndroidValidator extends DoctorValidator {
AndroidValidator(): super('Android toolchain - develop for Android devices',); AndroidValidator(): super('Android toolchain - develop for Android devices',);
@override
String get slowWarning => '${_task ?? 'This'} is taking a long time...';
String _task;
/// Returns false if we cannot determine the Java version or if the version /// Returns false if we cannot determine the Java version or if the version
/// is not compatible. /// is not compatible.
Future<bool> _checkJavaVersion(String javaBinary, List<ValidationMessage> messages) async { Future<bool> _checkJavaVersion(String javaBinary, List<ValidationMessage> messages) async {
_task = 'Checking Java status';
try {
if (!processManager.canRun(javaBinary)) { if (!processManager.canRun(javaBinary)) {
messages.add(ValidationMessage.error(userMessages.androidCantRunJavaBinary(javaBinary))); messages.add(ValidationMessage.error(userMessages.androidCantRunJavaBinary(javaBinary)));
return false; return false;
...@@ -82,9 +76,6 @@ class AndroidValidator extends DoctorValidator { ...@@ -82,9 +76,6 @@ class AndroidValidator extends DoctorValidator {
messages.add(ValidationMessage(userMessages.androidJavaVersion(javaVersion))); messages.add(ValidationMessage(userMessages.androidJavaVersion(javaVersion)));
// TODO(johnmccutchan): Validate version. // TODO(johnmccutchan): Validate version.
return true; return true;
} finally {
_task = null;
}
} }
@override @override
...@@ -158,9 +149,6 @@ class AndroidValidator extends DoctorValidator { ...@@ -158,9 +149,6 @@ class AndroidValidator extends DoctorValidator {
class AndroidLicenseValidator extends DoctorValidator { class AndroidLicenseValidator extends DoctorValidator {
AndroidLicenseValidator(): super('Android license subvalidator',); AndroidLicenseValidator(): super('Android license subvalidator',);
@override
String get slowWarning => 'Checking Android licenses is taking an unexpectedly long time...';
@override @override
Future<ValidationResult> validate() async { Future<ValidationResult> validate() async {
final List<ValidationMessage> messages = <ValidationMessage>[]; final List<ValidationMessage> messages = <ValidationMessage>[];
...@@ -220,8 +208,10 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -220,8 +208,10 @@ class AndroidLicenseValidator extends DoctorValidator {
Future<LicensesAccepted> get licensesAccepted async { Future<LicensesAccepted> get licensesAccepted async {
LicensesAccepted status; LicensesAccepted status;
void _handleLine(String line) { void _onLine(String line) {
if (licenseCounts.hasMatch(line)) { if (status == null && licenseAccepted.hasMatch(line)) {
status = LicensesAccepted.all;
} else if (licenseCounts.hasMatch(line)) {
final Match match = licenseCounts.firstMatch(line); final Match match = licenseCounts.firstMatch(line);
if (match.group(1) != match.group(2)) { if (match.group(1) != match.group(2)) {
status = LicensesAccepted.some; status = LicensesAccepted.some;
...@@ -229,12 +219,9 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -229,12 +219,9 @@ class AndroidLicenseValidator extends DoctorValidator {
status = LicensesAccepted.none; status = LicensesAccepted.none;
} }
} else if (licenseNotAccepted.hasMatch(line)) { } else if (licenseNotAccepted.hasMatch(line)) {
// The licenseNotAccepted pattern is trying to match the same line as // In case the format changes, a more general match will keep doctor
// licenseCounts, but is more general. In case the format changes, a // mostly working.
// more general match may keep doctor mostly working.
status = LicensesAccepted.none; status = LicensesAccepted.none;
} else if (licenseAccepted.hasMatch(line)) {
status ??= LicensesAccepted.all;
} }
} }
...@@ -248,14 +235,19 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -248,14 +235,19 @@ class AndroidLicenseValidator extends DoctorValidator {
final Future<void> output = process.stdout final Future<void> output = process.stdout
.transform<String>(const Utf8Decoder(allowMalformed: true)) .transform<String>(const Utf8Decoder(allowMalformed: true))
.transform<String>(const LineSplitter()) .transform<String>(const LineSplitter())
.listen(_handleLine) .listen(_onLine)
.asFuture<void>(null); .asFuture<void>(null);
final Future<void> errors = process.stderr final Future<void> errors = process.stderr
.transform<String>(const Utf8Decoder(allowMalformed: true)) .transform<String>(const Utf8Decoder(allowMalformed: true))
.transform<String>(const LineSplitter()) .transform<String>(const LineSplitter())
.listen(_handleLine) .listen(_onLine)
.asFuture<void>(null); .asFuture<void>(null);
await Future.wait<void>(<Future<void>>[output, errors]); try {
await Future.wait<void>(<Future<void>>[output, errors]).timeout(const Duration(seconds: 30));
} catch (TimeoutException) {
printTrace(userMessages.androidLicensesTimeout(androidSdk.sdkManagerPath));
processManager.killPid(process.pid);
}
return status ?? LicensesAccepted.unknown; return status ?? LicensesAccepted.unknown;
} }
...@@ -269,10 +261,9 @@ class AndroidLicenseValidator extends DoctorValidator { ...@@ -269,10 +261,9 @@ class AndroidLicenseValidator extends DoctorValidator {
_ensureCanRunSdkManager(); _ensureCanRunSdkManager();
final Version sdkManagerVersion = Version.parse(androidSdk.sdkManagerVersion); final Version sdkManagerVersion = Version.parse(androidSdk.sdkManagerVersion);
if (sdkManagerVersion == null || sdkManagerVersion.major < 26) { if (sdkManagerVersion == null || sdkManagerVersion.major < 26)
// SDK manager is found, but needs to be updated. // SDK manager is found, but needs to be updated.
throwToolExit(userMessages.androidSdkOutdated(androidSdk.sdkManagerPath)); throwToolExit(userMessages.androidSdkOutdated(androidSdk.sdkManagerPath));
}
final Process process = await runCommand( final Process process = await runCommand(
<String>[androidSdk.sdkManagerPath, '--licenses'], <String>[androidSdk.sdkManagerPath, '--licenses'],
......
...@@ -97,7 +97,7 @@ Future<GradleProject> _readGradleProject() async { ...@@ -97,7 +97,7 @@ Future<GradleProject> _readGradleProject() async {
final FlutterProject flutterProject = await FlutterProject.current(); final FlutterProject flutterProject = await FlutterProject.current();
final String gradle = await _ensureGradle(flutterProject); final String gradle = await _ensureGradle(flutterProject);
updateLocalProperties(project: flutterProject); updateLocalProperties(project: flutterProject);
final Status status = logger.startProgress('Resolving dependencies...', timeout: kSlowOperation); final Status status = logger.startProgress('Resolving dependencies...', expectSlowOperation: true);
GradleProject project; GradleProject project;
try { try {
final RunResult propertiesRunResult = await runCheckedAsync( final RunResult propertiesRunResult = await runCheckedAsync(
...@@ -174,7 +174,7 @@ Future<String> _ensureGradle(FlutterProject project) async { ...@@ -174,7 +174,7 @@ Future<String> _ensureGradle(FlutterProject project) async {
// of validating the Gradle executable. This may take several seconds. // of validating the Gradle executable. This may take several seconds.
Future<String> _initializeGradle(FlutterProject project) async { Future<String> _initializeGradle(FlutterProject project) async {
final Directory android = project.android.hostAppGradleRoot; final Directory android = project.android.hostAppGradleRoot;
final Status status = logger.startProgress('Initializing gradle...', timeout: kSlowOperation); final Status status = logger.startProgress('Initializing gradle...', expectSlowOperation: true);
String gradle = _locateGradlewExecutable(android); String gradle = _locateGradlewExecutable(android);
if (gradle == null) { if (gradle == null) {
injectGradleWrapper(android); injectGradleWrapper(android);
...@@ -312,8 +312,8 @@ Future<void> buildGradleProject({ ...@@ -312,8 +312,8 @@ Future<void> buildGradleProject({
Future<void> _buildGradleProjectV1(FlutterProject project, String gradle) async { Future<void> _buildGradleProjectV1(FlutterProject project, String gradle) async {
// Run 'gradlew build'. // Run 'gradlew build'.
final Status status = logger.startProgress( final Status status = logger.startProgress(
'Running \'gradlew build\'...', "Running 'gradlew build'...",
timeout: kSlowOperation, expectSlowOperation: true,
multilineOutput: true, multilineOutput: true,
); );
final int exitCode = await runCommandAndStreamOutput( final int exitCode = await runCommandAndStreamOutput(
...@@ -354,8 +354,8 @@ Future<void> _buildGradleProjectV2( ...@@ -354,8 +354,8 @@ Future<void> _buildGradleProjectV2(
} }
} }
final Status status = logger.startProgress( final Status status = logger.startProgress(
'Running Gradle task \'$assembleTask\'...', "Gradle task '$assembleTask'...",
timeout: kSlowOperation, expectSlowOperation: true,
multilineOutput: true, multilineOutput: true,
); );
final String gradlePath = fs.file(gradle).absolute.path; final String gradlePath = fs.file(gradle).absolute.path;
......
...@@ -107,7 +107,7 @@ class AppContext { ...@@ -107,7 +107,7 @@ class AppContext {
/// Gets the value associated with the specified [type], or `null` if no /// Gets the value associated with the specified [type], or `null` if no
/// such value has been associated. /// such value has been associated.
Object operator [](Type type) { dynamic operator [](Type type) {
dynamic value = _generateIfNecessary(type, _overrides); dynamic value = _generateIfNecessary(type, _overrides);
if (value == null && _parent != null) if (value == null && _parent != null)
value = _parent[type]; value = _parent[type];
......
...@@ -36,7 +36,9 @@ RecordingFileSystem getRecordingFileSystem(String location) { ...@@ -36,7 +36,9 @@ RecordingFileSystem getRecordingFileSystem(String location) {
final RecordingFileSystem fileSystem = RecordingFileSystem( final RecordingFileSystem fileSystem = RecordingFileSystem(
delegate: _kLocalFs, destination: dir); delegate: _kLocalFs, destination: dir);
addShutdownHook(() async { addShutdownHook(() async {
await fileSystem.recording.flush(); await fileSystem.recording.flush(
pendingResultTimeout: const Duration(seconds: 5),
);
}, ShutdownStage.SERIALIZE_RECORDING); }, ShutdownStage.SERIALIZE_RECORDING);
return fileSystem; return fileSystem;
} }
......
...@@ -162,7 +162,10 @@ class Stdio { ...@@ -162,7 +162,10 @@ class Stdio {
bool get supportsAnsiEscapes => hasTerminal ? io.stdout.supportsAnsiEscapes : false; bool get supportsAnsiEscapes => hasTerminal ? io.stdout.supportsAnsiEscapes : false;
} }
io.IOSink get stderr => context[Stdio].stderr;
Stream<List<int>> get stdin => context[Stdio].stdin;
io.IOSink get stdout => context[Stdio].stdout;
Stdio get stdio => context[Stdio]; Stdio get stdio => context[Stdio];
io.IOSink get stdout => stdio.stdout;
Stream<List<int>> get stdin => stdio.stdin;
io.IOSink get stderr => stdio.stderr;
...@@ -37,7 +37,7 @@ Future<List<int>> _attempt(Uri url, {bool onlyHeaders = false}) async { ...@@ -37,7 +37,7 @@ Future<List<int>> _attempt(Uri url, {bool onlyHeaders = false}) async {
printTrace('Downloading: $url'); printTrace('Downloading: $url');
HttpClient httpClient; HttpClient httpClient;
if (context[HttpClientFactory] != null) { if (context[HttpClientFactory] != null) {
httpClient = (context[HttpClientFactory] as HttpClientFactory)(); // ignore: avoid_as httpClient = context[HttpClientFactory]();
} else { } else {
httpClient = HttpClient(); httpClient = HttpClient();
} }
......
...@@ -203,6 +203,14 @@ Future<int> runInteractively(List<String> command, { ...@@ -203,6 +203,14 @@ Future<int> runInteractively(List<String> command, {
return await process.exitCode; return await process.exitCode;
} }
Future<void> runAndKill(List<String> cmd, Duration timeout) {
final Future<Process> proc = runDetached(cmd);
return Future<void>.delayed(timeout, () async {
printTrace('Intentionally killing ${cmd[0]}');
processManager.killPid((await proc).pid);
});
}
Future<Process> runDetached(List<String> cmd) { Future<Process> runDetached(List<String> cmd) {
_traceCommand(cmd); _traceCommand(cmd);
final Future<Process> proc = processManager.start( final Future<Process> proc = processManager.start(
......
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
import 'dart:async'; import 'dart:async';
import 'dart:convert' show AsciiDecoder; import 'dart:convert' show AsciiDecoder;
import 'package:quiver/strings.dart';
import '../globals.dart'; import '../globals.dart';
import 'context.dart'; import 'context.dart';
import 'io.dart' as io; import 'io.dart' as io;
...@@ -170,32 +172,31 @@ class AnsiTerminal { ...@@ -170,32 +172,31 @@ class AnsiTerminal {
/// Return keystrokes from the console. /// Return keystrokes from the console.
/// ///
/// Useful when the console is in [singleCharMode]. /// Useful when the console is in [singleCharMode].
Stream<String> get keystrokes { Stream<String> get onCharInput {
_broadcastStdInString ??= io.stdin.transform<String>(const AsciiDecoder(allowInvalid: true)).asBroadcastStream(); _broadcastStdInString ??= io.stdin.transform<String>(const AsciiDecoder(allowInvalid: true)).asBroadcastStream();
return _broadcastStdInString; return _broadcastStdInString;
} }
/// Prompts the user to input a character within a given list. Re-prompts if /// Prompts the user to input a character within the accepted list. Re-prompts
/// entered character is not in the list. /// if entered character is not in the list.
/// ///
/// The `prompt`, if non-null, is the text displayed prior to waiting for user /// The [prompt] is the text displayed prior to waiting for user input. The
/// input each time. If `prompt` is non-null and `displayAcceptedCharacters` /// [defaultChoiceIndex], if given, will be the character appearing in
/// is true, the accepted keys are printed next to the `prompt`. /// [acceptedCharacters] in the index given if the user presses enter without
/// any key input. Setting [displayAcceptedCharacters] also prints the
/// accepted keys next to the [prompt].
/// ///
/// The returned value is the user's input; if `defaultChoiceIndex` is not /// Throws a [TimeoutException] if a `timeout` is provided and its duration
/// null, and the user presses enter without any other input, the return value /// expired without user input. Duration resets per key press.
/// will be the character in `acceptedCharacters` at the index given by
/// `defaultChoiceIndex`.
Future<String> promptForCharInput( Future<String> promptForCharInput(
List<String> acceptedCharacters, { List<String> acceptedCharacters, {
String prompt, String prompt,
int defaultChoiceIndex, int defaultChoiceIndex,
bool displayAcceptedCharacters = true, bool displayAcceptedCharacters = true,
Duration timeout,
}) async { }) async {
assert(acceptedCharacters != null); assert(acceptedCharacters != null);
assert(acceptedCharacters.isNotEmpty); assert(acceptedCharacters.isNotEmpty);
assert(prompt == null || prompt.isNotEmpty);
assert(displayAcceptedCharacters != null);
List<String> charactersToDisplay = acceptedCharacters; List<String> charactersToDisplay = acceptedCharacters;
if (defaultChoiceIndex != null) { if (defaultChoiceIndex != null) {
assert(defaultChoiceIndex >= 0 && defaultChoiceIndex < acceptedCharacters.length); assert(defaultChoiceIndex >= 0 && defaultChoiceIndex < acceptedCharacters.length);
...@@ -205,14 +206,17 @@ class AnsiTerminal { ...@@ -205,14 +206,17 @@ class AnsiTerminal {
} }
String choice; String choice;
singleCharMode = true; singleCharMode = true;
while (choice == null || choice.length > 1 || !acceptedCharacters.contains(choice)) { while (isEmpty(choice) || choice.length != 1 || !acceptedCharacters.contains(choice)) {
if (prompt != null) { if (isNotEmpty(prompt)) {
printStatus(prompt, emphasis: true, newline: false); printStatus(prompt, emphasis: true, newline: false);
if (displayAcceptedCharacters) if (displayAcceptedCharacters)
printStatus(' [${charactersToDisplay.join("|")}]', newline: false); printStatus(' [${charactersToDisplay.join("|")}]', newline: false);
printStatus(': ', emphasis: true, newline: false); printStatus(': ', emphasis: true, newline: false);
} }
choice = await keystrokes.first; Future<String> inputFuture = onCharInput.first;
if (timeout != null)
inputFuture = inputFuture.timeout(timeout);
choice = await inputFuture;
printStatus(choice); printStatus(choice);
} }
singleCharMode = false; singleCharMode = false;
......
...@@ -299,7 +299,7 @@ abstract class CachedArtifact { ...@@ -299,7 +299,7 @@ abstract class CachedArtifact {
Future<void> _downloadArchive(String message, Uri url, Directory location, bool verifier(File f), void extractor(File f, Directory d)) { Future<void> _downloadArchive(String message, Uri url, Directory location, bool verifier(File f), void extractor(File f, Directory d)) {
return _withDownloadFile('${flattenNameSubdirs(url)}', (File tempFile) async { return _withDownloadFile('${flattenNameSubdirs(url)}', (File tempFile) async {
if (!verifier(tempFile)) { if (!verifier(tempFile)) {
final Status status = logger.startProgress(message, timeout: kSlowOperation); final Status status = logger.startProgress(message, expectSlowOperation: true);
try { try {
await _downloadFile(url, tempFile); await _downloadFile(url, tempFile);
status.stop(); status.stop();
...@@ -620,7 +620,7 @@ Future<void> _downloadFile(Uri url, File location) async { ...@@ -620,7 +620,7 @@ Future<void> _downloadFile(Uri url, File location) async {
} }
Future<bool> _doesRemoteExist(String message, Uri url) async { Future<bool> _doesRemoteExist(String message, Uri url) async {
final Status status = logger.startProgress(message, timeout: kSlowOperation); final Status status = logger.startProgress(message, expectSlowOperation: true);
final bool exists = await doesRemoteFileExist(url); final bool exists = await doesRemoteFileExist(url);
status.stop(); status.stop();
return exists; return exists;
......
...@@ -74,12 +74,11 @@ class AnalyzeContinuously extends AnalyzeBase { ...@@ -74,12 +74,11 @@ class AnalyzeContinuously extends AnalyzeBase {
analysisStatus?.cancel(); analysisStatus?.cancel();
if (!firstAnalysis) if (!firstAnalysis)
printStatus('\n'); printStatus('\n');
analysisStatus = logger.startProgress('Analyzing $analysisTarget...', timeout: kSlowOperation); analysisStatus = logger.startProgress('Analyzing $analysisTarget...');
analyzedPaths.clear(); analyzedPaths.clear();
analysisTimer = Stopwatch()..start(); analysisTimer = Stopwatch()..start();
} else { } else {
analysisStatus?.stop(); analysisStatus?.stop();
analysisStatus = null;
analysisTimer.stop(); analysisTimer.stop();
logger.printStatus(terminal.clearScreen(), newline: false); logger.printStatus(terminal.clearScreen(), newline: false);
......
...@@ -107,7 +107,7 @@ class AnalyzeOnce extends AnalyzeBase { ...@@ -107,7 +107,7 @@ class AnalyzeOnce extends AnalyzeBase {
? '${directories.length} ${directories.length == 1 ? 'directory' : 'directories'}' ? '${directories.length} ${directories.length == 1 ? 'directory' : 'directories'}'
: fs.path.basename(directories.first); : fs.path.basename(directories.first);
final Status progress = argResults['preamble'] final Status progress = argResults['preamble']
? logger.startProgress('Analyzing $message...', timeout: kSlowOperation) ? logger.startProgress('Analyzing $message...')
: null; : null;
await analysisCompleter.future; await analysisCompleter.future;
......
...@@ -149,7 +149,7 @@ class AttachCommand extends FlutterCommand { ...@@ -149,7 +149,7 @@ class AttachCommand extends FlutterCommand {
} }
final Status status = logger.startProgress( final Status status = logger.startProgress(
'Waiting for a connection from Flutter on ${device.name}...', 'Waiting for a connection from Flutter on ${device.name}...',
timeout: kSlowOperation, expectSlowOperation: true,
); );
try { try {
final int localPort = await device.findIsolatePort(module, localPorts); final int localPort = await device.findIsolatePort(module, localPorts);
...@@ -179,7 +179,7 @@ class AttachCommand extends FlutterCommand { ...@@ -179,7 +179,7 @@ class AttachCommand extends FlutterCommand {
observatoryUri = await observatoryDiscovery.uri; observatoryUri = await observatoryDiscovery.uri;
// Determine ipv6 status from the scanned logs. // Determine ipv6 status from the scanned logs.
usesIpv6 = observatoryDiscovery.ipv6; usesIpv6 = observatoryDiscovery.ipv6;
printStatus('Done.'); // FYI, this message is used as a sentinel in tests. printStatus('Done.');
} finally { } finally {
await observatoryDiscovery?.cancel(); await observatoryDiscovery?.cancel();
} }
...@@ -217,29 +217,20 @@ class AttachCommand extends FlutterCommand { ...@@ -217,29 +217,20 @@ class AttachCommand extends FlutterCommand {
flutterDevice.startEchoingDeviceLog(); flutterDevice.startEchoingDeviceLog();
} }
int result;
if (daemon != null) { if (daemon != null) {
AppInstance app; AppInstance app;
try { try {
app = await daemon.appDomain.launch( app = await daemon.appDomain.launch(hotRunner, hotRunner.attach,
hotRunner, device, null, true, fs.currentDirectory);
hotRunner.attach,
device,
null,
true,
fs.currentDirectory,
);
} catch (error) { } catch (error) {
throwToolExit(error.toString()); throwToolExit(error.toString());
} }
result = await app.runner.waitForAppToFinish(); final int result = await app.runner.waitForAppToFinish();
assert(result != null);
} else {
result = await hotRunner.attach();
assert(result != null);
}
if (result != 0) if (result != 0)
throwToolExit(null, exitCode: result); throwToolExit(null, exitCode: result);
} else {
await hotRunner.attach();
}
} finally { } finally {
final List<ForwardedPort> ports = device.portForwarder.forwardedPorts.toList(); final List<ForwardedPort> ports = device.portForwarder.forwardedPorts.toList();
for (ForwardedPort port in ports) { for (ForwardedPort port in ports) {
......
...@@ -71,7 +71,7 @@ class BuildAotCommand extends BuildSubCommand { ...@@ -71,7 +71,7 @@ class BuildAotCommand extends BuildSubCommand {
final String typeName = artifacts.getEngineType(platform, buildMode); final String typeName = artifacts.getEngineType(platform, buildMode);
status = logger.startProgress( status = logger.startProgress(
'Building AOT snapshot in ${getModeName(getBuildMode())} mode ($typeName)...', 'Building AOT snapshot in ${getModeName(getBuildMode())} mode ($typeName)...',
timeout: kSlowOperation, expectSlowOperation: true,
); );
} }
final String outputPath = argResults['output-dir'] ?? getAotBuildDirectory(); final String outputPath = argResults['output-dir'] ?? getAotBuildDirectory();
......
...@@ -428,10 +428,9 @@ class AppDomain extends Domain { ...@@ -428,10 +428,9 @@ class AppDomain extends Domain {
}); });
} }
final Completer<void> appStartedCompleter = Completer<void>(); final Completer<void> appStartedCompleter = Completer<void>();
// We don't want to wait for this future to complete and callbacks won't fail, // We don't want to wait for this future to complete and callbacks won't fail.
// as it just writes to stdout. // As it just writes to stdout.
appStartedCompleter.future // ignore: unawaited_futures appStartedCompleter.future.then<void>((_) { // ignore: unawaited_futures
.then<void>((void value) {
_sendAppEvent(app, 'started'); _sendAppEvent(app, 'started');
}); });
...@@ -516,15 +515,14 @@ class AppDomain extends Domain { ...@@ -516,15 +515,14 @@ class AppDomain extends Domain {
if (app == null) if (app == null)
throw "app '$appId' not found"; throw "app '$appId' not found";
return app.stop().then<bool>( return app.stop().timeout(const Duration(seconds: 5)).then<bool>((_) {
(void value) => true, return true;
onError: (dynamic error, StackTrace stack) { }).catchError((dynamic error) {
_sendAppEvent(app, 'log', <String, dynamic>{ 'log': '$error', 'error': true }); _sendAppEvent(app, 'log', <String, dynamic>{ 'log': '$error', 'error': true });
app.closeLogger(); app.closeLogger();
_apps.remove(app); _apps.remove(app);
return false; return false;
}, });
);
} }
Future<bool> detach(Map<String, dynamic> args) async { Future<bool> detach(Map<String, dynamic> args) async {
...@@ -534,15 +532,14 @@ class AppDomain extends Domain { ...@@ -534,15 +532,14 @@ class AppDomain extends Domain {
if (app == null) if (app == null)
throw "app '$appId' not found"; throw "app '$appId' not found";
return app.detach().then<bool>( return app.detach().timeout(const Duration(seconds: 5)).then<bool>((_) {
(void value) => true, return true;
onError: (dynamic error, StackTrace stack) { }).catchError((dynamic error) {
_sendAppEvent(app, 'log', <String, dynamic>{ 'log': '$error', 'error': true }); _sendAppEvent(app, 'log', <String, dynamic>{ 'log': '$error', 'error': true });
app.closeLogger(); app.closeLogger();
_apps.remove(app); _apps.remove(app);
return false; return false;
}, });
);
} }
AppInstance _getApp(String id) { AppInstance _getApp(String id) {
...@@ -775,14 +772,13 @@ class NotifyingLogger extends Logger { ...@@ -775,14 +772,13 @@ class NotifyingLogger extends Logger {
@override @override
Status startProgress( Status startProgress(
String message, { String message, {
@required Duration timeout,
String progressId, String progressId,
bool expectSlowOperation = false,
bool multilineOutput, bool multilineOutput,
int progressIndicatorPadding = kDefaultStatusPadding, int progressIndicatorPadding = kDefaultStatusPadding,
}) { }) {
assert(timeout != null);
printStatus(message); printStatus(message);
return SilentStatus(timeout: timeout); return Status();
} }
void dispose() { void dispose() {
...@@ -952,12 +948,11 @@ class _AppRunLogger extends Logger { ...@@ -952,12 +948,11 @@ class _AppRunLogger extends Logger {
@override @override
Status startProgress( Status startProgress(
String message, { String message, {
@required Duration timeout,
String progressId, String progressId,
bool expectSlowOperation = false,
bool multilineOutput, bool multilineOutput,
int progressIndicatorPadding = 52, int progressIndicatorPadding = 52,
}) { }) {
assert(timeout != null);
final int id = _nextProgressId++; final int id = _nextProgressId++;
_sendProgressEvent(<String, dynamic>{ _sendProgressEvent(<String, dynamic>{
...@@ -966,16 +961,13 @@ class _AppRunLogger extends Logger { ...@@ -966,16 +961,13 @@ class _AppRunLogger extends Logger {
'message': message, 'message': message,
}); });
_status = SilentStatus( _status = Status(onFinish: () {
timeout: timeout,
onFinish: () {
_status = null; _status = null;
_sendProgressEvent(<String, dynamic>{ _sendProgressEvent(<String, dynamic>{
'id': id.toString(), 'id': id.toString(),
'progressId': progressId, 'progressId': progressId,
'finished': true, 'finished': true
}, });
);
})..start(); })..start();
return _status; return _status;
} }
......
...@@ -29,11 +29,11 @@ class LogsCommand extends FlutterCommand { ...@@ -29,11 +29,11 @@ class LogsCommand extends FlutterCommand {
Device device; Device device;
@override @override
Future<FlutterCommandResult> verifyThenRunCommand(String commandPath) async { Future<FlutterCommandResult> verifyThenRunCommand() async {
device = await findTargetDevice(); device = await findTargetDevice();
if (device == null) if (device == null)
throwToolExit(null); throwToolExit(null);
return super.verifyThenRunCommand(commandPath); return super.verifyThenRunCommand();
} }
@override @override
......
...@@ -64,7 +64,7 @@ class ScreenshotCommand extends FlutterCommand { ...@@ -64,7 +64,7 @@ class ScreenshotCommand extends FlutterCommand {
Device device; Device device;
@override @override
Future<FlutterCommandResult> verifyThenRunCommand(String commandPath) async { Future<FlutterCommandResult> verifyThenRunCommand() async {
device = await findTargetDevice(); device = await findTargetDevice();
if (device == null) if (device == null)
throwToolExit('Must have a connected device'); throwToolExit('Must have a connected device');
...@@ -72,7 +72,7 @@ class ScreenshotCommand extends FlutterCommand { ...@@ -72,7 +72,7 @@ class ScreenshotCommand extends FlutterCommand {
throwToolExit('Screenshot not supported for ${device.name}.'); throwToolExit('Screenshot not supported for ${device.name}.');
if (argResults[_kType] != _kDeviceType && argResults[_kObservatoryPort] == null) if (argResults[_kType] != _kDeviceType && argResults[_kObservatoryPort] == null)
throwToolExit('Observatory port must be specified for screenshot type ${argResults[_kType]}'); throwToolExit('Observatory port must be specified for screenshot type ${argResults[_kType]}');
return super.verifyThenRunCommand(commandPath); return super.verifyThenRunCommand();
} }
@override @override
......
...@@ -95,7 +95,7 @@ class UpdatePackagesCommand extends FlutterCommand { ...@@ -95,7 +95,7 @@ class UpdatePackagesCommand extends FlutterCommand {
Future<void> _downloadCoverageData() async { Future<void> _downloadCoverageData() async {
final Status status = logger.startProgress( final Status status = logger.startProgress(
'Downloading lcov data for package:flutter...', 'Downloading lcov data for package:flutter...',
timeout: kSlowOperation, expectSlowOperation: true,
); );
final String urlBase = platform.environment['FLUTTER_STORAGE_BASE_URL'] ?? 'https://storage.googleapis.com'; final String urlBase = platform.environment['FLUTTER_STORAGE_BASE_URL'] ?? 'https://storage.googleapis.com';
final List<int> data = await fetchUrl(Uri.parse('$urlBase/flutter_infra/flutter/coverage/lcov.info')); final List<int> data = await fetchUrl(Uri.parse('$urlBase/flutter_infra/flutter/coverage/lcov.info'));
......
...@@ -92,7 +92,7 @@ Future<void> pubGet({ ...@@ -92,7 +92,7 @@ Future<void> pubGet({
final String command = upgrade ? 'upgrade' : 'get'; final String command = upgrade ? 'upgrade' : 'get';
final Status status = logger.startProgress( final Status status = logger.startProgress(
'Running "flutter packages $command" in ${fs.path.basename(directory)}...', 'Running "flutter packages $command" in ${fs.path.basename(directory)}...',
timeout: kSlowOperation, expectSlowOperation: true,
); );
final List<String> args = <String>['--verbosity=warning']; final List<String> args = <String>['--verbosity=warning'];
if (FlutterCommand.current != null && FlutterCommand.current.globalResults['verbose']) if (FlutterCommand.current != null && FlutterCommand.current.globalResults['verbose'])
......
...@@ -150,7 +150,7 @@ abstract class PollingDeviceDiscovery extends DeviceDiscovery { ...@@ -150,7 +150,7 @@ abstract class PollingDeviceDiscovery extends DeviceDiscovery {
final List<Device> devices = await pollingGetDevices().timeout(_pollingTimeout); final List<Device> devices = await pollingGetDevices().timeout(_pollingTimeout);
_items.updateWithNewList(devices); _items.updateWithNewList(devices);
} on TimeoutException { } on TimeoutException {
printTrace('Device poll timed out. Will retry.'); printTrace('Device poll timed out.');
} }
}, _pollingInterval); }, _pollingInterval);
} }
......
...@@ -184,10 +184,7 @@ class Doctor { ...@@ -184,10 +184,7 @@ class Doctor {
for (ValidatorTask validatorTask in startValidatorTasks()) { for (ValidatorTask validatorTask in startValidatorTasks()) {
final DoctorValidator validator = validatorTask.validator; final DoctorValidator validator = validatorTask.validator;
final Status status = Status.withSpinner( final Status status = Status.withSpinner();
timeout: kFastOperation,
slowWarningCallback: () => validator.slowWarning,
);
ValidationResult result; ValidationResult result;
try { try {
result = await validatorTask.result; result = await validatorTask.result;
...@@ -289,8 +286,6 @@ abstract class DoctorValidator { ...@@ -289,8 +286,6 @@ abstract class DoctorValidator {
final String title; final String title;
String get slowWarning => 'This is taking an unexpectedly long time...';
Future<ValidationResult> validate(); Future<ValidationResult> validate();
} }
...@@ -303,10 +298,6 @@ class GroupedValidator extends DoctorValidator { ...@@ -303,10 +298,6 @@ class GroupedValidator extends DoctorValidator {
final List<DoctorValidator> subValidators; final List<DoctorValidator> subValidators;
@override
String get slowWarning => _currentSlowWarning;
String _currentSlowWarning = 'Initializing...';
@override @override
Future<ValidationResult> validate() async { Future<ValidationResult> validate() async {
final List<ValidatorTask> tasks = <ValidatorTask>[]; final List<ValidatorTask> tasks = <ValidatorTask>[];
...@@ -316,10 +307,8 @@ class GroupedValidator extends DoctorValidator { ...@@ -316,10 +307,8 @@ class GroupedValidator extends DoctorValidator {
final List<ValidationResult> results = <ValidationResult>[]; final List<ValidationResult> results = <ValidationResult>[];
for (ValidatorTask subValidator in tasks) { for (ValidatorTask subValidator in tasks) {
_currentSlowWarning = subValidator.validator.slowWarning;
results.add(await subValidator.result); results.add(await subValidator.result);
} }
_currentSlowWarning = 'Merging results...';
return _mergeValidationResults(results); return _mergeValidationResults(results);
} }
...@@ -682,9 +671,6 @@ class IntelliJValidatorOnMac extends IntelliJValidator { ...@@ -682,9 +671,6 @@ class IntelliJValidatorOnMac extends IntelliJValidator {
class DeviceValidator extends DoctorValidator { class DeviceValidator extends DoctorValidator {
DeviceValidator() : super('Connected device'); DeviceValidator() : super('Connected device');
@override
String get slowWarning => 'Scanning for devices is taking a long time...';
@override @override
Future<ValidationResult> validate() async { Future<ValidationResult> validate() async {
final List<Device> devices = await deviceManager.getAllConnectedDevices().toList(); final List<Device> devices = await deviceManager.getAllConnectedDevices().toList();
......
...@@ -220,7 +220,7 @@ class CocoaPods { ...@@ -220,7 +220,7 @@ class CocoaPods {
} }
Future<void> _runPodInstall(IosProject iosProject, String engineDirectory) async { Future<void> _runPodInstall(IosProject iosProject, String engineDirectory) async {
final Status status = logger.startProgress('Running pod install...', timeout: kSlowOperation); final Status status = logger.startProgress('Running pod install...', expectSlowOperation: true);
final ProcessResult result = await processManager.run( final ProcessResult result = await processManager.run(
<String>['pod', 'install', '--verbose'], <String>['pod', 'install', '--verbose'],
workingDirectory: iosProject.hostAppRoot.path, workingDirectory: iosProject.hostAppRoot.path,
......
...@@ -26,6 +26,8 @@ const String _kIdeviceinstallerInstructions = ...@@ -26,6 +26,8 @@ const String _kIdeviceinstallerInstructions =
'To work with iOS devices, please install ideviceinstaller. To install, run:\n' 'To work with iOS devices, please install ideviceinstaller. To install, run:\n'
'brew install ideviceinstaller.'; 'brew install ideviceinstaller.';
const Duration kPortForwardTimeout = Duration(seconds: 10);
class IOSDeploy { class IOSDeploy {
const IOSDeploy(); const IOSDeploy();
...@@ -295,7 +297,7 @@ class IOSDevice extends Device { ...@@ -295,7 +297,7 @@ class IOSDevice extends Device {
int installationResult = -1; int installationResult = -1;
Uri localObservatoryUri; Uri localObservatoryUri;
final Status installStatus = logger.startProgress('Installing and launching...', timeout: kSlowOperation); final Status installStatus = logger.startProgress('Installing and launching...', expectSlowOperation: true);
if (!debuggingOptions.debuggingEnabled) { if (!debuggingOptions.debuggingEnabled) {
// If debugging is not enabled, just launch the application and continue. // If debugging is not enabled, just launch the application and continue.
......
...@@ -470,7 +470,7 @@ Future<XcodeBuildResult> buildXcodeProject({ ...@@ -470,7 +470,7 @@ Future<XcodeBuildResult> buildXcodeProject({
initialBuildStatus.cancel(); initialBuildStatus.cancel();
buildSubStatus = logger.startProgress( buildSubStatus = logger.startProgress(
line, line,
timeout: kSlowOperation, expectSlowOperation: true,
progressIndicatorPadding: kDefaultStatusPadding - 7, progressIndicatorPadding: kDefaultStatusPadding - 7,
); );
} }
...@@ -485,7 +485,7 @@ Future<XcodeBuildResult> buildXcodeProject({ ...@@ -485,7 +485,7 @@ Future<XcodeBuildResult> buildXcodeProject({
} }
final Stopwatch buildStopwatch = Stopwatch()..start(); final Stopwatch buildStopwatch = Stopwatch()..start();
initialBuildStatus = logger.startProgress('Starting Xcode build...', timeout: kFastOperation); initialBuildStatus = logger.startProgress('Starting Xcode build...');
final RunResult buildResult = await runAsync( final RunResult buildResult = await runAsync(
buildCommands, buildCommands,
workingDirectory: app.project.hostAppRoot.path, workingDirectory: app.project.hostAppRoot.path,
......
...@@ -9,6 +9,7 @@ import 'package:meta/meta.dart'; ...@@ -9,6 +9,7 @@ import 'package:meta/meta.dart';
import 'application_package.dart'; import 'application_package.dart';
import 'artifacts.dart'; import 'artifacts.dart';
import 'asset.dart'; import 'asset.dart';
import 'base/common.dart';
import 'base/file_system.dart'; import 'base/file_system.dart';
import 'base/io.dart'; import 'base/io.dart';
import 'base/logger.dart'; import 'base/logger.dart';
...@@ -71,13 +72,11 @@ class FlutterDevice { ...@@ -71,13 +72,11 @@ class FlutterDevice {
if (vmServices != null) if (vmServices != null)
return; return;
final List<VMService> localVmServices = List<VMService>(observatoryUris.length); final List<VMService> localVmServices = List<VMService>(observatoryUris.length);
for (int i = 0; i < observatoryUris.length; i += 1) { for (int i = 0; i < observatoryUris.length; i++) {
printTrace('Connecting to service protocol: ${observatoryUris[i]}'); printTrace('Connecting to service protocol: ${observatoryUris[i]}');
localVmServices[i] = await VMService.connect( localVmServices[i] = await VMService.connect(observatoryUris[i],
observatoryUris[i],
reloadSources: reloadSources, reloadSources: reloadSources,
compileExpression: compileExpression, compileExpression: compileExpression);
);
printTrace('Successfully connected to service protocol: ${observatoryUris[i]}'); printTrace('Successfully connected to service protocol: ${observatoryUris[i]}');
} }
vmServices = localVmServices; vmServices = localVmServices;
...@@ -113,16 +112,13 @@ class FlutterDevice { ...@@ -113,16 +112,13 @@ class FlutterDevice {
final List<FlutterView> flutterViews = views; final List<FlutterView> flutterViews = views;
if (flutterViews == null || flutterViews.isEmpty) if (flutterViews == null || flutterViews.isEmpty)
return; return;
final List<Future<void>> futures = <Future<void>>[];
for (FlutterView view in flutterViews) { for (FlutterView view in flutterViews) {
if (view != null && view.uiIsolate != null) { if (view != null && view.uiIsolate != null) {
futures.add(view.uiIsolate.flutterExit()); // Manage waits specifically below.
view.uiIsolate.flutterExit(); // ignore: unawaited_futures
} }
} }
// The flutterExit message only returns if it fails, so just wait a few await Future<void>.delayed(const Duration(milliseconds: 100));
// seconds then assume it worked.
// TODO(ianh): We should make this return once the VM service disconnects.
await Future.wait(futures).timeout(const Duration(seconds: 2), onTimeout: () { });
} }
Future<Uri> setupDevFS(String fsName, Future<Uri> setupDevFS(String fsName,
...@@ -386,7 +382,7 @@ class FlutterDevice { ...@@ -386,7 +382,7 @@ class FlutterDevice {
}) async { }) async {
final Status devFSStatus = logger.startProgress( final Status devFSStatus = logger.startProgress(
'Syncing files to device ${device.name}...', 'Syncing files to device ${device.name}...',
timeout: kFastOperation, expectSlowOperation: true,
); );
int bytes = 0; int bytes = 0;
try { try {
...@@ -478,14 +474,11 @@ abstract class ResidentRunner { ...@@ -478,14 +474,11 @@ abstract class ResidentRunner {
} }
/// Start the app and keep the process running during its lifetime. /// Start the app and keep the process running during its lifetime.
///
/// Returns the exit code that we should use for the flutter tool process; 0
/// for success, 1 for user error (e.g. bad arguments), 2 for other failures.
Future<int> run({ Future<int> run({
Completer<DebugConnectionInfo> connectionInfoCompleter, Completer<DebugConnectionInfo> connectionInfoCompleter,
Completer<void> appStartedCompleter, Completer<void> appStartedCompleter,
String route, String route,
bool shouldBuild = true, bool shouldBuild = true
}); });
bool get supportsRestart => false; bool get supportsRestart => false;
...@@ -500,7 +493,7 @@ abstract class ResidentRunner { ...@@ -500,7 +493,7 @@ abstract class ResidentRunner {
await _debugSaveCompilationTrace(); await _debugSaveCompilationTrace();
await stopEchoingDeviceLog(); await stopEchoingDeviceLog();
await preStop(); await preStop();
await stopApp(); return stopApp();
} }
Future<void> detach() async { Future<void> detach() async {
...@@ -565,7 +558,7 @@ abstract class ResidentRunner { ...@@ -565,7 +558,7 @@ abstract class ResidentRunner {
} }
Future<void> _screenshot(FlutterDevice device) async { Future<void> _screenshot(FlutterDevice device) async {
final Status status = logger.startProgress('Taking screenshot for ${device.device.name}...', timeout: kFastOperation); final Status status = logger.startProgress('Taking screenshot for ${device.device.name}...');
final File outputFile = getUniqueFile(fs.currentDirectory, 'flutter', 'png'); final File outputFile = getUniqueFile(fs.currentDirectory, 'flutter', 'png');
try { try {
if (supportsServiceProtocol && isRunningDebug) { if (supportsServiceProtocol && isRunningDebug) {
...@@ -680,32 +673,24 @@ abstract class ResidentRunner { ...@@ -680,32 +673,24 @@ abstract class ResidentRunner {
} }
/// If the [reloadSources] parameter is not null the 'reloadSources' service /// If the [reloadSources] parameter is not null the 'reloadSources' service
/// will be registered. /// will be registered
//
// Failures should be indicated by completing the future with an error, using
// a string as the error object, which will be used by the caller (attach())
// to display an error message.
Future<void> connectToServiceProtocol({ReloadSources reloadSources, CompileExpression compileExpression}) async { Future<void> connectToServiceProtocol({ReloadSources reloadSources, CompileExpression compileExpression}) async {
if (!debuggingOptions.debuggingEnabled) if (!debuggingOptions.debuggingEnabled)
throw 'The service protocol is not enabled.'; return Future<void>.error('Error the service protocol is not enabled.');
bool viewFound = false; bool viewFound = false;
for (FlutterDevice device in flutterDevices) { for (FlutterDevice device in flutterDevices) {
await device._connect( await device._connect(reloadSources: reloadSources,
reloadSources: reloadSources, compileExpression: compileExpression);
compileExpression: compileExpression,
);
await device.getVMs(); await device.getVMs();
await device.refreshViews(); await device.refreshViews();
if (device.views.isNotEmpty) if (device.views.isEmpty)
printStatus('No Flutter views available on ${device.device.name}');
else
viewFound = true; viewFound = true;
} }
if (!viewFound) { if (!viewFound)
if (flutterDevices.length == 1) throwToolExit('No Flutter view is available');
throw 'No Flutter view is available on ${flutterDevices.first.device.name}.';
throw 'No Flutter view is available on any device '
'(${flutterDevices.map<String>((FlutterDevice device) => device.device.name).join(', ')}).';
}
// Listen for service protocol connection to close. // Listen for service protocol connection to close.
for (FlutterDevice device in flutterDevices) { for (FlutterDevice device in flutterDevices) {
...@@ -856,13 +841,12 @@ abstract class ResidentRunner { ...@@ -856,13 +841,12 @@ abstract class ResidentRunner {
printHelp(details: false); printHelp(details: false);
} }
terminal.singleCharMode = true; terminal.singleCharMode = true;
terminal.keystrokes.listen(processTerminalInput); terminal.onCharInput.listen(processTerminalInput);
} }
} }
Future<int> waitForAppToFinish() async { Future<int> waitForAppToFinish() async {
final int exitCode = await _finished.future; final int exitCode = await _finished.future;
assert(exitCode != null);
await cleanupAtFinish(); await cleanupAtFinish();
return exitCode; return exitCode;
} }
...@@ -883,10 +867,8 @@ abstract class ResidentRunner { ...@@ -883,10 +867,8 @@ abstract class ResidentRunner {
Future<void> preStop() async { } Future<void> preStop() async { }
Future<void> stopApp() async { Future<void> stopApp() async {
final List<Future<void>> futures = <Future<void>>[];
for (FlutterDevice device in flutterDevices) for (FlutterDevice device in flutterDevices)
futures.add(device.stopApps()); await device.stopApps();
await Future.wait(futures);
appFinished(); appFinished();
} }
......
...@@ -64,14 +64,8 @@ class ColdRunner extends ResidentRunner { ...@@ -64,14 +64,8 @@ class ColdRunner extends ResidentRunner {
} }
// Connect to observatory. // Connect to observatory.
if (debuggingOptions.debuggingEnabled) { if (debuggingOptions.debuggingEnabled)
try {
await connectToServiceProtocol(); await connectToServiceProtocol();
} on String catch (message) {
printError(message);
return 2;
}
}
if (flutterDevices.first.observatoryUris != null) { if (flutterDevices.first.observatoryUris != null) {
// For now, only support one debugger connection. // For now, only support one debugger connection.
......
This diff is collapsed.
...@@ -454,17 +454,19 @@ abstract class FlutterCommand extends Command<void> { ...@@ -454,17 +454,19 @@ abstract class FlutterCommand extends Command<void> {
body: () async { body: () async {
if (flutterUsage.isFirstRun) if (flutterUsage.isFirstRun)
flutterUsage.printWelcome(); flutterUsage.printWelcome();
final String commandPath = await usagePath;
FlutterCommandResult commandResult; FlutterCommandResult commandResult;
try { try {
commandResult = await verifyThenRunCommand(commandPath); commandResult = await verifyThenRunCommand();
} on ToolExit { } on ToolExit {
commandResult = const FlutterCommandResult(ExitStatus.fail); commandResult = const FlutterCommandResult(ExitStatus.fail);
rethrow; rethrow;
} finally { } finally {
final DateTime endTime = systemClock.now(); final DateTime endTime = systemClock.now();
printTrace('"flutter $name" took ${getElapsedAsMilliseconds(endTime.difference(startTime))}.'); printTrace('"flutter $name" took ${getElapsedAsMilliseconds(endTime.difference(startTime))}.');
if (commandPath != null) { // This is checking the result of the call to 'usagePath'
// (a Future<String>), and not the result of evaluating the Future.
if (usagePath != null) {
final List<String> labels = <String>[]; final List<String> labels = <String>[];
if (commandResult?.exitStatus != null) if (commandResult?.exitStatus != null)
labels.add(getEnumName(commandResult.exitStatus)); labels.add(getEnumName(commandResult.exitStatus));
...@@ -498,7 +500,7 @@ abstract class FlutterCommand extends Command<void> { ...@@ -498,7 +500,7 @@ abstract class FlutterCommand extends Command<void> {
/// then call this method to execute the command /// then call this method to execute the command
/// rather than calling [runCommand] directly. /// rather than calling [runCommand] directly.
@mustCallSuper @mustCallSuper
Future<FlutterCommandResult> verifyThenRunCommand(String commandPath) async { Future<FlutterCommandResult> verifyThenRunCommand() async {
await validateCommand(); await validateCommand();
// Populate the cache. We call this before pub get below so that the sky_engine // Populate the cache. We call this before pub get below so that the sky_engine
...@@ -514,6 +516,8 @@ abstract class FlutterCommand extends Command<void> { ...@@ -514,6 +516,8 @@ abstract class FlutterCommand extends Command<void> {
setupApplicationPackages(); setupApplicationPackages();
final String commandPath = await usagePath;
if (commandPath != null) { if (commandPath != null) {
final Map<String, String> additionalUsageValues = await usageValues; final Map<String, String> additionalUsageValues = await usageValues;
flutterUsage.sendCommand(commandPath, parameters: additionalUsageValues); flutterUsage.sendCommand(commandPath, parameters: additionalUsageValues);
......
...@@ -57,7 +57,13 @@ class CoverageCollector extends TestWatcher { ...@@ -57,7 +57,13 @@ class CoverageCollector extends TestWatcher {
if (result == null) if (result == null)
throw Exception('Failed to collect coverage.'); throw Exception('Failed to collect coverage.');
data = result; data = result;
}); })
.timeout(
const Duration(minutes: 10),
onTimeout: () {
throw Exception('Timed out while collecting coverage.');
},
);
await Future.any<void>(<Future<void>>[ processComplete, collectionComplete ]); await Future.any<void>(<Future<void>>[ processComplete, collectionComplete ]);
assert(data != null); assert(data != null);
...@@ -71,8 +77,12 @@ class CoverageCollector extends TestWatcher { ...@@ -71,8 +77,12 @@ class CoverageCollector extends TestWatcher {
/// ///
/// This will not start any collection tasks. It us up to the caller of to /// This will not start any collection tasks. It us up to the caller of to
/// call [collectCoverage] for each process first. /// call [collectCoverage] for each process first.
///
/// If [timeout] is specified, the future will timeout (with a
/// [TimeoutException]) after the specified duration.
Future<String> finalizeCoverage({ Future<String> finalizeCoverage({
coverage.Formatter formatter, coverage.Formatter formatter,
Duration timeout,
Directory coverageDirectory, Directory coverageDirectory,
}) async { }) async {
printTrace('formating coverage data'); printTrace('formating coverage data');
...@@ -92,8 +102,9 @@ class CoverageCollector extends TestWatcher { ...@@ -92,8 +102,9 @@ class CoverageCollector extends TestWatcher {
} }
Future<bool> collectCoverageData(String coveragePath, { bool mergeCoverageData = false, Directory coverageDirectory }) async { Future<bool> collectCoverageData(String coveragePath, { bool mergeCoverageData = false, Directory coverageDirectory }) async {
final Status status = logger.startProgress('Collecting coverage information...', timeout: kFastOperation); final Status status = logger.startProgress('Collecting coverage information...');
final String coverageData = await finalizeCoverage( final String coverageData = await finalizeCoverage(
timeout: const Duration(seconds: 30),
coverageDirectory: coverageDirectory, coverageDirectory: coverageDirectory,
); );
status.stop(); status.stop();
......
...@@ -33,17 +33,11 @@ import 'watcher.dart'; ...@@ -33,17 +33,11 @@ import 'watcher.dart';
/// The timeout we give the test process to connect to the test harness /// The timeout we give the test process to connect to the test harness
/// once the process has entered its main method. /// once the process has entered its main method.
///
/// We time out test execution because we expect some tests to hang and we want
/// to know which test hung, rather than have the entire test harness just do
/// nothing for a few hours until the user (or CI environment) gets bored.
const Duration _kTestStartupTimeout = Duration(minutes: 1); const Duration _kTestStartupTimeout = Duration(minutes: 1);
/// The timeout we give the test process to start executing Dart code. When the /// The timeout we give the test process to start executing Dart code. When the
/// CPU is under severe load, this can take a while, but it's not indicative of /// CPU is under severe load, this can take a while, but it's not indicative of
/// any problem with Flutter, so we give it a large timeout. /// any problem with Flutter, so we give it a large timeout.
///
/// See comment under [_kTestStartupTimeout] regarding timeouts.
const Duration _kTestProcessTimeout = Duration(minutes: 5); const Duration _kTestProcessTimeout = Duration(minutes: 5);
/// Message logged by the test process to signal that its main method has begun /// Message logged by the test process to signal that its main method has begun
...@@ -294,10 +288,12 @@ class _Compiler { ...@@ -294,10 +288,12 @@ class _Compiler {
firstCompile = true; firstCompile = true;
} }
suppressOutput = false; suppressOutput = false;
final CompilerOutput compilerOutput = await compiler.recompile( final CompilerOutput compilerOutput = await handleTimeout<CompilerOutput>(
compiler.recompile(
request.path, request.path,
<String>[request.path], <String>[request.path],
outputPath: outputDill.path, outputPath: outputDill.path),
request.path,
); );
final String outputPath = compilerOutput?.outputFilename; final String outputPath = compilerOutput?.outputFilename;
...@@ -341,7 +337,7 @@ class _Compiler { ...@@ -341,7 +337,7 @@ class _Compiler {
Future<String> compile(String mainDart) { Future<String> compile(String mainDart) {
final Completer<String> completer = Completer<String>(); final Completer<String> completer = Completer<String>();
compilerController.add(_CompilationRequest(mainDart, completer)); compilerController.add(_CompilationRequest(mainDart, completer));
return completer.future; return handleTimeout<String>(completer.future, mainDart);
} }
Future<void> _shutdown() async { Future<void> _shutdown() async {
...@@ -357,6 +353,13 @@ class _Compiler { ...@@ -357,6 +353,13 @@ class _Compiler {
await _shutdown(); await _shutdown();
await compilerController.close(); await compilerController.close();
} }
static Future<T> handleTimeout<T>(Future<T> value, String path) {
return value.timeout(const Duration(minutes: 5), onTimeout: () {
printError('Compilation of $path timed out after 5 minutes.');
return null;
});
}
} }
class _FlutterPlatform extends PlatformPlugin { class _FlutterPlatform extends PlatformPlugin {
......
...@@ -35,12 +35,14 @@ class Tracing { ...@@ -35,12 +35,14 @@ class Tracing {
bool waitForFirstFrame = false bool waitForFirstFrame = false
}) async { }) async {
Map<String, dynamic> timeline; Map<String, dynamic> timeline;
if (!waitForFirstFrame) { if (!waitForFirstFrame) {
// Stop tracing immediately and get the timeline // Stop tracing immediately and get the timeline
await vmService.vm.setVMTimelineFlags(<String>[]); await vmService.vm.setVMTimelineFlags(<String>[]);
timeline = await vmService.vm.getVMTimeline(); timeline = await vmService.vm.getVMTimeline();
} else { } else {
final Completer<void> whenFirstFrameRendered = Completer<void>(); final Completer<void> whenFirstFrameRendered = Completer<void>();
(await vmService.onTimelineEvent).listen((ServiceEvent timelineEvent) { (await vmService.onTimelineEvent).listen((ServiceEvent timelineEvent) {
final List<Map<String, dynamic>> events = timelineEvent.timelineEvents; final List<Map<String, dynamic>> events = timelineEvent.timelineEvents;
for (Map<String, dynamic> event in events) { for (Map<String, dynamic> event in events) {
...@@ -48,10 +50,24 @@ class Tracing { ...@@ -48,10 +50,24 @@ class Tracing {
whenFirstFrameRendered.complete(); whenFirstFrameRendered.complete();
} }
}); });
await whenFirstFrameRendered.future;
await whenFirstFrameRendered.future.timeout(
const Duration(seconds: 10),
onTimeout: () {
printError(
'Timed out waiting for the first frame event. Either the '
'application failed to start, or the event was missed because '
'"flutter run" took too long to subscribe to timeline events.'
);
return null;
}
);
timeline = await vmService.vm.getVMTimeline(); timeline = await vmService.vm.getVMTimeline();
await vmService.vm.setVMTimelineFlags(<String>[]); await vmService.vm.setVMTimelineFlags(<String>[]);
} }
return timeline; return timeline;
} }
} }
......
...@@ -14,6 +14,7 @@ class VsCodeValidator extends DoctorValidator { ...@@ -14,6 +14,7 @@ class VsCodeValidator extends DoctorValidator {
final VsCode _vsCode; final VsCode _vsCode;
static Iterable<DoctorValidator> get installedValidators { static Iterable<DoctorValidator> get installedValidators {
return VsCode return VsCode
.allInstalled() .allInstalled()
......
...@@ -158,7 +158,7 @@ void main() { ...@@ -158,7 +158,7 @@ void main() {
fallbacks: <Type, Generator>{ fallbacks: <Type, Generator>{
int: () => int.parse(context[String]), int: () => int.parse(context[String]),
String: () => '${context[double]}', String: () => '${context[double]}',
double: () => (context[int] as int) * 1.0, // ignore: avoid_as double: () => context[int] * 1.0,
}, },
); );
try { try {
......
...@@ -165,7 +165,7 @@ Stream<String> mockStdInStream; ...@@ -165,7 +165,7 @@ Stream<String> mockStdInStream;
class TestTerminal extends AnsiTerminal { class TestTerminal extends AnsiTerminal {
@override @override
Stream<String> get keystrokes { Stream<String> get onCharInput {
return mockStdInStream; return mockStdInStream;
} }
} }
...@@ -90,5 +90,5 @@ void main() { ...@@ -90,5 +90,5 @@ void main() {
expect(result, isList); expect(result, isList);
expect(result, isNotEmpty); expect(result, isNotEmpty);
}); });
}, timeout: const Timeout.factor(10)); // This test uses the `flutter` tool, which could be blocked behind the startup lock for a long time. }, timeout: const Timeout.factor(2));
} }
...@@ -28,15 +28,13 @@ void main() { ...@@ -28,15 +28,13 @@ void main() {
}); });
test('can step over statements', () async { test('can step over statements', () async {
await _flutter.run(withDebugger: true, startPaused: true); await _flutter.run(withDebugger: true);
await _flutter.addBreakpoint(_project.breakpointUri, _project.breakpointLine);
await _flutter.resume();
await _flutter.waitForPause(); // Now we should be on the breakpoint.
expect((await _flutter.getSourceLocation()).line, equals(_project.breakpointLine)); // Stop at the initial breakpoint that the expected steps are based on.
await _flutter.breakAt(_project.breakpointUri, _project.breakpointLine, restart: true);
// Issue 5 steps, ensuring that we end up on the annotated lines each time. // Issue 5 steps, ensuring that we end up on the annotated lines each time.
for (int i = 1; i <= _project.numberOfSteps; i += 1) { for (int i = 1; i <= _project.numberOfSteps; i++) {
await _flutter.stepOverOrOverAsyncSuspension(); await _flutter.stepOverOrOverAsyncSuspension();
final SourcePosition location = await _flutter.getSourceLocation(); final SourcePosition location = await _flutter.getSourceLocation();
final int actualLine = location.line; final int actualLine = location.line;
...@@ -49,5 +47,5 @@ void main() { ...@@ -49,5 +47,5 @@ void main() {
reason: 'After $i steps, debugger should stop at $expectedLine but stopped at $actualLine'); reason: 'After $i steps, debugger should stop at $expectedLine but stopped at $actualLine');
} }
}); });
}, timeout: const Timeout.factor(10)); // The DevFS sync takes a really long time, so these tests can be slow. }, timeout: const Timeout.factor(3));
} }
...@@ -31,18 +31,16 @@ void main() { ...@@ -31,18 +31,16 @@ void main() {
tryToDelete(tempDir); tryToDelete(tempDir);
}); });
Future<void> breakInBuildMethod(FlutterTestDriver flutter) async { Future<Isolate> breakInBuildMethod(FlutterTestDriver flutter) async {
await _flutter.breakAt( return _flutter.breakAt(
_project.buildMethodBreakpointUri, _project.buildMethodBreakpointUri,
_project.buildMethodBreakpointLine, _project.buildMethodBreakpointLine);
);
} }
Future<void> breakInTopLevelFunction(FlutterTestDriver flutter) async { Future<Isolate> breakInTopLevelFunction(FlutterTestDriver flutter) async {
await _flutter.breakAt( return _flutter.breakAt(
_project.topLevelFunctionBreakpointUri, _project.topLevelFunctionBreakpointUri,
_project.topLevelFunctionBreakpointLine, _project.topLevelFunctionBreakpointLine);
);
} }
test('can evaluate trivial expressions in top level function', () async { test('can evaluate trivial expressions in top level function', () async {
...@@ -80,8 +78,7 @@ void main() { ...@@ -80,8 +78,7 @@ void main() {
await breakInBuildMethod(_flutter); await breakInBuildMethod(_flutter);
await evaluateComplexReturningExpressions(_flutter); await evaluateComplexReturningExpressions(_flutter);
}); });
}, timeout: const Timeout.factor(6));
}, timeout: const Timeout.factor(10)); // The DevFS sync takes a really long time, so these tests can be slow.
} }
Future<void> evaluateTrivialExpressions(FlutterTestDriver flutter) async { Future<void> evaluateTrivialExpressions(FlutterTestDriver flutter) async {
......
...@@ -18,8 +18,8 @@ void main() { ...@@ -18,8 +18,8 @@ void main() {
setUp(() async { setUp(() async {
tempDir = createResolvedTempDirectorySync(); tempDir = createResolvedTempDirectorySync();
await _project.setUpIn(tempDir); await _project.setUpIn(tempDir);
_flutterRun = FlutterRunTestDriver(tempDir, logPrefix: ' RUN '); _flutterRun = FlutterRunTestDriver(tempDir, logPrefix: 'RUN');
_flutterAttach = FlutterRunTestDriver(tempDir, logPrefix: 'ATTACH '); _flutterAttach = FlutterRunTestDriver(tempDir, logPrefix: 'ATTACH');
}); });
tearDown(() async { tearDown(() async {
...@@ -58,5 +58,5 @@ void main() { ...@@ -58,5 +58,5 @@ void main() {
await _flutterAttach.attach(_flutterRun.vmServicePort); await _flutterAttach.attach(_flutterRun.vmServicePort);
await _flutterAttach.hotReload(); await _flutterAttach.hotReload();
}); });
}, timeout: const Timeout.factor(10)); // The DevFS sync takes a really long time, so these tests can be slow. }, timeout: const Timeout.factor(6));
} }
...@@ -55,5 +55,5 @@ void main() { ...@@ -55,5 +55,5 @@ void main() {
await _flutter.run(pidFile: pidFile); await _flutter.run(pidFile: pidFile);
expect(pidFile.existsSync(), isTrue); expect(pidFile.existsSync(), isTrue);
}); });
}, timeout: const Timeout.factor(10)); // The DevFS sync takes a really long time, so these tests can be slow. }, timeout: const Timeout.factor(6));
} }
...@@ -14,7 +14,7 @@ import 'test_driver.dart'; ...@@ -14,7 +14,7 @@ import 'test_driver.dart';
import 'test_utils.dart'; import 'test_utils.dart';
void main() { void main() {
group('hot reload tests', () { group('hot', () {
Directory tempDir; Directory tempDir;
final HotReloadProject _project = HotReloadProject(); final HotReloadProject _project = HotReloadProject();
FlutterRunTestDriver _flutter; FlutterRunTestDriver _flutter;
...@@ -26,127 +26,39 @@ void main() { ...@@ -26,127 +26,39 @@ void main() {
}); });
tearDown(() async { tearDown(() async {
await _flutter?.stop(); await _flutter.stop();
tryToDelete(tempDir); tryToDelete(tempDir);
}); });
test('hot reload works without error', () async { test('reload works without error', () async {
await _flutter.run(); await _flutter.run();
await _flutter.hotReload(); await _flutter.hotReload();
}); });
test('newly added code executes during hot reload', () async { test('newly added code executes during reload', () async {
await _flutter.run(); await _flutter.run();
_project.uncommentHotReloadPrint(); _project.uncommentHotReloadPrint();
final StringBuffer stdout = StringBuffer(); final StringBuffer stdout = StringBuffer();
final StreamSubscription<String> subscription = _flutter.stdout.listen(stdout.writeln); final StreamSubscription<String> sub = _flutter.stdout.listen(stdout.writeln);
try { try {
await _flutter.hotReload(); await _flutter.hotReload();
expect(stdout.toString(), contains('(((((RELOAD WORKED)))))')); expect(stdout.toString(), contains('(((((RELOAD WORKED)))))'));
} finally { } finally {
await subscription.cancel(); await sub.cancel();
} }
}); });
test('hot restart works without error', () async { test('restart works without error', () async {
await _flutter.run(); await _flutter.run();
await _flutter.hotRestart(); await _flutter.hotRestart();
}); });
test('breakpoints are hit after hot reload', () async { test('reload hits breakpoints after reload', () async {
Isolate isolate;
await _flutter.run(withDebugger: true, startPaused: true);
final Completer<void> sawTick1 = Completer<void>();
final Completer<void> sawTick3 = Completer<void>();
final Completer<void> sawDebuggerPausedMessage = Completer<void>();
final StreamSubscription<String> subscription = _flutter.stdout.listen(
(String line) {
if (line.contains('((((TICK 1))))')) {
expect(sawTick1.isCompleted, isFalse);
sawTick1.complete();
}
if (line.contains('((((TICK 3))))')) {
expect(sawTick3.isCompleted, isFalse);
sawTick3.complete();
}
if (line.contains('The application is paused in the debugger on a breakpoint.')) {
expect(sawDebuggerPausedMessage.isCompleted, isFalse);
sawDebuggerPausedMessage.complete();
}
},
);
await _flutter.resume(); // we start paused so we can set up our TICK 1 listener before the app starts
sawTick1.future.timeout( // ignore: unawaited_futures
const Duration(seconds: 5),
onTimeout: () { print('The test app is taking longer than expected to print its synchronization line...'); },
);
await sawTick1.future; // after this, app is in steady state
await _flutter.addBreakpoint(
_project.scheduledBreakpointUri,
_project.scheduledBreakpointLine,
);
await _flutter.hotReload(); // reload triggers code which eventually hits the breakpoint
isolate = await _flutter.waitForPause();
expect(isolate.pauseEvent.kind, equals(EventKind.kPauseBreakpoint));
await _flutter.resume();
await _flutter.addBreakpoint(
_project.buildBreakpointUri,
_project.buildBreakpointLine,
);
bool reloaded = false;
final Future<void> reloadFuture = _flutter.hotReload().then((void value) { reloaded = true; });
await sawTick3.future; // this should happen before it pauses
isolate = await _flutter.waitForPause();
expect(isolate.pauseEvent.kind, equals(EventKind.kPauseBreakpoint));
await sawDebuggerPausedMessage.future;
expect(reloaded, isFalse);
await _flutter.resume();
await reloadFuture;
expect(reloaded, isTrue);
reloaded = false;
await subscription.cancel();
});
test('hot reload doesn\'t reassemble if paused', () async {
await _flutter.run(withDebugger: true); await _flutter.run(withDebugger: true);
final Completer<void> sawTick2 = Completer<void>(); final Isolate isolate = await _flutter.breakAt(
final Completer<void> sawTick3 = Completer<void>(); _project.breakpointUri,
final Completer<void> sawDebuggerPausedMessage1 = Completer<void>(); _project.breakpointLine);
final Completer<void> sawDebuggerPausedMessage2 = Completer<void>();
final StreamSubscription<String> subscription = _flutter.stdout.listen(
(String line) {
if (line.contains('((((TICK 2))))')) {
expect(sawTick2.isCompleted, isFalse);
sawTick2.complete();
}
if (line.contains('The application is paused in the debugger on a breakpoint.')) {
expect(sawDebuggerPausedMessage1.isCompleted, isFalse);
sawDebuggerPausedMessage1.complete();
}
if (line.contains('The application is paused in the debugger on a breakpoint; interface might not update.')) {
expect(sawDebuggerPausedMessage2.isCompleted, isFalse);
sawDebuggerPausedMessage2.complete();
}
},
);
await _flutter.addBreakpoint(
_project.buildBreakpointUri,
_project.buildBreakpointLine,
);
bool reloaded = false;
final Future<void> reloadFuture = _flutter.hotReload().then((void value) { reloaded = true; });
await sawTick2.future; // this should happen before it pauses
final Isolate isolate = await _flutter.waitForPause();
expect(isolate.pauseEvent.kind, equals(EventKind.kPauseBreakpoint)); expect(isolate.pauseEvent.kind, equals(EventKind.kPauseBreakpoint));
expect(reloaded, isFalse);
await sawDebuggerPausedMessage1.future; // this is the one where it say "uh, you broke into the debugger while reloading"
await reloadFuture; // this is the one where it times out because you're in the debugger
expect(reloaded, isTrue);
await _flutter.hotReload(); // now we're already paused
expect(sawTick3.isCompleted, isFalse);
await sawDebuggerPausedMessage2.future; // so we just get told that nothing is going to happen
await _flutter.resume();
await subscription.cancel();
}); });
}, timeout: const Timeout.factor(10)); // The DevFS sync takes a really long time, so these tests can be slow. }, timeout: const Timeout.factor(6));
} }
...@@ -45,5 +45,5 @@ void main() { ...@@ -45,5 +45,5 @@ void main() {
await Future<void>.delayed(requiredLifespan); await Future<void>.delayed(requiredLifespan);
expect(_flutter.hasExited, equals(false)); expect(_flutter.hasExited, equals(false));
}); });
}, timeout: const Timeout.factor(10)); // The DevFS sync takes a really long time, so these tests can be slow. }, timeout: const Timeout.factor(6));
} }
...@@ -19,22 +19,15 @@ class BasicProject extends Project { ...@@ -19,22 +19,15 @@ class BasicProject extends Project {
@override @override
final String main = r''' final String main = r'''
import 'dart:async';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
Future<void> main() async { void main() => runApp(new MyApp());
while (true) {
runApp(new MyApp());
await Future.delayed(const Duration(milliseconds: 50));
}
}
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
topLevelFunction(); topLevelFunction();
return new MaterialApp( // BUILD BREAKPOINT return new MaterialApp( // BREAKPOINT
title: 'Flutter Demo', title: 'Flutter Demo',
home: new Container(), home: new Container(),
); );
...@@ -46,9 +39,9 @@ class BasicProject extends Project { ...@@ -46,9 +39,9 @@ class BasicProject extends Project {
} }
'''; ''';
Uri get buildMethodBreakpointUri => mainDart; Uri get buildMethodBreakpointUri => breakpointUri;
int get buildMethodBreakpointLine => lineContaining(main, '// BUILD BREAKPOINT'); int get buildMethodBreakpointLine => breakpointLine;
Uri get topLevelFunctionBreakpointUri => mainDart; Uri get topLevelFunctionBreakpointUri => breakpointUri;
int get topLevelFunctionBreakpointLine => lineContaining(main, '// TOP LEVEL BREAKPOINT'); int get topLevelFunctionBreakpointLine => lineContaining(main, '// TOP LEVEL BREAKPOINT');
} }
...@@ -22,63 +22,33 @@ class HotReloadProject extends Project { ...@@ -22,63 +22,33 @@ class HotReloadProject extends Project {
@override @override
final String main = r''' final String main = r'''
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter/scheduler.dart';
void main() => runApp(new MyApp()); void main() => runApp(new MyApp());
int count = 1;
class MyApp extends StatelessWidget { class MyApp extends StatelessWidget {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
// This method gets called each time we hot reload, during reassemble. // Do not remove this line, it's uncommented by a test to verify that hot
// reloading worked.
// Do not remove the next line, it's uncommented by a test to verify that
// hot reloading worked:
// printHotReloadWorked(); // printHotReloadWorked();
print('((((TICK $count))))'); return new MaterialApp( // BREAKPOINT
// tick 1 = startup warmup frame
// tick 2 = hot reload warmup reassemble frame
// after that there's a post-hot-reload frame scheduled by the tool that
// doesn't trigger this to rebuild, but does trigger the first callback
// below, then that callback schedules another frame on which we do the
// breakpoint.
// tick 3 = second hot reload warmup reassemble frame (pre breakpoint)
if (count == 2) {
SchedulerBinding.instance.scheduleFrameCallback((Duration timestamp) {
SchedulerBinding.instance.scheduleFrameCallback((Duration timestamp) {
print('breakpoint line'); // SCHEDULED BREAKPOINT
});
});
}
count += 1;
return MaterialApp( // BUILD BREAKPOINT
title: 'Flutter Demo', title: 'Flutter Demo',
home: Container(), home: new Container(),
); );
} }
} }
void printHotReloadWorked() { printHotReloadWorked() {
// The call to this function is uncommented by a test to verify that hot // The call to this function is uncommented by a test to verify that hot
// reloading worked. // reloading worked.
print('(((((RELOAD WORKED)))))'); print('(((((RELOAD WORKED)))))');
} }
'''; ''';
Uri get scheduledBreakpointUri => mainDart;
int get scheduledBreakpointLine => lineContaining(main, '// SCHEDULED BREAKPOINT');
Uri get buildBreakpointUri => mainDart;
int get buildBreakpointLine => lineContaining(main, '// BUILD BREAKPOINT');
void uncommentHotReloadPrint() { void uncommentHotReloadPrint() {
final String newMainContents = main.replaceAll( final String newMainContents = main.replaceAll(
'// printHotReloadWorked();', '// printHotReloadWorked();', 'printHotReloadWorked();');
'printHotReloadWorked();'
);
writeFile(fs.path.join(dir.path, 'lib', 'main.dart'), newMainContents); writeFile(fs.path.join(dir.path, 'lib', 'main.dart'), newMainContents);
} }
} }
...@@ -15,7 +15,9 @@ abstract class Project { ...@@ -15,7 +15,9 @@ abstract class Project {
String get pubspec; String get pubspec;
String get main; String get main;
Uri get mainDart => Uri.parse('package:test/main.dart'); // Valid locations for a breakpoint for tests that just need to break somewhere.
Uri get breakpointUri => Uri.parse('package:test/main.dart');
int get breakpointLine => lineContaining(main, '// BREAKPOINT');
Future<void> setUpIn(Directory dir) async { Future<void> setUpIn(Directory dir) async {
this.dir = dir; this.dir = dir;
...@@ -30,6 +32,6 @@ abstract class Project { ...@@ -30,6 +32,6 @@ abstract class Project {
final int index = contents.split('\n').indexWhere((String l) => l.contains(search)); final int index = contents.split('\n').indexWhere((String l) => l.contains(search));
if (index == -1) if (index == -1)
throw Exception("Did not find '$search' inside the file"); throw Exception("Did not find '$search' inside the file");
return index + 1; // first line is line 1, not line 0 return index;
} }
} }
...@@ -35,11 +35,11 @@ class SteppingProject extends Project { ...@@ -35,11 +35,11 @@ class SteppingProject extends Project {
Future<void> doAsyncStuff() async { Future<void> doAsyncStuff() async {
print("test"); // BREAKPOINT print("test"); // BREAKPOINT
await new Future.value(true); // STEP 1 // STEP 2 await new Future.value(true); // STEP 1
await new Future.microtask(() => true); // STEP 3 // STEP 4 await new Future.microtask(() => true); // STEP 2 // STEP 3
await new Future.delayed(const Duration(milliseconds: 1)); // STEP 5 // STEP 6 await new Future.delayed(const Duration(milliseconds: 1)); // STEP 4 // STEP 5
print("done!"); // STEP 7 print("done!"); // STEP 6
} // STEP 8 }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
...@@ -51,9 +51,7 @@ class SteppingProject extends Project { ...@@ -51,9 +51,7 @@ class SteppingProject extends Project {
} }
'''; ''';
Uri get breakpointUri => mainDart;
int get breakpointLine => lineContaining(main, '// BREAKPOINT');
int lineForStep(int i) => lineContaining(main, '// STEP $i'); int lineForStep(int i) => lineContaining(main, '// STEP $i');
final int numberOfSteps = 8; final int numberOfSteps = 6;
} }
...@@ -470,7 +470,7 @@ class TestTerminal extends AnsiTerminal { ...@@ -470,7 +470,7 @@ class TestTerminal extends AnsiTerminal {
String bolden(String message) => '<bold>$message</bold>'; String bolden(String message) => '<bold>$message</bold>';
@override @override
Stream<String> get keystrokes { Stream<String> get onCharInput {
return mockTerminalStdInStream; return mockTerminalStdInStream;
} }
} }
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