Auto-format Framework (#160545)
This auto-formats all *.dart files in the repository outside of the `engine` subdirectory and enforces that these files stay formatted with a presubmit check. **Reviewers:** Please carefully review all the commits except for the one titled "formatted". The "formatted" commit was auto-generated by running `dev/tools/format.sh -a -f`. The other commits were hand-crafted to prepare the repo for the formatting change. I recommend reviewing the commits one-by-one via the "Commits" tab and avoiding Github's "Files changed" tab as it will likely slow down your browser because of the size of this PR. --------- Co-authored-by: Kate Lovett <katelovett@google.com> Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
parent
8e0993eda8
commit
5491c8c146
@@ -24,14 +24,14 @@ mixin DeserializeFinderFactory {
|
||||
/// Deserializes the finder from JSON generated by [SerializableFinder.serialize].
|
||||
SerializableFinder deserializeFinder(Map<String, String> json) {
|
||||
return switch (json['finderType']) {
|
||||
'ByType' => ByType.deserialize(json),
|
||||
'ByValueKey' => ByValueKey.deserialize(json),
|
||||
'ByType' => ByType.deserialize(json),
|
||||
'ByValueKey' => ByValueKey.deserialize(json),
|
||||
'ByTooltipMessage' => ByTooltipMessage.deserialize(json),
|
||||
'BySemanticsLabel' => BySemanticsLabel.deserialize(json),
|
||||
'ByText' => ByText.deserialize(json),
|
||||
'PageBack' => const PageBack(),
|
||||
'Descendant' => Descendant.deserialize(json, this),
|
||||
'Ancestor' => Ancestor.deserialize(json, this),
|
||||
'ByText' => ByText.deserialize(json),
|
||||
'PageBack' => const PageBack(),
|
||||
'Descendant' => Descendant.deserialize(json, this),
|
||||
'Ancestor' => Ancestor.deserialize(json, this),
|
||||
_ => throw DriverError('Unsupported search specification type ${json['finderType']}'),
|
||||
};
|
||||
}
|
||||
@@ -42,30 +42,30 @@ mixin DeserializeCommandFactory {
|
||||
/// Deserializes the finder from JSON generated by [Command.serialize] or [CommandWithTarget.serialize].
|
||||
Command deserializeCommand(Map<String, String> params, DeserializeFinderFactory finderFactory) {
|
||||
return switch (params['command']) {
|
||||
'get_health' => GetHealth.deserialize(params),
|
||||
'get_layer_tree' => GetLayerTree.deserialize(params),
|
||||
'get_render_tree' => GetRenderTree.deserialize(params),
|
||||
'enter_text' => EnterText.deserialize(params),
|
||||
'send_text_input_action' => SendTextInputAction.deserialize(params),
|
||||
'get_text' => GetText.deserialize(params, finderFactory),
|
||||
'request_data' => RequestData.deserialize(params),
|
||||
'scroll' => Scroll.deserialize(params, finderFactory),
|
||||
'scrollIntoView' => ScrollIntoView.deserialize(params, finderFactory),
|
||||
'set_frame_sync' => SetFrameSync.deserialize(params),
|
||||
'set_semantics' => SetSemantics.deserialize(params),
|
||||
'set_text_entry_emulation' => SetTextEntryEmulation.deserialize(params),
|
||||
'tap' => Tap.deserialize(params, finderFactory),
|
||||
'waitFor' => WaitFor.deserialize(params, finderFactory),
|
||||
'waitForAbsent' => WaitForAbsent.deserialize(params, finderFactory),
|
||||
'waitForTappable' => WaitForTappable.deserialize(params, finderFactory),
|
||||
'waitForCondition' => WaitForCondition.deserialize(params),
|
||||
'get_health' => GetHealth.deserialize(params),
|
||||
'get_layer_tree' => GetLayerTree.deserialize(params),
|
||||
'get_render_tree' => GetRenderTree.deserialize(params),
|
||||
'enter_text' => EnterText.deserialize(params),
|
||||
'send_text_input_action' => SendTextInputAction.deserialize(params),
|
||||
'get_text' => GetText.deserialize(params, finderFactory),
|
||||
'request_data' => RequestData.deserialize(params),
|
||||
'scroll' => Scroll.deserialize(params, finderFactory),
|
||||
'scrollIntoView' => ScrollIntoView.deserialize(params, finderFactory),
|
||||
'set_frame_sync' => SetFrameSync.deserialize(params),
|
||||
'set_semantics' => SetSemantics.deserialize(params),
|
||||
'set_text_entry_emulation' => SetTextEntryEmulation.deserialize(params),
|
||||
'tap' => Tap.deserialize(params, finderFactory),
|
||||
'waitFor' => WaitFor.deserialize(params, finderFactory),
|
||||
'waitForAbsent' => WaitForAbsent.deserialize(params, finderFactory),
|
||||
'waitForTappable' => WaitForTappable.deserialize(params, finderFactory),
|
||||
'waitForCondition' => WaitForCondition.deserialize(params),
|
||||
'waitUntilNoTransientCallbacks' => WaitForCondition.deserialize(params),
|
||||
'waitUntilNoPendingFrame' => WaitForCondition.deserialize(params),
|
||||
'waitUntilNoPendingFrame' => WaitForCondition.deserialize(params),
|
||||
'waitUntilFirstFrameRasterized' => WaitForCondition.deserialize(params),
|
||||
'get_semantics_id' => GetSemanticsId.deserialize(params, finderFactory),
|
||||
'get_offset' => GetOffset.deserialize(params, finderFactory),
|
||||
'get_diagnostics_tree' => GetDiagnosticsTree.deserialize(params, finderFactory),
|
||||
'screenshot' => ScreenshotCommand.deserialize(params),
|
||||
'get_semantics_id' => GetSemanticsId.deserialize(params, finderFactory),
|
||||
'get_offset' => GetOffset.deserialize(params, finderFactory),
|
||||
'get_diagnostics_tree' => GetDiagnosticsTree.deserialize(params, finderFactory),
|
||||
'screenshot' => ScreenshotCommand.deserialize(params),
|
||||
final String? kind => throw DriverError('Unsupported command kind $kind'),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -18,7 +18,9 @@ enum DiagnosticsType {
|
||||
widget,
|
||||
}
|
||||
|
||||
EnumIndex<DiagnosticsType> _diagnosticsTypeIndex = EnumIndex<DiagnosticsType>(DiagnosticsType.values);
|
||||
EnumIndex<DiagnosticsType> _diagnosticsTypeIndex = EnumIndex<DiagnosticsType>(
|
||||
DiagnosticsType.values,
|
||||
);
|
||||
|
||||
/// A Flutter Driver command to retrieve the JSON-serialized [DiagnosticsNode]
|
||||
/// tree of the object identified by [finder].
|
||||
@@ -27,7 +29,9 @@ EnumIndex<DiagnosticsType> _diagnosticsTypeIndex = EnumIndex<DiagnosticsType>(Di
|
||||
/// [diagnosticsType].
|
||||
class GetDiagnosticsTree extends CommandWithTarget {
|
||||
/// Creates a [GetDiagnosticsTree] Flutter Driver command.
|
||||
GetDiagnosticsTree(super.finder, this.diagnosticsType, {
|
||||
GetDiagnosticsTree(
|
||||
super.finder,
|
||||
this.diagnosticsType, {
|
||||
this.subtreeDepth = 0,
|
||||
this.includeProperties = true,
|
||||
super.timeout,
|
||||
@@ -35,10 +39,10 @@ class GetDiagnosticsTree extends CommandWithTarget {
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
GetDiagnosticsTree.deserialize(super.json, super.finderFactory)
|
||||
: subtreeDepth = int.parse(json['subtreeDepth']!),
|
||||
includeProperties = json['includeProperties'] == 'true',
|
||||
diagnosticsType = _diagnosticsTypeIndex.lookupBySimpleName(json['diagnosticsType']!),
|
||||
super.deserialize();
|
||||
: subtreeDepth = int.parse(json['subtreeDepth']!),
|
||||
includeProperties = json['includeProperties'] == 'true',
|
||||
diagnosticsType = _diagnosticsTypeIndex.lookupBySimpleName(json['diagnosticsType']!),
|
||||
super.deserialize();
|
||||
|
||||
/// How many levels of children to include in the JSON result.
|
||||
///
|
||||
@@ -53,11 +57,12 @@ class GetDiagnosticsTree extends CommandWithTarget {
|
||||
final DiagnosticsType diagnosticsType;
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'subtreeDepth': subtreeDepth.toString(),
|
||||
'includeProperties': includeProperties.toString(),
|
||||
'diagnosticsType': _diagnosticsTypeIndex.toSimpleName(diagnosticsType),
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()..addAll(<String, String>{
|
||||
'subtreeDepth': subtreeDepth.toString(),
|
||||
'includeProperties': includeProperties.toString(),
|
||||
'diagnosticsType': _diagnosticsTypeIndex.toSimpleName(diagnosticsType),
|
||||
});
|
||||
|
||||
@override
|
||||
String get kind => 'get_diagnostics_tree';
|
||||
|
||||
@@ -18,14 +18,8 @@
|
||||
class EnumIndex<E> {
|
||||
/// Creates an index of [enumValues].
|
||||
EnumIndex(List<E> enumValues)
|
||||
: _nameToValue = Map<String, E>.fromIterable(
|
||||
enumValues,
|
||||
key: _getSimpleName,
|
||||
),
|
||||
_valueToName = Map<E, String>.fromIterable(
|
||||
enumValues,
|
||||
value: _getSimpleName,
|
||||
);
|
||||
: _nameToValue = Map<String, E>.fromIterable(enumValues, key: _getSimpleName),
|
||||
_valueToName = Map<E, String>.fromIterable(enumValues, value: _getSimpleName);
|
||||
|
||||
final Map<String, E> _nameToValue;
|
||||
final Map<E, String> _valueToName;
|
||||
|
||||
@@ -19,7 +19,9 @@ import 'message.dart';
|
||||
const List<Type> _supportedKeyValueTypes = <Type>[String, int];
|
||||
|
||||
DriverError _createInvalidKeyValueTypeError(String invalidType) {
|
||||
return DriverError('Unsupported key value type $invalidType. Flutter Driver only supports ${_supportedKeyValueTypes.join(", ")}');
|
||||
return DriverError(
|
||||
'Unsupported key value type $invalidType. Flutter Driver only supports ${_supportedKeyValueTypes.join(", ")}',
|
||||
);
|
||||
}
|
||||
|
||||
/// A Flutter Driver command aimed at an object to be located by [finder].
|
||||
@@ -48,8 +50,7 @@ abstract class CommandWithTarget extends Command {
|
||||
/// 'foo': this.foo,
|
||||
/// });
|
||||
@override
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()..addAll(finder.serialize());
|
||||
Map<String, String> serialize() => super.serialize()..addAll(finder.serialize());
|
||||
}
|
||||
|
||||
/// A Flutter Driver command that waits until [finder] can locate the target.
|
||||
@@ -91,9 +92,7 @@ class WaitForTappable extends CommandWithTarget {
|
||||
WaitForTappable(super.finder, {super.timeout});
|
||||
|
||||
/// Deserialized this command from the value generated by [serialize].
|
||||
WaitForTappable.deserialize(
|
||||
super.json, super.finderFactory)
|
||||
: super.deserialize();
|
||||
WaitForTappable.deserialize(super.json, super.finderFactory) : super.deserialize();
|
||||
|
||||
@override
|
||||
String get kind => 'waitForTappable';
|
||||
@@ -102,7 +101,6 @@ class WaitForTappable extends CommandWithTarget {
|
||||
/// Base class for Flutter Driver finders, objects that describe how the driver
|
||||
/// should search for elements.
|
||||
abstract class SerializableFinder {
|
||||
|
||||
/// A const constructor to allow subclasses to be const.
|
||||
const SerializableFinder();
|
||||
|
||||
@@ -114,9 +112,7 @@ abstract class SerializableFinder {
|
||||
/// Methods that override [serialize] are expected to call `super.serialize`
|
||||
/// and add more fields to the returned [Map].
|
||||
@mustCallSuper
|
||||
Map<String, String> serialize() => <String, String>{
|
||||
'finderType': finderType,
|
||||
};
|
||||
Map<String, String> serialize() => <String, String>{'finderType': finderType};
|
||||
}
|
||||
|
||||
/// A Flutter Driver finder that finds widgets by tooltip text.
|
||||
@@ -131,9 +127,7 @@ class ByTooltipMessage extends SerializableFinder {
|
||||
String get finderType => 'ByTooltipMessage';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'text': text,
|
||||
});
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{'text': text});
|
||||
|
||||
/// Deserializes the finder from JSON generated by [serialize].
|
||||
static ByTooltipMessage deserialize(Map<String, String> json) {
|
||||
@@ -161,14 +155,10 @@ class BySemanticsLabel extends SerializableFinder {
|
||||
Map<String, String> serialize() {
|
||||
if (label is RegExp) {
|
||||
final RegExp regExp = label as RegExp;
|
||||
return super.serialize()..addAll(<String, String>{
|
||||
'label': regExp.pattern,
|
||||
'isRegExp': 'true',
|
||||
});
|
||||
return super.serialize()
|
||||
..addAll(<String, String>{'label': regExp.pattern, 'isRegExp': 'true'});
|
||||
} else {
|
||||
return super.serialize()..addAll(<String, String>{
|
||||
'label': label as String,
|
||||
});
|
||||
return super.serialize()..addAll(<String, String>{'label': label as String});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -193,9 +183,7 @@ class ByText extends SerializableFinder {
|
||||
String get finderType => 'ByText';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'text': text,
|
||||
});
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{'text': text});
|
||||
|
||||
/// Deserializes the finder from JSON generated by [serialize].
|
||||
static ByText deserialize(Map<String, String> json) {
|
||||
@@ -207,8 +195,8 @@ class ByText extends SerializableFinder {
|
||||
class ByValueKey extends SerializableFinder {
|
||||
/// Creates a finder given the key value.
|
||||
ByValueKey(this.keyValue)
|
||||
: keyValueString = '$keyValue',
|
||||
keyValueType = '${keyValue.runtimeType}' {
|
||||
: keyValueString = '$keyValue',
|
||||
keyValueType = '${keyValue.runtimeType}' {
|
||||
if (!_supportedKeyValueTypes.contains(keyValue.runtimeType)) {
|
||||
throw _createInvalidKeyValueTypeError('$keyValue.runtimeType');
|
||||
}
|
||||
@@ -229,16 +217,15 @@ class ByValueKey extends SerializableFinder {
|
||||
String get finderType => 'ByValueKey';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'keyValueString': keyValueString,
|
||||
'keyValueType': keyValueType,
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()
|
||||
..addAll(<String, String>{'keyValueString': keyValueString, 'keyValueType': keyValueType});
|
||||
|
||||
/// Deserializes the finder from JSON generated by [serialize].
|
||||
static ByValueKey deserialize(Map<String, String> json) {
|
||||
final String keyValueString = json['keyValueString']!;
|
||||
return switch (json['keyValueType']!) {
|
||||
'int' => ByValueKey(int.parse(keyValueString)),
|
||||
'int' => ByValueKey(int.parse(keyValueString)),
|
||||
'String' => ByValueKey(keyValueString),
|
||||
final String keyValueType => throw _createInvalidKeyValueTypeError(keyValueType),
|
||||
};
|
||||
@@ -257,9 +244,7 @@ class ByType extends SerializableFinder {
|
||||
String get finderType => 'ByType';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'type': type,
|
||||
});
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{'type': type});
|
||||
|
||||
/// Deserializes the finder from JSON generated by [serialize].
|
||||
static ByType deserialize(Map<String, String> json) {
|
||||
@@ -312,21 +297,22 @@ class Descendant extends SerializableFinder {
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() {
|
||||
return super.serialize()
|
||||
..addAll(<String, String>{
|
||||
'of': jsonEncode(of.serialize()),
|
||||
'matching': jsonEncode(matching.serialize()),
|
||||
'matchRoot': matchRoot ? 'true' : 'false',
|
||||
'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
|
||||
});
|
||||
return super.serialize()..addAll(<String, String>{
|
||||
'of': jsonEncode(of.serialize()),
|
||||
'matching': jsonEncode(matching.serialize()),
|
||||
'matchRoot': matchRoot ? 'true' : 'false',
|
||||
'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
|
||||
});
|
||||
}
|
||||
|
||||
/// Deserializes the finder from JSON generated by [serialize].
|
||||
static Descendant deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory) {
|
||||
final Map<String, String> jsonOfMatcher =
|
||||
Map<String, String>.from(jsonDecode(json['of']!) as Map<String, dynamic>);
|
||||
final Map<String, String> jsonMatchingMatcher =
|
||||
Map<String, String>.from(jsonDecode(json['matching']!) as Map<String, dynamic>);
|
||||
final Map<String, String> jsonOfMatcher = Map<String, String>.from(
|
||||
jsonDecode(json['of']!) as Map<String, dynamic>,
|
||||
);
|
||||
final Map<String, String> jsonMatchingMatcher = Map<String, String>.from(
|
||||
jsonDecode(json['matching']!) as Map<String, dynamic>,
|
||||
);
|
||||
return Descendant(
|
||||
of: finderFactory.deserializeFinder(jsonOfMatcher),
|
||||
matching: finderFactory.deserializeFinder(jsonMatchingMatcher),
|
||||
@@ -367,21 +353,22 @@ class Ancestor extends SerializableFinder {
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() {
|
||||
return super.serialize()
|
||||
..addAll(<String, String>{
|
||||
'of': jsonEncode(of.serialize()),
|
||||
'matching': jsonEncode(matching.serialize()),
|
||||
'matchRoot': matchRoot ? 'true' : 'false',
|
||||
'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
|
||||
});
|
||||
return super.serialize()..addAll(<String, String>{
|
||||
'of': jsonEncode(of.serialize()),
|
||||
'matching': jsonEncode(matching.serialize()),
|
||||
'matchRoot': matchRoot ? 'true' : 'false',
|
||||
'firstMatchOnly': firstMatchOnly ? 'true' : 'false',
|
||||
});
|
||||
}
|
||||
|
||||
/// Deserializes the finder from JSON generated by [serialize].
|
||||
static Ancestor deserialize(Map<String, String> json, DeserializeFinderFactory finderFactory) {
|
||||
final Map<String, String> jsonOfMatcher =
|
||||
Map<String, String>.from(jsonDecode(json['of']!) as Map<String, dynamic>);
|
||||
final Map<String, String> jsonMatchingMatcher =
|
||||
Map<String, String>.from(jsonDecode(json['matching']!) as Map<String, dynamic>);
|
||||
final Map<String, String> jsonOfMatcher = Map<String, String>.from(
|
||||
jsonDecode(json['of']!) as Map<String, dynamic>,
|
||||
);
|
||||
final Map<String, String> jsonMatchingMatcher = Map<String, String>.from(
|
||||
jsonDecode(json['matching']!) as Map<String, dynamic>,
|
||||
);
|
||||
return Ancestor(
|
||||
of: finderFactory.deserializeFinder(jsonOfMatcher),
|
||||
matching: finderFactory.deserializeFinder(jsonMatchingMatcher),
|
||||
@@ -404,13 +391,11 @@ class Ancestor extends SerializableFinder {
|
||||
/// Semantics must be enabled to use this method, either using a platform
|
||||
/// specific shell command or [FlutterDriver.setSemantics].
|
||||
class GetSemanticsId extends CommandWithTarget {
|
||||
|
||||
/// Creates a command which finds a Widget and then looks up the semantic id.
|
||||
GetSemanticsId(super.finder, {super.timeout});
|
||||
|
||||
/// Creates a command from a JSON map.
|
||||
GetSemanticsId.deserialize(super.json, super.finderFactory)
|
||||
: super.deserialize();
|
||||
GetSemanticsId.deserialize(super.json, super.finderFactory) : super.deserialize();
|
||||
|
||||
@override
|
||||
String get kind => 'get_semantics_id';
|
||||
@@ -418,7 +403,6 @@ class GetSemanticsId extends CommandWithTarget {
|
||||
|
||||
/// The result of a [GetSemanticsId] command.
|
||||
class GetSemanticsIdResult extends Result {
|
||||
|
||||
/// Creates a new [GetSemanticsId] result.
|
||||
const GetSemanticsIdResult(this.id);
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ import 'message.dart';
|
||||
/// A Flutter Driver command that enables or disables the FrameSync mechanism.
|
||||
class SetFrameSync extends Command {
|
||||
/// Creates a command to toggle the FrameSync mechanism.
|
||||
const SetFrameSync(this.enabled, { super.timeout });
|
||||
const SetFrameSync(this.enabled, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
SetFrameSync.deserialize(super.json)
|
||||
@@ -21,7 +21,6 @@ class SetFrameSync extends Command {
|
||||
String get kind => 'set_frame_sync';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'enabled': '$enabled',
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()..addAll(<String, String>{'enabled': '$enabled'});
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ class _DummyPortForwarder implements PortForwarder {
|
||||
String get openPortAddress => InternetAddress.loopbackIPv4.address;
|
||||
|
||||
@override
|
||||
Future<void> stop() async { }
|
||||
Future<void> stop() async {}
|
||||
}
|
||||
|
||||
class _DummySshCommandRunner implements SshCommandRunner {
|
||||
@@ -99,7 +99,6 @@ abstract final class FuchsiaCompat {
|
||||
/// [FuchsiaRemoteConnection.stop].
|
||||
static Future<FuchsiaRemoteConnection> connect() async {
|
||||
FuchsiaCompat._init();
|
||||
return FuchsiaRemoteConnection.connectWithSshCommandRunner(
|
||||
_DummySshCommandRunner());
|
||||
return FuchsiaRemoteConnection.connectWithSshCommandRunner(_DummySshCommandRunner());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -33,17 +33,17 @@ EnumIndex<OffsetType> _offsetTypeIndex = EnumIndex<OffsetType>(OffsetType.values
|
||||
/// to device pixels via [dart:ui.FlutterView.devicePixelRatio].
|
||||
class GetOffset extends CommandWithTarget {
|
||||
/// The `finder` looks for an element to get its rect.
|
||||
GetOffset(super.finder, this.offsetType, { super.timeout });
|
||||
GetOffset(super.finder, this.offsetType, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
GetOffset.deserialize(super.json, super.finderFactory)
|
||||
: offsetType = _offsetTypeIndex.lookupBySimpleName(json['offsetType']!),
|
||||
super.deserialize();
|
||||
: offsetType = _offsetTypeIndex.lookupBySimpleName(json['offsetType']!),
|
||||
super.deserialize();
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'offsetType': _offsetTypeIndex.toSimpleName(offsetType),
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()
|
||||
..addAll(<String, String>{'offsetType': _offsetTypeIndex.toSimpleName(offsetType)});
|
||||
|
||||
/// The type of the requested offset.
|
||||
final OffsetType offsetType;
|
||||
@@ -58,7 +58,7 @@ class GetOffset extends CommandWithTarget {
|
||||
/// to device pixels via [dart:ui.FlutterView.devicePixelRatio].
|
||||
class GetOffsetResult extends Result {
|
||||
/// Creates a result with the offset defined by [dx] and [dy].
|
||||
const GetOffsetResult({ this.dx = 0.0, this.dy = 0.0});
|
||||
const GetOffsetResult({this.dx = 0.0, this.dy = 0.0});
|
||||
|
||||
/// The x component of the offset in logical pixels.
|
||||
///
|
||||
@@ -74,15 +74,9 @@ class GetOffsetResult extends Result {
|
||||
|
||||
/// Deserializes the result from JSON.
|
||||
static GetOffsetResult fromJson(Map<String, dynamic> json) {
|
||||
return GetOffsetResult(
|
||||
dx: json['dx'] as double,
|
||||
dy: json['dy'] as double,
|
||||
);
|
||||
return GetOffsetResult(dx: json['dx'] as double, dy: json['dy'] as double);
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => <String, double>{
|
||||
'dx': dx,
|
||||
'dy': dy,
|
||||
};
|
||||
Map<String, dynamic> toJson() => <String, double>{'dx': dx, 'dy': dy};
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import 'find.dart';
|
||||
/// A Flutter Driver command that taps on a target widget located by [finder].
|
||||
class Tap extends CommandWithTarget {
|
||||
/// Creates a tap command to tap on a widget located by [finder].
|
||||
Tap(super.finder, { super.timeout });
|
||||
Tap(super.finder, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
Tap.deserialize(super.json, super.finderFactory) : super.deserialize();
|
||||
@@ -23,14 +23,7 @@ class Tap extends CommandWithTarget {
|
||||
class Scroll extends CommandWithTarget {
|
||||
/// Creates a scroll command that will attempt to scroll a scrollable view by
|
||||
/// dragging a widget located by the given [finder].
|
||||
Scroll(
|
||||
super.finder,
|
||||
this.dx,
|
||||
this.dy,
|
||||
this.duration,
|
||||
this.frequency, {
|
||||
super.timeout,
|
||||
});
|
||||
Scroll(super.finder, this.dx, this.dy, this.duration, this.frequency, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
Scroll.deserialize(super.json, super.finderFactory)
|
||||
@@ -56,12 +49,13 @@ class Scroll extends CommandWithTarget {
|
||||
String get kind => 'scroll';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'dx': '$dx',
|
||||
'dy': '$dy',
|
||||
'duration': '${duration.inMicroseconds}',
|
||||
'frequency': '$frequency',
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()..addAll(<String, String>{
|
||||
'dx': '$dx',
|
||||
'dy': '$dy',
|
||||
'duration': '${duration.inMicroseconds}',
|
||||
'frequency': '$frequency',
|
||||
});
|
||||
}
|
||||
|
||||
/// A Flutter Driver command that commands the driver to ensure that the element
|
||||
@@ -69,7 +63,7 @@ class Scroll extends CommandWithTarget {
|
||||
class ScrollIntoView extends CommandWithTarget {
|
||||
/// Creates this command given a [finder] used to locate the widget to be
|
||||
/// scrolled into view.
|
||||
ScrollIntoView(super.finder, { this.alignment = 0.0, super.timeout });
|
||||
ScrollIntoView(super.finder, {this.alignment = 0.0, super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
ScrollIntoView.deserialize(super.json, super.finderFactory)
|
||||
@@ -88,7 +82,6 @@ class ScrollIntoView extends CommandWithTarget {
|
||||
String get kind => 'scrollIntoView';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'alignment': '$alignment',
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()..addAll(<String, String>{'alignment': '$alignment'});
|
||||
}
|
||||
|
||||
@@ -39,14 +39,14 @@ mixin CreateFinderFactory {
|
||||
/// Creates the flutter widget finder from [SerializableFinder].
|
||||
Finder createFinder(SerializableFinder finder) {
|
||||
return switch (finder.finderType) {
|
||||
'ByText' => _createByTextFinder(finder as ByText),
|
||||
'ByText' => _createByTextFinder(finder as ByText),
|
||||
'ByTooltipMessage' => _createByTooltipMessageFinder(finder as ByTooltipMessage),
|
||||
'BySemanticsLabel' => _createBySemanticsLabelFinder(finder as BySemanticsLabel),
|
||||
'ByValueKey' => _createByValueKeyFinder(finder as ByValueKey),
|
||||
'ByType' => _createByTypeFinder(finder as ByType),
|
||||
'PageBack' => _createPageBackFinder(),
|
||||
'Ancestor' => _createAncestorFinder(finder as Ancestor),
|
||||
'Descendant' => _createDescendantFinder(finder as Descendant),
|
||||
'ByValueKey' => _createByValueKeyFinder(finder as ByValueKey),
|
||||
'ByType' => _createByTypeFinder(finder as ByType),
|
||||
'PageBack' => _createPageBackFinder(),
|
||||
'Ancestor' => _createAncestorFinder(finder as Ancestor),
|
||||
'Descendant' => _createDescendantFinder(finder as Descendant),
|
||||
final String type => throw DriverError('Unsupported search specification type $type'),
|
||||
};
|
||||
}
|
||||
@@ -75,15 +75,13 @@ mixin CreateFinderFactory {
|
||||
return false;
|
||||
}
|
||||
final Pattern label = arguments.label;
|
||||
return label is RegExp
|
||||
? label.hasMatch(semanticsLabel)
|
||||
: label == semanticsLabel;
|
||||
return label is RegExp ? label.hasMatch(semanticsLabel) : label == semanticsLabel;
|
||||
}, description: 'widget with semantic label "${arguments.label}"');
|
||||
}
|
||||
|
||||
Finder _createByValueKeyFinder(ByValueKey arguments) {
|
||||
return switch (arguments.keyValueType) {
|
||||
'int' => find.byKey(ValueKey<int>(arguments.keyValue as int)),
|
||||
'int' => find.byKey(ValueKey<int>(arguments.keyValue as int)),
|
||||
'String' => find.byKey(ValueKey<String>(arguments.keyValue as String)),
|
||||
_ => throw UnimplementedError('Unsupported ByValueKey type: ${arguments.keyValueType}'),
|
||||
};
|
||||
@@ -96,11 +94,14 @@ mixin CreateFinderFactory {
|
||||
}
|
||||
|
||||
Finder _createPageBackFinder() {
|
||||
return find.byElementPredicate((Element element) => switch (element.widget) {
|
||||
Tooltip(message: 'Back') => true,
|
||||
CupertinoNavigationBarBackButton() => true,
|
||||
_ => false,
|
||||
}, description: 'Material or Cupertino back button');
|
||||
return find.byElementPredicate(
|
||||
(Element element) => switch (element.widget) {
|
||||
Tooltip(message: 'Back') => true,
|
||||
CupertinoNavigationBarBackButton() => true,
|
||||
_ => false,
|
||||
},
|
||||
description: 'Material or Cupertino back button',
|
||||
);
|
||||
}
|
||||
|
||||
Finder _createAncestorFinder(Ancestor arguments) {
|
||||
@@ -141,35 +142,38 @@ mixin CommandHandlerFactory {
|
||||
final TestTextInput _testTextInput = TestTextInput();
|
||||
|
||||
/// Deserializes the finder from JSON generated by [Command.serialize] or [CommandWithTarget.serialize].
|
||||
Future<Result> handleCommand(Command command, WidgetController prober, CreateFinderFactory finderFactory) {
|
||||
Future<Result> handleCommand(
|
||||
Command command,
|
||||
WidgetController prober,
|
||||
CreateFinderFactory finderFactory,
|
||||
) {
|
||||
return switch (command.kind) {
|
||||
'get_health' => _getHealth(command),
|
||||
'get_layer_tree' => _getLayerTree(command),
|
||||
'get_render_tree' => _getRenderTree(command),
|
||||
'enter_text' => _enterText(command),
|
||||
'send_text_input_action' => _sendTextInputAction(command),
|
||||
'get_text' => _getText(command, finderFactory),
|
||||
'request_data' => _requestData(command),
|
||||
'scroll' => _scroll(command, prober, finderFactory),
|
||||
'scrollIntoView' => _scrollIntoView(command, finderFactory),
|
||||
'set_frame_sync' => _setFrameSync(command),
|
||||
'set_semantics' => _setSemantics(command),
|
||||
'set_text_entry_emulation' => _setTextEntryEmulation(command),
|
||||
'tap' => _tap(command, prober, finderFactory),
|
||||
'waitFor' => _waitFor(command, finderFactory),
|
||||
'waitForAbsent' => _waitForAbsent(command, finderFactory),
|
||||
'waitForTappable' => _waitForTappable(command, finderFactory),
|
||||
'waitForCondition' => _waitForCondition(command),
|
||||
'get_health' => _getHealth(command),
|
||||
'get_layer_tree' => _getLayerTree(command),
|
||||
'get_render_tree' => _getRenderTree(command),
|
||||
'enter_text' => _enterText(command),
|
||||
'send_text_input_action' => _sendTextInputAction(command),
|
||||
'get_text' => _getText(command, finderFactory),
|
||||
'request_data' => _requestData(command),
|
||||
'scroll' => _scroll(command, prober, finderFactory),
|
||||
'scrollIntoView' => _scrollIntoView(command, finderFactory),
|
||||
'set_frame_sync' => _setFrameSync(command),
|
||||
'set_semantics' => _setSemantics(command),
|
||||
'set_text_entry_emulation' => _setTextEntryEmulation(command),
|
||||
'tap' => _tap(command, prober, finderFactory),
|
||||
'waitFor' => _waitFor(command, finderFactory),
|
||||
'waitForAbsent' => _waitForAbsent(command, finderFactory),
|
||||
'waitForTappable' => _waitForTappable(command, finderFactory),
|
||||
'waitForCondition' => _waitForCondition(command),
|
||||
'waitUntilNoTransientCallbacks' => _waitUntilNoTransientCallbacks(command),
|
||||
'waitUntilNoPendingFrame' => _waitUntilNoPendingFrame(command),
|
||||
'waitUntilNoPendingFrame' => _waitUntilNoPendingFrame(command),
|
||||
'waitUntilFirstFrameRasterized' => _waitUntilFirstFrameRasterized(command),
|
||||
'get_semantics_id' => _getSemanticsId(command, finderFactory),
|
||||
'get_offset' => _getOffset(command, finderFactory),
|
||||
'get_diagnostics_tree' => _getDiagnosticsTree(command, finderFactory),
|
||||
'screenshot' => _takeScreenshot(command),
|
||||
'get_semantics_id' => _getSemanticsId(command, finderFactory),
|
||||
'get_offset' => _getOffset(command, finderFactory),
|
||||
'get_diagnostics_tree' => _getDiagnosticsTree(command, finderFactory),
|
||||
'screenshot' => _takeScreenshot(command),
|
||||
final String kind => throw DriverError('Unsupported command kind $kind'),
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
Future<Health> _getHealth(Command command) async => const Health(HealthStatus.ok);
|
||||
@@ -177,8 +181,7 @@ mixin CommandHandlerFactory {
|
||||
Future<LayerTree> _getLayerTree(Command command) async {
|
||||
final String trees = <String>[
|
||||
for (final RenderView renderView in RendererBinding.instance.renderViews)
|
||||
if (renderView.debugLayer != null)
|
||||
renderView.debugLayer!.toStringDeep(),
|
||||
if (renderView.debugLayer != null) renderView.debugLayer!.toStringDeep(),
|
||||
].join('\n\n');
|
||||
return LayerTree(trees.isNotEmpty ? trees : null);
|
||||
}
|
||||
@@ -205,8 +208,10 @@ mixin CommandHandlerFactory {
|
||||
|
||||
Future<Result> _sendTextInputAction(Command command) async {
|
||||
if (!_testTextInput.isRegistered) {
|
||||
throw StateError('Unable to fulfill `FlutterDriver.sendTextInputAction`. Text emulation is '
|
||||
'disabled. You can enable it using `FlutterDriver.setTextEntryEmulation`.');
|
||||
throw StateError(
|
||||
'Unable to fulfill `FlutterDriver.sendTextInputAction`. Text emulation is '
|
||||
'disabled. You can enable it using `FlutterDriver.setTextEntryEmulation`.',
|
||||
);
|
||||
}
|
||||
final SendTextInputAction sendTextInputAction = command as SendTextInputAction;
|
||||
_testTextInput.receiveAction(TextInputAction.values[sendTextInputAction.textInputAction.index]);
|
||||
@@ -216,9 +221,11 @@ mixin CommandHandlerFactory {
|
||||
Future<RequestDataResult> _requestData(Command command) async {
|
||||
final RequestData requestDataCommand = command as RequestData;
|
||||
final DataHandler? dataHandler = getDataHandler();
|
||||
return RequestDataResult(dataHandler == null
|
||||
? 'No requestData Extension registered'
|
||||
: await dataHandler(requestDataCommand.message));
|
||||
return RequestDataResult(
|
||||
dataHandler == null
|
||||
? 'No requestData Extension registered'
|
||||
: await dataHandler(requestDataCommand.message),
|
||||
);
|
||||
}
|
||||
|
||||
Future<Result> _setFrameSync(Command command) async {
|
||||
@@ -227,7 +234,11 @@ mixin CommandHandlerFactory {
|
||||
return Result.empty;
|
||||
}
|
||||
|
||||
Future<Result> _tap(Command command, WidgetController prober, CreateFinderFactory finderFactory) async {
|
||||
Future<Result> _tap(
|
||||
Command command,
|
||||
WidgetController prober,
|
||||
CreateFinderFactory finderFactory,
|
||||
) async {
|
||||
final Tap tapCommand = command as Tap;
|
||||
final Finder computedFinder = await waitForElement(
|
||||
finderFactory.createFinder(tapCommand.finder).hitTestable(),
|
||||
@@ -250,9 +261,7 @@ mixin CommandHandlerFactory {
|
||||
|
||||
Future<Result> _waitForTappable(Command command, CreateFinderFactory finderFactory) async {
|
||||
final WaitForTappable waitForTappableCommand = command as WaitForTappable;
|
||||
await waitForElement(
|
||||
finderFactory.createFinder(waitForTappableCommand.finder).hitTestable(),
|
||||
);
|
||||
await waitForElement(finderFactory.createFinder(waitForTappableCommand.finder).hitTestable());
|
||||
return Result.empty;
|
||||
}
|
||||
|
||||
@@ -265,7 +274,7 @@ mixin CommandHandlerFactory {
|
||||
|
||||
@Deprecated(
|
||||
'This method has been deprecated in favor of _waitForCondition. '
|
||||
'This feature was deprecated after v1.9.3.'
|
||||
'This feature was deprecated after v1.9.3.',
|
||||
)
|
||||
Future<Result> _waitUntilNoTransientCallbacks(Command command) async {
|
||||
if (SchedulerBinding.instance.transientCallbackCount != 0) {
|
||||
@@ -295,17 +304,20 @@ mixin CommandHandlerFactory {
|
||||
/// This method has been deprecated in favor of [_waitForCondition].
|
||||
@Deprecated(
|
||||
'This method has been deprecated in favor of _waitForCondition. '
|
||||
'This feature was deprecated after v1.9.3.'
|
||||
'This feature was deprecated after v1.9.3.',
|
||||
)
|
||||
Future<Result> _waitUntilNoPendingFrame(Command command) async {
|
||||
await _waitUntilFrame(() {
|
||||
return SchedulerBinding.instance.transientCallbackCount == 0
|
||||
&& !SchedulerBinding.instance.hasScheduledFrame;
|
||||
return SchedulerBinding.instance.transientCallbackCount == 0 &&
|
||||
!SchedulerBinding.instance.hasScheduledFrame;
|
||||
});
|
||||
return Result.empty;
|
||||
}
|
||||
|
||||
Future<GetSemanticsIdResult> _getSemanticsId(Command command, CreateFinderFactory finderFactory) async {
|
||||
Future<GetSemanticsIdResult> _getSemanticsId(
|
||||
Command command,
|
||||
CreateFinderFactory finderFactory,
|
||||
) async {
|
||||
final GetSemanticsId semanticsCommand = command as GetSemanticsId;
|
||||
final Finder target = await waitForElement(finderFactory.createFinder(semanticsCommand.finder));
|
||||
final Iterable<Element> elements = target.evaluate();
|
||||
@@ -331,28 +343,37 @@ mixin CommandHandlerFactory {
|
||||
final Element element = finder.evaluate().single;
|
||||
final RenderBox box = (element.renderObject as RenderBox?)!;
|
||||
final Offset localPoint = switch (getOffsetCommand.offsetType) {
|
||||
OffsetType.topLeft => Offset.zero,
|
||||
OffsetType.topRight => box.size.topRight(Offset.zero),
|
||||
OffsetType.bottomLeft => box.size.bottomLeft(Offset.zero),
|
||||
OffsetType.topLeft => Offset.zero,
|
||||
OffsetType.topRight => box.size.topRight(Offset.zero),
|
||||
OffsetType.bottomLeft => box.size.bottomLeft(Offset.zero),
|
||||
OffsetType.bottomRight => box.size.bottomRight(Offset.zero),
|
||||
OffsetType.center => box.size.center(Offset.zero),
|
||||
OffsetType.center => box.size.center(Offset.zero),
|
||||
};
|
||||
final Offset globalPoint = box.localToGlobal(localPoint);
|
||||
return GetOffsetResult(dx: globalPoint.dx, dy: globalPoint.dy);
|
||||
}
|
||||
|
||||
Future<DiagnosticsTreeResult> _getDiagnosticsTree(Command command, CreateFinderFactory finderFactory) async {
|
||||
Future<DiagnosticsTreeResult> _getDiagnosticsTree(
|
||||
Command command,
|
||||
CreateFinderFactory finderFactory,
|
||||
) async {
|
||||
final GetDiagnosticsTree diagnosticsCommand = command as GetDiagnosticsTree;
|
||||
final Finder finder = await waitForElement(finderFactory.createFinder(diagnosticsCommand.finder));
|
||||
final Finder finder = await waitForElement(
|
||||
finderFactory.createFinder(diagnosticsCommand.finder),
|
||||
);
|
||||
final Element element = finder.evaluate().single;
|
||||
final DiagnosticsNode diagnosticsNode = switch (diagnosticsCommand.diagnosticsType) {
|
||||
DiagnosticsType.renderObject => element.renderObject!.toDiagnosticsNode(),
|
||||
DiagnosticsType.widget => element.toDiagnosticsNode(),
|
||||
};
|
||||
return DiagnosticsTreeResult(diagnosticsNode.toJsonMap(DiagnosticsSerializationDelegate(
|
||||
subtreeDepth: diagnosticsCommand.subtreeDepth,
|
||||
includeProperties: diagnosticsCommand.includeProperties,
|
||||
)));
|
||||
return DiagnosticsTreeResult(
|
||||
diagnosticsNode.toJsonMap(
|
||||
DiagnosticsSerializationDelegate(
|
||||
subtreeDepth: diagnosticsCommand.subtreeDepth,
|
||||
includeProperties: diagnosticsCommand.includeProperties,
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<ScreenshotResult> _takeScreenshot(Command command) async {
|
||||
@@ -367,10 +388,17 @@ mixin CommandHandlerFactory {
|
||||
return ScreenshotResult(buffer.buffer.asUint8List());
|
||||
}
|
||||
|
||||
Future<Result> _scroll(Command command, WidgetController prober, CreateFinderFactory finderFactory) async {
|
||||
Future<Result> _scroll(
|
||||
Command command,
|
||||
WidgetController prober,
|
||||
CreateFinderFactory finderFactory,
|
||||
) async {
|
||||
final Scroll scrollCommand = command as Scroll;
|
||||
final Finder target = await waitForElement(finderFactory.createFinder(scrollCommand.finder));
|
||||
final int totalMoves = scrollCommand.duration.inMicroseconds * scrollCommand.frequency ~/ Duration.microsecondsPerSecond;
|
||||
final int totalMoves =
|
||||
scrollCommand.duration.inMicroseconds *
|
||||
scrollCommand.frequency ~/
|
||||
Duration.microsecondsPerSecond;
|
||||
final Offset delta = Offset(scrollCommand.dx, scrollCommand.dy) / totalMoves.toDouble();
|
||||
final Duration pause = scrollCommand.duration ~/ totalMoves;
|
||||
final Offset startLocation = prober.getCenter(target);
|
||||
@@ -390,8 +418,14 @@ mixin CommandHandlerFactory {
|
||||
|
||||
Future<Result> _scrollIntoView(Command command, CreateFinderFactory finderFactory) async {
|
||||
final ScrollIntoView scrollIntoViewCommand = command as ScrollIntoView;
|
||||
final Finder target = await waitForElement(finderFactory.createFinder(scrollIntoViewCommand.finder));
|
||||
await Scrollable.ensureVisible(target.evaluate().single, duration: const Duration(milliseconds: 100), alignment: scrollIntoViewCommand.alignment);
|
||||
final Finder target = await waitForElement(
|
||||
finderFactory.createFinder(scrollIntoViewCommand.finder),
|
||||
);
|
||||
await Scrollable.ensureVisible(
|
||||
target.evaluate().single,
|
||||
duration: const Duration(milliseconds: 100),
|
||||
alignment: scrollIntoViewCommand.alignment,
|
||||
);
|
||||
return Result.empty;
|
||||
}
|
||||
|
||||
@@ -406,10 +440,7 @@ mixin CommandHandlerFactory {
|
||||
text = (widget as Text).data;
|
||||
} else if (widget.runtimeType == RichText) {
|
||||
final RichText richText = widget as RichText;
|
||||
text = richText.text.toPlainText(
|
||||
includeSemanticsLabels: false,
|
||||
includePlaceholders: false,
|
||||
);
|
||||
text = richText.text.toPlainText(includeSemanticsLabels: false, includePlaceholders: false);
|
||||
} else if (widget.runtimeType == TextField) {
|
||||
text = (widget as TextField).controller?.text;
|
||||
} else if (widget.runtimeType == TextFormField) {
|
||||
@@ -461,7 +492,7 @@ mixin CommandHandlerFactory {
|
||||
// This can be used to wait for the first frame being rasterized during app launch.
|
||||
@Deprecated(
|
||||
'This method has been deprecated in favor of _waitForCondition. '
|
||||
'This feature was deprecated after v1.9.3.'
|
||||
'This feature was deprecated after v1.9.3.',
|
||||
)
|
||||
Future<Result> _waitUntilFirstFrameRasterized(Command command) async {
|
||||
await WidgetsBinding.instance.waitUntilFirstFrameRasterized;
|
||||
@@ -499,7 +530,7 @@ mixin CommandHandlerFactory {
|
||||
}
|
||||
|
||||
// Waits until at the end of a frame the provided [condition] is [true].
|
||||
Future<void> _waitUntilFrame(bool Function() condition, [ Completer<void>? completer ]) {
|
||||
Future<void> _waitUntilFrame(bool Function() condition, [Completer<void>? completer]) {
|
||||
completer ??= Completer<void>();
|
||||
if (!condition()) {
|
||||
SchedulerBinding.instance.addPostFrameCallback((Duration timestamp) {
|
||||
|
||||
@@ -11,7 +11,7 @@ import 'message.dart';
|
||||
/// A Flutter Driver command that requests an application health check.
|
||||
class GetHealth extends Command {
|
||||
/// Create a health check command.
|
||||
const GetHealth({ super.timeout });
|
||||
const GetHealth({super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
GetHealth.deserialize(super.json) : super.deserialize();
|
||||
@@ -32,8 +32,7 @@ enum HealthStatus {
|
||||
bad,
|
||||
}
|
||||
|
||||
final EnumIndex<HealthStatus> _healthStatusIndex =
|
||||
EnumIndex<HealthStatus>(HealthStatus.values);
|
||||
final EnumIndex<HealthStatus> _healthStatusIndex = EnumIndex<HealthStatus>(HealthStatus.values);
|
||||
|
||||
/// A description of the application state, as provided in response to a
|
||||
/// [FlutterDriver.checkHealth] test.
|
||||
|
||||
@@ -10,7 +10,7 @@ import 'message.dart';
|
||||
/// A Flutter Driver command that requests a string representation of the layer tree.
|
||||
class GetLayerTree extends Command {
|
||||
/// Create a command to request a string representation of the layer tree.
|
||||
const GetLayerTree({ super.timeout });
|
||||
const GetLayerTree({super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
GetLayerTree.deserialize(super.json) : super.deserialize();
|
||||
@@ -32,7 +32,5 @@ class LayerTree extends Result {
|
||||
final String? tree;
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'tree': tree,
|
||||
};
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{'tree': tree};
|
||||
}
|
||||
|
||||
@@ -12,11 +12,10 @@ 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({this.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
Command.deserialize(Map<String, String> json)
|
||||
: timeout = _parseTimeout(json);
|
||||
Command.deserialize(Map<String, String> json) : timeout = _parseTimeout(json);
|
||||
|
||||
static Duration? _parseTimeout(Map<String, String> json) {
|
||||
final String? timeout = json['timeout'];
|
||||
@@ -53,9 +52,7 @@ abstract class Command {
|
||||
/// Serializes this command to parameter name/value pairs.
|
||||
@mustCallSuper
|
||||
Map<String, String> serialize() {
|
||||
final Map<String, String> result = <String, String>{
|
||||
'command': kind,
|
||||
};
|
||||
final Map<String, String> result = <String, String>{'command': kind};
|
||||
if (timeout != null) {
|
||||
result['timeout'] = '${timeout!.inMilliseconds}';
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ import 'message.dart';
|
||||
/// A Flutter Driver command that requests a string representation of the render tree.
|
||||
class GetRenderTree extends Command {
|
||||
/// Create a command to request a string representation of the render tree.
|
||||
const GetRenderTree({ super.timeout });
|
||||
const GetRenderTree({super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
GetRenderTree.deserialize(super.json) : super.deserialize();
|
||||
@@ -34,7 +34,5 @@ class RenderTree extends Result {
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'tree': tree,
|
||||
};
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{'tree': tree};
|
||||
}
|
||||
|
||||
@@ -8,12 +8,10 @@ import 'message.dart';
|
||||
/// string response.
|
||||
class RequestData extends Command {
|
||||
/// Create a command that sends a message.
|
||||
const RequestData(this.message, { super.timeout });
|
||||
const RequestData(this.message, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
RequestData.deserialize(super.json)
|
||||
: message = json['message'],
|
||||
super.deserialize();
|
||||
RequestData.deserialize(super.json) : message = json['message'], super.deserialize();
|
||||
|
||||
/// The message being sent from the test to the application.
|
||||
final String? message;
|
||||
@@ -25,10 +23,8 @@ class RequestData extends Command {
|
||||
bool get requiresRootWidgetAttached => false;
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
if (message != null)
|
||||
'message': message!,
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()..addAll(<String, String>{if (message != null) 'message': message!});
|
||||
}
|
||||
|
||||
/// The result of the [RequestData] command.
|
||||
@@ -45,7 +41,5 @@ class RequestDataResult extends Result {
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => <String, String>{
|
||||
'message': message,
|
||||
};
|
||||
Map<String, dynamic> toJson() => <String, String>{'message': message};
|
||||
}
|
||||
|
||||
@@ -39,7 +39,8 @@ class ScreenshotCommand extends Command {
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
ScreenshotCommand.deserialize(super.json)
|
||||
: format = ScreenshotFormat.values[int.tryParse(json['format']!) ?? 4], super.deserialize();
|
||||
: format = ScreenshotFormat.values[int.tryParse(json['format']!) ?? 4],
|
||||
super.deserialize();
|
||||
|
||||
/// Whether the resulting data is PNG compressed.
|
||||
final ScreenshotFormat format;
|
||||
@@ -47,9 +48,7 @@ class ScreenshotCommand extends Command {
|
||||
/// Serializes this command to parameter name/value pairs.
|
||||
@override
|
||||
Map<String, String> serialize() {
|
||||
return super.serialize()..addAll(<String, String>{
|
||||
'format': format.index.toString()
|
||||
});
|
||||
return super.serialize()..addAll(<String, String>{'format': format.index.toString()});
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -65,8 +64,6 @@ class ScreenshotResult extends Result {
|
||||
|
||||
@override
|
||||
Map<String, Object?> toJson() {
|
||||
return <String, Object?>{
|
||||
'data': base64.encode(_data)
|
||||
};
|
||||
return <String, Object?>{'data': base64.encode(_data)};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ import 'message.dart';
|
||||
/// A Flutter Driver command that enables or disables semantics.
|
||||
class SetSemantics extends Command {
|
||||
/// Creates a command that enables or disables semantics.
|
||||
const SetSemantics(this.enabled, { super.timeout });
|
||||
const SetSemantics(this.enabled, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
SetSemantics.deserialize(super.json)
|
||||
@@ -21,9 +21,8 @@ class SetSemantics extends Command {
|
||||
String get kind => 'set_semantics';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'enabled': '$enabled',
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()..addAll(<String, String>{'enabled': '$enabled'});
|
||||
}
|
||||
|
||||
/// The result of a [SetSemantics] command.
|
||||
@@ -41,7 +40,5 @@ class SetSemanticsResult extends Result {
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{
|
||||
'changedState': changedState,
|
||||
};
|
||||
Map<String, dynamic> toJson() => <String, dynamic>{'changedState': changedState};
|
||||
}
|
||||
|
||||
@@ -8,7 +8,7 @@ import 'message.dart';
|
||||
/// A Flutter Driver command that reads the text from a given element.
|
||||
class GetText extends CommandWithTarget {
|
||||
/// [finder] looks for an element that contains a piece of text.
|
||||
GetText(super.finder, { super.timeout });
|
||||
GetText(super.finder, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
GetText.deserialize(super.json, super.finderFactory) : super.deserialize();
|
||||
@@ -31,20 +31,16 @@ class GetTextResult extends Result {
|
||||
}
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => <String, String>{
|
||||
'text': text,
|
||||
};
|
||||
Map<String, dynamic> toJson() => <String, String>{'text': text};
|
||||
}
|
||||
|
||||
/// A Flutter Driver command that enters text into the currently focused widget.
|
||||
class EnterText extends Command {
|
||||
/// Creates a command that enters text into the currently focused widget.
|
||||
const EnterText(this.text, { super.timeout });
|
||||
const EnterText(this.text, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
EnterText.deserialize(super.json)
|
||||
: text = json['text']!,
|
||||
super.deserialize();
|
||||
EnterText.deserialize(super.json) : text = json['text']!, super.deserialize();
|
||||
|
||||
/// The text extracted by the [GetText] command.
|
||||
final String text;
|
||||
@@ -53,15 +49,13 @@ class EnterText extends Command {
|
||||
String get kind => 'enter_text';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'text': text,
|
||||
});
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{'text': text});
|
||||
}
|
||||
|
||||
/// A Flutter Driver command that enables and disables text entry emulation.
|
||||
class SetTextEntryEmulation extends Command {
|
||||
/// Creates a command that enables and disables text entry emulation.
|
||||
const SetTextEntryEmulation(this.enabled, { super.timeout });
|
||||
const SetTextEntryEmulation(this.enabled, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
SetTextEntryEmulation.deserialize(super.json)
|
||||
@@ -75,7 +69,6 @@ class SetTextEntryEmulation extends Command {
|
||||
String get kind => 'set_text_entry_emulation';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()..addAll(<String, String>{
|
||||
'enabled': '$enabled',
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()..addAll(<String, String>{'enabled': '$enabled'});
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@ library;
|
||||
import 'enum_util.dart';
|
||||
import 'message.dart';
|
||||
|
||||
EnumIndex<TextInputAction> _textInputActionIndex =
|
||||
EnumIndex<TextInputAction>(TextInputAction.values);
|
||||
EnumIndex<TextInputAction> _textInputActionIndex = EnumIndex<TextInputAction>(
|
||||
TextInputAction.values,
|
||||
);
|
||||
|
||||
/// A Flutter Driver command that send a text input action.
|
||||
class SendTextInputAction extends Command {
|
||||
@@ -18,9 +19,8 @@ class SendTextInputAction extends Command {
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
SendTextInputAction.deserialize(super.json)
|
||||
: textInputAction =
|
||||
_textInputActionIndex.lookupBySimpleName(json['action']!),
|
||||
super.deserialize();
|
||||
: textInputAction = _textInputActionIndex.lookupBySimpleName(json['action']!),
|
||||
super.deserialize();
|
||||
|
||||
/// The [TextInputAction]
|
||||
final TextInputAction textInputAction;
|
||||
@@ -29,10 +29,9 @@ class SendTextInputAction extends Command {
|
||||
String get kind => 'send_text_input_action';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() => super.serialize()
|
||||
..addAll(<String, String>{
|
||||
'action': _textInputActionIndex.toSimpleName(textInputAction),
|
||||
});
|
||||
Map<String, String> serialize() =>
|
||||
super.serialize()
|
||||
..addAll(<String, String>{'action': _textInputActionIndex.toSimpleName(textInputAction)});
|
||||
}
|
||||
|
||||
/// An action the user has requested the text input control to perform.
|
||||
|
||||
@@ -15,9 +15,7 @@ class WaitForCondition extends Command {
|
||||
const WaitForCondition(this.condition, {super.timeout});
|
||||
|
||||
/// Deserializes this command from the value generated by [serialize].
|
||||
WaitForCondition.deserialize(super.json)
|
||||
: condition = _deserialize(json),
|
||||
super.deserialize();
|
||||
WaitForCondition.deserialize(super.json) : condition = _deserialize(json), super.deserialize();
|
||||
|
||||
/// The condition that this command shall wait for.
|
||||
final SerializableWaitCondition condition;
|
||||
@@ -61,9 +59,7 @@ abstract class SerializableWaitCondition {
|
||||
|
||||
/// Serializes the object to JSON.
|
||||
Map<String, String> serialize() {
|
||||
return <String, String>{
|
||||
'conditionName': conditionName,
|
||||
};
|
||||
return <String, String>{'conditionName': conditionName};
|
||||
}
|
||||
|
||||
/// Whether this command requires the widget tree to be initialized before
|
||||
@@ -90,7 +86,9 @@ class NoTransientCallbacks extends SerializableWaitCondition {
|
||||
/// given JSON map.
|
||||
factory NoTransientCallbacks.deserialize(Map<String, String> json) {
|
||||
if (json['conditionName'] != 'NoTransientCallbacksCondition') {
|
||||
throw SerializationException('Error occurred during deserializing the NoTransientCallbacksCondition JSON string: $json');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing the NoTransientCallbacksCondition JSON string: $json',
|
||||
);
|
||||
}
|
||||
return const NoTransientCallbacks();
|
||||
}
|
||||
@@ -108,7 +106,9 @@ class NoPendingFrame extends SerializableWaitCondition {
|
||||
/// JSON map.
|
||||
factory NoPendingFrame.deserialize(Map<String, String> json) {
|
||||
if (json['conditionName'] != 'NoPendingFrameCondition') {
|
||||
throw SerializationException('Error occurred during deserializing the NoPendingFrameCondition JSON string: $json');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing the NoPendingFrameCondition JSON string: $json',
|
||||
);
|
||||
}
|
||||
return const NoPendingFrame();
|
||||
}
|
||||
@@ -126,7 +126,9 @@ class FirstFrameRasterized extends SerializableWaitCondition {
|
||||
/// given JSON map.
|
||||
factory FirstFrameRasterized.deserialize(Map<String, String> json) {
|
||||
if (json['conditionName'] != 'FirstFrameRasterizedCondition') {
|
||||
throw SerializationException('Error occurred during deserializing the FirstFrameRasterizedCondition JSON string: $json');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing the FirstFrameRasterizedCondition JSON string: $json',
|
||||
);
|
||||
}
|
||||
return const FirstFrameRasterized();
|
||||
}
|
||||
@@ -147,7 +149,9 @@ class NoPendingPlatformMessages extends SerializableWaitCondition {
|
||||
/// given JSON map.
|
||||
factory NoPendingPlatformMessages.deserialize(Map<String, String> json) {
|
||||
if (json['conditionName'] != 'NoPendingPlatformMessagesCondition') {
|
||||
throw SerializationException('Error occurred during deserializing the NoPendingPlatformMessagesCondition JSON string: $json');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing the NoPendingPlatformMessagesCondition JSON string: $json',
|
||||
);
|
||||
}
|
||||
return const NoPendingPlatformMessages();
|
||||
}
|
||||
@@ -165,14 +169,17 @@ class CombinedCondition extends SerializableWaitCondition {
|
||||
/// given JSON map.
|
||||
factory CombinedCondition.deserialize(Map<String, String> jsonMap) {
|
||||
if (jsonMap['conditionName'] != 'CombinedCondition') {
|
||||
throw SerializationException('Error occurred during deserializing the CombinedCondition JSON string: $jsonMap');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing the CombinedCondition JSON string: $jsonMap',
|
||||
);
|
||||
}
|
||||
if (jsonMap['conditions'] == null) {
|
||||
return const CombinedCondition(<SerializableWaitCondition>[]);
|
||||
}
|
||||
|
||||
final List<SerializableWaitCondition> conditions = <SerializableWaitCondition>[];
|
||||
for (final Map<String, dynamic> condition in (json.decode(jsonMap['conditions']!) as List<dynamic>).cast<Map<String, dynamic>>()) {
|
||||
for (final Map<String, dynamic> condition
|
||||
in (json.decode(jsonMap['conditions']!) as List<dynamic>).cast<Map<String, dynamic>>()) {
|
||||
conditions.add(_deserialize(condition.cast<String, String>()));
|
||||
}
|
||||
return CombinedCondition(conditions);
|
||||
@@ -187,10 +194,10 @@ class CombinedCondition extends SerializableWaitCondition {
|
||||
@override
|
||||
Map<String, String> serialize() {
|
||||
final Map<String, String> jsonMap = super.serialize();
|
||||
final List<Map<String, String>> jsonConditions = conditions.map(
|
||||
(SerializableWaitCondition condition) {
|
||||
return condition.serialize();
|
||||
}).toList();
|
||||
final List<Map<String, String>> jsonConditions =
|
||||
conditions.map((SerializableWaitCondition condition) {
|
||||
return condition.serialize();
|
||||
}).toList();
|
||||
jsonMap['conditions'] = json.encode(jsonConditions);
|
||||
return jsonMap;
|
||||
}
|
||||
@@ -199,13 +206,14 @@ class CombinedCondition extends SerializableWaitCondition {
|
||||
/// Parses a [SerializableWaitCondition] or its subclass from the given [json] map.
|
||||
SerializableWaitCondition _deserialize(Map<String, String> json) {
|
||||
return switch (json['conditionName']!) {
|
||||
'NoTransientCallbacksCondition' => NoTransientCallbacks.deserialize(json),
|
||||
'NoPendingFrameCondition' => NoPendingFrame.deserialize(json),
|
||||
'FirstFrameRasterizedCondition' => FirstFrameRasterized.deserialize(json),
|
||||
'NoTransientCallbacksCondition' => NoTransientCallbacks.deserialize(json),
|
||||
'NoPendingFrameCondition' => NoPendingFrame.deserialize(json),
|
||||
'FirstFrameRasterizedCondition' => FirstFrameRasterized.deserialize(json),
|
||||
'NoPendingPlatformMessagesCondition' => NoPendingPlatformMessages.deserialize(json),
|
||||
'CombinedCondition' => CombinedCondition.deserialize(json),
|
||||
final String condition => throw SerializationException(
|
||||
'Unsupported wait condition $condition in the JSON string $json',
|
||||
),
|
||||
'CombinedCondition' => CombinedCondition.deserialize(json),
|
||||
final String condition =>
|
||||
throw SerializationException(
|
||||
'Unsupported wait condition $condition in the JSON string $json',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -199,22 +199,22 @@ abstract class FlutterDriver {
|
||||
Future<Map<String, dynamic>> sendCommand(Command command) async => throw UnimplementedError();
|
||||
|
||||
/// Checks the status of the Flutter Driver extension.
|
||||
Future<Health> checkHealth({ Duration? timeout }) async {
|
||||
Future<Health> checkHealth({Duration? timeout}) async {
|
||||
return Health.fromJson(await sendCommand(GetHealth(timeout: timeout)));
|
||||
}
|
||||
|
||||
/// Returns a dump of the render tree.
|
||||
Future<RenderTree> getRenderTree({ Duration? timeout }) async {
|
||||
Future<RenderTree> getRenderTree({Duration? timeout}) async {
|
||||
return RenderTree.fromJson(await sendCommand(GetRenderTree(timeout: timeout)));
|
||||
}
|
||||
|
||||
/// Returns a dump of the layer tree.
|
||||
Future<LayerTree> getLayerTree({ Duration? timeout }) async {
|
||||
Future<LayerTree> getLayerTree({Duration? timeout}) async {
|
||||
return LayerTree.fromJson(await sendCommand(GetLayerTree(timeout: timeout)));
|
||||
}
|
||||
|
||||
/// Taps at the center of the widget located by [finder].
|
||||
Future<void> tap(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<void> tap(SerializableFinder finder, {Duration? timeout}) async {
|
||||
await sendCommand(Tap(finder, timeout: timeout));
|
||||
}
|
||||
|
||||
@@ -227,22 +227,25 @@ abstract class FlutterDriver {
|
||||
///
|
||||
/// * [FlutterDriver.runUnsynchronized], which will execute an action
|
||||
/// with frame sync disabled even while frames are pending.
|
||||
Future<void> waitFor(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<void> waitFor(SerializableFinder finder, {Duration? timeout}) async {
|
||||
await sendCommand(WaitFor(finder, timeout: timeout));
|
||||
}
|
||||
|
||||
/// Waits until [finder] can no longer locate the target.
|
||||
Future<void> waitForAbsent(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<void> waitForAbsent(SerializableFinder finder, {Duration? timeout}) async {
|
||||
await sendCommand(WaitForAbsent(finder, timeout: timeout));
|
||||
}
|
||||
|
||||
/// Waits until [finder] is tappable.
|
||||
Future<void> waitForTappable(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<void> waitForTappable(SerializableFinder finder, {Duration? timeout}) async {
|
||||
await sendCommand(WaitForTappable(finder, timeout: timeout));
|
||||
}
|
||||
|
||||
/// Waits until the given [waitCondition] is satisfied.
|
||||
Future<void> waitForCondition(SerializableWaitCondition waitCondition, {Duration? timeout}) async {
|
||||
Future<void> waitForCondition(
|
||||
SerializableWaitCondition waitCondition, {
|
||||
Duration? timeout,
|
||||
}) async {
|
||||
await sendCommand(WaitForCondition(waitCondition, timeout: timeout));
|
||||
}
|
||||
|
||||
@@ -250,7 +253,7 @@ abstract 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 {
|
||||
Future<void> waitUntilNoTransientCallbacks({Duration? timeout}) async {
|
||||
await sendCommand(WaitForCondition(const NoTransientCallbacks(), timeout: timeout));
|
||||
}
|
||||
|
||||
@@ -265,7 +268,11 @@ abstract class FlutterDriver {
|
||||
await sendCommand(const WaitForCondition(FirstFrameRasterized()));
|
||||
}
|
||||
|
||||
Future<DriverOffset> _getOffset(SerializableFinder finder, OffsetType type, { Duration? timeout }) async {
|
||||
Future<DriverOffset> _getOffset(
|
||||
SerializableFinder finder,
|
||||
OffsetType type, {
|
||||
Duration? timeout,
|
||||
}) async {
|
||||
final GetOffset command = GetOffset(finder, type, timeout: timeout);
|
||||
final GetOffsetResult result = GetOffsetResult.fromJson(await sendCommand(command));
|
||||
return DriverOffset(result.dx, result.dy);
|
||||
@@ -275,7 +282,7 @@ abstract class FlutterDriver {
|
||||
///
|
||||
/// The offset is expressed in logical pixels and can be translated to
|
||||
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
|
||||
Future<DriverOffset> getTopLeft(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<DriverOffset> getTopLeft(SerializableFinder finder, {Duration? timeout}) async {
|
||||
return _getOffset(finder, OffsetType.topLeft, timeout: timeout);
|
||||
}
|
||||
|
||||
@@ -283,7 +290,7 @@ abstract class FlutterDriver {
|
||||
///
|
||||
/// The offset is expressed in logical pixels and can be translated to
|
||||
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
|
||||
Future<DriverOffset> getTopRight(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<DriverOffset> getTopRight(SerializableFinder finder, {Duration? timeout}) async {
|
||||
return _getOffset(finder, OffsetType.topRight, timeout: timeout);
|
||||
}
|
||||
|
||||
@@ -291,7 +298,7 @@ abstract class FlutterDriver {
|
||||
///
|
||||
/// The offset is expressed in logical pixels and can be translated to
|
||||
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
|
||||
Future<DriverOffset> getBottomLeft(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<DriverOffset> getBottomLeft(SerializableFinder finder, {Duration? timeout}) async {
|
||||
return _getOffset(finder, OffsetType.bottomLeft, timeout: timeout);
|
||||
}
|
||||
|
||||
@@ -299,7 +306,7 @@ abstract class FlutterDriver {
|
||||
///
|
||||
/// The offset is expressed in logical pixels and can be translated to
|
||||
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
|
||||
Future<DriverOffset> getBottomRight(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<DriverOffset> getBottomRight(SerializableFinder finder, {Duration? timeout}) async {
|
||||
return _getOffset(finder, OffsetType.bottomRight, timeout: timeout);
|
||||
}
|
||||
|
||||
@@ -307,7 +314,7 @@ abstract class FlutterDriver {
|
||||
///
|
||||
/// The offset is expressed in logical pixels and can be translated to
|
||||
/// device pixels via [dart:ui.FlutterView.devicePixelRatio].
|
||||
Future<DriverOffset> getCenter(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<DriverOffset> getCenter(SerializableFinder finder, {Duration? timeout}) async {
|
||||
return _getOffset(finder, OffsetType.center, timeout: timeout);
|
||||
}
|
||||
|
||||
@@ -333,18 +340,20 @@ abstract class FlutterDriver {
|
||||
///
|
||||
/// * [getWidgetDiagnostics], which gets the [DiagnosticsNode] of a [Widget].
|
||||
Future<Map<String, Object?>> getRenderObjectDiagnostics(
|
||||
SerializableFinder finder, {
|
||||
int subtreeDepth = 0,
|
||||
bool includeProperties = true,
|
||||
Duration? timeout,
|
||||
SerializableFinder finder, {
|
||||
int subtreeDepth = 0,
|
||||
bool includeProperties = true,
|
||||
Duration? timeout,
|
||||
}) async {
|
||||
return sendCommand(GetDiagnosticsTree(
|
||||
finder,
|
||||
DiagnosticsType.renderObject,
|
||||
subtreeDepth: subtreeDepth,
|
||||
includeProperties: includeProperties,
|
||||
timeout: timeout,
|
||||
));
|
||||
return sendCommand(
|
||||
GetDiagnosticsTree(
|
||||
finder,
|
||||
DiagnosticsType.renderObject,
|
||||
subtreeDepth: subtreeDepth,
|
||||
includeProperties: includeProperties,
|
||||
timeout: timeout,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Returns a JSON map of the [DiagnosticsNode] that is associated with the
|
||||
@@ -371,13 +380,15 @@ abstract class FlutterDriver {
|
||||
bool includeProperties = true,
|
||||
Duration? timeout,
|
||||
}) async {
|
||||
return sendCommand(GetDiagnosticsTree(
|
||||
finder,
|
||||
DiagnosticsType.widget,
|
||||
subtreeDepth: subtreeDepth,
|
||||
includeProperties: includeProperties,
|
||||
timeout: timeout,
|
||||
));
|
||||
return sendCommand(
|
||||
GetDiagnosticsTree(
|
||||
finder,
|
||||
DiagnosticsType.widget,
|
||||
subtreeDepth: subtreeDepth,
|
||||
includeProperties: includeProperties,
|
||||
timeout: timeout,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/// Tell the driver to perform a scrolling action.
|
||||
@@ -393,7 +404,14 @@ abstract 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 {
|
||||
Future<void> scroll(
|
||||
SerializableFinder finder,
|
||||
double dx,
|
||||
double dy,
|
||||
Duration duration, {
|
||||
int frequency = 60,
|
||||
Duration? timeout,
|
||||
}) async {
|
||||
await sendCommand(Scroll(finder, dx, dy, duration, frequency, timeout: timeout));
|
||||
}
|
||||
|
||||
@@ -404,7 +422,11 @@ abstract class FlutterDriver {
|
||||
/// that lazily creates its children, like [ListView] or [CustomScrollView],
|
||||
/// 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 {
|
||||
Future<void> scrollIntoView(
|
||||
SerializableFinder finder, {
|
||||
double alignment = 0.0,
|
||||
Duration? timeout,
|
||||
}) async {
|
||||
await sendCommand(ScrollIntoView(finder, alignment: alignment, timeout: timeout));
|
||||
}
|
||||
|
||||
@@ -445,7 +467,9 @@ abstract class FlutterDriver {
|
||||
// the chance to complete if the item is already onscreen; if not, scroll
|
||||
// repeatedly until we either find the item or time out.
|
||||
bool isVisible = false;
|
||||
waitFor(item, timeout: timeout).then<void>((_) { isVisible = true; });
|
||||
waitFor(item, timeout: timeout).then<void>((_) {
|
||||
isVisible = true;
|
||||
});
|
||||
await Future<void>.delayed(const Duration(milliseconds: 500));
|
||||
while (!isVisible) {
|
||||
await scroll(scrollable, dxScroll, dyScroll, const Duration(milliseconds: 100));
|
||||
@@ -456,7 +480,7 @@ abstract class FlutterDriver {
|
||||
}
|
||||
|
||||
/// Returns the text in the `Text` widget located by [finder].
|
||||
Future<String> getText(SerializableFinder finder, { Duration? timeout }) async {
|
||||
Future<String> getText(SerializableFinder finder, {Duration? timeout}) async {
|
||||
return GetTextResult.fromJson(await sendCommand(GetText(finder, timeout: timeout))).text;
|
||||
}
|
||||
|
||||
@@ -492,7 +516,7 @@ abstract class FlutterDriver {
|
||||
/// await driver.waitFor(find.text('World!')); // verify new text appears
|
||||
/// });
|
||||
/// ```
|
||||
Future<void> enterText(String text, { Duration? timeout }) async {
|
||||
Future<void> enterText(String text, {Duration? timeout}) async {
|
||||
await sendCommand(EnterText(text, timeout: timeout));
|
||||
}
|
||||
|
||||
@@ -509,7 +533,7 @@ abstract class FlutterDriver {
|
||||
/// When enabled, the operating system's configured keyboard will not be
|
||||
/// invoked when the widget is focused, as the [SystemChannels.textInput]
|
||||
/// channel will be mocked out.
|
||||
Future<void> setTextEntryEmulation({ required bool enabled, Duration? timeout }) async {
|
||||
Future<void> setTextEntryEmulation({required bool enabled, Duration? timeout}) async {
|
||||
await sendCommand(SetTextEntryEmulation(enabled, timeout: timeout));
|
||||
}
|
||||
|
||||
@@ -535,8 +559,7 @@ abstract class FlutterDriver {
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
///
|
||||
Future<void> sendTextInputAction(TextInputAction action,
|
||||
{Duration? timeout}) async {
|
||||
Future<void> sendTextInputAction(TextInputAction action, {Duration? timeout}) async {
|
||||
await sendCommand(SendTextInputAction(action, timeout: timeout));
|
||||
}
|
||||
|
||||
@@ -546,8 +569,10 @@ abstract class FlutterDriver {
|
||||
/// It's expected that the application has registered a [DataHandler]
|
||||
/// callback in [enableFlutterDriverExtension] that can successfully handle
|
||||
/// these requests.
|
||||
Future<String> requestData(String? message, { Duration? timeout }) async {
|
||||
return RequestDataResult.fromJson(await sendCommand(RequestData(message, timeout: timeout))).message;
|
||||
Future<String> requestData(String? message, {Duration? timeout}) async {
|
||||
return RequestDataResult.fromJson(
|
||||
await sendCommand(RequestData(message, timeout: timeout)),
|
||||
).message;
|
||||
}
|
||||
|
||||
/// Turns semantics on or off in the Flutter app under test.
|
||||
@@ -561,8 +586,10 @@ abstract class FlutterDriver {
|
||||
///
|
||||
/// Enabling semantics on the web causes the engine to render ARIA-annotated
|
||||
/// HTML.
|
||||
Future<bool> setSemantics(bool enabled, { Duration? timeout }) async {
|
||||
final SetSemanticsResult result = SetSemanticsResult.fromJson(await sendCommand(SetSemantics(enabled, timeout: timeout)));
|
||||
Future<bool> setSemantics(bool enabled, {Duration? timeout}) async {
|
||||
final SetSemanticsResult result = SetSemanticsResult.fromJson(
|
||||
await sendCommand(SetSemantics(enabled, timeout: timeout)),
|
||||
);
|
||||
return result.changedState;
|
||||
}
|
||||
|
||||
@@ -574,8 +601,10 @@ abstract 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 {
|
||||
final Map<String, dynamic> jsonResponse = await sendCommand(GetSemanticsId(finder, timeout: timeout));
|
||||
Future<int> getSemanticsId(SerializableFinder finder, {Duration? timeout}) async {
|
||||
final Map<String, dynamic> jsonResponse = await sendCommand(
|
||||
GetSemanticsId(finder, timeout: timeout),
|
||||
);
|
||||
final GetSemanticsIdResult result = GetSemanticsIdResult.fromJson(jsonResponse);
|
||||
return result.id;
|
||||
}
|
||||
@@ -663,6 +692,7 @@ abstract class FlutterDriver {
|
||||
Future<List<Map<String, dynamic>>> getVmFlags() async {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
/// Starts recording performance traces.
|
||||
///
|
||||
/// The `timeout` argument causes a warning to be displayed to the user if the
|
||||
@@ -689,6 +719,7 @@ abstract class FlutterDriver {
|
||||
}) async {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
/// Runs [action] and outputs a performance trace for it.
|
||||
///
|
||||
/// Waits for the `Future` returned by [action] to complete prior to stopping
|
||||
@@ -723,11 +754,10 @@ abstract class FlutterDriver {
|
||||
/// operation.
|
||||
///
|
||||
/// For [WebFlutterDriver], this is only supported for Chrome.
|
||||
Future<void> clearTimeline({
|
||||
Duration timeout = kUnusuallyLongTimeout,
|
||||
}) async {
|
||||
Future<void> clearTimeline({Duration timeout = kUnusuallyLongTimeout}) async {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
/// [action] will be executed with the frame sync mechanism disabled.
|
||||
///
|
||||
/// By default, Flutter Driver waits until there is no pending frame scheduled
|
||||
@@ -744,7 +774,7 @@ abstract class FlutterDriver {
|
||||
/// With frame sync disabled, it's the responsibility of the test author to
|
||||
/// ensure that no action is performed while the app is undergoing a
|
||||
/// transition to avoid flakiness.
|
||||
Future<T> runUnsynchronized<T>(Future<T> Function() action, { Duration? timeout }) async {
|
||||
Future<T> runUnsynchronized<T>(Future<T> Function() action, {Duration? timeout}) async {
|
||||
await sendCommand(SetFrameSync(false, timeout: timeout));
|
||||
T result;
|
||||
try {
|
||||
@@ -821,7 +851,8 @@ class CommonFinders {
|
||||
required SerializableFinder matching,
|
||||
bool matchRoot = false,
|
||||
bool firstMatchOnly = false,
|
||||
}) => Descendant(of: of, matching: matching, matchRoot: matchRoot, firstMatchOnly: firstMatchOnly);
|
||||
}) =>
|
||||
Descendant(of: of, matching: matching, matchRoot: matchRoot, firstMatchOnly: firstMatchOnly);
|
||||
}
|
||||
|
||||
/// An immutable 2D floating-point offset used by Flutter Driver.
|
||||
@@ -841,9 +872,7 @@ class DriverOffset {
|
||||
|
||||
@override
|
||||
bool operator ==(Object other) {
|
||||
return other is DriverOffset
|
||||
&& other.dx == dx
|
||||
&& other.dy == dy;
|
||||
return other is DriverOffset && other.dx == dx && other.dy == dy;
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -21,8 +21,7 @@ class FrameRequestPendingLatencySummarizer {
|
||||
|
||||
/// Computes the average `FrameRequestPendingLatency` over the period of the timeline.
|
||||
double computeAverageFrameRequestPendingLatency() {
|
||||
final List<double> frameRequestPendingLatencies =
|
||||
_computeFrameRequestPendingLatencies();
|
||||
final List<double> frameRequestPendingLatencies = _computeFrameRequestPendingLatencies();
|
||||
if (frameRequestPendingLatencies.isEmpty) {
|
||||
return 0;
|
||||
}
|
||||
@@ -34,8 +33,7 @@ class FrameRequestPendingLatencySummarizer {
|
||||
/// Computes the [percentile]-th percentile `FrameRequestPendingLatency` over the
|
||||
/// period of the timeline.
|
||||
double computePercentileFrameRequestPendingLatency(double percentile) {
|
||||
final List<double> frameRequestPendingLatencies =
|
||||
_computeFrameRequestPendingLatencies();
|
||||
final List<double> frameRequestPendingLatencies = _computeFrameRequestPendingLatencies();
|
||||
if (frameRequestPendingLatencies.isEmpty) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -42,8 +42,10 @@ class GCSummarizer {
|
||||
lastGCBeginEvent = event;
|
||||
} else if (lastGCBeginEvent != null) {
|
||||
// These events must not overlap.
|
||||
assert(event.name == lastGCBeginEvent.name,
|
||||
'Expected "${lastGCBeginEvent.name}" got "${event.name}"');
|
||||
assert(
|
||||
event.name == lastGCBeginEvent.name,
|
||||
'Expected "${lastGCBeginEvent.name}" got "${event.name}"',
|
||||
);
|
||||
final double st = lastGCBeginEvent.timestampMicros!.toDouble();
|
||||
final double end = event.timestampMicros!.toDouble();
|
||||
lastGCBeginEvent = null;
|
||||
|
||||
@@ -9,11 +9,7 @@ import 'timeline.dart';
|
||||
///
|
||||
/// We do not use a profiling category for these as all the dart timeline events
|
||||
/// have the same profiling category "embedder".
|
||||
const Set<String> kProfilingEvents = <String>{
|
||||
_kCpuProfile,
|
||||
_kGpuProfile,
|
||||
_kMemoryProfile,
|
||||
};
|
||||
const Set<String> kProfilingEvents = <String>{_kCpuProfile, _kGpuProfile, _kMemoryProfile};
|
||||
|
||||
// These field names need to be in-sync with:
|
||||
// https://github.com/flutter/engine/blob/main/shell/profiling/sampling_profiler.cc
|
||||
@@ -55,8 +51,7 @@ class ProfilingSummarizer {
|
||||
|
||||
/// Creates a ProfilingSummarizer given the timeline events.
|
||||
static ProfilingSummarizer fromEvents(List<TimelineEvent> profilingEvents) {
|
||||
final Map<ProfileType, List<TimelineEvent>> eventsByType =
|
||||
<ProfileType, List<TimelineEvent>>{};
|
||||
final Map<ProfileType, List<TimelineEvent>> eventsByType = <ProfileType, List<TimelineEvent>>{};
|
||||
for (final TimelineEvent event in profilingEvents) {
|
||||
assert(kProfilingEvents.contains(event.name));
|
||||
final ProfileType type = _getProfileType(event.name);
|
||||
@@ -114,16 +109,15 @@ class ProfilingSummarizer {
|
||||
double computePercentile(ProfileType profileType, double percentile) {
|
||||
final List<TimelineEvent> events = eventByType[profileType]!;
|
||||
assert(events.isNotEmpty);
|
||||
final List<double> doubles = events
|
||||
.map((TimelineEvent e) => _getProfileValue(profileType, e))
|
||||
.toList();
|
||||
final List<double> doubles =
|
||||
events.map((TimelineEvent e) => _getProfileValue(profileType, e)).toList();
|
||||
return findPercentile(doubles, percentile);
|
||||
}
|
||||
|
||||
static ProfileType _getProfileType(String? eventName) {
|
||||
return switch (eventName) {
|
||||
_kCpuProfile => ProfileType.CPU,
|
||||
_kGpuProfile => ProfileType.GPU,
|
||||
_kCpuProfile => ProfileType.CPU,
|
||||
_kGpuProfile => ProfileType.GPU,
|
||||
_kMemoryProfile => ProfileType.Memory,
|
||||
_ => throw Exception('Invalid profiling event: $eventName.'),
|
||||
};
|
||||
@@ -137,8 +131,7 @@ class ProfilingSummarizer {
|
||||
return _getArgValue('gpu_usage', e);
|
||||
case ProfileType.Memory:
|
||||
final double dirtyMem = _getArgValue('dirty_memory_usage', e);
|
||||
final double ownedSharedMem =
|
||||
_getArgValue('owned_shared_memory_usage', e);
|
||||
final double ownedSharedMem = _getArgValue('owned_shared_memory_usage', e);
|
||||
return dirtyMem + ownedSharedMem;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,16 +58,20 @@ class RasterCacheSummarizer {
|
||||
double computeAveragePictureMemory() => _computeAverage(_pictureMemories);
|
||||
|
||||
/// The [percentile]-th percentile `LayerCount` over the cache events.
|
||||
double computePercentileLayerCount(double percentile) => _computePercentile(_layerCounts, percentile);
|
||||
double computePercentileLayerCount(double percentile) =>
|
||||
_computePercentile(_layerCounts, percentile);
|
||||
|
||||
/// The [percentile]-th percentile `LayerMemory` over the cache events.
|
||||
double computePercentileLayerMemory(double percentile) => _computePercentile(_layerMemories, percentile);
|
||||
double computePercentileLayerMemory(double percentile) =>
|
||||
_computePercentile(_layerMemories, percentile);
|
||||
|
||||
/// The [percentile]-th percentile `PictureCount` over the cache events.
|
||||
double computePercentilePictureCount(double percentile) => _computePercentile(_pictureCounts, percentile);
|
||||
double computePercentilePictureCount(double percentile) =>
|
||||
_computePercentile(_pictureCounts, percentile);
|
||||
|
||||
/// The [percentile]-th percentile `PictureMemory` over the cache events.
|
||||
double computePercentilePictureMemory(double percentile) => _computePercentile(_pictureMemories, percentile);
|
||||
double computePercentilePictureMemory(double percentile) =>
|
||||
_computePercentile(_pictureMemories, percentile);
|
||||
|
||||
/// Computes the worst of the `LayerCount` values over the cache events.
|
||||
double computeWorstLayerCount() => _computeWorst(_layerCounts);
|
||||
|
||||
@@ -38,13 +38,15 @@ class RefreshRateSummary {
|
||||
}
|
||||
_framesWithIllegalRefreshRate.add(refreshRate);
|
||||
}
|
||||
assert(_numberOfTotalFrames ==
|
||||
_numberOf30HzFrames +
|
||||
_numberOf60HzFrames +
|
||||
_numberOf80HzFrames +
|
||||
_numberOf90HzFrames +
|
||||
_numberOf120HzFrames +
|
||||
_framesWithIllegalRefreshRate.length);
|
||||
assert(
|
||||
_numberOfTotalFrames ==
|
||||
_numberOf30HzFrames +
|
||||
_numberOf60HzFrames +
|
||||
_numberOf80HzFrames +
|
||||
_numberOf90HzFrames +
|
||||
_numberOf120HzFrames +
|
||||
_framesWithIllegalRefreshRate.length,
|
||||
);
|
||||
}
|
||||
|
||||
// The error margin to determine the frame refresh rate.
|
||||
@@ -56,48 +58,42 @@ class RefreshRateSummary {
|
||||
///
|
||||
/// For example, if this value is 20, it means there are 20 percent of total
|
||||
/// frames are 30hz. 0 means no frames are 30hz, 100 means all frames are 30hz.
|
||||
double get percentageOf30HzFrames => _numberOfTotalFrames > 0
|
||||
? _numberOf30HzFrames / _numberOfTotalFrames * 100
|
||||
: 0;
|
||||
double get percentageOf30HzFrames =>
|
||||
_numberOfTotalFrames > 0 ? _numberOf30HzFrames / _numberOfTotalFrames * 100 : 0;
|
||||
|
||||
/// The percentage of 60hz frames.
|
||||
///
|
||||
/// For example, if this value is 20, it means there are 20 percent of total
|
||||
/// frames are 60hz. 0 means no frames are 60hz, 100 means all frames are 60hz.
|
||||
double get percentageOf60HzFrames => _numberOfTotalFrames > 0
|
||||
? _numberOf60HzFrames / _numberOfTotalFrames * 100
|
||||
: 0;
|
||||
double get percentageOf60HzFrames =>
|
||||
_numberOfTotalFrames > 0 ? _numberOf60HzFrames / _numberOfTotalFrames * 100 : 0;
|
||||
|
||||
/// The percentage of 80hz frames.
|
||||
///
|
||||
/// For example, if this value is 20, it means there are 20 percent of total
|
||||
/// frames are 80hz. 0 means no frames are 80hz, 100 means all frames are 80hz.
|
||||
double get percentageOf80HzFrames => _numberOfTotalFrames > 0
|
||||
? _numberOf80HzFrames / _numberOfTotalFrames * 100
|
||||
: 0;
|
||||
double get percentageOf80HzFrames =>
|
||||
_numberOfTotalFrames > 0 ? _numberOf80HzFrames / _numberOfTotalFrames * 100 : 0;
|
||||
|
||||
/// The percentage of 90hz frames.
|
||||
///
|
||||
/// For example, if this value is 20, it means there are 20 percent of total
|
||||
/// frames are 90hz. 0 means no frames are 90hz, 100 means all frames are 90hz.
|
||||
double get percentageOf90HzFrames => _numberOfTotalFrames > 0
|
||||
? _numberOf90HzFrames / _numberOfTotalFrames * 100
|
||||
: 0;
|
||||
double get percentageOf90HzFrames =>
|
||||
_numberOfTotalFrames > 0 ? _numberOf90HzFrames / _numberOfTotalFrames * 100 : 0;
|
||||
|
||||
/// The percentage of 120hz frames.
|
||||
///
|
||||
/// For example, if this value is 20, it means there are 20 percent of total
|
||||
/// frames are 120hz. 0 means no frames are 120hz, 100 means all frames are 120hz.
|
||||
double get percentageOf120HzFrames => _numberOfTotalFrames > 0
|
||||
? _numberOf120HzFrames / _numberOfTotalFrames * 100
|
||||
: 0;
|
||||
double get percentageOf120HzFrames =>
|
||||
_numberOfTotalFrames > 0 ? _numberOf120HzFrames / _numberOfTotalFrames * 100 : 0;
|
||||
|
||||
/// A list of all the frames with Illegal refresh rate.
|
||||
///
|
||||
/// A refresh rate is consider illegal if it does not belong to anyone of the refresh rate this class is
|
||||
/// explicitly tracking.
|
||||
List<double> get framesWithIllegalRefreshRate =>
|
||||
_framesWithIllegalRefreshRate;
|
||||
List<double> get framesWithIllegalRefreshRate => _framesWithIllegalRefreshRate;
|
||||
|
||||
int _numberOf30HzFrames = 0;
|
||||
int _numberOf60HzFrames = 0;
|
||||
@@ -122,8 +118,7 @@ class RefreshRateSummary {
|
||||
final int startTimeInNanoseconds = int.parse(arguments['StartTime'] as String);
|
||||
final int targetTimeInNanoseconds = int.parse(arguments['TargetTime'] as String);
|
||||
final int frameDurationInNanoseconds = targetTimeInNanoseconds - startTimeInNanoseconds;
|
||||
final double refreshRate = nanosecondsPerSecond /
|
||||
frameDurationInNanoseconds;
|
||||
final double refreshRate = nanosecondsPerSecond / frameDurationInNanoseconds;
|
||||
result.add(refreshRate);
|
||||
}
|
||||
return result;
|
||||
|
||||
@@ -59,8 +59,7 @@ class SceneDisplayLagSummarizer {
|
||||
return 0;
|
||||
}
|
||||
|
||||
final List<double> doubles =
|
||||
sceneDisplayLagEvents.map(_getVsyncTransitionsMissed).toList();
|
||||
final List<double> doubles = sceneDisplayLagEvents.map(_getVsyncTransitionsMissed).toList();
|
||||
return findPercentile(doubles, percentile);
|
||||
}
|
||||
|
||||
|
||||
@@ -28,20 +28,16 @@ class Timeline {
|
||||
class TimelineEvent {
|
||||
/// Creates a timeline event given JSON-encoded event data.
|
||||
TimelineEvent(this.json)
|
||||
: name = json['name'] as String?,
|
||||
category = json['cat'] as String?,
|
||||
phase = json['ph'] as String?,
|
||||
processId = json['pid'] as int?,
|
||||
threadId = json['tid'] as int?,
|
||||
duration = json['dur'] != null
|
||||
? Duration(microseconds: json['dur'] as int)
|
||||
: null,
|
||||
threadDuration = json['tdur'] != null
|
||||
? Duration(microseconds: json['tdur'] as int)
|
||||
: null,
|
||||
timestampMicros = json['ts'] as int?,
|
||||
threadTimestampMicros = json['tts'] as int?,
|
||||
arguments = json['args'] as Map<String, dynamic>?;
|
||||
: name = json['name'] as String?,
|
||||
category = json['cat'] as String?,
|
||||
phase = json['ph'] as String?,
|
||||
processId = json['pid'] as int?,
|
||||
threadId = json['tid'] as int?,
|
||||
duration = json['dur'] != null ? Duration(microseconds: json['dur'] as int) : null,
|
||||
threadDuration = json['tdur'] != null ? Duration(microseconds: json['tdur'] as int) : null,
|
||||
timestampMicros = json['ts'] as int?,
|
||||
threadTimestampMicros = json['tts'] as int?,
|
||||
arguments = json['args'] as Map<String, dynamic>?;
|
||||
|
||||
/// The original event JSON.
|
||||
final Map<String, dynamic> json;
|
||||
@@ -111,17 +107,17 @@ List<TimelineEvent>? _parseEvents(Map<String, dynamic> json) {
|
||||
return null;
|
||||
}
|
||||
|
||||
final List<TimelineEvent> timelineEvents = jsonEvents
|
||||
.cast<Map<String, dynamic>>()
|
||||
.map<TimelineEvent>(
|
||||
(Map<String, dynamic> eventJson) => TimelineEvent(eventJson))
|
||||
.toList();
|
||||
final List<TimelineEvent> timelineEvents =
|
||||
jsonEvents
|
||||
.cast<Map<String, dynamic>>()
|
||||
.map<TimelineEvent>((Map<String, dynamic> eventJson) => TimelineEvent(eventJson))
|
||||
.toList();
|
||||
|
||||
timelineEvents.sort((TimelineEvent e1, TimelineEvent e2) {
|
||||
return switch ((e1.timestampMicros, e2.timestampMicros)) {
|
||||
(null, null) => 0,
|
||||
(_, null) => 1,
|
||||
(null, _) => -1,
|
||||
(null, null) => 0,
|
||||
(_, null) => 1,
|
||||
(null, _) => -1,
|
||||
(final int ts1, final int ts2) => ts1.compareTo(ts2),
|
||||
};
|
||||
});
|
||||
|
||||
@@ -82,9 +82,7 @@ class TimelineSummary {
|
||||
/// This does not take into account the real device frame rate. Prefer using
|
||||
/// [computePercentileFrameBuildTimeMillis] for evaluating performance.
|
||||
int computeMissedFrameBuildBudgetCount() {
|
||||
return _extractFrameDurations()
|
||||
.where((Duration duration) => duration > kBuildBudget)
|
||||
.length;
|
||||
return _extractFrameDurations().where((Duration duration) => duration > kBuildBudget).length;
|
||||
}
|
||||
|
||||
/// Average amount of time spent per frame in the engine rasterizer.
|
||||
@@ -275,8 +273,11 @@ class TimelineSummary {
|
||||
final Map<String, dynamic> profilingSummary = _profilingSummarizer().summarize();
|
||||
final RasterCacheSummarizer rasterCacheSummarizer = _rasterCacheSummarizer();
|
||||
final GCSummarizer gcSummarizer = _gcSummarizer();
|
||||
final RefreshRateSummary refreshRateSummary = RefreshRateSummary(vsyncEvents: _extractNamedEvents(kUIThreadVsyncProcessEvent));
|
||||
final FrameRequestPendingLatencySummarizer frameRequestPendingLatencySummarizer = _frameRequestPendingLatencySummarizer();
|
||||
final RefreshRateSummary refreshRateSummary = RefreshRateSummary(
|
||||
vsyncEvents: _extractNamedEvents(kUIThreadVsyncProcessEvent),
|
||||
);
|
||||
final FrameRequestPendingLatencySummarizer frameRequestPendingLatencySummarizer =
|
||||
_frameRequestPendingLatencySummarizer();
|
||||
final GpuSumarizer gpuSummarizer = _gpuSumarizer();
|
||||
final GPUMemorySumarizer memorySumarizer = _memorySummarizer();
|
||||
|
||||
@@ -288,50 +289,80 @@ class TimelineSummary {
|
||||
'missed_frame_build_budget_count': computeMissedFrameBuildBudgetCount(),
|
||||
'average_frame_rasterizer_time_millis': computeAverageFrameRasterizerTimeMillis(),
|
||||
'stddev_frame_rasterizer_time_millis': computeStandardDeviationFrameRasterizerTimeMillis(),
|
||||
'90th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(90.0),
|
||||
'99th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(99.0),
|
||||
'90th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(
|
||||
90.0,
|
||||
),
|
||||
'99th_percentile_frame_rasterizer_time_millis': computePercentileFrameRasterizerTimeMillis(
|
||||
99.0,
|
||||
),
|
||||
'worst_frame_rasterizer_time_millis': computeWorstFrameRasterizerTimeMillis(),
|
||||
'missed_frame_rasterizer_budget_count': computeMissedFrameRasterizerBudgetCount(),
|
||||
'frame_count': countFrames(),
|
||||
'frame_rasterizer_count': countRasterizations(),
|
||||
'new_gen_gc_count': newGenerationGarbageCollections(),
|
||||
'old_gen_gc_count': oldGenerationGarbageCollections(),
|
||||
'frame_build_times': _extractFrameDurations()
|
||||
.map<int>((Duration duration) => duration.inMicroseconds)
|
||||
.toList(),
|
||||
'frame_rasterizer_times': _extractGpuRasterizerDrawDurations()
|
||||
.map<int>((Duration duration) => duration.inMicroseconds)
|
||||
.toList(),
|
||||
'frame_begin_times': _extractBeginTimestamps(kBuildFrameEventName)
|
||||
.map<int>((Duration duration) => duration.inMicroseconds)
|
||||
.toList(),
|
||||
'frame_rasterizer_begin_times': _extractBeginTimestamps(kRasterizeFrameEventName)
|
||||
.map<int>((Duration duration) => duration.inMicroseconds)
|
||||
.toList(),
|
||||
'average_vsync_transitions_missed': sceneDisplayLagSummarizer.computeAverageVsyncTransitionsMissed(),
|
||||
'90th_percentile_vsync_transitions_missed': sceneDisplayLagSummarizer.computePercentileVsyncTransitionsMissed(90.0),
|
||||
'99th_percentile_vsync_transitions_missed': sceneDisplayLagSummarizer.computePercentileVsyncTransitionsMissed(99.0),
|
||||
'frame_build_times':
|
||||
_extractFrameDurations()
|
||||
.map<int>((Duration duration) => duration.inMicroseconds)
|
||||
.toList(),
|
||||
'frame_rasterizer_times':
|
||||
_extractGpuRasterizerDrawDurations()
|
||||
.map<int>((Duration duration) => duration.inMicroseconds)
|
||||
.toList(),
|
||||
'frame_begin_times':
|
||||
_extractBeginTimestamps(
|
||||
kBuildFrameEventName,
|
||||
).map<int>((Duration duration) => duration.inMicroseconds).toList(),
|
||||
'frame_rasterizer_begin_times':
|
||||
_extractBeginTimestamps(
|
||||
kRasterizeFrameEventName,
|
||||
).map<int>((Duration duration) => duration.inMicroseconds).toList(),
|
||||
'average_vsync_transitions_missed':
|
||||
sceneDisplayLagSummarizer.computeAverageVsyncTransitionsMissed(),
|
||||
'90th_percentile_vsync_transitions_missed': sceneDisplayLagSummarizer
|
||||
.computePercentileVsyncTransitionsMissed(90.0),
|
||||
'99th_percentile_vsync_transitions_missed': sceneDisplayLagSummarizer
|
||||
.computePercentileVsyncTransitionsMissed(99.0),
|
||||
'average_vsync_frame_lag': vsyncFrameLagSummarizer.computeAverageVsyncFrameLag(),
|
||||
'90th_percentile_vsync_frame_lag': vsyncFrameLagSummarizer.computePercentileVsyncFrameLag(90.0),
|
||||
'99th_percentile_vsync_frame_lag': vsyncFrameLagSummarizer.computePercentileVsyncFrameLag(99.0),
|
||||
'90th_percentile_vsync_frame_lag': vsyncFrameLagSummarizer.computePercentileVsyncFrameLag(
|
||||
90.0,
|
||||
),
|
||||
'99th_percentile_vsync_frame_lag': vsyncFrameLagSummarizer.computePercentileVsyncFrameLag(
|
||||
99.0,
|
||||
),
|
||||
'average_layer_cache_count': rasterCacheSummarizer.computeAverageLayerCount(),
|
||||
'90th_percentile_layer_cache_count': rasterCacheSummarizer.computePercentileLayerCount(90.0),
|
||||
'99th_percentile_layer_cache_count': rasterCacheSummarizer.computePercentileLayerCount(99.0),
|
||||
'average_frame_request_pending_latency': frameRequestPendingLatencySummarizer.computeAverageFrameRequestPendingLatency(),
|
||||
'90th_percentile_frame_request_pending_latency': frameRequestPendingLatencySummarizer.computePercentileFrameRequestPendingLatency(90.0),
|
||||
'99th_percentile_frame_request_pending_latency': frameRequestPendingLatencySummarizer.computePercentileFrameRequestPendingLatency(99.0),
|
||||
'average_frame_request_pending_latency':
|
||||
frameRequestPendingLatencySummarizer.computeAverageFrameRequestPendingLatency(),
|
||||
'90th_percentile_frame_request_pending_latency': frameRequestPendingLatencySummarizer
|
||||
.computePercentileFrameRequestPendingLatency(90.0),
|
||||
'99th_percentile_frame_request_pending_latency': frameRequestPendingLatencySummarizer
|
||||
.computePercentileFrameRequestPendingLatency(99.0),
|
||||
'worst_layer_cache_count': rasterCacheSummarizer.computeWorstLayerCount(),
|
||||
'average_layer_cache_memory': rasterCacheSummarizer.computeAverageLayerMemory(),
|
||||
'90th_percentile_layer_cache_memory': rasterCacheSummarizer.computePercentileLayerMemory(90.0),
|
||||
'99th_percentile_layer_cache_memory': rasterCacheSummarizer.computePercentileLayerMemory(99.0),
|
||||
'90th_percentile_layer_cache_memory': rasterCacheSummarizer.computePercentileLayerMemory(
|
||||
90.0,
|
||||
),
|
||||
'99th_percentile_layer_cache_memory': rasterCacheSummarizer.computePercentileLayerMemory(
|
||||
99.0,
|
||||
),
|
||||
'worst_layer_cache_memory': rasterCacheSummarizer.computeWorstLayerMemory(),
|
||||
'average_picture_cache_count': rasterCacheSummarizer.computeAveragePictureCount(),
|
||||
'90th_percentile_picture_cache_count': rasterCacheSummarizer.computePercentilePictureCount(90.0),
|
||||
'99th_percentile_picture_cache_count': rasterCacheSummarizer.computePercentilePictureCount(99.0),
|
||||
'90th_percentile_picture_cache_count': rasterCacheSummarizer.computePercentilePictureCount(
|
||||
90.0,
|
||||
),
|
||||
'99th_percentile_picture_cache_count': rasterCacheSummarizer.computePercentilePictureCount(
|
||||
99.0,
|
||||
),
|
||||
'worst_picture_cache_count': rasterCacheSummarizer.computeWorstPictureCount(),
|
||||
'average_picture_cache_memory': rasterCacheSummarizer.computeAveragePictureMemory(),
|
||||
'90th_percentile_picture_cache_memory': rasterCacheSummarizer.computePercentilePictureMemory(90.0),
|
||||
'99th_percentile_picture_cache_memory': rasterCacheSummarizer.computePercentilePictureMemory(99.0),
|
||||
'90th_percentile_picture_cache_memory': rasterCacheSummarizer.computePercentilePictureMemory(
|
||||
90.0,
|
||||
),
|
||||
'99th_percentile_picture_cache_memory': rasterCacheSummarizer.computePercentilePictureMemory(
|
||||
99.0,
|
||||
),
|
||||
'worst_picture_cache_memory': rasterCacheSummarizer.computeWorstPictureMemory(),
|
||||
'total_ui_gc_time': gcSummarizer.totalGCTimeMillis,
|
||||
'30hz_frame_percentage': refreshRateSummary.percentageOf30HzFrames,
|
||||
@@ -375,7 +406,11 @@ class TimelineSummary {
|
||||
await file.writeAsString(_encodeJson(_timeline.json, pretty));
|
||||
|
||||
if (includeSummary) {
|
||||
await _writeSummaryToFile(traceName, destinationDirectory: destinationDirectory, pretty: pretty);
|
||||
await _writeSummaryToFile(
|
||||
traceName,
|
||||
destinationDirectory: destinationDirectory,
|
||||
pretty: pretty,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -390,21 +425,15 @@ class TimelineSummary {
|
||||
}
|
||||
|
||||
String _encodeJson(Map<String, dynamic> jsonObject, bool pretty) {
|
||||
return pretty
|
||||
? _prettyEncoder.convert(jsonObject)
|
||||
: json.encode(jsonObject);
|
||||
return pretty ? _prettyEncoder.convert(jsonObject) : json.encode(jsonObject);
|
||||
}
|
||||
|
||||
List<TimelineEvent> _extractNamedEvents(String name) {
|
||||
return _timeline.events!
|
||||
.where((TimelineEvent event) => event.name == name)
|
||||
.toList();
|
||||
return _timeline.events!.where((TimelineEvent event) => event.name == name).toList();
|
||||
}
|
||||
|
||||
List<TimelineEvent> _extractEventsWithNames(Set<String> names) {
|
||||
return _timeline.events!
|
||||
.where((TimelineEvent event) => names.contains(event.name))
|
||||
.toList();
|
||||
return _timeline.events!.where((TimelineEvent event) => names.contains(event.name)).toList();
|
||||
}
|
||||
|
||||
List<Duration> _extractDurations(
|
||||
@@ -441,21 +470,18 @@ class TimelineSummary {
|
||||
/// See [SceneDisplayLagSummarizer].
|
||||
/// See: https://docs.google.com/document/d/1CvAClvFfyA5R-PhYUmn5OOQtYMH4h6I0nSsKchNAySU
|
||||
List<Duration> _extractBeginEndEvents(String name) {
|
||||
return _extractDurations(
|
||||
name,
|
||||
(TimelineEvent beginEvent, TimelineEvent endEvent) {
|
||||
return Duration(microseconds: endEvent.timestampMicros! - beginEvent.timestampMicros!);
|
||||
},
|
||||
);
|
||||
return _extractDurations(name, (TimelineEvent beginEvent, TimelineEvent endEvent) {
|
||||
return Duration(microseconds: endEvent.timestampMicros! - beginEvent.timestampMicros!);
|
||||
});
|
||||
}
|
||||
|
||||
List<Duration> _extractBeginTimestamps(String name) {
|
||||
final List<Duration> result = _extractDurations(
|
||||
name,
|
||||
(TimelineEvent beginEvent, TimelineEvent endEvent) {
|
||||
return Duration(microseconds: beginEvent.timestampMicros!);
|
||||
},
|
||||
);
|
||||
final List<Duration> result = _extractDurations(name, (
|
||||
TimelineEvent beginEvent,
|
||||
TimelineEvent endEvent,
|
||||
) {
|
||||
return Duration(microseconds: beginEvent.timestampMicros!);
|
||||
});
|
||||
|
||||
// Align timestamps so the first event is at 0.
|
||||
for (int i = result.length - 1; i >= 0; i -= 1) {
|
||||
@@ -468,7 +494,10 @@ class TimelineSummary {
|
||||
if (durations.isEmpty) {
|
||||
throw StateError(_kEmptyDurationMessage);
|
||||
}
|
||||
final double total = durations.fold<double>(0.0, (double t, Duration duration) => t + duration.inMicroseconds.toDouble() / 1000.0);
|
||||
final double total = durations.fold<double>(
|
||||
0.0,
|
||||
(double t, Duration duration) => t + duration.inMicroseconds.toDouble() / 1000.0,
|
||||
);
|
||||
return total / durations.length;
|
||||
}
|
||||
|
||||
@@ -477,7 +506,10 @@ class TimelineSummary {
|
||||
throw StateError(_kEmptyDurationMessage);
|
||||
}
|
||||
assert(percentile >= 0.0 && percentile <= 100.0);
|
||||
final List<double> doubles = durations.map<double>((Duration duration) => duration.inMicroseconds.toDouble() / 1000.0).toList();
|
||||
final List<double> doubles =
|
||||
durations
|
||||
.map<double>((Duration duration) => duration.inMicroseconds.toDouble() / 1000.0)
|
||||
.toList();
|
||||
return findPercentile(doubles, percentile);
|
||||
}
|
||||
|
||||
@@ -490,23 +522,30 @@ class TimelineSummary {
|
||||
.reduce(math.max);
|
||||
}
|
||||
|
||||
SceneDisplayLagSummarizer _sceneDisplayLagSummarizer() => SceneDisplayLagSummarizer(_extractNamedEvents(kSceneDisplayLagEvent));
|
||||
SceneDisplayLagSummarizer _sceneDisplayLagSummarizer() =>
|
||||
SceneDisplayLagSummarizer(_extractNamedEvents(kSceneDisplayLagEvent));
|
||||
|
||||
List<Duration> _extractGpuRasterizerDrawDurations() => _extractBeginEndEvents(kRasterizeFrameEventName);
|
||||
List<Duration> _extractGpuRasterizerDrawDurations() =>
|
||||
_extractBeginEndEvents(kRasterizeFrameEventName);
|
||||
|
||||
ProfilingSummarizer _profilingSummarizer() => ProfilingSummarizer.fromEvents(_extractEventsWithNames(kProfilingEvents));
|
||||
ProfilingSummarizer _profilingSummarizer() =>
|
||||
ProfilingSummarizer.fromEvents(_extractEventsWithNames(kProfilingEvents));
|
||||
|
||||
List<Duration> _extractFrameDurations() => _extractBeginEndEvents(kBuildFrameEventName);
|
||||
|
||||
VsyncFrameLagSummarizer _vsyncFrameLagSummarizer() => VsyncFrameLagSummarizer(_extractEventsWithNames(kVsyncTimelineEventNames));
|
||||
VsyncFrameLagSummarizer _vsyncFrameLagSummarizer() =>
|
||||
VsyncFrameLagSummarizer(_extractEventsWithNames(kVsyncTimelineEventNames));
|
||||
|
||||
RasterCacheSummarizer _rasterCacheSummarizer() => RasterCacheSummarizer(_extractNamedEvents(kRasterCacheEvent));
|
||||
RasterCacheSummarizer _rasterCacheSummarizer() =>
|
||||
RasterCacheSummarizer(_extractNamedEvents(kRasterCacheEvent));
|
||||
|
||||
FrameRequestPendingLatencySummarizer _frameRequestPendingLatencySummarizer() => FrameRequestPendingLatencySummarizer(_extractNamedEvents(kFrameRequestPendingEvent));
|
||||
FrameRequestPendingLatencySummarizer _frameRequestPendingLatencySummarizer() =>
|
||||
FrameRequestPendingLatencySummarizer(_extractNamedEvents(kFrameRequestPendingEvent));
|
||||
|
||||
GCSummarizer _gcSummarizer() => GCSummarizer.fromEvents(_extractEventsWithNames(kGCRootEvents));
|
||||
|
||||
GpuSumarizer _gpuSumarizer() => GpuSumarizer(_extractEventsWithNames(GpuSumarizer.kGpuEvents));
|
||||
|
||||
GPUMemorySumarizer _memorySummarizer() => GPUMemorySumarizer(_extractEventsWithNames(GPUMemorySumarizer.kMemoryEvents));
|
||||
GPUMemorySumarizer _memorySummarizer() =>
|
||||
GPUMemorySumarizer(_extractEventsWithNames(GPUMemorySumarizer.kMemoryEvents));
|
||||
}
|
||||
|
||||
@@ -23,14 +23,13 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
VMServiceFlutterDriver.connectedTo(
|
||||
this._serviceClient,
|
||||
this._appIsolate, {
|
||||
bool printCommunication = false,
|
||||
bool logCommunicationToFile = true,
|
||||
}) : _printCommunication = printCommunication,
|
||||
_logCommunicationToFile = logCommunicationToFile,
|
||||
_driverId = _nextDriverId++
|
||||
{
|
||||
_logFilePathName = p.join(testOutputsDirectory, 'flutter_driver_commands_$_driverId.log');
|
||||
}
|
||||
bool printCommunication = false,
|
||||
bool logCommunicationToFile = true,
|
||||
}) : _printCommunication = printCommunication,
|
||||
_logCommunicationToFile = logCommunicationToFile,
|
||||
_driverId = _nextDriverId++ {
|
||||
_logFilePathName = p.join(testOutputsDirectory, 'flutter_driver_commands_$_driverId.log');
|
||||
}
|
||||
|
||||
/// Connects to a Flutter application.
|
||||
///
|
||||
@@ -57,13 +56,15 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
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.'
|
||||
'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 List<fuchsia.IsolateRef> refs = await fuchsiaConnection.getMainIsolatesByPattern(
|
||||
fuchsiaModuleTarget,
|
||||
);
|
||||
if (refs.isEmpty) {
|
||||
throw DriverError('Failed to get any isolate refs!');
|
||||
}
|
||||
@@ -78,9 +79,9 @@ class VMServiceFlutterDriver extends 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 '
|
||||
'URL should be provided to the FlutterDriver.connect() method.',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -96,9 +97,7 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
await Future<void>.delayed(_kPauseBetweenReconnectAttempts);
|
||||
continue;
|
||||
}
|
||||
return isolateNumber == null
|
||||
? vm.isolates!.first
|
||||
: vm.isolates!.firstWhere(checkIsolate);
|
||||
return isolateNumber == null ? vm.isolates!.first : vm.isolates!.firstWhere(checkIsolate);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,18 +116,21 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
}
|
||||
}
|
||||
|
||||
final vms.IsolateRef isolateRef = (await _warnIfSlow<vms.IsolateRef?>(
|
||||
future: waitForRootIsolate(),
|
||||
timeout: kUnusuallyLongTimeout,
|
||||
message: isolateNumber == null
|
||||
? 'The root isolate is taking an unusually long time to start.'
|
||||
: 'Isolate $isolateNumber is taking an unusually long time to start.',
|
||||
))!;
|
||||
final vms.IsolateRef isolateRef =
|
||||
(await _warnIfSlow<vms.IsolateRef?>(
|
||||
future: waitForRootIsolate(),
|
||||
timeout: kUnusuallyLongTimeout,
|
||||
message:
|
||||
isolateNumber == null
|
||||
? 'The root isolate is taking an unusually long time to start.'
|
||||
: 'Isolate $isolateNumber is taking an unusually long time to start.',
|
||||
))!;
|
||||
_log('Isolate found with number: ${isolateRef.number}');
|
||||
final vms.Isolate isolate = await _warnIfSlow<vms.Isolate>(
|
||||
future: waitForIsolateToBeRunnable(isolateRef),
|
||||
timeout: kUnusuallyLongTimeout,
|
||||
message: 'The isolate ${isolateRef.number} is taking unusually long time '
|
||||
message:
|
||||
'The isolate ${isolateRef.number} is taking unusually long time '
|
||||
'to initialize. It still reports ${vms.EventKind.kNone} as pause '
|
||||
'event which is incorrect.',
|
||||
);
|
||||
@@ -160,9 +162,9 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
if (e is vms.RPCError && e.code == vmMustBePausedCode) {
|
||||
// No biggie; something else must have resumed the isolate
|
||||
_log(
|
||||
'Attempted to resume an already resumed isolate. This may happen '
|
||||
'when another tool (usually a debugger) resumed the isolate '
|
||||
'before the flutter_driver did.'
|
||||
'Attempted to resume an already resumed isolate. This may happen '
|
||||
'when another tool (usually a debugger) resumed the isolate '
|
||||
'before the flutter_driver did.',
|
||||
);
|
||||
return vms.Success();
|
||||
} else {
|
||||
@@ -179,23 +181,24 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
Future<void> waitForServiceExtension() async {
|
||||
await client.streamListen(vms.EventStreams.kIsolate);
|
||||
|
||||
final Future<void> extensionAlreadyAdded = client
|
||||
.getIsolate(isolateRef.id!)
|
||||
.then((vms.Isolate isolate) async {
|
||||
if (isolate.extensionRPCs!.contains(_flutterExtensionMethodName)) {
|
||||
return;
|
||||
}
|
||||
// Never complete. Rely on the stream listener to find the service
|
||||
// extension instead.
|
||||
return Completer<void>().future;
|
||||
});
|
||||
final Future<void> extensionAlreadyAdded = client.getIsolate(isolateRef.id!).then((
|
||||
vms.Isolate isolate,
|
||||
) async {
|
||||
if (isolate.extensionRPCs!.contains(_flutterExtensionMethodName)) {
|
||||
return;
|
||||
}
|
||||
// Never complete. Rely on the stream listener to find the service
|
||||
// extension instead.
|
||||
return Completer<void>().future;
|
||||
});
|
||||
|
||||
final Completer<void> extensionAdded = Completer<void>();
|
||||
late StreamSubscription<vms.Event> isolateAddedSubscription;
|
||||
|
||||
isolateAddedSubscription = client.onIsolateEvent.listen(
|
||||
(vms.Event data) {
|
||||
if (data.kind == vms.EventKind.kServiceExtensionAdded && data.extensionRPC == _flutterExtensionMethodName) {
|
||||
if (data.kind == vms.EventKind.kServiceExtensionAdded &&
|
||||
data.extensionRPC == _flutterExtensionMethodName) {
|
||||
extensionAdded.complete();
|
||||
isolateAddedSubscription.cancel();
|
||||
}
|
||||
@@ -204,10 +207,7 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
cancelOnError: true,
|
||||
);
|
||||
|
||||
await Future.any(<Future<void>>[
|
||||
extensionAlreadyAdded,
|
||||
extensionAdded.future,
|
||||
]);
|
||||
await Future.any(<Future<void>>[extensionAlreadyAdded, extensionAdded.future]);
|
||||
await isolateAddedSubscription.cancel();
|
||||
await client.streamCancel(vms.EventStreams.kIsolate);
|
||||
}
|
||||
@@ -230,8 +230,8 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
_log('Isolate is not paused. Assuming application is ready.');
|
||||
} else {
|
||||
_log(
|
||||
'Unknown pause event type ${isolate.pauseEvent.runtimeType}. '
|
||||
'Assuming application is ready.'
|
||||
'Unknown pause event type ${isolate.pauseEvent.runtimeType}. '
|
||||
'Assuming application is ready.',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -240,7 +240,8 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
await _warnIfSlow<void>(
|
||||
future: waitForServiceExtension(),
|
||||
timeout: kUnusuallyLongTimeout,
|
||||
message: 'Flutter Driver extension is taking a long time to become available. '
|
||||
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().',
|
||||
@@ -277,6 +278,7 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
│ ┊
|
||||
└─────────────────────────────────────────────────╌┄┈ 🐢
|
||||
''';
|
||||
|
||||
/// The unique ID of this driver instance.
|
||||
final int _driverId;
|
||||
|
||||
@@ -295,7 +297,8 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
vms.VmService get serviceClient => _serviceClient;
|
||||
|
||||
@override
|
||||
async_io.WebDriver get webDriver => throw UnsupportedError('VMServiceFlutterDriver does not support webDriver');
|
||||
async_io.WebDriver get webDriver =>
|
||||
throw UnsupportedError('VMServiceFlutterDriver does not support webDriver');
|
||||
|
||||
/// The main isolate hosting the Flutter application.
|
||||
///
|
||||
@@ -316,18 +319,19 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
/// Getter for file pathname where logs are written when _logCommunicationToFile is true.
|
||||
String get logFilePathName => _logFilePathName;
|
||||
|
||||
|
||||
@override
|
||||
Future<Map<String, dynamic>> sendCommand(Command command) async {
|
||||
late Map<String, dynamic> response;
|
||||
try {
|
||||
final Map<String, String> serialized = command.serialize();
|
||||
_logCommunication('>>> $serialized');
|
||||
final Future<Map<String, dynamic>> future = _serviceClient.callServiceExtension(
|
||||
_flutterExtensionMethodName,
|
||||
isolateId: _appIsolate.id,
|
||||
args: serialized,
|
||||
).then<Map<String, dynamic>>((vms.Response value) => value.json!);
|
||||
final Future<Map<String, dynamic>> future = _serviceClient
|
||||
.callServiceExtension(
|
||||
_flutterExtensionMethodName,
|
||||
isolateId: _appIsolate.id,
|
||||
args: serialized,
|
||||
)
|
||||
.then<Map<String, dynamic>>((vms.Response value) => value.json!);
|
||||
response = await _warnIfSlow<Map<String, dynamic>>(
|
||||
future: future,
|
||||
timeout: command.timeout ?? kUnusuallyLongTimeout,
|
||||
@@ -378,18 +382,12 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
assert(streams.isNotEmpty);
|
||||
try {
|
||||
await _warnIfSlow<vms.Success>(
|
||||
future: _serviceClient.setVMTimelineFlags(
|
||||
_timelineStreamsToString(streams),
|
||||
),
|
||||
future: _serviceClient.setVMTimelineFlags(_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',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
throw DriverError('Failed to start tracing due to remote error', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -399,8 +397,7 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
int? startTime,
|
||||
int? endTime,
|
||||
}) async {
|
||||
assert((startTime == null && endTime == null) ||
|
||||
(startTime != null && endTime != null));
|
||||
assert((startTime == null && endTime == null) || (startTime != null && endTime != null));
|
||||
|
||||
try {
|
||||
await _warnIfSlow<vms.Success>(
|
||||
@@ -428,17 +425,13 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
currentEnd += kSecondInMicros;
|
||||
} while (currentStart < endTime!);
|
||||
return Timeline.fromJson(<String, Object>{
|
||||
'traceEvents': <Object?> [
|
||||
'traceEvents': <Object?>[
|
||||
for (final Map<String, Object?>? chunk in chunks)
|
||||
...chunk!['traceEvents']! as List<Object?>,
|
||||
],
|
||||
});
|
||||
} catch (error, stackTrace) {
|
||||
throw DriverError(
|
||||
'Failed to stop tracing due to remote error',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
throw DriverError('Failed to stop tracing due to remote error', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -454,10 +447,10 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
|
||||
@override
|
||||
Future<Timeline> traceAction(
|
||||
Future<dynamic> Function() action, {
|
||||
List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all],
|
||||
bool retainPriorEvents = false,
|
||||
}) async {
|
||||
Future<dynamic> Function() action, {
|
||||
List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all],
|
||||
bool retainPriorEvents = false,
|
||||
}) async {
|
||||
if (retainPriorEvents) {
|
||||
await startTracing(streams: streams);
|
||||
await action();
|
||||
@@ -487,21 +480,16 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> clearTimeline({
|
||||
Duration timeout = kUnusuallyLongTimeout,
|
||||
}) async {
|
||||
Future<void> clearTimeline({Duration timeout = kUnusuallyLongTimeout}) async {
|
||||
try {
|
||||
await _warnIfSlow<vms.Success>(
|
||||
future: _serviceClient.clearVMTimeline(),
|
||||
timeout: timeout,
|
||||
message: 'VM is taking an unusually long time to respond to being told to clear its timeline buffer...',
|
||||
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',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
throw DriverError('Failed to clear event timeline due to remote error', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -510,11 +498,7 @@ class VMServiceFlutterDriver extends FlutterDriver {
|
||||
try {
|
||||
await _serviceClient.callMethod(_collectAllGarbageMethodName, isolateId: _appIsolate.id);
|
||||
} catch (error, stackTrace) {
|
||||
throw DriverError(
|
||||
'Failed to force a GC due to remote error',
|
||||
error,
|
||||
stackTrace,
|
||||
);
|
||||
throw DriverError('Failed to force a GC due to remote error', error, stackTrace);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -568,7 +552,7 @@ Future<vms.VmService> _waitAndConnect(String url, Map<String, dynamic>? headers)
|
||||
controller.stream,
|
||||
socket.add,
|
||||
disposeHandler: () => socket!.close(),
|
||||
streamClosed: streamClosedCompleter.future
|
||||
streamClosed: streamClosedCompleter.future,
|
||||
);
|
||||
// This call is to ensure we are able to establish a connection instead of
|
||||
// keeping on trucking and failing farther down the process.
|
||||
@@ -597,18 +581,22 @@ const Duration _kPauseBetweenIsolateRefresh = Duration(milliseconds: 100);
|
||||
// See `timeline_streams` in
|
||||
// https://github.com/dart-lang/sdk/blob/main/runtime/vm/timeline.cc
|
||||
List<String> _timelineStreamsToString(List<TimelineStream> streams) {
|
||||
return streams.map<String>((TimelineStream stream) => switch (stream) {
|
||||
TimelineStream.all => 'all',
|
||||
TimelineStream.api => 'API',
|
||||
TimelineStream.dart => 'Dart',
|
||||
TimelineStream.debugger => 'Debugger',
|
||||
TimelineStream.embedder => 'Embedder',
|
||||
TimelineStream.gc => 'GC',
|
||||
TimelineStream.isolate => 'Isolate',
|
||||
TimelineStream.vm => 'VM',
|
||||
TimelineStream.compiler => 'Compiler',
|
||||
TimelineStream.compilerVerbose => 'CompilerVerbose',
|
||||
}).toList();
|
||||
return streams
|
||||
.map<String>(
|
||||
(TimelineStream stream) => switch (stream) {
|
||||
TimelineStream.all => 'all',
|
||||
TimelineStream.api => 'API',
|
||||
TimelineStream.dart => 'Dart',
|
||||
TimelineStream.debugger => 'Debugger',
|
||||
TimelineStream.embedder => 'Embedder',
|
||||
TimelineStream.gc => 'GC',
|
||||
TimelineStream.isolate => 'Isolate',
|
||||
TimelineStream.vm => 'VM',
|
||||
TimelineStream.compiler => 'Compiler',
|
||||
TimelineStream.compilerVerbose => 'CompilerVerbose',
|
||||
},
|
||||
)
|
||||
.toList();
|
||||
}
|
||||
|
||||
void _log(String message) {
|
||||
@@ -621,12 +609,17 @@ Future<T> _warnIfSlow<T>({
|
||||
required String message,
|
||||
}) async {
|
||||
final Completer<void> completer = Completer<void>();
|
||||
completer.future.timeout(timeout, onTimeout: () {
|
||||
_log(message);
|
||||
return null;
|
||||
});
|
||||
completer.future.timeout(
|
||||
timeout,
|
||||
onTimeout: () {
|
||||
_log(message);
|
||||
return null;
|
||||
},
|
||||
);
|
||||
try {
|
||||
await future.whenComplete(() { completer.complete(); });
|
||||
await future.whenComplete(() {
|
||||
completer.complete();
|
||||
});
|
||||
} catch (e) {
|
||||
// Don't duplicate errors if [future] completes with an error.
|
||||
}
|
||||
@@ -634,4 +627,5 @@ Future<T> _warnIfSlow<T>({
|
||||
}
|
||||
|
||||
/// A function that connects to a Dart VM service given the `url` and `headers`.
|
||||
typedef VMServiceConnectFunction = Future<vms.VmService> Function(String url, Map<String, dynamic>? headers);
|
||||
typedef VMServiceConnectFunction =
|
||||
Future<vms.VmService> Function(String url, Map<String, dynamic>? headers);
|
||||
|
||||
@@ -29,8 +29,7 @@ class VsyncFrameLagSummarizer {
|
||||
|
||||
/// Computes the average `VsyncFrameLag` over the period of the timeline.
|
||||
double computeAverageVsyncFrameLag() {
|
||||
final List<double> vsyncFrameLags =
|
||||
_computePlatformToFlutterVsyncBeginLags();
|
||||
final List<double> vsyncFrameLags = _computePlatformToFlutterVsyncBeginLags();
|
||||
if (vsyncFrameLags.isEmpty) {
|
||||
return 0;
|
||||
}
|
||||
@@ -42,8 +41,7 @@ class VsyncFrameLagSummarizer {
|
||||
/// Computes the [percentile]-th percentile `VsyncFrameLag` over the
|
||||
/// period of the timeline.
|
||||
double computePercentileVsyncFrameLag(double percentile) {
|
||||
final List<double> vsyncFrameLags =
|
||||
_computePlatformToFlutterVsyncBeginLags();
|
||||
final List<double> vsyncFrameLags = _computePlatformToFlutterVsyncBeginLags();
|
||||
if (vsyncFrameLags.isEmpty) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -32,14 +32,12 @@ class WebFlutterDriver extends FlutterDriver {
|
||||
this._connection, {
|
||||
bool printCommunication = false,
|
||||
bool logCommunicationToFile = true,
|
||||
}) : _printCommunication = printCommunication,
|
||||
_logCommunicationToFile = logCommunicationToFile,
|
||||
_startTime = DateTime.now(),
|
||||
_driverId = _nextDriverId++
|
||||
{
|
||||
_logFilePathName = path.join(testOutputsDirectory, 'flutter_driver_commands_$_driverId.log');
|
||||
}
|
||||
|
||||
}) : _printCommunication = printCommunication,
|
||||
_logCommunicationToFile = logCommunicationToFile,
|
||||
_startTime = DateTime.now(),
|
||||
_driverId = _nextDriverId++ {
|
||||
_logFilePathName = path.join(testOutputsDirectory, 'flutter_driver_commands_$_driverId.log');
|
||||
}
|
||||
|
||||
final FlutterWebConnection _connection;
|
||||
DateTime _startTime;
|
||||
@@ -53,10 +51,12 @@ class WebFlutterDriver extends FlutterDriver {
|
||||
DateTime get startTime => _startTime;
|
||||
|
||||
@override
|
||||
vms.Isolate get appIsolate => throw UnsupportedError('WebFlutterDriver does not support appIsolate');
|
||||
vms.Isolate get appIsolate =>
|
||||
throw UnsupportedError('WebFlutterDriver does not support appIsolate');
|
||||
|
||||
@override
|
||||
vms.VmService get serviceClient => throw UnsupportedError('WebFlutterDriver does not support serviceClient');
|
||||
vms.VmService get serviceClient =>
|
||||
throw UnsupportedError('WebFlutterDriver does not support serviceClient');
|
||||
|
||||
@override
|
||||
async_io.WebDriver get webDriver => _connection._driver;
|
||||
@@ -96,8 +96,11 @@ class WebFlutterDriver extends FlutterDriver {
|
||||
'android-chrome-on-emulator': Platform.environment['ANDROID_CHROME_ON_EMULATOR'] == 'true',
|
||||
'session-capabilities': Platform.environment['DRIVER_SESSION_CAPABILITIES'],
|
||||
};
|
||||
final FlutterWebConnection connection = await FlutterWebConnection.connect
|
||||
(hostUrl!, settings, timeout: timeout);
|
||||
final FlutterWebConnection connection = await FlutterWebConnection.connect(
|
||||
hostUrl!,
|
||||
settings,
|
||||
timeout: timeout,
|
||||
);
|
||||
return WebFlutterDriver.connectedTo(
|
||||
connection,
|
||||
printCommunication: printCommunication,
|
||||
@@ -109,7 +112,7 @@ class WebFlutterDriver extends FlutterDriver {
|
||||
throw DriverError(
|
||||
'Received malformed response from the FlutterDriver extension.\n'
|
||||
'Expected a JSON map containing a "response" field and, optionally, an '
|
||||
'"isError" field, but got ${data.runtimeType}: $data'
|
||||
'"isError" field, but got ${data.runtimeType}: $data',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -120,7 +123,10 @@ class WebFlutterDriver extends FlutterDriver {
|
||||
final Map<String, String> serialized = command.serialize();
|
||||
_logCommunication('>>> $serialized');
|
||||
try {
|
||||
data = await _connection.sendCommand("window.\$flutterDriver('${jsonEncode(serialized)}')", command.timeout);
|
||||
data = await _connection.sendCommand(
|
||||
"window.\$flutterDriver('${jsonEncode(serialized)}')",
|
||||
command.timeout,
|
||||
);
|
||||
|
||||
// The returned data is expected to be a string. If it's null or anything
|
||||
// other than a string, something's wrong.
|
||||
@@ -143,7 +149,7 @@ class WebFlutterDriver extends FlutterDriver {
|
||||
'FlutterDriver command ${command.runtimeType} failed due to a remote error.\n'
|
||||
'Command sent: ${jsonEncode(serialized)}',
|
||||
error,
|
||||
stackTrace
|
||||
stackTrace,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -199,13 +205,16 @@ class WebFlutterDriver extends FlutterDriver {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Timeline> stopTracingAndDownloadTimeline({Duration timeout = kUnusuallyLongTimeout}) async {
|
||||
Future<Timeline> stopTracingAndDownloadTimeline({
|
||||
Duration timeout = kUnusuallyLongTimeout,
|
||||
}) async {
|
||||
_checkBrowserSupportsTimeline();
|
||||
|
||||
final List<Map<String, dynamic>> events = <Map<String, dynamic>>[];
|
||||
for (final async_io.LogEntry entry in await _connection.logs.toList()) {
|
||||
if (_startTime.isBefore(entry.timestamp)) {
|
||||
final Map<String, dynamic> data = (jsonDecode(entry.message!) as Map<String, dynamic>)['message'] as Map<String, dynamic>;
|
||||
final Map<String, dynamic> data =
|
||||
(jsonDecode(entry.message!) as Map<String, dynamic>)['message'] as Map<String, dynamic>;
|
||||
if (data['method'] == 'Tracing.dataCollected') {
|
||||
// 'ts' data collected from Chrome is in double format, conversion needed
|
||||
try {
|
||||
@@ -219,14 +228,13 @@ class WebFlutterDriver extends FlutterDriver {
|
||||
}
|
||||
}
|
||||
}
|
||||
final Map<String, dynamic> json = <String, dynamic>{
|
||||
'traceEvents': events,
|
||||
};
|
||||
final Map<String, dynamic> json = <String, dynamic>{'traceEvents': events};
|
||||
return Timeline.fromJson(json);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Timeline> traceAction(Future<dynamic> Function() action, {
|
||||
Future<Timeline> traceAction(
|
||||
Future<dynamic> Function() action, {
|
||||
List<TimelineStream> streams = const <TimelineStream>[TimelineStream.all],
|
||||
bool retainPriorEvents = false,
|
||||
}) async {
|
||||
@@ -270,9 +278,10 @@ class FlutterWebConnection {
|
||||
/// Starts WebDriver with the given [settings] and
|
||||
/// establishes the connection to Flutter Web application.
|
||||
static Future<FlutterWebConnection> connect(
|
||||
String url,
|
||||
Map<String, dynamic> settings,
|
||||
{Duration? timeout}) async {
|
||||
String url,
|
||||
Map<String, dynamic> settings, {
|
||||
Duration? timeout,
|
||||
}) async {
|
||||
final String sessionId = settings['session-id'].toString();
|
||||
final Uri sessionUri = Uri.parse(settings['session-uri'].toString());
|
||||
final async_io.WebDriver driver = async_io.WebDriver(
|
||||
@@ -287,7 +296,7 @@ class FlutterWebConnection {
|
||||
// Converts to Android Emulator Uri.
|
||||
// Hardcode the host to 10.0.2.2 based on
|
||||
// https://developer.android.com/studio/run/emulator-networking
|
||||
url = Uri(scheme: localUri.scheme, host: '10.0.2.2', port:localUri.port).toString();
|
||||
url = Uri(scheme: localUri.scheme, host: '10.0.2.2', port: localUri.port).toString();
|
||||
}
|
||||
await driver.get(url);
|
||||
|
||||
@@ -350,7 +359,7 @@ class FlutterWebConnection {
|
||||
Stream<async_io.LogEntry> get logs => _driver.logs.get(async_io.LogType.performance);
|
||||
|
||||
/// Takes screenshot via WebDriver.
|
||||
Future<List<int>> screenshot() => _driver.captureScreenshotAsList();
|
||||
Future<List<int>> screenshot() => _driver.captureScreenshotAsList();
|
||||
|
||||
/// Closes the WebDriver.
|
||||
Future<void> close() async {
|
||||
@@ -360,8 +369,9 @@ class FlutterWebConnection {
|
||||
|
||||
/// Waits until extension is installed.
|
||||
Future<void> waitUntilExtensionInstalled(async_io.WebDriver driver, Duration? timeout) async {
|
||||
await waitFor<void>(() =>
|
||||
driver.execute(r'return typeof(window.$flutterDriver)', <String>[]),
|
||||
matcher: 'function',
|
||||
timeout: timeout ?? const Duration(days: 365));
|
||||
await waitFor<void>(
|
||||
() => driver.execute(r'return typeof(window.$flutterDriver)', <String>[]),
|
||||
matcher: 'function',
|
||||
timeout: timeout ?? const Duration(days: 365),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -21,11 +21,15 @@ void registerWebServiceExtension(Future<Map<String, dynamic>> Function(Map<Strin
|
||||
// undefined at the time of the check, WebDriver throws an exception.
|
||||
_window.setProperty(r'$flutterDriverResult'.toJS, null);
|
||||
|
||||
_window.setProperty(r'$flutterDriver'.toJS, (JSAny message) {
|
||||
final Map<String, String> params = Map<String, String>.from(
|
||||
jsonDecode((message as JSString).toDart) as Map<String, dynamic>);
|
||||
call(params).then((Map<String, dynamic> result) {
|
||||
_window.setProperty(r'$flutterDriverResult'.toJS, json.encode(result).toJS);
|
||||
});
|
||||
}.toJS);
|
||||
_window.setProperty(
|
||||
r'$flutterDriver'.toJS,
|
||||
(JSAny message) {
|
||||
final Map<String, String> params = Map<String, String>.from(
|
||||
jsonDecode((message as JSString).toDart) as Map<String, dynamic>,
|
||||
);
|
||||
call(params).then((Map<String, dynamic> result) {
|
||||
_window.setProperty(r'$flutterDriverResult'.toJS, json.encode(result).toJS);
|
||||
});
|
||||
}.toJS,
|
||||
);
|
||||
}
|
||||
|
||||
@@ -33,8 +33,23 @@ const String _extensionMethodName = 'driver';
|
||||
/// eventually completes to a string response.
|
||||
typedef DataHandler = Future<String> Function(String? message);
|
||||
|
||||
class _DriverBinding extends BindingBase with SchedulerBinding, ServicesBinding, GestureBinding, PaintingBinding, SemanticsBinding, RendererBinding, WidgetsBinding, TestDefaultBinaryMessengerBinding {
|
||||
_DriverBinding(this._handler, this._silenceErrors, this._enableTextEntryEmulation, this.finders, this.commands);
|
||||
class _DriverBinding extends BindingBase
|
||||
with
|
||||
SchedulerBinding,
|
||||
ServicesBinding,
|
||||
GestureBinding,
|
||||
PaintingBinding,
|
||||
SemanticsBinding,
|
||||
RendererBinding,
|
||||
WidgetsBinding,
|
||||
TestDefaultBinaryMessengerBinding {
|
||||
_DriverBinding(
|
||||
this._handler,
|
||||
this._silenceErrors,
|
||||
this._enableTextEntryEmulation,
|
||||
this.finders,
|
||||
this.commands,
|
||||
);
|
||||
|
||||
final DataHandler? _handler;
|
||||
final bool _silenceErrors;
|
||||
@@ -45,16 +60,21 @@ class _DriverBinding extends BindingBase with SchedulerBinding, ServicesBinding,
|
||||
// Because you can't really control which zone a driver test uses,
|
||||
// we override the test for zones here.
|
||||
@override
|
||||
bool debugCheckZone(String entryPoint) { return true; }
|
||||
bool debugCheckZone(String entryPoint) {
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
void initServiceExtensions() {
|
||||
super.initServiceExtensions();
|
||||
final FlutterDriverExtension extension = FlutterDriverExtension(_handler, _silenceErrors, _enableTextEntryEmulation, finders: finders ?? const <FinderExtension>[], commands: commands ?? const <CommandExtension>[]);
|
||||
registerServiceExtension(
|
||||
name: _extensionMethodName,
|
||||
callback: extension.call,
|
||||
final FlutterDriverExtension extension = FlutterDriverExtension(
|
||||
_handler,
|
||||
_silenceErrors,
|
||||
_enableTextEntryEmulation,
|
||||
finders: finders ?? const <FinderExtension>[],
|
||||
commands: commands ?? const <CommandExtension>[],
|
||||
);
|
||||
registerServiceExtension(name: _extensionMethodName, callback: extension.call);
|
||||
if (kIsWeb) {
|
||||
registerWebServiceExtension(extension.call);
|
||||
}
|
||||
@@ -220,8 +240,20 @@ class _DriverBinding extends BindingBase with SchedulerBinding, ServicesBinding,
|
||||
/// }
|
||||
/// }
|
||||
/// ```
|
||||
void enableFlutterDriverExtension({ DataHandler? handler, bool silenceErrors = false, bool enableTextEntryEmulation = true, List<FinderExtension>? finders, List<CommandExtension>? commands}) {
|
||||
_DriverBinding(handler, silenceErrors, enableTextEntryEmulation, finders ?? <FinderExtension>[], commands ?? <CommandExtension>[]);
|
||||
void enableFlutterDriverExtension({
|
||||
DataHandler? handler,
|
||||
bool silenceErrors = false,
|
||||
bool enableTextEntryEmulation = true,
|
||||
List<FinderExtension>? finders,
|
||||
List<CommandExtension>? commands,
|
||||
}) {
|
||||
_DriverBinding(
|
||||
handler,
|
||||
silenceErrors,
|
||||
enableTextEntryEmulation,
|
||||
finders ?? <FinderExtension>[],
|
||||
commands ?? <CommandExtension>[],
|
||||
);
|
||||
assert(WidgetsBinding.instance is _DriverBinding);
|
||||
}
|
||||
|
||||
@@ -233,7 +265,6 @@ typedef CommandDeserializerCallback = Command Function(Map<String, String> param
|
||||
|
||||
/// Used to expand the new [Finder].
|
||||
abstract class FinderExtension {
|
||||
|
||||
/// Identifies the type of finder to be used by the driver extension.
|
||||
String get finderType;
|
||||
|
||||
@@ -243,7 +274,10 @@ abstract class FinderExtension {
|
||||
///
|
||||
/// See also:
|
||||
/// * [Ancestor], a finder that uses other [Finder]s as parameters.
|
||||
SerializableFinder deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory);
|
||||
SerializableFinder deserialize(
|
||||
Map<String, String> params,
|
||||
DeserializeFinderFactory finderFactory,
|
||||
);
|
||||
|
||||
/// Signature for functions that run the given finder and return the [Element]
|
||||
/// found, if any, or null otherwise.
|
||||
@@ -270,7 +304,11 @@ abstract class CommandExtension {
|
||||
/// See also:
|
||||
/// * [CommandWithTarget], a base class for commands with target finders.
|
||||
/// * [Tap], a command that uses [Finder]s as parameter.
|
||||
Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory);
|
||||
Command deserialize(
|
||||
Map<String, String> params,
|
||||
DeserializeFinderFactory finderFactory,
|
||||
DeserializeCommandFactory commandFactory,
|
||||
);
|
||||
|
||||
/// Calls action for given [command].
|
||||
/// Returns action [Result].
|
||||
@@ -303,7 +341,12 @@ abstract class CommandExtension {
|
||||
/// return const StubCommandResult('stub response');
|
||||
/// }
|
||||
/// ```
|
||||
Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory);
|
||||
Future<Result> call(
|
||||
Command command,
|
||||
WidgetController prober,
|
||||
CreateFinderFactory finderFactory,
|
||||
CommandHandlerFactory handlerFactory,
|
||||
);
|
||||
}
|
||||
|
||||
/// The class that manages communication between a Flutter Driver test and the
|
||||
@@ -312,7 +355,12 @@ abstract class CommandExtension {
|
||||
/// This is not normally used directly. It is instantiated automatically when
|
||||
/// calling [enableFlutterDriverExtension].
|
||||
@visibleForTesting
|
||||
class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory, DeserializeCommandFactory, CommandHandlerFactory {
|
||||
class FlutterDriverExtension
|
||||
with
|
||||
DeserializeFinderFactory,
|
||||
CreateFinderFactory,
|
||||
DeserializeCommandFactory,
|
||||
CommandHandlerFactory {
|
||||
/// Creates an object to manage a Flutter Driver connection.
|
||||
FlutterDriverExtension(
|
||||
this._requestDataHandler,
|
||||
@@ -364,8 +412,10 @@ class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory,
|
||||
final String commandKind = params['command']!;
|
||||
try {
|
||||
final Command command = deserializeCommand(params, this);
|
||||
assert(WidgetsBinding.instance.isRootWidgetAttached || !command.requiresRootWidgetAttached,
|
||||
'No root widget is attached; have you remembered to call runApp()?');
|
||||
assert(
|
||||
WidgetsBinding.instance.isRootWidgetAttached || !command.requiresRootWidgetAttached,
|
||||
'No root widget is attached; have you remembered to call runApp()?',
|
||||
);
|
||||
Future<Result> responseFuture = handleCommand(command, _prober, this);
|
||||
if (command.timeout != null) {
|
||||
responseFuture = responseFuture.timeout(command.timeout!);
|
||||
@@ -377,7 +427,8 @@ class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory,
|
||||
_log(message);
|
||||
return _makeResponse(message, isError: true);
|
||||
} catch (error, stackTrace) {
|
||||
final String message = 'Uncaught extension error while executing $commandKind: $error\n$stackTrace';
|
||||
final String message =
|
||||
'Uncaught extension error while executing $commandKind: $error\n$stackTrace';
|
||||
if (!_silenceErrors) {
|
||||
_log(message);
|
||||
}
|
||||
@@ -385,11 +436,8 @@ class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory,
|
||||
}
|
||||
}
|
||||
|
||||
Map<String, dynamic> _makeResponse(dynamic response, { bool isError = false }) {
|
||||
return <String, dynamic>{
|
||||
'isError': isError,
|
||||
'response': response,
|
||||
};
|
||||
Map<String, dynamic> _makeResponse(dynamic response, {bool isError = false}) {
|
||||
return <String, dynamic>{'isError': isError, 'response': response};
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -429,7 +477,11 @@ class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory,
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Result> handleCommand(Command command, WidgetController prober, CreateFinderFactory finderFactory) {
|
||||
Future<Result> handleCommand(
|
||||
Command command,
|
||||
WidgetController prober,
|
||||
CreateFinderFactory finderFactory,
|
||||
) {
|
||||
final String kind = command.kind;
|
||||
if (_commandExtensions.containsKey(kind)) {
|
||||
return _commandExtensions[kind]!.call(command, prober, finderFactory, this);
|
||||
|
||||
@@ -41,7 +41,9 @@ class _InternalNoTransientCallbacksCondition implements WaitCondition {
|
||||
/// instance from the given [SerializableWaitCondition] instance.
|
||||
factory _InternalNoTransientCallbacksCondition.deserialize(SerializableWaitCondition condition) {
|
||||
if (condition.conditionName != 'NoTransientCallbacksCondition') {
|
||||
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing from the given condition: ${condition.serialize()}',
|
||||
);
|
||||
}
|
||||
return const _InternalNoTransientCallbacksCondition();
|
||||
}
|
||||
@@ -67,7 +69,9 @@ class _InternalNoPendingFrameCondition implements WaitCondition {
|
||||
/// from the given [SerializableWaitCondition] instance.
|
||||
factory _InternalNoPendingFrameCondition.deserialize(SerializableWaitCondition condition) {
|
||||
if (condition.conditionName != 'NoPendingFrameCondition') {
|
||||
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing from the given condition: ${condition.serialize()}',
|
||||
);
|
||||
}
|
||||
return const _InternalNoPendingFrameCondition();
|
||||
}
|
||||
@@ -93,7 +97,9 @@ class _InternalFirstFrameRasterizedCondition implements WaitCondition {
|
||||
/// from the given [SerializableWaitCondition] instance.
|
||||
factory _InternalFirstFrameRasterizedCondition.deserialize(SerializableWaitCondition condition) {
|
||||
if (condition.conditionName != 'FirstFrameRasterizedCondition') {
|
||||
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing from the given condition: ${condition.serialize()}',
|
||||
);
|
||||
}
|
||||
return const _InternalFirstFrameRasterizedCondition();
|
||||
}
|
||||
@@ -115,22 +121,28 @@ class _InternalNoPendingPlatformMessagesCondition implements WaitCondition {
|
||||
|
||||
/// Factory constructor to parse an [_InternalNoPendingPlatformMessagesCondition] instance
|
||||
/// from the given [SerializableWaitCondition] instance.
|
||||
factory _InternalNoPendingPlatformMessagesCondition.deserialize(SerializableWaitCondition condition) {
|
||||
factory _InternalNoPendingPlatformMessagesCondition.deserialize(
|
||||
SerializableWaitCondition condition,
|
||||
) {
|
||||
if (condition.conditionName != 'NoPendingPlatformMessagesCondition') {
|
||||
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing from the given condition: ${condition.serialize()}',
|
||||
);
|
||||
}
|
||||
return const _InternalNoPendingPlatformMessagesCondition();
|
||||
}
|
||||
|
||||
@override
|
||||
bool get condition {
|
||||
final TestDefaultBinaryMessenger binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger as TestDefaultBinaryMessenger;
|
||||
final TestDefaultBinaryMessenger binaryMessenger =
|
||||
ServicesBinding.instance.defaultBinaryMessenger as TestDefaultBinaryMessenger;
|
||||
return binaryMessenger.pendingMessageCount == 0;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> wait() async {
|
||||
final TestDefaultBinaryMessenger binaryMessenger = ServicesBinding.instance.defaultBinaryMessenger as TestDefaultBinaryMessenger;
|
||||
final TestDefaultBinaryMessenger binaryMessenger =
|
||||
ServicesBinding.instance.defaultBinaryMessenger as TestDefaultBinaryMessenger;
|
||||
while (!condition) {
|
||||
await binaryMessenger.platformMessagesFinished;
|
||||
}
|
||||
@@ -148,10 +160,13 @@ class _InternalCombinedCondition implements WaitCondition {
|
||||
/// the given [SerializableWaitCondition] instance.
|
||||
factory _InternalCombinedCondition.deserialize(SerializableWaitCondition condition) {
|
||||
if (condition.conditionName != 'CombinedCondition') {
|
||||
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
|
||||
throw SerializationException(
|
||||
'Error occurred during deserializing from the given condition: ${condition.serialize()}',
|
||||
);
|
||||
}
|
||||
final CombinedCondition combinedCondition = condition as CombinedCondition;
|
||||
final List<WaitCondition> conditions = combinedCondition.conditions.map(deserializeCondition).toList();
|
||||
final List<WaitCondition> conditions =
|
||||
combinedCondition.conditions.map(deserializeCondition).toList();
|
||||
return _InternalCombinedCondition(conditions);
|
||||
}
|
||||
|
||||
@@ -178,11 +193,20 @@ class _InternalCombinedCondition implements WaitCondition {
|
||||
WaitCondition deserializeCondition(SerializableWaitCondition waitCondition) {
|
||||
final String conditionName = waitCondition.conditionName;
|
||||
return switch (conditionName) {
|
||||
'NoTransientCallbacksCondition' => _InternalNoTransientCallbacksCondition.deserialize(waitCondition),
|
||||
'NoPendingFrameCondition' => _InternalNoPendingFrameCondition.deserialize(waitCondition),
|
||||
'FirstFrameRasterizedCondition' => _InternalFirstFrameRasterizedCondition.deserialize(waitCondition),
|
||||
'NoPendingPlatformMessagesCondition' => _InternalNoPendingPlatformMessagesCondition.deserialize(waitCondition),
|
||||
'CombinedCondition' => _InternalCombinedCondition.deserialize(waitCondition),
|
||||
_ => throw SerializationException('Unsupported wait condition $conditionName in ${waitCondition.serialize()}'),
|
||||
'NoTransientCallbacksCondition' => _InternalNoTransientCallbacksCondition.deserialize(
|
||||
waitCondition,
|
||||
),
|
||||
'NoPendingFrameCondition' => _InternalNoPendingFrameCondition.deserialize(waitCondition),
|
||||
'FirstFrameRasterizedCondition' => _InternalFirstFrameRasterizedCondition.deserialize(
|
||||
waitCondition,
|
||||
),
|
||||
'NoPendingPlatformMessagesCondition' => _InternalNoPendingPlatformMessagesCondition.deserialize(
|
||||
waitCondition,
|
||||
),
|
||||
'CombinedCondition' => _InternalCombinedCondition.deserialize(waitCondition),
|
||||
_ =>
|
||||
throw SerializationException(
|
||||
'Unsupported wait condition $conditionName in ${waitCondition.serialize()}',
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -10,17 +10,13 @@ import '../common.dart';
|
||||
TimelineEvent newGPUTraceEvent(double ms) => TimelineEvent(<String, dynamic>{
|
||||
'name': 'AllocatorVK',
|
||||
'ph': 'b',
|
||||
'args': <String, String>{
|
||||
'MemoryBudgetUsageMB': ms.toString()
|
||||
},
|
||||
'args': <String, String>{'MemoryBudgetUsageMB': ms.toString()},
|
||||
});
|
||||
|
||||
TimelineEvent newMetalGPUTraceEvent(double ms) => TimelineEvent(<String, dynamic>{
|
||||
'name': 'AllocatorMTL',
|
||||
'ph': 'b',
|
||||
'args': <String, String>{
|
||||
'MemoryBudgetUsageMB': ms.toString()
|
||||
},
|
||||
'args': <String, String>{'MemoryBudgetUsageMB': ms.toString()},
|
||||
});
|
||||
|
||||
void main() {
|
||||
|
||||
@@ -10,9 +10,7 @@ import '../common.dart';
|
||||
TimelineEvent newGPUTraceEvent(double ms) => TimelineEvent(<String, dynamic>{
|
||||
'name': 'GPUStart',
|
||||
'ph': 'b',
|
||||
'args': <String, String>{
|
||||
'FrameTimeMS': ms.toString()
|
||||
},
|
||||
'args': <String, String>{'FrameTimeMS': ms.toString()},
|
||||
});
|
||||
|
||||
void main() {
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -13,12 +13,7 @@ void main() {
|
||||
const SerializableFinder of = ByType('Text');
|
||||
final SerializableFinder matching = ByValueKey('hello');
|
||||
|
||||
final Ancestor a = Ancestor(
|
||||
of: of,
|
||||
matching: matching,
|
||||
matchRoot: true,
|
||||
firstMatchOnly: true,
|
||||
);
|
||||
final Ancestor a = Ancestor(of: of, matching: matching, matchRoot: true, firstMatchOnly: true);
|
||||
expect(a.serialize(), <String, String>{
|
||||
'finderType': 'Ancestor',
|
||||
'of': '{"finderType":"ByType","type":"Text"}',
|
||||
@@ -80,4 +75,4 @@ void main() {
|
||||
});
|
||||
}
|
||||
|
||||
class FakeDeserialize extends Fake with DeserializeFinderFactory { }
|
||||
class FakeDeserialize extends Fake with DeserializeFinderFactory {}
|
||||
|
||||
@@ -42,7 +42,7 @@ void main() {
|
||||
fakeIsolate = createFakeIsolate();
|
||||
fakeVM = FakeVM(fakeIsolate);
|
||||
fakeClient = FakeVmService(fakeVM);
|
||||
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{'status':'ok'});
|
||||
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{'status': 'ok'});
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
@@ -62,15 +62,28 @@ void main() {
|
||||
expect(exists, true, reason: 'Not found ${logFile.path}');
|
||||
|
||||
final String commandLog = await logFile.readAsString();
|
||||
const String waitForCommandLog = '>>> {command: waitFor, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo}';
|
||||
const String waitForCommandLog =
|
||||
'>>> {command: waitFor, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo}';
|
||||
const String responseLog = '<<< {isError: false, response: {status: ok}}';
|
||||
|
||||
expect(commandLog.contains(waitForCommandLog), true, reason: '$commandLog not contains $waitForCommandLog');
|
||||
expect(commandLog.contains(responseLog), true, reason: '$commandLog not contains $responseLog');
|
||||
expect(
|
||||
commandLog.contains(waitForCommandLog),
|
||||
true,
|
||||
reason: '$commandLog not contains $waitForCommandLog',
|
||||
);
|
||||
expect(
|
||||
commandLog.contains(responseLog),
|
||||
true,
|
||||
reason: '$commandLog not contains $responseLog',
|
||||
);
|
||||
});
|
||||
|
||||
test('logCommunicationToFile = false', () async {
|
||||
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate, logCommunicationToFile: false);
|
||||
driver = VMServiceFlutterDriver.connectedTo(
|
||||
fakeClient,
|
||||
fakeIsolate,
|
||||
logCommunicationToFile: false,
|
||||
);
|
||||
logFile = File(driver.logFilePathName);
|
||||
// clear log file if left in filetree from previous run
|
||||
if (logFile.existsSync()) {
|
||||
@@ -101,11 +114,15 @@ void main() {
|
||||
fakeIsolate = createFakeIsolate();
|
||||
fakeVM = FakeVM(fakeIsolate);
|
||||
fakeClient = FakeVmService(fakeVM);
|
||||
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{'status':'ok'});
|
||||
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{'status': 'ok'});
|
||||
});
|
||||
|
||||
test('printCommunication = true', () async {
|
||||
driver = VMServiceFlutterDriver.connectedTo(fakeClient, fakeIsolate, printCommunication: true);
|
||||
driver = VMServiceFlutterDriver.connectedTo(
|
||||
fakeClient,
|
||||
fakeIsolate,
|
||||
printCommunication: true,
|
||||
);
|
||||
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
|
||||
expect(log, <String>[
|
||||
'VMServiceFlutterDriver: >>> {command: waitFor, timeout: $_kSerializedTestTimeout, finderType: ByTooltipMessage, text: foo}',
|
||||
@@ -152,8 +169,10 @@ void main() {
|
||||
// becomes available. `.timeout` is used here to exit the infinite loop,
|
||||
// expecting that no other types of error are thrown during the process.
|
||||
expect(
|
||||
vmServiceConnectFunction('http://foo.bar', <String, dynamic>{})
|
||||
.timeout(const Duration(seconds: 1)),
|
||||
vmServiceConnectFunction(
|
||||
'http://foo.bar',
|
||||
<String, dynamic>{},
|
||||
).timeout(const Duration(seconds: 1)),
|
||||
throwsA(isA<TimeoutException>()),
|
||||
);
|
||||
});
|
||||
@@ -175,18 +194,15 @@ void main() {
|
||||
fakeVM.numberOfTriesBeforeResolvingIsolate = 5;
|
||||
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
|
||||
expect(driver, isNotNull);
|
||||
expect(
|
||||
fakeClient.connectionLog,
|
||||
<String>[
|
||||
'getIsolate',
|
||||
'setFlag pause_isolates_on_start false',
|
||||
'resume',
|
||||
'streamListen Isolate',
|
||||
'getIsolate',
|
||||
'onIsolateEvent',
|
||||
'streamCancel Isolate',
|
||||
],
|
||||
);
|
||||
expect(fakeClient.connectionLog, <String>[
|
||||
'getIsolate',
|
||||
'setFlag pause_isolates_on_start false',
|
||||
'resume',
|
||||
'streamListen Isolate',
|
||||
'getIsolate',
|
||||
'onIsolateEvent',
|
||||
'streamCancel Isolate',
|
||||
]);
|
||||
});
|
||||
|
||||
test('Refreshes isolate if it is not started for long time', () async {
|
||||
@@ -198,40 +214,37 @@ void main() {
|
||||
|
||||
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
|
||||
expect(driver, isNotNull);
|
||||
expect(
|
||||
fakeClient.connectionLog,
|
||||
<String>[
|
||||
'getIsolate',
|
||||
'getIsolate',
|
||||
'getIsolate',
|
||||
'getIsolate',
|
||||
'getIsolate',
|
||||
'setFlag pause_isolates_on_start false',
|
||||
'resume',
|
||||
'streamListen Isolate',
|
||||
'getIsolate',
|
||||
'onIsolateEvent',
|
||||
'streamCancel Isolate',
|
||||
],
|
||||
);
|
||||
expect(fakeClient.connectionLog, <String>[
|
||||
'getIsolate',
|
||||
'getIsolate',
|
||||
'getIsolate',
|
||||
'getIsolate',
|
||||
'getIsolate',
|
||||
'setFlag pause_isolates_on_start false',
|
||||
'resume',
|
||||
'streamListen Isolate',
|
||||
'getIsolate',
|
||||
'onIsolateEvent',
|
||||
'streamCancel Isolate',
|
||||
]);
|
||||
});
|
||||
|
||||
test('Connects to isolate number', () async {
|
||||
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPauseStart, timestamp: 0);
|
||||
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '', isolateNumber: int.parse(fakeIsolate.number!));
|
||||
expect(driver, isNotNull);
|
||||
expect(
|
||||
fakeClient.connectionLog,
|
||||
<String>[
|
||||
'getIsolate',
|
||||
'setFlag pause_isolates_on_start false',
|
||||
'resume',
|
||||
'streamListen Isolate',
|
||||
'getIsolate',
|
||||
'onIsolateEvent',
|
||||
'streamCancel Isolate',
|
||||
],
|
||||
final FlutterDriver driver = await FlutterDriver.connect(
|
||||
dartVmServiceUrl: '',
|
||||
isolateNumber: int.parse(fakeIsolate.number!),
|
||||
);
|
||||
expect(driver, isNotNull);
|
||||
expect(fakeClient.connectionLog, <String>[
|
||||
'getIsolate',
|
||||
'setFlag pause_isolates_on_start false',
|
||||
'resume',
|
||||
'streamListen Isolate',
|
||||
'getIsolate',
|
||||
'onIsolateEvent',
|
||||
'streamCancel Isolate',
|
||||
]);
|
||||
});
|
||||
|
||||
test('connects to isolate paused at start', () async {
|
||||
@@ -240,18 +253,15 @@ void main() {
|
||||
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
|
||||
expect(driver, isNotNull);
|
||||
expectLogContains('Isolate is paused at start');
|
||||
expect(
|
||||
fakeClient.connectionLog,
|
||||
<String>[
|
||||
'getIsolate',
|
||||
'setFlag pause_isolates_on_start false',
|
||||
'resume',
|
||||
'streamListen Isolate',
|
||||
'getIsolate',
|
||||
'onIsolateEvent',
|
||||
'streamCancel Isolate',
|
||||
],
|
||||
);
|
||||
expect(fakeClient.connectionLog, <String>[
|
||||
'getIsolate',
|
||||
'setFlag pause_isolates_on_start false',
|
||||
'resume',
|
||||
'streamListen Isolate',
|
||||
'getIsolate',
|
||||
'onIsolateEvent',
|
||||
'streamCancel Isolate',
|
||||
]);
|
||||
});
|
||||
|
||||
test('ignores setFlag failure', () async {
|
||||
@@ -259,12 +269,13 @@ void main() {
|
||||
fakeClient.failOnSetFlag = true;
|
||||
|
||||
final FlutterDriver driver = await FlutterDriver.connect(dartVmServiceUrl: '');
|
||||
expectLogContains('Failed to set pause_isolates_on_start=false, proceeding. '
|
||||
'Error: Exception: setFlag failed');
|
||||
expectLogContains(
|
||||
'Failed to set pause_isolates_on_start=false, proceeding. '
|
||||
'Error: Exception: setFlag failed',
|
||||
);
|
||||
expect(driver, isNotNull);
|
||||
});
|
||||
|
||||
|
||||
test('connects to isolate paused mid-flight', () async {
|
||||
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kPauseBreakpoint, timestamp: 0);
|
||||
|
||||
@@ -303,7 +314,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('connects to unpaused when onExtensionAdded does not contain the '
|
||||
'driver extension', () async {
|
||||
'driver extension', () async {
|
||||
fakeIsolate.pauseEvent = vms.Event(kind: vms.EventKind.kResume, timestamp: 0);
|
||||
fakeIsolate.extensionRPCs!.add('ext.flutter.driver');
|
||||
|
||||
@@ -403,9 +414,7 @@ void main() {
|
||||
'tree': 'hello',
|
||||
});
|
||||
final LayerTree result = await driver.getLayerTree(timeout: _kTestTimeout);
|
||||
final LayerTree referenceTree = LayerTree.fromJson(<String, String>{
|
||||
'tree': 'hello',
|
||||
});
|
||||
final LayerTree referenceTree = LayerTree.fromJson(<String, String>{'tree': 'hello'});
|
||||
expect(result.tree, referenceTree.tree);
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
'ext.flutter.driver {command: get_layer_tree, timeout: $_kSerializedTestTimeout}',
|
||||
@@ -462,10 +471,11 @@ void main() {
|
||||
|
||||
test('sends the waitForCondition of combined conditions command', () async {
|
||||
fakeClient.responses['waitForCondition'] = makeFakeResponse(<String, dynamic>{});
|
||||
const SerializableWaitCondition combinedCondition =
|
||||
CombinedCondition(<SerializableWaitCondition>[NoPendingFrame(), NoTransientCallbacks()]);
|
||||
const SerializableWaitCondition combinedCondition = CombinedCondition(
|
||||
<SerializableWaitCondition>[NoPendingFrame(), NoTransientCallbacks()],
|
||||
);
|
||||
await driver.waitForCondition(combinedCondition, timeout: _kTestTimeout);
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
'ext.flutter.driver {command: waitForCondition, timeout: $_kSerializedTestTimeout, conditionName: CombinedCondition, conditions: [{"conditionName":"NoPendingFrameCondition"},{"conditionName":"NoTransientCallbacksCondition"}]}',
|
||||
]);
|
||||
});
|
||||
@@ -493,49 +503,61 @@ void main() {
|
||||
|
||||
group('getOffset', () {
|
||||
setUp(() {
|
||||
fakeClient.responses['get_offset'] = makeFakeResponse(<String, double>{
|
||||
'dx': 11,
|
||||
'dy': 12,
|
||||
});
|
||||
fakeClient.responses['get_offset'] = makeFakeResponse(<String, double>{'dx': 11, 'dy': 12});
|
||||
});
|
||||
|
||||
test('sends the getCenter command', () async {
|
||||
final DriverOffset result = await driver.getCenter(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getCenter(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: center}',
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: center}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('sends the getTopLeft command', () async {
|
||||
final DriverOffset result = await driver.getTopLeft(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getTopLeft(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: topLeft}',
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: topLeft}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('sends the getTopRight command', () async {
|
||||
final DriverOffset result = await driver.getTopRight(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getTopRight(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: topRight}',
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: topRight}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('sends the getBottomLeft command', () async {
|
||||
final DriverOffset result = await driver.getBottomLeft(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getBottomLeft(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: bottomLeft}',
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: bottomLeft}',
|
||||
]);
|
||||
});
|
||||
|
||||
test('sends the getBottomRight command', () async {
|
||||
final DriverOffset result = await driver.getBottomRight(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getBottomRight(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: bottomRight}',
|
||||
'ext.flutter.driver {command: get_offset, timeout: 1234, finderType: ByValueKey, keyValueString: 123, keyValueType: int, offsetType: bottomRight}',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -585,9 +607,7 @@ void main() {
|
||||
fakeClient.incrementMicros = true;
|
||||
fakeClient.timelineResponses[1000001] = vms.Timeline.parse(<String, dynamic>{
|
||||
'traceEvents': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'name': 'test event 2',
|
||||
},
|
||||
<String, dynamic>{'name': 'test event 2'},
|
||||
],
|
||||
'timeOriginMicros': 1000000,
|
||||
'timeExtentMicros': 999999,
|
||||
@@ -618,15 +638,17 @@ void main() {
|
||||
test('specify non-default timeline streams', () async {
|
||||
bool actionCalled = false;
|
||||
|
||||
final Timeline timeline = await driver.traceAction(() async {
|
||||
actionCalled = true;
|
||||
},
|
||||
streams: const <TimelineStream>[
|
||||
TimelineStream.dart,
|
||||
TimelineStream.gc,
|
||||
TimelineStream.compiler,
|
||||
],
|
||||
retainPriorEvents: true);
|
||||
final Timeline timeline = await driver.traceAction(
|
||||
() async {
|
||||
actionCalled = true;
|
||||
},
|
||||
streams: const <TimelineStream>[
|
||||
TimelineStream.dart,
|
||||
TimelineStream.gc,
|
||||
TimelineStream.compiler,
|
||||
],
|
||||
retainPriorEvents: true,
|
||||
);
|
||||
|
||||
expect(actionCalled, isTrue);
|
||||
expect(fakeClient.connectionLog, <String>[
|
||||
@@ -649,7 +671,9 @@ void main() {
|
||||
expect(log, <String>[]);
|
||||
time.elapse(kUnusuallyLongTimeout);
|
||||
});
|
||||
expect(log, <String>['VMServiceFlutterDriver: waitFor message is taking a long time to complete...']);
|
||||
expect(log, <String>[
|
||||
'VMServiceFlutterDriver: waitFor message is taking a long time to complete...',
|
||||
]);
|
||||
});
|
||||
|
||||
test('local custom timeout', () async {
|
||||
@@ -661,7 +685,9 @@ void main() {
|
||||
expect(log, <String>[]);
|
||||
time.elapse(customTimeout);
|
||||
});
|
||||
expect(log, <String>['VMServiceFlutterDriver: waitFor message is taking a long time to complete...']);
|
||||
expect(log, <String>[
|
||||
'VMServiceFlutterDriver: waitFor message is taking a long time to complete...',
|
||||
]);
|
||||
});
|
||||
|
||||
test('remote error', () async {
|
||||
@@ -670,11 +696,13 @@ void main() {
|
||||
}, isError: true);
|
||||
await expectLater(
|
||||
() => driver.waitFor(find.byTooltip('foo')),
|
||||
throwsA(isA<DriverError>().having(
|
||||
(DriverError error) => error.message,
|
||||
'message',
|
||||
'Error in Flutter application: {message: This is a failure}',
|
||||
)),
|
||||
throwsA(
|
||||
isA<DriverError>().having(
|
||||
(DriverError error) => error.message,
|
||||
'message',
|
||||
'Error in Flutter application: {message: This is a failure}',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -718,7 +746,7 @@ void main() {
|
||||
fakeClient.responses['waitFor'] = makeFakeResponse(<String, dynamic>{});
|
||||
fakeClient.responses['set_frame_sync'] = makeFakeResponse(<String, dynamic>{});
|
||||
|
||||
await driver.runUnsynchronized(() async {
|
||||
await driver.runUnsynchronized(() async {
|
||||
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
|
||||
});
|
||||
|
||||
@@ -747,18 +775,14 @@ void main() {
|
||||
|
||||
test('GetHealth has no default timeout', () async {
|
||||
await driver.checkHealth();
|
||||
expect(
|
||||
fakeClient.commandLog,
|
||||
<String>['ext.flutter.driver {command: get_health}'],
|
||||
);
|
||||
expect(fakeClient.commandLog, <String>['ext.flutter.driver {command: get_health}']);
|
||||
});
|
||||
|
||||
test('does not interfere with explicit timeouts', () async {
|
||||
await driver.checkHealth(timeout: _kTestTimeout);
|
||||
expect(
|
||||
fakeClient.commandLog,
|
||||
<String>['ext.flutter.driver {command: get_health, timeout: $_kSerializedTestTimeout}'],
|
||||
);
|
||||
expect(fakeClient.commandLog, <String>[
|
||||
'ext.flutter.driver {command: get_health, timeout: $_kSerializedTestTimeout}',
|
||||
]);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -770,7 +794,9 @@ void main() {
|
||||
setUp(() {
|
||||
fakeConnection = FakeFlutterWebConnection();
|
||||
fakeConnection.supportsTimelineAction = true;
|
||||
fakeConnection.responses['waitFor'] = jsonEncode(makeFakeResponse(<String, dynamic>{'status': 'ok'}));
|
||||
fakeConnection.responses['waitFor'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{'status': 'ok'}),
|
||||
);
|
||||
});
|
||||
|
||||
tearDown(() {
|
||||
@@ -788,10 +814,15 @@ void main() {
|
||||
expect(exists, true, reason: 'Not found ${logFile.path}');
|
||||
|
||||
final String commandLog = await logFile.readAsString();
|
||||
const String waitForCommandLog = '>>> {command: waitFor, timeout: 1234, finderType: ByTooltipMessage, text: logCommunicationToFile test}';
|
||||
const String waitForCommandLog =
|
||||
'>>> {command: waitFor, timeout: 1234, finderType: ByTooltipMessage, text: logCommunicationToFile test}';
|
||||
const String responseLog = '<<< {isError: false, response: {status: ok}, type: Response}';
|
||||
|
||||
expect(commandLog, contains(waitForCommandLog), reason: '$commandLog not contains $waitForCommandLog');
|
||||
expect(
|
||||
commandLog,
|
||||
contains(waitForCommandLog),
|
||||
reason: '$commandLog not contains $waitForCommandLog',
|
||||
);
|
||||
expect(commandLog, contains(responseLog), reason: '$commandLog not contains $responseLog');
|
||||
});
|
||||
|
||||
@@ -816,7 +847,9 @@ void main() {
|
||||
log.clear();
|
||||
fakeConnection = FakeFlutterWebConnection();
|
||||
fakeConnection.supportsTimelineAction = true;
|
||||
fakeConnection.responses['waitFor'] = jsonEncode(makeFakeResponse(<String, dynamic>{'status': 'ok'}));
|
||||
fakeConnection.responses['waitFor'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{'status': 'ok'}),
|
||||
);
|
||||
});
|
||||
|
||||
test('printCommunication = true', () async {
|
||||
@@ -851,8 +884,7 @@ void main() {
|
||||
|
||||
group('ByValueKey', () {
|
||||
test('restricts value types', () async {
|
||||
expect(() => find.byValueKey(null),
|
||||
throwsDriverError);
|
||||
expect(() => find.byValueKey(null), throwsDriverError);
|
||||
});
|
||||
|
||||
test('finds by ValueKey', () async {
|
||||
@@ -894,7 +926,9 @@ void main() {
|
||||
|
||||
group('getText', () {
|
||||
test('sends the getText command', () async {
|
||||
fakeConnection.responses['get_text'] = jsonEncode(makeFakeResponse(<String, dynamic>{'text': 'hello'}));
|
||||
fakeConnection.responses['get_text'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{'text': 'hello'}),
|
||||
);
|
||||
final String result = await driver.getText(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
expect(result, 'hello');
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
@@ -905,7 +939,9 @@ void main() {
|
||||
|
||||
group('waitFor', () {
|
||||
test('sends the waitFor command', () async {
|
||||
fakeConnection.responses['waitFor'] = jsonEncode(makeFakeResponse(<String, dynamic>{'text': 'hello'}));
|
||||
fakeConnection.responses['waitFor'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{'text': 'hello'}),
|
||||
);
|
||||
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
r'''window.$flutterDriver('{"command":"waitFor","timeout":"1234","finderType":"ByTooltipMessage","text":"foo"}') 0:00:01.234000''',
|
||||
@@ -915,7 +951,9 @@ void main() {
|
||||
|
||||
group('waitForCondition', () {
|
||||
setUp(() {
|
||||
fakeConnection.responses['waitForCondition'] = jsonEncode(makeFakeResponse(<String, dynamic>{'text': 'hello'}));
|
||||
fakeConnection.responses['waitForCondition'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{'text': 'hello'}),
|
||||
);
|
||||
});
|
||||
|
||||
test('sends the wait for NoPendingFrameCondition command', () async {
|
||||
@@ -945,7 +983,9 @@ void main() {
|
||||
|
||||
group('waitUntilNoTransientCallbacks', () {
|
||||
test('sends the waitUntilNoTransientCallbacks command', () async {
|
||||
fakeConnection.responses['waitForCondition'] = jsonEncode(makeFakeResponse(<String, dynamic>{}));
|
||||
fakeConnection.responses['waitForCondition'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{}),
|
||||
);
|
||||
await driver.waitUntilNoTransientCallbacks(timeout: _kTestTimeout);
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
r'''window.$flutterDriver('{"command":"waitForCondition","timeout":"1234","conditionName":"NoTransientCallbacksCondition"}') 0:00:01.234000''',
|
||||
@@ -955,14 +995,16 @@ void main() {
|
||||
|
||||
group('getOffset', () {
|
||||
setUp(() {
|
||||
fakeConnection.responses['get_offset'] = jsonEncode(makeFakeResponse(<String, double>{
|
||||
'dx': 11,
|
||||
'dy': 12,
|
||||
}));
|
||||
fakeConnection.responses['get_offset'] = jsonEncode(
|
||||
makeFakeResponse(<String, double>{'dx': 11, 'dy': 12}),
|
||||
);
|
||||
});
|
||||
|
||||
test('sends the getCenter command', () async {
|
||||
final DriverOffset result = await driver.getCenter(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getCenter(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"center"}') 0:00:01.234000''',
|
||||
@@ -970,7 +1012,10 @@ void main() {
|
||||
});
|
||||
|
||||
test('sends the getTopLeft command', () async {
|
||||
final DriverOffset result = await driver.getTopLeft(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getTopLeft(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"topLeft"}') 0:00:01.234000''',
|
||||
@@ -978,7 +1023,10 @@ void main() {
|
||||
});
|
||||
|
||||
test('sends the getTopRight command', () async {
|
||||
final DriverOffset result = await driver.getTopRight(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getTopRight(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"topRight"}') 0:00:01.234000''',
|
||||
@@ -986,7 +1034,10 @@ void main() {
|
||||
});
|
||||
|
||||
test('sends the getBottomLeft command', () async {
|
||||
final DriverOffset result = await driver.getBottomLeft(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getBottomLeft(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"bottomLeft"}') 0:00:01.234000''',
|
||||
@@ -994,7 +1045,10 @@ void main() {
|
||||
});
|
||||
|
||||
test('sends the getBottomRight command', () async {
|
||||
final DriverOffset result = await driver.getBottomRight(find.byValueKey(123), timeout: _kTestTimeout);
|
||||
final DriverOffset result = await driver.getBottomRight(
|
||||
find.byValueKey(123),
|
||||
timeout: _kTestTimeout,
|
||||
);
|
||||
expect(result, const DriverOffset(11, 12));
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
r'''window.$flutterDriver('{"command":"get_offset","timeout":"1234","finderType":"ByValueKey","keyValueString":"123","keyValueType":"int","offsetType":"bottomRight"}') 0:00:01.234000''',
|
||||
@@ -1003,7 +1057,9 @@ void main() {
|
||||
});
|
||||
|
||||
test('checks the health of the driver extension', () async {
|
||||
fakeConnection.responses['get_health'] = jsonEncode(makeFakeResponse(<String, dynamic>{'status': 'ok'}));
|
||||
fakeConnection.responses['get_health'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{'status': 'ok'}),
|
||||
);
|
||||
await driver.checkHealth();
|
||||
expect(fakeConnection.commandLog, <String>[
|
||||
r'''window.$flutterDriver('{"command":"get_health"}') null''',
|
||||
@@ -1034,8 +1090,12 @@ void main() {
|
||||
|
||||
group('runUnsynchronized', () {
|
||||
test('wrap waitFor with runUnsynchronized', () async {
|
||||
fakeConnection.responses['waitFor'] = jsonEncode(makeFakeResponse(<String, dynamic>{'text': 'hello'}));
|
||||
fakeConnection.responses['set_frame_sync'] = jsonEncode(makeFakeResponse(<String, dynamic>{}));
|
||||
fakeConnection.responses['waitFor'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{'text': 'hello'}),
|
||||
);
|
||||
fakeConnection.responses['set_frame_sync'] = jsonEncode(
|
||||
makeFakeResponse(<String, dynamic>{}),
|
||||
);
|
||||
|
||||
await driver.runUnsynchronized(() async {
|
||||
await driver.waitFor(find.byTooltip('foo'), timeout: _kTestTimeout);
|
||||
@@ -1060,7 +1120,12 @@ void main() {
|
||||
});
|
||||
|
||||
test('tracing', () async {
|
||||
expect(driver.traceAction(() async { return Future<dynamic>.value(); }), throwsUnsupportedError);
|
||||
expect(
|
||||
driver.traceAction(() async {
|
||||
return Future<dynamic>.value();
|
||||
}),
|
||||
throwsUnsupportedError,
|
||||
);
|
||||
expect(driver.startTracing(), throwsUnsupportedError);
|
||||
expect(driver.stopTracingAndDownloadTimeline(), throwsUnsupportedError);
|
||||
expect(driver.clearTimeline(), throwsUnsupportedError);
|
||||
@@ -1080,14 +1145,8 @@ String _checkAndEncode(dynamic script) {
|
||||
return scriptString.substring(_kWebScriptPrefix.length, script.length - 2);
|
||||
}
|
||||
|
||||
vms.Response? makeFakeResponse(
|
||||
Map<String, dynamic> response, {
|
||||
bool isError = false,
|
||||
}) {
|
||||
return vms.Response.parse(<String, dynamic>{
|
||||
'isError': isError,
|
||||
'response': response,
|
||||
});
|
||||
vms.Response? makeFakeResponse(Map<String, dynamic> response, {bool isError = false}) {
|
||||
return vms.Response.parse(<String, dynamic>{'isError': isError, 'response': response});
|
||||
}
|
||||
|
||||
void Function(vms.Isolate) changeIsolateEventAfter(int gets, vms.Event nextEvent) {
|
||||
@@ -1108,7 +1167,8 @@ class FakeFlutterWebConnection extends Fake implements FlutterWebConnection {
|
||||
@override
|
||||
Future<dynamic> sendCommand(String script, Duration? duration) async {
|
||||
commandLog.add('$script $duration');
|
||||
final Map<String, dynamic> decoded = jsonDecode(_checkAndEncode(script)) as Map<String, dynamic>;
|
||||
final Map<String, dynamic> decoded =
|
||||
jsonDecode(_checkAndEncode(script)) as Map<String, dynamic>;
|
||||
final dynamic response = responses[decoded['command']];
|
||||
assert(response != null, 'Missing ${decoded['command']} in responses.');
|
||||
return response;
|
||||
@@ -1189,7 +1249,11 @@ class FakeVmService extends Fake implements vms.VmService {
|
||||
Future<void>? artificialExtensionDelay;
|
||||
|
||||
@override
|
||||
Future<vms.Response> callServiceExtension(String method, {Map<dynamic, dynamic>? args, String? isolateId}) async {
|
||||
Future<vms.Response> callServiceExtension(
|
||||
String method, {
|
||||
Map<dynamic, dynamic>? args,
|
||||
String? isolateId,
|
||||
}) async {
|
||||
commandLog.add('$method $args');
|
||||
await artificialExtensionDelay;
|
||||
|
||||
@@ -1231,9 +1295,7 @@ class FakeVmService extends Fake implements vms.VmService {
|
||||
final Map<int, vms.Timeline?> timelineResponses = <int, vms.Timeline?>{
|
||||
1: vms.Timeline.parse(<String, dynamic>{
|
||||
'traceEvents': <dynamic>[
|
||||
<String, dynamic>{
|
||||
'name': 'test event',
|
||||
},
|
||||
<String, dynamic>{'name': 'test event'},
|
||||
],
|
||||
'timeOriginMicros': 0,
|
||||
'timeExtentMicros': 999999,
|
||||
@@ -1267,15 +1329,8 @@ class FakeVM extends Fake implements vms.VM {
|
||||
@override
|
||||
List<vms.IsolateRef> get isolates {
|
||||
numberOfTriesBeforeResolvingIsolate -= 1;
|
||||
return <vms.Isolate>[
|
||||
if (numberOfTriesBeforeResolvingIsolate <= 0)
|
||||
isolate!,
|
||||
];
|
||||
return <vms.Isolate>[if (numberOfTriesBeforeResolvingIsolate <= 0) isolate!];
|
||||
}
|
||||
}
|
||||
|
||||
vms.Isolate createFakeIsolate() => vms.Isolate(
|
||||
id: '123',
|
||||
number: '123',
|
||||
extensionRPCs: <String>[],
|
||||
);
|
||||
vms.Isolate createFakeIsolate() => vms.Isolate(id: '123', number: '123', extensionRPCs: <String>[]);
|
||||
|
||||
@@ -7,7 +7,7 @@ import 'package:flutter_driver/src/extension/_extension_io.dart';
|
||||
import '../../common.dart';
|
||||
|
||||
void main() {
|
||||
group('test io_extension',() {
|
||||
group('test io_extension', () {
|
||||
late Future<Map<String, dynamic>> Function(Map<String, String>) call;
|
||||
|
||||
setUp(() {
|
||||
|
||||
@@ -7,10 +7,9 @@ import 'package:flutter_driver/flutter_driver.dart';
|
||||
class StubNestedCommand extends CommandWithTarget {
|
||||
StubNestedCommand(super.finder, this.times, {super.timeout});
|
||||
|
||||
StubNestedCommand.deserialize(
|
||||
super.json, super.finderFactory)
|
||||
: times = int.parse(json['times']!),
|
||||
super.deserialize();
|
||||
StubNestedCommand.deserialize(super.json, super.finderFactory)
|
||||
: times = int.parse(json['times']!),
|
||||
super.deserialize();
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() {
|
||||
@@ -27,8 +26,8 @@ class StubProberCommand extends CommandWithTarget {
|
||||
StubProberCommand(super.finder, this.times, {super.timeout});
|
||||
|
||||
StubProberCommand.deserialize(super.json, super.finderFactory)
|
||||
: times = int.parse(json['times']!),
|
||||
super.deserialize();
|
||||
: times = int.parse(json['times']!),
|
||||
super.deserialize();
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() {
|
||||
@@ -48,8 +47,6 @@ class StubCommandResult extends Result {
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() {
|
||||
return <String, dynamic>{
|
||||
'resultParam': resultParam,
|
||||
};
|
||||
return <String, dynamic>{'resultParam': resultParam};
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,7 +13,12 @@ class StubNestedCommandExtension extends CommandExtension {
|
||||
String get commandKind => 'StubNestedCommand';
|
||||
|
||||
@override
|
||||
Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async {
|
||||
Future<Result> call(
|
||||
Command command,
|
||||
WidgetController prober,
|
||||
CreateFinderFactory finderFactory,
|
||||
CommandHandlerFactory handlerFactory,
|
||||
) async {
|
||||
final StubNestedCommand stubCommand = command as StubNestedCommand;
|
||||
handlerFactory.waitForElement(finderFactory.createFinder(stubCommand.finder));
|
||||
for (int index = 0; index < stubCommand.times; index++) {
|
||||
@@ -23,7 +28,11 @@ class StubNestedCommandExtension extends CommandExtension {
|
||||
}
|
||||
|
||||
@override
|
||||
Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory) {
|
||||
Command deserialize(
|
||||
Map<String, String> params,
|
||||
DeserializeFinderFactory finderFactory,
|
||||
DeserializeCommandFactory commandFactory,
|
||||
) {
|
||||
return StubNestedCommand.deserialize(params, finderFactory);
|
||||
}
|
||||
}
|
||||
@@ -33,7 +42,12 @@ class StubProberCommandExtension extends CommandExtension {
|
||||
String get commandKind => 'StubProberCommand';
|
||||
|
||||
@override
|
||||
Future<Result> call(Command command, WidgetController prober, CreateFinderFactory finderFactory, CommandHandlerFactory handlerFactory) async {
|
||||
Future<Result> call(
|
||||
Command command,
|
||||
WidgetController prober,
|
||||
CreateFinderFactory finderFactory,
|
||||
CommandHandlerFactory handlerFactory,
|
||||
) async {
|
||||
final StubProberCommand stubCommand = command as StubProberCommand;
|
||||
final Finder finder = finderFactory.createFinder(stubCommand.finder);
|
||||
handlerFactory.waitForElement(finder);
|
||||
@@ -44,7 +58,11 @@ class StubProberCommandExtension extends CommandExtension {
|
||||
}
|
||||
|
||||
@override
|
||||
Command deserialize(Map<String, String> params, DeserializeFinderFactory finderFactory, DeserializeCommandFactory commandFactory) {
|
||||
Command deserialize(
|
||||
Map<String, String> params,
|
||||
DeserializeFinderFactory finderFactory,
|
||||
DeserializeCommandFactory commandFactory,
|
||||
) {
|
||||
return StubProberCommand.deserialize(params, finderFactory);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,10 +11,7 @@ import 'stub_finder.dart';
|
||||
|
||||
class StubFinderExtension extends FinderExtension {
|
||||
@override
|
||||
Finder createFinder(
|
||||
SerializableFinder finder,
|
||||
CreateFinderFactory finderFactory,
|
||||
) {
|
||||
Finder createFinder(SerializableFinder finder, CreateFinderFactory finderFactory) {
|
||||
return find.byWidgetPredicate((Widget widget) {
|
||||
final Key? key = widget.key;
|
||||
if (key is! ValueKey<String>) {
|
||||
|
||||
@@ -6,14 +6,13 @@ import 'package:flutter_driver/flutter_driver.dart' as flutter_driver;
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
void main() {
|
||||
test('flutter_driver.TextInputAction should be sync with TextInputAction',
|
||||
() {
|
||||
final List<String> actual = flutter_driver.TextInputAction.values
|
||||
.map((flutter_driver.TextInputAction action) => action.name)
|
||||
.toList();
|
||||
final List<String> matcher = TextInputAction.values
|
||||
.map((TextInputAction action) => action.name)
|
||||
.toList();
|
||||
test('flutter_driver.TextInputAction should be sync with TextInputAction', () {
|
||||
final List<String> actual =
|
||||
flutter_driver.TextInputAction.values
|
||||
.map((flutter_driver.TextInputAction action) => action.name)
|
||||
.toList();
|
||||
final List<String> matcher =
|
||||
TextInputAction.values.map((TextInputAction action) => action.name).toList();
|
||||
expect(actual, matcher);
|
||||
});
|
||||
}
|
||||
|
||||
@@ -17,11 +17,10 @@ import '../../common.dart';
|
||||
|
||||
void main() {
|
||||
group('TimelineSummary', () {
|
||||
|
||||
TimelineSummary summarize(List<Map<String, dynamic>> testEvents) {
|
||||
return TimelineSummary.summarize(Timeline.fromJson(<String, dynamic>{
|
||||
'traceEvents': testEvents,
|
||||
}));
|
||||
return TimelineSummary.summarize(
|
||||
Timeline.fromJson(<String, dynamic>{'traceEvents': testEvents}),
|
||||
);
|
||||
}
|
||||
|
||||
Map<String, dynamic> frameBegin(int timeStamp) => <String, dynamic>{
|
||||
@@ -52,38 +51,33 @@ void main() {
|
||||
'name': 'SceneDisplayLag',
|
||||
'ph': 'b',
|
||||
'ts': timeStamp,
|
||||
'args': <String, String>{
|
||||
'vsync_transitions_missed': vsyncsMissed.toString(),
|
||||
},
|
||||
'args': <String, String>{'vsync_transitions_missed': vsyncsMissed.toString()},
|
||||
};
|
||||
|
||||
Map<String, dynamic> lagEnd(int timeStamp, int vsyncsMissed) => <String, dynamic>{
|
||||
'name': 'SceneDisplayLag',
|
||||
'ph': 'e',
|
||||
'ts': timeStamp,
|
||||
'args': <String, String>{
|
||||
'vsync_transitions_missed': vsyncsMissed.toString(),
|
||||
},
|
||||
'args': <String, String>{'vsync_transitions_missed': vsyncsMissed.toString()},
|
||||
};
|
||||
|
||||
Map<String, dynamic> cpuUsage(int timeStamp, double cpuUsage) => <String, dynamic>{
|
||||
'cat': 'embedder',
|
||||
'name': 'CpuUsage',
|
||||
'ts': timeStamp,
|
||||
'args': <String, String>{
|
||||
'total_cpu_usage': cpuUsage.toString(),
|
||||
},
|
||||
'args': <String, String>{'total_cpu_usage': cpuUsage.toString()},
|
||||
};
|
||||
|
||||
Map<String, dynamic> memoryUsage(int timeStamp, double dirty, double shared) => <String, dynamic>{
|
||||
'cat': 'embedder',
|
||||
'name': 'MemoryUsage',
|
||||
'ts': timeStamp,
|
||||
'args': <String, String>{
|
||||
'owned_shared_memory_usage': shared.toString(),
|
||||
'dirty_memory_usage': dirty.toString(),
|
||||
},
|
||||
};
|
||||
Map<String, dynamic> memoryUsage(int timeStamp, double dirty, double shared) =>
|
||||
<String, dynamic>{
|
||||
'cat': 'embedder',
|
||||
'name': 'MemoryUsage',
|
||||
'ts': timeStamp,
|
||||
'args': <String, String>{
|
||||
'owned_shared_memory_usage': shared.toString(),
|
||||
'dirty_memory_usage': dirty.toString(),
|
||||
},
|
||||
};
|
||||
|
||||
Map<String, dynamic> platformVsync(int timeStamp) => <String, dynamic>{
|
||||
'name': 'VSYNC',
|
||||
@@ -91,14 +85,16 @@ void main() {
|
||||
'ts': timeStamp,
|
||||
};
|
||||
|
||||
Map<String, dynamic> vsyncCallback(int timeStamp, {String phase = 'B', String startTime = '2750850055428', String endTime = '2750866722095'}) => <String, dynamic>{
|
||||
Map<String, dynamic> vsyncCallback(
|
||||
int timeStamp, {
|
||||
String phase = 'B',
|
||||
String startTime = '2750850055428',
|
||||
String endTime = '2750866722095',
|
||||
}) => <String, dynamic>{
|
||||
'name': 'VsyncProcessCallback',
|
||||
'ph': phase,
|
||||
'ts': timeStamp,
|
||||
'args': <String, dynamic>{
|
||||
'StartTime': startTime,
|
||||
'TargetTime': endTime,
|
||||
},
|
||||
'args': <String, dynamic>{'StartTime': startTime, 'TargetTime': endTime},
|
||||
};
|
||||
|
||||
List<Map<String, dynamic>> genGC(String name, int count, int startTime, int timeDiff) {
|
||||
@@ -114,9 +110,7 @@ void main() {
|
||||
'ts': ts,
|
||||
'tts': ts,
|
||||
'ph': begin ? 'B' : 'E',
|
||||
'args': <String, dynamic>{
|
||||
'isolateGroupId': 'isolateGroups/10824099774666259225',
|
||||
},
|
||||
'args': <String, dynamic>{'isolateGroupId': 'isolateGroups/10824099774666259225'},
|
||||
});
|
||||
ts = ts + timeDiff;
|
||||
begin = !begin;
|
||||
@@ -161,8 +155,10 @@ void main() {
|
||||
test('counts frames', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
frameBegin(1000), frameEnd(2000),
|
||||
frameBegin(3000), frameEnd(5000),
|
||||
frameBegin(1000),
|
||||
frameEnd(2000),
|
||||
frameBegin(3000),
|
||||
frameEnd(5000),
|
||||
]).countFrames(),
|
||||
2,
|
||||
);
|
||||
@@ -174,19 +170,22 @@ void main() {
|
||||
expect(
|
||||
() => summarize(<Map<String, dynamic>>[]).computeAverageFrameBuildTimeMillis(),
|
||||
throwsA(
|
||||
isA<StateError>()
|
||||
.having((StateError e) => e.message,
|
||||
isA<StateError>().having(
|
||||
(StateError e) => e.message,
|
||||
'message',
|
||||
contains('The TimelineSummary had no events to summarize.'),
|
||||
)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('computes average frame build time in milliseconds', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
frameBegin(1000), frameEnd(2000),
|
||||
frameBegin(3000), frameEnd(5000),
|
||||
frameBegin(1000),
|
||||
frameEnd(2000),
|
||||
frameBegin(3000),
|
||||
frameEnd(5000),
|
||||
]).computeAverageFrameBuildTimeMillis(),
|
||||
1.5,
|
||||
);
|
||||
@@ -196,7 +195,8 @@ void main() {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
frameEnd(1000),
|
||||
frameBegin(2000), frameEnd(4000),
|
||||
frameBegin(2000),
|
||||
frameEnd(4000),
|
||||
]).computeAverageFrameBuildTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
@@ -205,7 +205,8 @@ void main() {
|
||||
test('skips trailing "begin" events', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
frameBegin(2000), frameEnd(4000),
|
||||
frameBegin(2000),
|
||||
frameEnd(4000),
|
||||
frameBegin(5000),
|
||||
]).computeAverageFrameBuildTimeMillis(),
|
||||
2.0,
|
||||
@@ -243,26 +244,31 @@ void main() {
|
||||
expect(
|
||||
() => summarize(<Map<String, dynamic>>[]).computeWorstFrameBuildTimeMillis(),
|
||||
throwsA(
|
||||
isA<StateError>()
|
||||
.having((StateError e) => e.message,
|
||||
isA<StateError>().having(
|
||||
(StateError e) => e.message,
|
||||
'message',
|
||||
contains('The TimelineSummary had no events to summarize.'),
|
||||
)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('computes worst frame build time in milliseconds', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
frameBegin(1000), frameEnd(2000),
|
||||
frameBegin(3000), frameEnd(5000),
|
||||
frameBegin(1000),
|
||||
frameEnd(2000),
|
||||
frameBegin(3000),
|
||||
frameEnd(5000),
|
||||
]).computeWorstFrameBuildTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
frameBegin(3000), frameEnd(5000),
|
||||
frameBegin(1000), frameEnd(2000),
|
||||
frameBegin(3000),
|
||||
frameEnd(5000),
|
||||
frameBegin(1000),
|
||||
frameEnd(2000),
|
||||
]).computeWorstFrameBuildTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
@@ -272,7 +278,8 @@ void main() {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
frameEnd(1000),
|
||||
frameBegin(2000), frameEnd(4000),
|
||||
frameBegin(2000),
|
||||
frameEnd(4000),
|
||||
]).computeWorstFrameBuildTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
@@ -281,7 +288,8 @@ void main() {
|
||||
test('skips trailing "begin" events', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
frameBegin(2000), frameEnd(4000),
|
||||
frameBegin(2000),
|
||||
frameEnd(4000),
|
||||
frameBegin(5000),
|
||||
]).computeWorstFrameBuildTimeMillis(),
|
||||
2.0,
|
||||
@@ -292,9 +300,12 @@ void main() {
|
||||
group('computeMissedFrameBuildBudgetCount', () {
|
||||
test('computes the number of missed build budgets', () {
|
||||
final TimelineSummary summary = summarize(<Map<String, dynamic>>[
|
||||
frameBegin(1000), frameEnd(18000),
|
||||
frameBegin(19000), frameEnd(28000),
|
||||
frameBegin(29000), frameEnd(47000),
|
||||
frameBegin(1000),
|
||||
frameEnd(18000),
|
||||
frameBegin(19000),
|
||||
frameEnd(28000),
|
||||
frameBegin(29000),
|
||||
frameEnd(47000),
|
||||
]);
|
||||
|
||||
expect(summary.countFrames(), 3);
|
||||
@@ -307,41 +318,46 @@ void main() {
|
||||
expect(
|
||||
() => summarize(<Map<String, dynamic>>[]).computeAverageFrameRasterizerTimeMillis(),
|
||||
throwsA(
|
||||
isA<StateError>()
|
||||
.having((StateError e) => e.message,
|
||||
isA<StateError>().having(
|
||||
(StateError e) => e.message,
|
||||
'message',
|
||||
contains('The TimelineSummary had no events to summarize.'),
|
||||
)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('computes average frame rasterizer time in milliseconds', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(1000), end(2000),
|
||||
begin(3000), end(5000),
|
||||
]).computeAverageFrameRasterizerTimeMillis(),
|
||||
1.5,
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(1000),
|
||||
end(2000),
|
||||
begin(3000),
|
||||
end(5000),
|
||||
]).computeAverageFrameRasterizerTimeMillis(),
|
||||
1.5,
|
||||
);
|
||||
});
|
||||
|
||||
test('skips leading "end" events', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
end(1000),
|
||||
begin(2000), end(4000),
|
||||
]).computeAverageFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
summarize(<Map<String, dynamic>>[
|
||||
end(1000),
|
||||
begin(2000),
|
||||
end(4000),
|
||||
]).computeAverageFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
});
|
||||
|
||||
test('skips trailing "begin" events', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(2000), end(4000),
|
||||
begin(5000),
|
||||
]).computeAverageFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(2000),
|
||||
end(4000),
|
||||
begin(5000),
|
||||
]).computeAverageFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -351,49 +367,55 @@ void main() {
|
||||
expect(
|
||||
() => summarize(<Map<String, dynamic>>[]).computeWorstFrameRasterizerTimeMillis(),
|
||||
throwsA(
|
||||
isA<StateError>()
|
||||
.having((StateError e) => e.message,
|
||||
isA<StateError>().having(
|
||||
(StateError e) => e.message,
|
||||
'message',
|
||||
contains('The TimelineSummary had no events to summarize.'),
|
||||
)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
test('computes worst frame rasterizer time in milliseconds', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(1000), end(2000),
|
||||
begin(3000), end(5000),
|
||||
]).computeWorstFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(1000),
|
||||
end(2000),
|
||||
begin(3000),
|
||||
end(5000),
|
||||
]).computeWorstFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(3000), end(5000),
|
||||
begin(1000), end(2000),
|
||||
]).computeWorstFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(3000),
|
||||
end(5000),
|
||||
begin(1000),
|
||||
end(2000),
|
||||
]).computeWorstFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
});
|
||||
|
||||
test('skips leading "end" events', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
end(1000),
|
||||
begin(2000), end(4000),
|
||||
]).computeWorstFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
summarize(<Map<String, dynamic>>[
|
||||
end(1000),
|
||||
begin(2000),
|
||||
end(4000),
|
||||
]).computeWorstFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
});
|
||||
|
||||
test('skips trailing "begin" events', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(2000), end(4000),
|
||||
begin(5000),
|
||||
]).computeWorstFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(2000),
|
||||
end(4000),
|
||||
begin(5000),
|
||||
]).computeWorstFrameRasterizerTimeMillis(),
|
||||
2.0,
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -401,33 +423,32 @@ void main() {
|
||||
group('percentile_frame_rasterizer_time_millis', () {
|
||||
test('throws when there is no data', () {
|
||||
expect(
|
||||
() => summarize(<Map<String, dynamic>>[]).computePercentileFrameRasterizerTimeMillis(90.0),
|
||||
() =>
|
||||
summarize(<Map<String, dynamic>>[]).computePercentileFrameRasterizerTimeMillis(90.0),
|
||||
throwsA(
|
||||
isA<StateError>()
|
||||
.having((StateError e) => e.message,
|
||||
isA<StateError>().having(
|
||||
(StateError e) => e.message,
|
||||
'message',
|
||||
contains('The TimelineSummary had no events to summarize.'),
|
||||
)),
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
|
||||
const List<List<int>> sequences = <List<int>>[
|
||||
<int>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
|
||||
<int>[1, 2, 3, 4, 5],
|
||||
<int>[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],
|
||||
];
|
||||
|
||||
const List<int> p90s = <int>[
|
||||
9,
|
||||
5,
|
||||
18,
|
||||
];
|
||||
const List<int> p90s = <int>[9, 5, 18];
|
||||
|
||||
test('computes 90th frame rasterizer time in milliseconds', () {
|
||||
for (int i = 0; i < sequences.length; ++i) {
|
||||
expect(
|
||||
summarize(rasterizeTimeSequenceInMillis(sequences[i])).computePercentileFrameRasterizerTimeMillis(90.0),
|
||||
summarize(
|
||||
rasterizeTimeSequenceInMillis(sequences[i]),
|
||||
).computePercentileFrameRasterizerTimeMillis(90.0),
|
||||
p90s[i],
|
||||
);
|
||||
}
|
||||
@@ -439,7 +460,9 @@ void main() {
|
||||
sequence.add(i);
|
||||
}
|
||||
expect(
|
||||
summarize(rasterizeTimeSequenceInMillis(sequence)).computePercentileFrameRasterizerTimeMillis(99.0),
|
||||
summarize(
|
||||
rasterizeTimeSequenceInMillis(sequence),
|
||||
).computePercentileFrameRasterizerTimeMillis(99.0),
|
||||
99,
|
||||
);
|
||||
});
|
||||
@@ -448,9 +471,12 @@ void main() {
|
||||
group('computeMissedFrameRasterizerBudgetCount', () {
|
||||
test('computes the number of missed rasterizer budgets', () {
|
||||
final TimelineSummary summary = summarize(<Map<String, dynamic>>[
|
||||
begin(1000), end(18000),
|
||||
begin(19000), end(28000),
|
||||
begin(29000), end(47000),
|
||||
begin(1000),
|
||||
end(18000),
|
||||
begin(19000),
|
||||
end(28000),
|
||||
begin(29000),
|
||||
end(47000),
|
||||
]);
|
||||
|
||||
expect(summary.computeMissedFrameRasterizerBudgetCount(), 2);
|
||||
@@ -461,14 +487,20 @@ void main() {
|
||||
test('computes and returns summary as JSON', () {
|
||||
expect(
|
||||
summarize(<Map<String, dynamic>>[
|
||||
begin(1000), end(19000),
|
||||
begin(19001), end(29001),
|
||||
begin(29002), end(49002),
|
||||
begin(1000),
|
||||
end(19000),
|
||||
begin(19001),
|
||||
end(29001),
|
||||
begin(29002),
|
||||
end(49002),
|
||||
...newGenGC(4, 10, 100),
|
||||
...oldGenGC(5, 10000, 100),
|
||||
frameBegin(1000), frameEnd(18000),
|
||||
frameBegin(19000), frameEnd(28000),
|
||||
frameBegin(29000), frameEnd(48000),
|
||||
frameBegin(1000),
|
||||
frameEnd(18000),
|
||||
frameBegin(19000),
|
||||
frameEnd(28000),
|
||||
frameBegin(29000),
|
||||
frameEnd(48000),
|
||||
frameRequestPendingStart('1', 1000),
|
||||
frameRequestPendingEnd('1', 2000),
|
||||
frameRequestPendingStart('2', 3000),
|
||||
@@ -542,7 +574,6 @@ void main() {
|
||||
});
|
||||
|
||||
group('writeTimelineToFile', () {
|
||||
|
||||
late Directory tempDir;
|
||||
|
||||
setUp(() {
|
||||
@@ -556,8 +587,9 @@ void main() {
|
||||
});
|
||||
|
||||
test('writes timeline to JSON file without summary', () async {
|
||||
await summarize(<Map<String, String>>[<String, String>{'foo': 'bar'}])
|
||||
.writeTimelineToFile('test', destinationDirectory: tempDir.path, includeSummary: false);
|
||||
await summarize(<Map<String, String>>[
|
||||
<String, String>{'foo': 'bar'},
|
||||
]).writeTimelineToFile('test', destinationDirectory: tempDir.path, includeSummary: false);
|
||||
final String written =
|
||||
await fs.file(path.join(tempDir.path, 'test.timeline.json')).readAsString();
|
||||
expect(written, '{"traceEvents":[{"foo":"bar"}]}');
|
||||
@@ -566,12 +598,11 @@ void main() {
|
||||
test('writes timeline to JSON file with summary', () async {
|
||||
await summarize(<Map<String, dynamic>>[
|
||||
<String, String>{'foo': 'bar'},
|
||||
begin(1000), end(19000),
|
||||
frameBegin(1000), frameEnd(18000),
|
||||
]).writeTimelineToFile(
|
||||
'test',
|
||||
destinationDirectory: tempDir.path,
|
||||
);
|
||||
begin(1000),
|
||||
end(19000),
|
||||
frameBegin(1000),
|
||||
frameEnd(18000),
|
||||
]).writeTimelineToFile('test', destinationDirectory: tempDir.path);
|
||||
final String written =
|
||||
await fs.file(path.join(tempDir.path, 'test.timeline.json')).readAsString();
|
||||
expect(
|
||||
@@ -586,20 +617,32 @@ void main() {
|
||||
|
||||
test('writes summary to JSON file', () async {
|
||||
await summarize(<Map<String, dynamic>>[
|
||||
begin(1000), end(19000),
|
||||
begin(19001), end(29001),
|
||||
begin(29002), end(49002),
|
||||
frameBegin(1000), frameEnd(18000),
|
||||
frameBegin(19000), frameEnd(28000),
|
||||
frameBegin(29000), frameEnd(48000),
|
||||
lagBegin(1000, 4), lagEnd(2000, 4),
|
||||
lagBegin(1200, 12), lagEnd(2400, 12),
|
||||
lagBegin(4200, 8), lagEnd(9400, 8),
|
||||
begin(1000),
|
||||
end(19000),
|
||||
begin(19001),
|
||||
end(29001),
|
||||
begin(29002),
|
||||
end(49002),
|
||||
frameBegin(1000),
|
||||
frameEnd(18000),
|
||||
frameBegin(19000),
|
||||
frameEnd(28000),
|
||||
frameBegin(29000),
|
||||
frameEnd(48000),
|
||||
lagBegin(1000, 4),
|
||||
lagEnd(2000, 4),
|
||||
lagBegin(1200, 12),
|
||||
lagEnd(2400, 12),
|
||||
lagBegin(4200, 8),
|
||||
lagEnd(9400, 8),
|
||||
...newGenGC(4, 10, 100),
|
||||
...oldGenGC(5, 10000, 100),
|
||||
cpuUsage(5000, 20), cpuUsage(5010, 60),
|
||||
memoryUsage(6000, 20, 40), memoryUsage(6100, 30, 45),
|
||||
platformVsync(7000), vsyncCallback(7500),
|
||||
cpuUsage(5000, 20),
|
||||
cpuUsage(5010, 60),
|
||||
memoryUsage(6000, 20, 40),
|
||||
memoryUsage(6100, 30, 45),
|
||||
platformVsync(7000),
|
||||
vsyncCallback(7500),
|
||||
frameRequestPendingStart('1', 1000),
|
||||
frameRequestPendingEnd('1', 2000),
|
||||
frameRequestPendingStart('2', 3000),
|
||||
@@ -681,17 +724,18 @@ void main() {
|
||||
|
||||
group('SceneDisplayLagSummarizer tests', () {
|
||||
SceneDisplayLagSummarizer summarize(List<Map<String, dynamic>> traceEvents) {
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
|
||||
'traceEvents': traceEvents,
|
||||
});
|
||||
return SceneDisplayLagSummarizer(timeline.events!);
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{'traceEvents': traceEvents});
|
||||
return SceneDisplayLagSummarizer(timeline.events!);
|
||||
}
|
||||
|
||||
test('average_vsyncs_missed', () async {
|
||||
final SceneDisplayLagSummarizer summarizer = summarize(<Map<String, dynamic>>[
|
||||
lagBegin(1000, 4), lagEnd(2000, 4),
|
||||
lagBegin(1200, 12), lagEnd(2400, 12),
|
||||
lagBegin(4200, 8), lagEnd(9400, 8),
|
||||
lagBegin(1000, 4),
|
||||
lagEnd(2000, 4),
|
||||
lagBegin(1200, 12),
|
||||
lagEnd(2400, 12),
|
||||
lagBegin(4200, 8),
|
||||
lagEnd(9400, 8),
|
||||
]);
|
||||
expect(summarizer.computeAverageVsyncTransitionsMissed(), 8.0);
|
||||
});
|
||||
@@ -705,26 +749,40 @@ void main() {
|
||||
|
||||
test('90th_percentile_vsyncs_missed', () async {
|
||||
final SceneDisplayLagSummarizer summarizer = summarize(<Map<String, dynamic>>[
|
||||
lagBegin(1000, 4), lagEnd(2000, 4),
|
||||
lagBegin(1200, 12), lagEnd(2400, 12),
|
||||
lagBegin(4200, 8), lagEnd(9400, 8),
|
||||
lagBegin(6100, 14), lagEnd(11000, 14),
|
||||
lagBegin(7100, 16), lagEnd(11500, 16),
|
||||
lagBegin(7400, 11), lagEnd(13000, 11),
|
||||
lagBegin(8200, 27), lagEnd(14100, 27),
|
||||
lagBegin(8700, 7), lagEnd(14300, 7),
|
||||
lagBegin(24200, 4187), lagEnd(39400, 4187),
|
||||
lagBegin(1000, 4),
|
||||
lagEnd(2000, 4),
|
||||
lagBegin(1200, 12),
|
||||
lagEnd(2400, 12),
|
||||
lagBegin(4200, 8),
|
||||
lagEnd(9400, 8),
|
||||
lagBegin(6100, 14),
|
||||
lagEnd(11000, 14),
|
||||
lagBegin(7100, 16),
|
||||
lagEnd(11500, 16),
|
||||
lagBegin(7400, 11),
|
||||
lagEnd(13000, 11),
|
||||
lagBegin(8200, 27),
|
||||
lagEnd(14100, 27),
|
||||
lagBegin(8700, 7),
|
||||
lagEnd(14300, 7),
|
||||
lagBegin(24200, 4187),
|
||||
lagEnd(39400, 4187),
|
||||
]);
|
||||
expect(summarizer.computePercentileVsyncTransitionsMissed(90), 27.0);
|
||||
});
|
||||
|
||||
test('99th_percentile_vsyncs_missed', () async {
|
||||
final SceneDisplayLagSummarizer summarizer = summarize(<Map<String, dynamic>>[
|
||||
lagBegin(1000, 4), lagEnd(2000, 4),
|
||||
lagBegin(1200, 12), lagEnd(2400, 12),
|
||||
lagBegin(4200, 8), lagEnd(9400, 8),
|
||||
lagBegin(6100, 14), lagEnd(11000, 14),
|
||||
lagBegin(24200, 4187), lagEnd(39400, 4187),
|
||||
lagBegin(1000, 4),
|
||||
lagEnd(2000, 4),
|
||||
lagBegin(1200, 12),
|
||||
lagEnd(2400, 12),
|
||||
lagBegin(4200, 8),
|
||||
lagEnd(9400, 8),
|
||||
lagBegin(6100, 14),
|
||||
lagEnd(11000, 14),
|
||||
lagBegin(24200, 4187),
|
||||
lagEnd(39400, 4187),
|
||||
]);
|
||||
expect(summarizer.computePercentileVsyncTransitionsMissed(99), 4187.0);
|
||||
});
|
||||
@@ -732,10 +790,8 @@ void main() {
|
||||
|
||||
group('ProfilingSummarizer tests', () {
|
||||
ProfilingSummarizer summarize(List<Map<String, dynamic>> traceEvents) {
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
|
||||
'traceEvents': traceEvents,
|
||||
});
|
||||
return ProfilingSummarizer.fromEvents(timeline.events!);
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{'traceEvents': traceEvents});
|
||||
return ProfilingSummarizer.fromEvents(timeline.events!);
|
||||
}
|
||||
|
||||
test('has_both_cpu_and_memory_usage', () async {
|
||||
@@ -760,10 +816,14 @@ void main() {
|
||||
|
||||
test('90th_percentile_cpu_usage', () async {
|
||||
final ProfilingSummarizer summarizer = summarize(<Map<String, dynamic>>[
|
||||
cpuUsage(0, 10), cpuUsage(1, 20),
|
||||
cpuUsage(2, 20), cpuUsage(3, 80),
|
||||
cpuUsage(4, 70), cpuUsage(4, 72),
|
||||
cpuUsage(4, 85), cpuUsage(4, 100),
|
||||
cpuUsage(0, 10),
|
||||
cpuUsage(1, 20),
|
||||
cpuUsage(2, 20),
|
||||
cpuUsage(3, 80),
|
||||
cpuUsage(4, 70),
|
||||
cpuUsage(4, 72),
|
||||
cpuUsage(4, 85),
|
||||
cpuUsage(4, 100),
|
||||
]);
|
||||
expect(summarizer.computePercentile(ProfileType.CPU, 90), 85.0);
|
||||
});
|
||||
@@ -771,9 +831,7 @@ void main() {
|
||||
|
||||
group('VsyncFrameLagSummarizer tests', () {
|
||||
VsyncFrameLagSummarizer summarize(List<Map<String, dynamic>> traceEvents) {
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
|
||||
'traceEvents': traceEvents,
|
||||
});
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{'traceEvents': traceEvents});
|
||||
return VsyncFrameLagSummarizer(timeline.events!);
|
||||
}
|
||||
|
||||
@@ -829,22 +887,30 @@ void main() {
|
||||
});
|
||||
|
||||
group('RefreshRateSummarizer tests', () {
|
||||
|
||||
const double kCompareDelta = 0.01;
|
||||
RefreshRateSummary summarizeRefresh(List<Map<String, dynamic>> traceEvents) {
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
|
||||
'traceEvents': traceEvents,
|
||||
});
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{'traceEvents': traceEvents});
|
||||
return RefreshRateSummary(vsyncEvents: timeline.events!);
|
||||
}
|
||||
|
||||
List<Map<String, dynamic>> populateEvents({required int numberOfEvents, required int startTime, required int interval, required int margin}) {
|
||||
List<Map<String, dynamic>> populateEvents({
|
||||
required int numberOfEvents,
|
||||
required int startTime,
|
||||
required int interval,
|
||||
required int margin,
|
||||
}) {
|
||||
final List<Map<String, dynamic>> events = <Map<String, dynamic>>[];
|
||||
int startTimeInNanoseconds = startTime;
|
||||
for (int i = 0; i < numberOfEvents; i ++) {
|
||||
final int randomMargin = margin >= 1 ? (-margin + Random().nextInt(margin*2)) : 0;
|
||||
for (int i = 0; i < numberOfEvents; i++) {
|
||||
final int randomMargin = margin >= 1 ? (-margin + Random().nextInt(margin * 2)) : 0;
|
||||
final int endTime = startTimeInNanoseconds + interval + randomMargin;
|
||||
events.add(vsyncCallback(0, startTime: startTimeInNanoseconds.toString(), endTime: endTime.toString()));
|
||||
events.add(
|
||||
vsyncCallback(
|
||||
0,
|
||||
startTime: startTimeInNanoseconds.toString(),
|
||||
endTime: endTime.toString(),
|
||||
),
|
||||
);
|
||||
startTimeInNanoseconds = endTime;
|
||||
}
|
||||
return events;
|
||||
@@ -855,11 +921,12 @@ void main() {
|
||||
const int intervalInNanoseconds = 33333333;
|
||||
// allow some margins
|
||||
const int margin = 3000000;
|
||||
final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 100,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: margin,
|
||||
);
|
||||
final List<Map<String, dynamic>> events = populateEvents(
|
||||
numberOfEvents: 100,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: margin,
|
||||
);
|
||||
final RefreshRateSummary summary = summarizeRefresh(events);
|
||||
expect(summary.percentageOf30HzFrames, closeTo(100, kCompareDelta));
|
||||
expect(summary.percentageOf60HzFrames, 0);
|
||||
@@ -873,11 +940,12 @@ void main() {
|
||||
const int intervalInNanoseconds = 16666666;
|
||||
// allow some margins
|
||||
const int margin = 1200000;
|
||||
final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 100,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: margin,
|
||||
);
|
||||
final List<Map<String, dynamic>> events = populateEvents(
|
||||
numberOfEvents: 100,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: margin,
|
||||
);
|
||||
|
||||
final RefreshRateSummary summary = summarizeRefresh(events);
|
||||
expect(summary.percentageOf30HzFrames, 0);
|
||||
@@ -892,11 +960,12 @@ void main() {
|
||||
const int intervalInNanoseconds = 11111111;
|
||||
// allow some margins
|
||||
const int margin = 500000;
|
||||
final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 100,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: margin,
|
||||
);
|
||||
final List<Map<String, dynamic>> events = populateEvents(
|
||||
numberOfEvents: 100,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: margin,
|
||||
);
|
||||
|
||||
final RefreshRateSummary summary = summarizeRefresh(events);
|
||||
expect(summary.percentageOf30HzFrames, 0);
|
||||
@@ -911,11 +980,12 @@ void main() {
|
||||
const int intervalInNanoseconds = 8333333;
|
||||
// allow some margins
|
||||
const int margin = 300000;
|
||||
final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 100,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: margin,
|
||||
);
|
||||
final List<Map<String, dynamic>> events = populateEvents(
|
||||
numberOfEvents: 100,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: margin,
|
||||
);
|
||||
final RefreshRateSummary summary = summarizeRefresh(events);
|
||||
expect(summary.percentageOf30HzFrames, 0);
|
||||
expect(summary.percentageOf60HzFrames, 0);
|
||||
@@ -927,11 +997,12 @@ void main() {
|
||||
test('Identify illegal refresh rates.', () async {
|
||||
const int startTimeInNanoseconds = 2750850055430;
|
||||
const int intervalInNanoseconds = 10000000;
|
||||
final List<Map<String, dynamic>> events = populateEvents(numberOfEvents: 1,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: 0,
|
||||
);
|
||||
final List<Map<String, dynamic>> events = populateEvents(
|
||||
numberOfEvents: 1,
|
||||
startTime: startTimeInNanoseconds,
|
||||
interval: intervalInNanoseconds,
|
||||
margin: 0,
|
||||
);
|
||||
final RefreshRateSummary summary = summarizeRefresh(events);
|
||||
expect(summary.percentageOf30HzFrames, 0);
|
||||
expect(summary.percentageOf60HzFrames, 0);
|
||||
@@ -942,7 +1013,6 @@ void main() {
|
||||
});
|
||||
|
||||
test('Mixed refresh rates.', () async {
|
||||
|
||||
final List<Map<String, dynamic>> events = <Map<String, dynamic>>[];
|
||||
const int num30Hz = 10;
|
||||
const int num60Hz = 20;
|
||||
@@ -953,54 +1023,45 @@ void main() {
|
||||
const int totalFrames = num30Hz + num60Hz + num80Hz + num90Hz + num120Hz + numIllegal;
|
||||
|
||||
// Add 30hz frames
|
||||
events.addAll(populateEvents(numberOfEvents: num30Hz,
|
||||
startTime: 0,
|
||||
interval: 32000000,
|
||||
margin: 0,
|
||||
));
|
||||
events.addAll(
|
||||
populateEvents(numberOfEvents: num30Hz, startTime: 0, interval: 32000000, margin: 0),
|
||||
);
|
||||
|
||||
// Add 60hz frames
|
||||
events.addAll(populateEvents(numberOfEvents: num60Hz,
|
||||
startTime: 0,
|
||||
interval: 16000000,
|
||||
margin: 0,
|
||||
));
|
||||
events.addAll(
|
||||
populateEvents(numberOfEvents: num60Hz, startTime: 0, interval: 16000000, margin: 0),
|
||||
);
|
||||
|
||||
// Add 80hz frames
|
||||
events.addAll(populateEvents(numberOfEvents: num80Hz,
|
||||
startTime: 0,
|
||||
interval: 12000000,
|
||||
margin: 0,
|
||||
));
|
||||
events.addAll(
|
||||
populateEvents(numberOfEvents: num80Hz, startTime: 0, interval: 12000000, margin: 0),
|
||||
);
|
||||
|
||||
// Add 90hz frames
|
||||
events.addAll(populateEvents(numberOfEvents: num90Hz,
|
||||
startTime: 0,
|
||||
interval: 11000000,
|
||||
margin: 0,
|
||||
));
|
||||
events.addAll(
|
||||
populateEvents(numberOfEvents: num90Hz, startTime: 0, interval: 11000000, margin: 0),
|
||||
);
|
||||
|
||||
// Add 120hz frames
|
||||
events.addAll(populateEvents(numberOfEvents: num120Hz,
|
||||
startTime: 0,
|
||||
interval: 8000000,
|
||||
margin: 0,
|
||||
));
|
||||
events.addAll(
|
||||
populateEvents(numberOfEvents: num120Hz, startTime: 0, interval: 8000000, margin: 0),
|
||||
);
|
||||
|
||||
// Add illegal refresh rate frames
|
||||
events.addAll(populateEvents(numberOfEvents: numIllegal,
|
||||
startTime: 0,
|
||||
interval: 60000,
|
||||
margin: 0,
|
||||
));
|
||||
events.addAll(
|
||||
populateEvents(numberOfEvents: numIllegal, startTime: 0, interval: 60000, margin: 0),
|
||||
);
|
||||
|
||||
final RefreshRateSummary summary = summarizeRefresh(events);
|
||||
final RefreshRateSummary summary = summarizeRefresh(events);
|
||||
|
||||
expect(summary.percentageOf30HzFrames, closeTo(num30Hz/totalFrames*100, kCompareDelta));
|
||||
expect(summary.percentageOf60HzFrames, closeTo(num60Hz/totalFrames*100, kCompareDelta));
|
||||
expect(summary.percentageOf80HzFrames, closeTo(num80Hz/totalFrames*100, kCompareDelta));
|
||||
expect(summary.percentageOf90HzFrames, closeTo(num90Hz/totalFrames*100, kCompareDelta));
|
||||
expect(summary.percentageOf120HzFrames, closeTo(num120Hz/totalFrames*100, kCompareDelta));
|
||||
expect(summary.percentageOf30HzFrames, closeTo(num30Hz / totalFrames * 100, kCompareDelta));
|
||||
expect(summary.percentageOf60HzFrames, closeTo(num60Hz / totalFrames * 100, kCompareDelta));
|
||||
expect(summary.percentageOf80HzFrames, closeTo(num80Hz / totalFrames * 100, kCompareDelta));
|
||||
expect(summary.percentageOf90HzFrames, closeTo(num90Hz / totalFrames * 100, kCompareDelta));
|
||||
expect(
|
||||
summary.percentageOf120HzFrames,
|
||||
closeTo(num120Hz / totalFrames * 100, kCompareDelta),
|
||||
);
|
||||
expect(summary.framesWithIllegalRefreshRate, isNotEmpty);
|
||||
expect(summary.framesWithIllegalRefreshRate.length, 10);
|
||||
});
|
||||
|
||||
@@ -21,9 +21,7 @@ void main() {
|
||||
'tdur': 245,
|
||||
'ts': 456,
|
||||
'tts': 567,
|
||||
'args': <String, dynamic>{
|
||||
'arg1': true,
|
||||
},
|
||||
'args': <String, dynamic>{'arg1': true},
|
||||
},
|
||||
// Tests that we don't choke on missing data
|
||||
<String, dynamic>{},
|
||||
@@ -60,14 +58,8 @@ void main() {
|
||||
test('sorts JSON', () {
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
|
||||
'traceEvents': <Map<String, dynamic>>[
|
||||
<String, dynamic>{
|
||||
'name': 'test event 1',
|
||||
'ts': 457,
|
||||
},
|
||||
<String, dynamic>{
|
||||
'name': 'test event 2',
|
||||
'ts': 456,
|
||||
},
|
||||
<String, dynamic>{'name': 'test event 1', 'ts': 457},
|
||||
<String, dynamic>{'name': 'test event 2', 'ts': 456},
|
||||
],
|
||||
});
|
||||
|
||||
@@ -81,22 +73,10 @@ void main() {
|
||||
test('sorts JSON nulls first', () {
|
||||
final Timeline timeline = Timeline.fromJson(<String, dynamic>{
|
||||
'traceEvents': <Map<String, dynamic>>[
|
||||
<String, dynamic>{
|
||||
'name': 'test event 0',
|
||||
'ts': null,
|
||||
},
|
||||
<String, dynamic>{
|
||||
'name': 'test event 1',
|
||||
'ts': 457,
|
||||
},
|
||||
<String, dynamic>{
|
||||
'name': 'test event 2',
|
||||
'ts': 456,
|
||||
},
|
||||
<String, dynamic>{
|
||||
'name': 'test event 3',
|
||||
'ts': null,
|
||||
},
|
||||
<String, dynamic>{'name': 'test event 0', 'ts': null},
|
||||
<String, dynamic>{'name': 'test event 1', 'ts': 457},
|
||||
<String, dynamic>{'name': 'test event 2', 'ts': 456},
|
||||
<String, dynamic>{'name': 'test event 3', 'ts': null},
|
||||
],
|
||||
});
|
||||
|
||||
|
||||
@@ -9,15 +9,24 @@ import '../../common.dart';
|
||||
void main() {
|
||||
group('WaitForCondition', () {
|
||||
test('WaitForCondition serialize', () {
|
||||
expect(
|
||||
const WaitForCondition(NoTransientCallbacks()).serialize(),
|
||||
<String, String>{'command': 'waitForCondition', 'conditionName': 'NoTransientCallbacksCondition'});
|
||||
expect(const WaitForCondition(NoTransientCallbacks()).serialize(), <String, String>{
|
||||
'command': 'waitForCondition',
|
||||
'conditionName': 'NoTransientCallbacksCondition',
|
||||
});
|
||||
});
|
||||
|
||||
test('WaitForCondition serialize with timeout', () {
|
||||
expect(
|
||||
const WaitForCondition(NoTransientCallbacks(), timeout: Duration(milliseconds: 10)).serialize(),
|
||||
<String, String>{'command': 'waitForCondition', 'timeout': '10', 'conditionName': 'NoTransientCallbacksCondition'});
|
||||
const WaitForCondition(
|
||||
NoTransientCallbacks(),
|
||||
timeout: Duration(milliseconds: 10),
|
||||
).serialize(),
|
||||
<String, String>{
|
||||
'command': 'waitForCondition',
|
||||
'timeout': '10',
|
||||
'conditionName': 'NoTransientCallbacksCondition',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('WaitForCondition deserialize', () {
|
||||
@@ -43,22 +52,16 @@ void main() {
|
||||
});
|
||||
|
||||
test('WaitForCondition requiresRootWidget', () {
|
||||
expect(
|
||||
const WaitForCondition(NoTransientCallbacks())
|
||||
.requiresRootWidgetAttached,
|
||||
isTrue);
|
||||
expect(
|
||||
const WaitForCondition(FirstFrameRasterized())
|
||||
.requiresRootWidgetAttached,
|
||||
isFalse);
|
||||
});
|
||||
expect(const WaitForCondition(NoTransientCallbacks()).requiresRootWidgetAttached, isTrue);
|
||||
expect(const WaitForCondition(FirstFrameRasterized()).requiresRootWidgetAttached, isFalse);
|
||||
});
|
||||
});
|
||||
|
||||
group('NoTransientCallbacksCondition', () {
|
||||
test('NoTransientCallbacksCondition serialize', () {
|
||||
expect(
|
||||
const NoTransientCallbacks().serialize(),
|
||||
<String, String>{'conditionName': 'NoTransientCallbacksCondition'});
|
||||
expect(const NoTransientCallbacks().serialize(), <String, String>{
|
||||
'conditionName': 'NoTransientCallbacksCondition',
|
||||
});
|
||||
});
|
||||
|
||||
test('NoTransientCallbacksCondition deserialize', () {
|
||||
@@ -72,9 +75,15 @@ void main() {
|
||||
|
||||
test('NoTransientCallbacksCondition deserialize error', () {
|
||||
expect(
|
||||
() => NoTransientCallbacks.deserialize(<String, String>{'conditionName': 'Unknown'}),
|
||||
throwsA(predicate<SerializationException>((SerializationException e) =>
|
||||
e.message == 'Error occurred during deserializing the NoTransientCallbacksCondition JSON string: {conditionName: Unknown}')));
|
||||
() => NoTransientCallbacks.deserialize(<String, String>{'conditionName': 'Unknown'}),
|
||||
throwsA(
|
||||
predicate<SerializationException>(
|
||||
(SerializationException e) =>
|
||||
e.message ==
|
||||
'Error occurred during deserializing the NoTransientCallbacksCondition JSON string: {conditionName: Unknown}',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -96,17 +105,23 @@ void main() {
|
||||
|
||||
test('NoPendingFrameCondition deserialize error', () {
|
||||
expect(
|
||||
() => NoPendingFrame.deserialize(<String, String>{'conditionName': 'Unknown'}),
|
||||
throwsA(predicate<SerializationException>((SerializationException e) =>
|
||||
e.message == 'Error occurred during deserializing the NoPendingFrameCondition JSON string: {conditionName: Unknown}')));
|
||||
() => NoPendingFrame.deserialize(<String, String>{'conditionName': 'Unknown'}),
|
||||
throwsA(
|
||||
predicate<SerializationException>(
|
||||
(SerializationException e) =>
|
||||
e.message ==
|
||||
'Error occurred during deserializing the NoPendingFrameCondition JSON string: {conditionName: Unknown}',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
group('FirstFrameRasterizedCondition', () {
|
||||
test('FirstFrameRasterizedCondition serialize', () {
|
||||
expect(
|
||||
const FirstFrameRasterized().serialize(),
|
||||
<String, String>{'conditionName': 'FirstFrameRasterizedCondition'});
|
||||
expect(const FirstFrameRasterized().serialize(), <String, String>{
|
||||
'conditionName': 'FirstFrameRasterizedCondition',
|
||||
});
|
||||
});
|
||||
|
||||
test('FirstFrameRasterizedCondition deserialize', () {
|
||||
@@ -120,9 +135,15 @@ void main() {
|
||||
|
||||
test('FirstFrameRasterizedCondition deserialize error', () {
|
||||
expect(
|
||||
() => FirstFrameRasterized.deserialize(<String, String>{'conditionName': 'Unknown'}),
|
||||
throwsA(predicate<SerializationException>((SerializationException e) =>
|
||||
e.message == 'Error occurred during deserializing the FirstFrameRasterizedCondition JSON string: {conditionName: Unknown}')));
|
||||
() => FirstFrameRasterized.deserialize(<String, String>{'conditionName': 'Unknown'}),
|
||||
throwsA(
|
||||
predicate<SerializationException>(
|
||||
(SerializationException e) =>
|
||||
e.message ==
|
||||
'Error occurred during deserializing the FirstFrameRasterizedCondition JSON string: {conditionName: Unknown}',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('FirstFrameRasterizedCondition requiresRootWidget', () {
|
||||
@@ -132,8 +153,7 @@ void main() {
|
||||
|
||||
group('CombinedCondition', () {
|
||||
test('CombinedCondition serialize', () {
|
||||
const CombinedCondition combinedCondition =
|
||||
CombinedCondition(<SerializableWaitCondition>[
|
||||
const CombinedCondition combinedCondition = CombinedCondition(<SerializableWaitCondition>[
|
||||
NoTransientCallbacks(),
|
||||
NoPendingFrame(),
|
||||
]);
|
||||
@@ -170,20 +190,18 @@ void main() {
|
||||
'conditions':
|
||||
'[{"conditionName":"NoPendingFrameCondition"},{"conditionName":"NoTransientCallbacksCondition"}]',
|
||||
};
|
||||
final CombinedCondition condition =
|
||||
CombinedCondition.deserialize(jsonMap);
|
||||
final CombinedCondition condition = CombinedCondition.deserialize(jsonMap);
|
||||
expect(
|
||||
condition.conditions,
|
||||
equals(<SerializableWaitCondition>[
|
||||
const NoPendingFrame(),
|
||||
const NoTransientCallbacks(),
|
||||
]));
|
||||
condition.conditions,
|
||||
equals(<SerializableWaitCondition>[const NoPendingFrame(), const NoTransientCallbacks()]),
|
||||
);
|
||||
expect(condition.serialize(), jsonMap);
|
||||
});
|
||||
|
||||
test('CombinedCondition deserialize - no condition list', () {
|
||||
final CombinedCondition condition =
|
||||
CombinedCondition.deserialize(<String, String>{'conditionName': 'CombinedCondition',});
|
||||
final CombinedCondition condition = CombinedCondition.deserialize(<String, String>{
|
||||
'conditionName': 'CombinedCondition',
|
||||
});
|
||||
expect(condition.conditions, equals(<SerializableWaitCondition>[]));
|
||||
expect(condition.serialize(), <String, String>{
|
||||
'conditionName': 'CombinedCondition',
|
||||
@@ -193,22 +211,34 @@ void main() {
|
||||
|
||||
test('CombinedCondition deserialize error', () {
|
||||
expect(
|
||||
() => CombinedCondition.deserialize(<String, String>{'conditionName': 'Unknown'}),
|
||||
throwsA(predicate<SerializationException>((SerializationException e) =>
|
||||
e.message == 'Error occurred during deserializing the CombinedCondition JSON string: {conditionName: Unknown}')));
|
||||
() => CombinedCondition.deserialize(<String, String>{'conditionName': 'Unknown'}),
|
||||
throwsA(
|
||||
predicate<SerializationException>(
|
||||
(SerializationException e) =>
|
||||
e.message ==
|
||||
'Error occurred during deserializing the CombinedCondition JSON string: {conditionName: Unknown}',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('CombinedCondition deserialize error - Unknown condition type', () {
|
||||
expect(
|
||||
() {
|
||||
return CombinedCondition.deserialize(<String, String>{
|
||||
'conditionName': 'CombinedCondition',
|
||||
'conditions':
|
||||
'[{"conditionName":"UnknownCondition"},{"conditionName":"NoTransientCallbacksCondition"}]',
|
||||
});
|
||||
},
|
||||
throwsA(predicate<SerializationException>((SerializationException e) =>
|
||||
e.message == 'Unsupported wait condition UnknownCondition in the JSON string {conditionName: UnknownCondition}')));
|
||||
() {
|
||||
return CombinedCondition.deserialize(<String, String>{
|
||||
'conditionName': 'CombinedCondition',
|
||||
'conditions':
|
||||
'[{"conditionName":"UnknownCondition"},{"conditionName":"NoTransientCallbacksCondition"}]',
|
||||
});
|
||||
},
|
||||
throwsA(
|
||||
predicate<SerializationException>(
|
||||
(SerializationException e) =>
|
||||
e.message ==
|
||||
'Unsupported wait condition UnknownCondition in the JSON string {conditionName: UnknownCondition}',
|
||||
),
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ void main() {
|
||||
() => driver.sendCommand(const GetHealth()),
|
||||
_throwsDriverErrorWithMessage(
|
||||
'FlutterDriver command GetHealth failed due to a remote error.\n'
|
||||
'Command sent: {"command":"get_health"}'
|
||||
'Command sent: {"command":"get_health"}',
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -69,9 +69,7 @@ void main() {
|
||||
''';
|
||||
expect(
|
||||
() => driver.sendCommand(const GetHealth()),
|
||||
_throwsDriverErrorWithMessage(
|
||||
'Error in Flutter application: test error message'
|
||||
),
|
||||
_throwsDriverErrorWithMessage('Error in Flutter application: test error message'),
|
||||
);
|
||||
});
|
||||
|
||||
@@ -94,20 +92,22 @@ void main() {
|
||||
}
|
||||
|
||||
Matcher _throwsDriverErrorWithMessage(String expectedMessage) {
|
||||
return throwsA(allOf(
|
||||
isA<DriverError>(),
|
||||
predicate<DriverError>((DriverError error) {
|
||||
final String actualMessage = error.message;
|
||||
return actualMessage == expectedMessage;
|
||||
}, 'contains message: $expectedMessage'),
|
||||
));
|
||||
return throwsA(
|
||||
allOf(
|
||||
isA<DriverError>(),
|
||||
predicate<DriverError>((DriverError error) {
|
||||
final String actualMessage = error.message;
|
||||
return actualMessage == expectedMessage;
|
||||
}, 'contains message: $expectedMessage'),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Matcher _throwsDriverErrorWithDataString(String dataType, String dataString) {
|
||||
return _throwsDriverErrorWithMessage(
|
||||
'Received malformed response from the FlutterDriver extension.\n'
|
||||
'Expected a JSON map containing a "response" field and, optionally, an '
|
||||
'"isError" field, but got $dataType: $dataString'
|
||||
'"isError" field, but got $dataType: $dataString',
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -22,8 +22,7 @@ void main() {
|
||||
});
|
||||
|
||||
test('web_extension should register a function', () {
|
||||
expect(() => registerWebServiceExtension(call),
|
||||
returnsNormally);
|
||||
expect(() => registerWebServiceExtension(call), returnsNormally);
|
||||
|
||||
expect(_window.hasProperty(r'$flutterDriver'.toJS).toDart, true);
|
||||
expect(_window.getProperty(r'$flutterDriver'.toJS), isNotNull);
|
||||
|
||||
Reference in New Issue
Block a user