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

This reverts commit 76f70810e4.
This commit is contained in:
Ian Hickson
2018-12-20 18:46:36 -08:00
committed by GitHub
parent 76f70810e4
commit 8426910a19
59 changed files with 1199 additions and 1831 deletions

View File

@@ -9,24 +9,16 @@ 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({ this.timeout });
const Command({ Duration timeout })
: timeout = timeout ?? const Duration(seconds: 5);
/// Deserializes this command from the value generated by [serialize].
Command.deserialize(Map<String, String> json)
: 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));
}
: timeout = Duration(milliseconds: int.parse(json['timeout']));
/// 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
/// long in test environments (e.g. because the test host is overloaded), and
/// having timeouts essentially means having race conditions.
/// Defaults to 5 seconds.
final Duration timeout;
/// Identifies the type of the command object and of the handler.
@@ -36,7 +28,7 @@ abstract class Command {
@mustCallSuper
Map<String, String> serialize() => <String, String>{
'command': kind,
'timeout': timeout == null ? null : '${timeout.inMilliseconds}',
'timeout': '${timeout.inMilliseconds}',
};
}

View File

@@ -61,13 +61,38 @@ enum TimelineStream {
const List<TimelineStream> _defaultStreams = <TimelineStream>[TimelineStream.all];
/// How long to wait before showing a message saying that
/// things seem to be taking a long time.
const Duration _kUnusuallyLongTimeout = Duration(seconds: 5);
/// 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;
/// The amount of time we wait prior to making the next attempt to connect to
/// the VM service.
const Duration _kPauseBetweenReconnectAttempts = Duration(seconds: 1);
Duration _pauseBetweenReconnectAttempts(double multiplier) => _shortTimeout(multiplier) ~/ 5;
// See https://github.com/dart-lang/sdk/blob/master/runtime/vm/timeline.cc#L32
String _timelineStreamsToString(List<TimelineStream> streams) {
@@ -91,27 +116,6 @@ 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:
@@ -138,6 +142,7 @@ class FlutterDriver {
this._appIsolate, {
bool printCommunication = false,
bool logCommunicationToFile = true,
this.timeoutMultiplier = _kDefaultTimeoutMultiplier,
}) : _printCommunication = printCommunication,
_logCommunicationToFile = logCommunicationToFile,
_driverId = _nextDriverId++;
@@ -154,38 +159,41 @@ 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`.
///
/// `isolateNumber` determines the specific isolate to connect to.
/// [FlutterDriver] multiplies all command timeouts by [timeoutMultiplier].
///
/// [isolateNumber] (optional) 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].
///
/// `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.
/// [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].
///
/// 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.
/// [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.
static Future<FlutterDriver> connect({
String dartVmServiceUrl,
bool printCommunication = false,
bool logCommunicationToFile = true,
double timeoutMultiplier = _kDefaultTimeoutMultiplier,
int isolateNumber,
Duration isolateReadyTimeout,
Pattern fuchsiaModuleTarget,
}) async {
// If running on a Fuchsia device, connect to the first isolate whose name
isolateReadyTimeout ??= _isolateLoadRunnableTimeout(timeoutMultiplier);
// 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
@@ -193,17 +201,16 @@ 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 '
'environment variable.'
);
throw DriverError('No Fuchsia module target has been specified.\n'
'Please make sure to specify the FUCHSIA_MODULE_TARGET\n'
'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();
@@ -218,14 +225,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 '
'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\n'
'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;
@@ -236,7 +243,12 @@ class FlutterDriver {
(VMIsolateRef isolate) => isolate.number == isolateNumber);
_log.trace('Isolate found with number: ${isolateRef.number}');
VMIsolate isolate = await isolateRef.loadRunnable();
VMIsolate isolate = await isolateRef
.loadRunnable()
.timeout(isolateReadyTimeout, onTimeout: () {
throw TimeoutException(
'Timeout while waiting for the isolate to become runnable');
});
// 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
@@ -251,6 +263,7 @@ 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();
}
@@ -258,6 +271,7 @@ 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
@@ -310,21 +324,23 @@ class FlutterDriver {
// option, then the VM service extension is not registered yet. Wait for
// it to be registered.
await enableIsolateStreams();
final Future<String> whenServiceExtensionReady = waitForServiceExtension();
final Future<dynamic> whenServiceExtensionReady = waitForServiceExtension();
final Future<dynamic> whenResumed = resumeLeniently();
await whenResumed;
_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().'
);
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().'
);
}
} else if (isolate.pauseEvent is VMPauseExitEvent ||
isolate.pauseEvent is VMPauseBreakpointEvent ||
isolate.pauseEvent is VMPauseExceptionEvent ||
@@ -357,7 +373,7 @@ class FlutterDriver {
'registered.'
);
await enableIsolateStreams();
await waitForServiceExtension();
await waitForServiceExtension().timeout(_longTimeout(timeoutMultiplier) * 2);
return driver.checkHealth();
}
}
@@ -390,17 +406,29 @@ 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 _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...',
);
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,
);
} catch (error, stackTrace) {
throw DriverError(
'Failed to fulfill ${command.runtimeType} due to remote error',
@@ -425,26 +453,31 @@ 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));
}
@@ -453,6 +486,7 @@ 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));
}
@@ -470,6 +504,7 @@ 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));
}
@@ -481,6 +516,7 @@ 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));
}
@@ -505,12 +541,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 to not time out.
/// as needed to bring an item into view. The default is 10 seconds.
Future<void> scrollUntilVisible(SerializableFinder scrollable, SerializableFinder item, {
double alignment = 0.0,
double dxScroll = 0.0,
double dyScroll = 0.0,
Duration timeout,
Duration timeout = const Duration(seconds: 10),
}) async {
assert(scrollable != null);
assert(item != null);
@@ -518,6 +554,7 @@ 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
@@ -536,6 +573,7 @@ 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;
}
@@ -572,6 +610,7 @@ class FlutterDriver {
/// });
/// ```
Future<void> enterText(String text, { Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
await _sendCommand(EnterText(text, timeout: timeout));
}
@@ -590,6 +629,7 @@ 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));
}
@@ -600,6 +640,7 @@ 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;
}
@@ -608,6 +649,7 @@ 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;
}
@@ -621,15 +663,16 @@ 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() async {
/// Take a screenshot. The image will be returned as a PNG.
Future<List<int>> screenshot({ Duration timeout }) async {
timeout ??= _longTimeout(timeoutMultiplier);
// 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
@@ -637,7 +680,7 @@ class FlutterDriver {
// in ASCII art:
//
// -------------------------------------------------------------------
// Without this timeout:
// Before this change:
// -------------------------------------------------------------------
// UI : <-- build -->
// GPU : <-- rasterize -->
@@ -648,13 +691,12 @@ 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, 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.
// 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.
//
// -------------------------------------------------------------------
// With this timeout, if we're lucky:
// After this change:
// -------------------------------------------------------------------
// UI : <-- build -->
// GPU : <-- rasterize -->
@@ -664,28 +706,16 @@ 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');
final Map<String, dynamic> result = await _peer.sendRequest('_flutter.screenshot').timeout(timeout);
return base64.decode(result['screenshot']);
}
/// Returns the Flags set in the Dart VM as JSON.
///
/// See the complete documentation for [the `getFlagList` Dart VM service
/// method][getFlagList].
/// See the complete documentation for `getFlagList` Dart VM service method
/// [here][getFlagList].
///
/// Example return value:
///
@@ -701,30 +731,23 @@ class FlutterDriver {
/// ]
///
/// [getFlagList]: https://github.com/dart-lang/sdk/blob/master/runtime/vm/service/service.md#getflaglist
Future<List<Map<String, dynamic>>> getVmFlags() async {
final Map<String, dynamic> result = await _peer.sendRequest('getFlagList');
Future<List<Map<String, dynamic>>> getVmFlags({ Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
final Map<String, dynamic> result = await _peer.sendRequest('getFlagList').timeout(timeout);
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 = _kUnusuallyLongTimeout,
Duration timeout,
}) async {
timeout ??= _shortTimeout(timeoutMultiplier);
assert(streams != null && streams.isNotEmpty);
assert(timeout != null);
try {
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...',
);
await _peer.sendRequest(_setVMTimelineFlagsMethodName, <String, String>{
'recordedStreams': _timelineStreamsToString(streams)
}).timeout(timeout);
} catch (error, stackTrace) {
throw DriverError(
'Failed to start tracing due to remote error',
@@ -735,20 +758,12 @@ class FlutterDriver {
}
/// Stops recording performance traces and downloads the timeline.
///
/// 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);
Future<Timeline> stopTracingAndDownloadTimeline({ Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
try {
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...',
);
await _peer
.sendRequest(_setVMTimelineFlagsMethodName, <String, String>{'recordedStreams': '[]'})
.timeout(timeout);
return Timeline.fromJson(await _peer.sendRequest(_getVMTimelineMethodName));
} catch (error, stackTrace) {
throw DriverError(
@@ -787,20 +802,12 @@ class FlutterDriver {
}
/// Clears all timeline events recorded up until now.
///
/// 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);
Future<void> clearTimeline({ Duration timeout }) async {
timeout ??= _shortTimeout(timeoutMultiplier);
try {
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...',
);
await _peer
.sendRequest(_clearVMTimelineMethodName, <String, String>{})
.timeout(timeout);
} catch (error, stackTrace) {
throw DriverError(
'Failed to clear event timeline due to remote error',
@@ -827,6 +834,7 @@ 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 {
@@ -886,6 +894,11 @@ 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.
@@ -895,30 +908,44 @@ 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 {
Uri uri = Uri.parse(url);
if (uri.scheme == 'http')
uri = uri.replace(scheme: 'ws', path: '/ws');
int attempts = 0;
while (true) {
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');
WebSocket ws1;
WebSocket ws2;
try {
ws1 = await WebSocket.connect(uri.toString());
ws2 = await WebSocket.connect(uri.toString());
ws1 = await WebSocket.connect(uri.toString()).timeout(_shortTimeout(connectionTimeoutMultiplier));
ws2 = await WebSocket.connect(uri.toString()).timeout(_shortTimeout(connectionTimeoutMultiplier));
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 (attempts > 5)
_log.warning('It is taking an unusually long time to connect to the VM...');
attempts += 1;
await Future<void>.delayed(_kPauseBetweenReconnectAttempts);
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;
}
}
}
return attemptConnection();
}
/// Provides convenient accessors to frequently used finders.

View File

@@ -177,10 +177,7 @@ class FlutterDriverExtension {
if (commandHandler == null || commandDeserializer == null)
throw 'Extension $_extensionMethod does not support command $commandKind';
final Command command = commandDeserializer(params);
Future<Result> responseFuture = commandHandler(command);
if (command.timeout != null)
responseFuture = responseFuture.timeout(command.timeout);
final Result response = await responseFuture;
final Result response = await commandHandler(command).timeout(command.timeout);
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,19 +358,17 @@ 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 completed to trigger timeout
// completer never competed to trigger timeout
return Completer<Map<String, dynamic>>().future;
});
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();
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');
}
});
test('remote error', () async {
@@ -391,6 +389,7 @@ void main() {
});
group('FlutterDriver with custom timeout', () {
const double kTestMultiplier = 3.0;
MockVMServiceClient mockClient;
MockPeer mockPeer;
MockIsolate mockIsolate;
@@ -400,21 +399,21 @@ void main() {
mockClient = MockVMServiceClient();
mockPeer = MockPeer();
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) {
expect(i.positionalArguments[1], <String, String>{
'command': 'get_health',
'timeout': null,
'timeout': '${(_kDefaultCommandTimeout * kTestMultiplier).inMilliseconds}',
});
return makeMockResponse(<String, dynamic>{'status': 'ok'});
});
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) {
expect(i.positionalArguments[1], <String, String>{
'command': 'get_health',