[O] Remove many timeouts. (#23531)

* Remove many timeouts.

These are essentially self-inflicted race conditions. Instead of timeouts we're going to try a more verbose logging mechanism that points out when things are taking a long time.

* Get the attach tests to pass.

* Apply review comments from Todd

* More review comment fixes

* Put back the extended timeouts here now that I know why we have them...
This commit is contained in:
Ian Hickson
2018-12-20 17:10:40 -08:00
committed by GitHub
parent b3b764c9d3
commit 76f70810e4
59 changed files with 1832 additions and 1200 deletions

View File

@@ -9,16 +9,24 @@ import 'package:meta/meta.dart';
abstract class Command {
/// Abstract const constructor. This constructor enables subclasses to provide
/// const constructors so that they can be used in const expressions.
const Command({ Duration timeout })
: timeout = timeout ?? const Duration(seconds: 5);
const Command({ this.timeout });
/// Deserializes this command from the value generated by [serialize].
Command.deserialize(Map<String, String> json)
: timeout = Duration(milliseconds: int.parse(json['timeout']));
: timeout = _parseTimeout(json);
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.
///
/// Defaults to 5 seconds.
/// Defaults to no timeout, because it is common for operations to take oddly
/// long in test environments (e.g. because the test host is overloaded), and
/// having timeouts essentially means having race conditions.
final Duration timeout;
/// Identifies the type of the command object and of the handler.
@@ -28,7 +36,7 @@ abstract class Command {
@mustCallSuper
Map<String, String> serialize() => <String, String>{
'command': kind,
'timeout': '${timeout.inMilliseconds}',
'timeout': timeout == null ? null : '${timeout.inMilliseconds}',
};
}

View File

@@ -61,38 +61,13 @@ enum TimelineStream {
const List<TimelineStream> _defaultStreams = <TimelineStream>[TimelineStream.all];
/// Multiplies the timeout values used when establishing a connection to the
/// Flutter app under test and obtain an instance of [FlutterDriver].
///
/// This multiplier applies automatically when using the default implementation
/// of the [vmServiceConnectFunction].
///
/// See also:
///
/// * [FlutterDriver.timeoutMultiplier], which multiplies all command timeouts by this number.
double connectionTimeoutMultiplier = _kDefaultTimeoutMultiplier;
const double _kDefaultTimeoutMultiplier = 1.0;
/// Default timeout for short-running RPCs.
Duration _shortTimeout(double multiplier) => const Duration(seconds: 5) * multiplier;
/// Default timeout for awaiting an Isolate to become runnable.
Duration _isolateLoadRunnableTimeout(double multiplier) => const Duration(minutes: 1) * multiplier;
/// Time to delay before driving a Fuchsia module.
Duration _fuchsiaDriveDelay(double multiplier) => const Duration(milliseconds: 500) * multiplier;
/// Default timeout for long-running RPCs.
Duration _longTimeout(double multiplier) => _shortTimeout(multiplier) * 6;
/// Additional amount of time we give the command to finish or timeout remotely
/// before timing out locally.
Duration _rpcGraceTime(double multiplier) => _shortTimeout(multiplier) ~/ 2;
/// How long to wait before showing a message saying that
/// things seem to be taking a long time.
const Duration _kUnusuallyLongTimeout = Duration(seconds: 5);
/// The amount of time we wait prior to making the next attempt to connect to
/// the VM service.
Duration _pauseBetweenReconnectAttempts(double multiplier) => _shortTimeout(multiplier) ~/ 5;
const Duration _kPauseBetweenReconnectAttempts = Duration(seconds: 1);
// See https://github.com/dart-lang/sdk/blob/master/runtime/vm/timeline.cc#L32
String _timelineStreamsToString(List<TimelineStream> streams) {
@@ -116,6 +91,27 @@ String _timelineStreamsToString(List<TimelineStream> streams) {
final Logger _log = Logger('FlutterDriver');
Future<T> _warnIfSlow<T>({
@required Future<T> future,
@required Duration timeout,
@required String message,
}) {
assert(future != null);
assert(timeout != null);
assert(message != null);
return future..timeout(timeout, onTimeout: () { _log.warning(message); });
}
Duration _maxDuration(Duration a, Duration b) {
if (a == null)
return b;
if (b == null)
return a;
if (a > b)
return a;
return b;
}
/// A convenient accessor to frequently used finders.
///
/// Examples:
@@ -142,7 +138,6 @@ class FlutterDriver {
this._appIsolate, {
bool printCommunication = false,
bool logCommunicationToFile = true,
this.timeoutMultiplier = _kDefaultTimeoutMultiplier,
}) : _printCommunication = printCommunication,
_logCommunicationToFile = logCommunicationToFile,
_driverId = _nextDriverId++;
@@ -159,41 +154,38 @@ class FlutterDriver {
///
/// Resumes the application if it is currently paused (e.g. at a breakpoint).
///
/// [dartVmServiceUrl] is the URL to Dart observatory (a.k.a. VM service). If
/// `dartVmServiceUrl` is the URL to Dart observatory (a.k.a. VM service). If
/// not specified, the URL specified by the `VM_SERVICE_URL` environment
/// variable is used. One or the other must be specified.
///
/// [printCommunication] determines whether the command communication between
/// `printCommunication` determines whether the command communication between
/// the test and the app should be printed to stdout.
///
/// [logCommunicationToFile] determines whether the command communication
/// `logCommunicationToFile` determines whether the command communication
/// between the test and the app should be logged to `flutter_driver_commands.log`.
///
/// [FlutterDriver] multiplies all command timeouts by [timeoutMultiplier].
///
/// [isolateNumber] (optional) determines the specific isolate to connect to.
/// `isolateNumber` determines the specific isolate to connect to.
/// If this is left as `null`, will connect to the first isolate found
/// running on [dartVmServiceUrl].
/// running on `dartVmServiceUrl`.
///
/// [isolateReadyTimeout] determines how long after we connect to the VM
/// service we will wait for the first isolate to become runnable. Explicitly
/// specified non-null values are not affected by [timeoutMultiplier].
/// `fuchsiaModuleTarget` specifies the pattern for determining which mod to
/// control. When running on a Fuchsia device, either this or the environment
/// variable `FUCHSIA_MODULE_TARGET` must be set (the environment variable is
/// treated as a substring pattern). This field will be ignored if
/// `isolateNumber` is set, as this is already enough information to connect
/// to an isolate.
///
/// [fuchsiaModuleTarget] (optional) If running on a Fuchsia Device, either
/// this or the environment variable `FUCHSIA_MODULE_TARGET` must be set. This
/// field will be ignored if [isolateNumber] is set, as this is already
/// enough information to connect to an Isolate.
/// The return value is a future. This method never times out, though it may
/// fail (completing with an error). A timeout can be applied by the caller
/// using [Future.timeout] if necessary.
static Future<FlutterDriver> connect({
String dartVmServiceUrl,
bool printCommunication = false,
bool logCommunicationToFile = true,
double timeoutMultiplier = _kDefaultTimeoutMultiplier,
int isolateNumber,
Duration isolateReadyTimeout,
Pattern fuchsiaModuleTarget,
}) async {
isolateReadyTimeout ??= _isolateLoadRunnableTimeout(timeoutMultiplier);
// If running on a Fuchsia device, connect to the first Isolate whose name
// If running on a Fuchsia device, connect to the first isolate whose name
// matches FUCHSIA_MODULE_TARGET.
//
// If the user has already supplied an isolate number/URL to the Dart VM
@@ -201,16 +193,17 @@ class FlutterDriver {
if (Platform.isFuchsia && isolateNumber == null) {
fuchsiaModuleTarget ??= Platform.environment['FUCHSIA_MODULE_TARGET'];
if (fuchsiaModuleTarget == null) {
throw DriverError('No Fuchsia module target has been specified.\n'
'Please make sure to specify the FUCHSIA_MODULE_TARGET\n'
'environment variable.');
throw DriverError(
'No Fuchsia module target has been specified.\n'
'Please make sure to specify the FUCHSIA_MODULE_TARGET '
'environment variable.'
);
}
final fuchsia.FuchsiaRemoteConnection fuchsiaConnection =
await FuchsiaCompat.connect();
final List<fuchsia.IsolateRef> refs =
await fuchsiaConnection.getMainIsolatesByPattern(fuchsiaModuleTarget);
final fuchsia.IsolateRef ref = refs.first;
await Future<void>.delayed(_fuchsiaDriveDelay(timeoutMultiplier));
isolateNumber = ref.number;
dartVmServiceUrl = ref.dartVm.uri.toString();
await fuchsiaConnection.stop();
@@ -225,14 +218,14 @@ class FlutterDriver {
if (dartVmServiceUrl == null) {
throw DriverError(
'Could not determine URL to connect to application.\n'
'Either the VM_SERVICE_URL environment variable should be set, or an explicit\n'
'URL should be provided to the FlutterDriver.connect() method.');
'Could not determine URL to connect to application.\n'
'Either the VM_SERVICE_URL environment variable should be set, or an explicit '
'URL should be provided to the FlutterDriver.connect() method.'
);
}
// Connect to Dart VM services
_log.info('Connecting to Flutter application at $dartVmServiceUrl');
connectionTimeoutMultiplier = timeoutMultiplier;
final VMServiceClientConnection connection =
await vmServiceConnectFunction(dartVmServiceUrl);
final VMServiceClient client = connection.client;
@@ -243,12 +236,7 @@ class FlutterDriver {
(VMIsolateRef isolate) => isolate.number == isolateNumber);
_log.trace('Isolate found with number: ${isolateRef.number}');
VMIsolate isolate = await isolateRef
.loadRunnable()
.timeout(isolateReadyTimeout, onTimeout: () {
throw TimeoutException(
'Timeout while waiting for the isolate to become runnable');
});
VMIsolate isolate = await isolateRef.loadRunnable();
// TODO(yjbanov): vm_service_client does not support "None" pause event yet.
// It is currently reported as null, but we cannot rely on it because
@@ -263,7 +251,6 @@ class FlutterDriver {
isolate.pauseEvent is! VMPauseExceptionEvent &&
isolate.pauseEvent is! VMPauseInterruptedEvent &&
isolate.pauseEvent is! VMResumeEvent) {
await Future<void>.delayed(_shortTimeout(timeoutMultiplier) ~/ 10);
isolate = await isolateRef.loadRunnable();
}
@@ -271,7 +258,6 @@ class FlutterDriver {
client, connection.peer, isolate,
printCommunication: printCommunication,
logCommunicationToFile: logCommunicationToFile,
timeoutMultiplier: timeoutMultiplier,
);
// Attempts to resume the isolate, but does not crash if it fails because
@@ -324,23 +310,21 @@ class FlutterDriver {
// option, then the VM service extension is not registered yet. Wait for
// it to be registered.
await enableIsolateStreams();
final Future<dynamic> whenServiceExtensionReady = waitForServiceExtension();
final Future<String> whenServiceExtensionReady = waitForServiceExtension();
final Future<dynamic> whenResumed = resumeLeniently();
await whenResumed;
try {
_log.trace('Waiting for service extension');
// We will never receive the extension event if the user does not
// register it. If that happens time out.
await whenServiceExtensionReady.timeout(_longTimeout(timeoutMultiplier) * 2);
} on TimeoutException catch (_) {
throw DriverError(
'Timed out waiting for Flutter Driver extension to become available. '
'Ensure your test app (often: lib/main.dart) imports '
'"package:flutter_driver/driver_extension.dart" and '
'calls enableFlutterDriverExtension() as the first call in main().'
);
}
_log.trace('Waiting for service extension');
// We will never receive the extension event if the user does not
// register it. If that happens, show a message but continue waiting.
await _warnIfSlow<String>(
future: whenServiceExtensionReady,
timeout: _kUnusuallyLongTimeout,
message: 'Flutter Driver extension is taking a long time to become available. '
'Ensure your test app (often "lib/main.dart") imports '
'"package:flutter_driver/driver_extension.dart" and '
'calls enableFlutterDriverExtension() as the first call in main().'
);
} else if (isolate.pauseEvent is VMPauseExitEvent ||
isolate.pauseEvent is VMPauseBreakpointEvent ||
isolate.pauseEvent is VMPauseExceptionEvent ||
@@ -373,7 +357,7 @@ class FlutterDriver {
'registered.'
);
await enableIsolateStreams();
await waitForServiceExtension().timeout(_longTimeout(timeoutMultiplier) * 2);
await waitForServiceExtension();
return driver.checkHealth();
}
}
@@ -406,29 +390,17 @@ class FlutterDriver {
/// Whether to log communication between host and app to `flutter_driver_commands.log`.
final bool _logCommunicationToFile;
/// [FlutterDriver] multiplies all command timeouts by this number.
///
/// The right amount of time a driver command should be given to complete
/// depends on various environmental factors, such as the speed of the
/// device or the emulator, connection speed and latency, and others. Use
/// this multiplier to tailor the timeouts to your environment.
final double timeoutMultiplier;
Future<Map<String, dynamic>> _sendCommand(Command command) async {
Map<String, dynamic> response;
try {
final Map<String, String> serialized = command.serialize();
_logCommunication('>>> $serialized');
response = await _appIsolate
.invokeExtension(_flutterExtensionMethodName, serialized)
.timeout(command.timeout + _rpcGraceTime(timeoutMultiplier));
_logCommunication('<<< $response');
} on TimeoutException catch (error, stackTrace) {
throw DriverError(
'Failed to fulfill ${command.runtimeType}: Flutter application not responding',
error,
stackTrace,
response = await _warnIfSlow<Map<String, dynamic>>(
future: _appIsolate.invokeExtension(_flutterExtensionMethodName, serialized),
timeout: _maxDuration(command.timeout, _kUnusuallyLongTimeout),
message: '${command.kind} message is taking a long time to complete...',
);
_logCommunication('<<< $response');
} catch (error, stackTrace) {
throw DriverError(
'Failed to fulfill ${command.runtimeType} due to remote error',
@@ -453,31 +425,26 @@ class FlutterDriver {
/// Checks the status of the Flutter Driver extension.
Future<Health> checkHealth({Duration timeout}) async {
timeout ??= _shortTimeout(timeoutMultiplier);
return Health.fromJson(await _sendCommand(GetHealth(timeout: timeout)));
}
/// Returns a dump of the render tree.
Future<RenderTree> getRenderTree({Duration timeout}) async {
timeout ??= _shortTimeout(timeoutMultiplier);
return RenderTree.fromJson(await _sendCommand(GetRenderTree(timeout: timeout)));
}
/// Taps at the center of the widget located by [finder].
Future<void> tap(SerializableFinder finder, {Duration timeout}) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(Tap(finder, timeout: timeout));
}
/// Waits until [finder] locates the target.
Future<void> waitFor(SerializableFinder finder, {Duration timeout}) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(WaitFor(finder, timeout: timeout));
}
/// Waits until [finder] can no longer locate the target.
Future<void> waitForAbsent(SerializableFinder finder, {Duration timeout}) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(WaitForAbsent(finder, timeout: timeout));
}
@@ -486,7 +453,6 @@ class FlutterDriver {
/// Use this method when you need to wait for the moment when the application
/// becomes "stable", for example, prior to taking a [screenshot].
Future<void> waitUntilNoTransientCallbacks({Duration timeout}) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(WaitUntilNoTransientCallbacks(timeout: timeout));
}
@@ -504,7 +470,6 @@ class FlutterDriver {
/// The move events are generated at a given [frequency] in Hz (or events per
/// second). It defaults to 60Hz.
Future<void> scroll(SerializableFinder finder, double dx, double dy, Duration duration, { int frequency = 60, Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(Scroll(finder, dx, dy, duration, frequency, timeout: timeout));
}
@@ -516,7 +481,6 @@ class FlutterDriver {
/// then this method may fail because [finder] doesn't actually exist.
/// The [scrollUntilVisible] method can be used in this case.
Future<void> scrollIntoView(SerializableFinder finder, { double alignment = 0.0, Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(ScrollIntoView(finder, alignment: alignment, timeout: timeout));
}
@@ -541,12 +505,12 @@ class FlutterDriver {
/// for [dyScroll].
///
/// The [timeout] value should be long enough to accommodate as many scrolls
/// as needed to bring an item into view. The default is 10 seconds.
/// as needed to bring an item into view. The default is to not time out.
Future<void> scrollUntilVisible(SerializableFinder scrollable, SerializableFinder item, {
double alignment = 0.0,
double dxScroll = 0.0,
double dyScroll = 0.0,
Duration timeout = const Duration(seconds: 10),
Duration timeout,
}) async {
assert(scrollable != null);
assert(item != null);
@@ -554,7 +518,6 @@ class FlutterDriver {
assert(dxScroll != null);
assert(dyScroll != null);
assert(dxScroll != 0.0 || dyScroll != 0.0);
assert(timeout != null);
// Kick off an (unawaited) waitFor that will complete when the item we're
// looking for finally scrolls onscreen. We add an initial pause to give it
@@ -573,7 +536,6 @@ class FlutterDriver {
/// Returns the text in the `Text` widget located by [finder].
Future<String> getText(SerializableFinder finder, { Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
return GetTextResult.fromJson(await _sendCommand(GetText(finder, timeout: timeout))).text;
}
@@ -610,7 +572,6 @@ class FlutterDriver {
/// });
/// ```
Future<void> enterText(String text, { Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(EnterText(text, timeout: timeout));
}
@@ -629,7 +590,6 @@ class FlutterDriver {
/// channel will be mocked out.
Future<void> setTextEntryEmulation({ @required bool enabled, Duration timeout }) async {
assert(enabled != null);
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(SetTextEntryEmulation(enabled, timeout: timeout));
}
@@ -640,7 +600,6 @@ class FlutterDriver {
/// callback in [enableFlutterDriverExtension] that can successfully handle
/// these requests.
Future<String> requestData(String message, { Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
return RequestDataResult.fromJson(await _sendCommand(RequestData(message, timeout: timeout))).message;
}
@@ -649,7 +608,6 @@ class FlutterDriver {
/// Returns true when the call actually changed the state from on to off or
/// vice versa.
Future<bool> setSemantics(bool enabled, { Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
final SetSemanticsResult result = SetSemanticsResult.fromJson(await _sendCommand(SetSemantics(enabled, timeout: timeout)));
return result.changedState;
}
@@ -663,16 +621,15 @@ class FlutterDriver {
/// Semantics must be enabled to use this method, either using a platform
/// specific shell command or [setSemantics].
Future<int> getSemanticsId(SerializableFinder finder, { Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
final Map<String, dynamic> jsonResponse = await _sendCommand(GetSemanticsId(finder, timeout: timeout));
final GetSemanticsIdResult result = GetSemanticsIdResult.fromJson(jsonResponse);
return result.id;
}
/// Take a screenshot. The image will be returned as a PNG.
Future<List<int>> screenshot({ Duration timeout }) async {
timeout ??= _longTimeout(timeoutMultiplier);
/// Take a screenshot.
///
/// The image will be returned as a PNG.
Future<List<int>> screenshot() async {
// HACK: this artificial delay here is to deal with a race between the
// driver script and the GPU thread. The issue is that driver API
// synchronizes with the framework based on transient callbacks, which
@@ -680,7 +637,7 @@ class FlutterDriver {
// in ASCII art:
//
// -------------------------------------------------------------------
// Before this change:
// Without this timeout:
// -------------------------------------------------------------------
// UI : <-- build -->
// GPU : <-- rasterize -->
@@ -691,12 +648,13 @@ class FlutterDriver {
// action taken, such as a `tap()`, and the subsequent call to
// `screenshot()`. The gap is random because it is determined by the
// unpredictable network communication between the driver process and
// the application. If this gap is too short, the screenshot is taken
// before the GPU thread is done rasterizing the frame, so the
// screenshot of the previous frame is taken, which is wrong.
// the application. If this gap is too short, which it typically will
// be, the screenshot is taken before the GPU thread is done
// rasterizing the frame, so the screenshot of the previous frame is
// taken, which is wrong.
//
// -------------------------------------------------------------------
// After this change:
// With this timeout, if we're lucky:
// -------------------------------------------------------------------
// UI : <-- build -->
// GPU : <-- rasterize -->
@@ -706,16 +664,28 @@ class FlutterDriver {
// The two-second gap should be long enough for the GPU thread to
// finish rasterizing the frame, but not longer than necessary to keep
// driver tests as fast a possible.
//
// -------------------------------------------------------------------
// With this timeout, if we're not lucky:
// -------------------------------------------------------------------
// UI : <-- build -->
// GPU : <-- rasterize randomly slow today -->
// Gap : | 2 seconds or more |
// Driver: <-- screenshot -->
//
// In practice, sometimes the device gets really busy for a while and
// even two seconds isn't enough, which means that this is still racy
// and a source of flakes.
await Future<void>.delayed(const Duration(seconds: 2));
final Map<String, dynamic> result = await _peer.sendRequest('_flutter.screenshot').timeout(timeout);
final Map<String, dynamic> result = await _peer.sendRequest('_flutter.screenshot');
return base64.decode(result['screenshot']);
}
/// Returns the Flags set in the Dart VM as JSON.
///
/// See the complete documentation for `getFlagList` Dart VM service method
/// [here][getFlagList].
/// See the complete documentation for [the `getFlagList` Dart VM service
/// method][getFlagList].
///
/// Example return value:
///
@@ -731,23 +701,30 @@ class FlutterDriver {
/// ]
///
/// [getFlagList]: https://github.com/dart-lang/sdk/blob/master/runtime/vm/service/service.md#getflaglist
Future<List<Map<String, dynamic>>> getVmFlags({ Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
final Map<String, dynamic> result = await _peer.sendRequest('getFlagList').timeout(timeout);
Future<List<Map<String, dynamic>>> getVmFlags() async {
final Map<String, dynamic> result = await _peer.sendRequest('getFlagList');
return result['flags'];
}
/// Starts recording performance traces.
///
/// The `timeout` argument causes a warning to be displayed to the user if the
/// operation exceeds the specified timeout; it does not actually cancel the
/// operation.
Future<void> startTracing({
List<TimelineStream> streams = _defaultStreams,
Duration timeout,
Duration timeout = _kUnusuallyLongTimeout,
}) async {
timeout ??= _shortTimeout(timeoutMultiplier);
assert(streams != null && streams.isNotEmpty);
assert(timeout != null);
try {
await _peer.sendRequest(_setVMTimelineFlagsMethodName, <String, String>{
'recordedStreams': _timelineStreamsToString(streams)
}).timeout(timeout);
await _warnIfSlow<void>(
future: _peer.sendRequest(_setVMTimelineFlagsMethodName, <String, String>{
'recordedStreams': _timelineStreamsToString(streams)
}),
timeout: timeout,
message: 'VM is taking an unusually long time to respond to being told to start tracing...',
);
} catch (error, stackTrace) {
throw DriverError(
'Failed to start tracing due to remote error',
@@ -758,12 +735,20 @@ class FlutterDriver {
}
/// Stops recording performance traces and downloads the timeline.
Future<Timeline> stopTracingAndDownloadTimeline({ Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
///
/// The `timeout` argument causes a warning to be displayed to the user if the
/// operation exceeds the specified timeout; it does not actually cancel the
/// operation.
Future<Timeline> stopTracingAndDownloadTimeline({
Duration timeout = _kUnusuallyLongTimeout,
}) async {
assert(timeout != null);
try {
await _peer
.sendRequest(_setVMTimelineFlagsMethodName, <String, String>{'recordedStreams': '[]'})
.timeout(timeout);
await _warnIfSlow<void>(
future: _peer.sendRequest(_setVMTimelineFlagsMethodName, <String, String>{'recordedStreams': '[]'}),
timeout: timeout,
message: 'VM is taking an unusually long time to respond to being told to stop tracing...',
);
return Timeline.fromJson(await _peer.sendRequest(_getVMTimelineMethodName));
} catch (error, stackTrace) {
throw DriverError(
@@ -802,12 +787,20 @@ class FlutterDriver {
}
/// Clears all timeline events recorded up until now.
Future<void> clearTimeline({ Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
///
/// The `timeout` argument causes a warning to be displayed to the user if the
/// operation exceeds the specified timeout; it does not actually cancel the
/// operation.
Future<void> clearTimeline({
Duration timeout = _kUnusuallyLongTimeout
}) async {
assert(timeout != null);
try {
await _peer
.sendRequest(_clearVMTimelineMethodName, <String, String>{})
.timeout(timeout);
await _warnIfSlow<void>(
future: _peer.sendRequest(_clearVMTimelineMethodName, <String, String>{}),
timeout: timeout,
message: 'VM is taking an unusually long time to respond to being told to clear its timeline buffer...',
);
} catch (error, stackTrace) {
throw DriverError(
'Failed to clear event timeline due to remote error',
@@ -834,7 +827,6 @@ class FlutterDriver {
/// ensure that no action is performed while the app is undergoing a
/// transition to avoid flakiness.
Future<T> runUnsynchronized<T>(Future<T> action(), { Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(SetFrameSync(false, timeout: timeout));
T result;
try {
@@ -894,11 +886,6 @@ typedef VMServiceConnectFunction = Future<VMServiceClientConnection> Function(St
///
/// Overwrite this function if you require a custom method for connecting to
/// the VM service.
///
/// See also:
///
/// * [connectionTimeoutMultiplier], which controls the timeouts while
/// establishing a connection using the default connection function.
VMServiceConnectFunction vmServiceConnectFunction = _waitAndConnect;
/// Restores [vmServiceConnectFunction] to its default value.
@@ -908,44 +895,30 @@ void restoreVmServiceConnectFunction() {
/// Waits for a real Dart VM service to become available, then connects using
/// the [VMServiceClient].
///
/// Times out after 30 seconds.
Future<VMServiceClientConnection> _waitAndConnect(String url) async {
final Stopwatch timer = Stopwatch()..start();
Future<VMServiceClientConnection> attemptConnection() async {
Uri uri = Uri.parse(url);
if (uri.scheme == 'http')
uri = uri.replace(scheme: 'ws', path: '/ws');
Uri uri = Uri.parse(url);
if (uri.scheme == 'http')
uri = uri.replace(scheme: 'ws', path: '/ws');
int attempts = 0;
while (true) {
WebSocket ws1;
WebSocket ws2;
try {
ws1 = await WebSocket.connect(uri.toString()).timeout(_shortTimeout(connectionTimeoutMultiplier));
ws2 = await WebSocket.connect(uri.toString()).timeout(_shortTimeout(connectionTimeoutMultiplier));
ws1 = await WebSocket.connect(uri.toString());
ws2 = await WebSocket.connect(uri.toString());
return VMServiceClientConnection(
VMServiceClient(IOWebSocketChannel(ws1).cast()),
rpc.Peer(IOWebSocketChannel(ws2).cast())..listen()
rpc.Peer(IOWebSocketChannel(ws2).cast())..listen(),
);
} catch (e) {
await ws1?.close();
await ws2?.close();
if (timer.elapsed < _longTimeout(connectionTimeoutMultiplier) * 2) {
_log.info('Waiting for application to start');
await Future<void>.delayed(_pauseBetweenReconnectAttempts(connectionTimeoutMultiplier));
return attemptConnection();
} else {
_log.critical(
'Application has not started in 30 seconds. '
'Giving up.'
);
rethrow;
}
if (attempts > 5)
_log.warning('It is taking an unusually long time to connect to the VM...');
attempts += 1;
await Future<void>.delayed(_kPauseBetweenReconnectAttempts);
}
}
return attemptConnection();
}
/// Provides convenient accessors to frequently used finders.

View File

@@ -177,7 +177,10 @@ class FlutterDriverExtension {
if (commandHandler == null || commandDeserializer == null)
throw 'Extension $_extensionMethod does not support command $commandKind';
final Command command = commandDeserializer(params);
final Result response = await commandHandler(command).timeout(command.timeout);
Future<Result> responseFuture = commandHandler(command);
if (command.timeout != null)
responseFuture = responseFuture.timeout(command.timeout);
final Result response = await responseFuture;
return _makeResponse(response?.toJson());
} on TimeoutException catch (error, stackTrace) {
final String msg = 'Timeout while executing $commandKind: $error\n$stackTrace';

View File

@@ -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:mockito/mockito.dart';
import 'package:vm_service_client/vm_service_client.dart';
import 'package:quiver/testing/async.dart';
import 'common.dart';
/// Magical timeout value that's different from the default.
const Duration _kTestTimeout = Duration(milliseconds: 1234);
const String _kSerializedTestTimeout = '1234';
const Duration _kDefaultCommandTimeout = Duration(seconds: 5);
void main() {
group('FlutterDriver.connect', () {
@@ -358,17 +358,19 @@ void main() {
group('sendCommand error conditions', () {
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) {
// completer never competed to trigger timeout
// completer never completed to trigger timeout
return Completer<Map<String, dynamic>>().future;
});
try {
await driver.waitFor(find.byTooltip('foo'), timeout: const Duration(milliseconds: 100));
fail('expected an exception');
} catch (error) {
expect(error is DriverError, isTrue);
expect(error.message, 'Failed to fulfill WaitFor: Flutter application not responding');
}
FakeAsync().run((FakeAsync time) {
driver.waitFor(find.byTooltip('foo'));
expect(log, <String>[]);
time.elapse(const Duration(hours: 1));
});
expect(log, <String>['[warning] FlutterDriver: waitFor message is taking a long time to complete...']);
await logSub.cancel();
});
test('remote error', () async {
@@ -389,7 +391,6 @@ void main() {
});
group('FlutterDriver with custom timeout', () {
const double kTestMultiplier = 3.0;
MockVMServiceClient mockClient;
MockPeer mockPeer;
MockIsolate mockIsolate;
@@ -399,21 +400,21 @@ void main() {
mockClient = MockVMServiceClient();
mockPeer = MockPeer();
mockIsolate = MockIsolate();
driver = FlutterDriver.connectedTo(mockClient, mockPeer, mockIsolate, timeoutMultiplier: kTestMultiplier);
driver = FlutterDriver.connectedTo(mockClient, mockPeer, mockIsolate);
});
test('multiplies the timeout', () async {
test('GetHealth has no default timeout', () async {
when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) {
expect(i.positionalArguments[1], <String, String>{
'command': 'get_health',
'timeout': '${(_kDefaultCommandTimeout * kTestMultiplier).inMilliseconds}',
'timeout': null,
});
return makeMockResponse(<String, dynamic>{'status': 'ok'});
});
await driver.checkHealth();
});
test('does not multiply explicit timeouts', () async {
test('does not interfere with explicit timeouts', () async {
when(mockIsolate.invokeExtension(any, any)).thenAnswer((Invocation i) {
expect(i.positionalArguments[1], <String, String>{
'command': 'get_health',