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:
Michael Goderbauer
2024-12-19 12:06:21 -08:00
committed by GitHub
parent 8e0993eda8
commit 5491c8c146
4411 changed files with 455108 additions and 415991 deletions

View File

@@ -17,7 +17,8 @@ import 'package:integration_test/integration_test.dart';
import 'package:integration_test_example/main.dart' as app;
void main() {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('verify text', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
@@ -33,8 +34,7 @@ void main() {
expect(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text &&
widget.data!.startsWith('Platform: ${Platform.operatingSystem}'),
widget is Text && widget.data!.startsWith('Platform: ${Platform.operatingSystem}'),
),
findsOneWidget,
);

View File

@@ -29,8 +29,7 @@ void main() {
find.byWidgetPredicate(
(Widget widget) =>
widget is Text &&
widget.data!
.startsWith('Platform: ${web.window.navigator.platform}\n'),
widget.data!.startsWith('Platform: ${web.window.navigator.platform}\n'),
),
findsOneWidget,
);

View File

@@ -18,7 +18,8 @@ import 'package:integration_test/integration_test.dart';
import 'package:integration_test_example/main.dart' as app;
void main() {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
testWidgets('verify text', (WidgetTester tester) async {
// Build our app.
@@ -31,8 +32,7 @@ void main() {
expect(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text &&
widget.data!.startsWith('Platform: ${Platform.operatingSystem}'),
widget is Text && widget.data!.startsWith('Platform: ${Platform.operatingSystem}'),
),
findsOneWidget,
);

View File

@@ -36,9 +36,7 @@ void main() {
// could look up environment variables in this test that were passed to
// the run command via `--dart-define=`, and then pass the values to the
// [integrationDriver.onScreenshot] handler through this 'args' map.
<String, Object?>{
'someArgumentKey': 'someArgumentValue',
},
<String, Object?>{'someArgumentKey': 'someArgumentValue'},
);
// Verify that platform is retrieved.
@@ -46,8 +44,7 @@ void main() {
find.byWidgetPredicate(
(Widget widget) =>
widget is Text &&
widget.data!
.startsWith('Platform: ${web.window.navigator.platform}\n'),
widget.data!.startsWith('Platform: ${web.window.navigator.platform}\n'),
),
findsOneWidget,
);
@@ -72,9 +69,7 @@ void main() {
// could look up environment variables in this test that were passed to
// the run command via `--dart-define=`, and then pass the values to the
// [integrationDriver.onScreenshot] handler through this 'args' map.
<String, Object?>{
'someArgumentKey': 'someArgumentValue',
},
<String, Object?>{'someArgumentKey': 'someArgumentValue'},
);
});
}

View File

@@ -21,12 +21,8 @@ class _MyAppState extends State<MyApp> {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
body: Center(
child: Text('Platform: ${Platform.operatingSystem}\n'),
),
appBar: AppBar(title: const Text('Plugin example app')),
body: Center(child: Text('Platform: ${Platform.operatingSystem}\n')),
),
);
}

View File

@@ -22,9 +22,7 @@ class _MyWebAppState extends State<MyWebApp> {
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Plugin example app'),
),
appBar: AppBar(title: const Text('Plugin example app')),
body: Center(
key: const Key('mainapp'),
child: Text('Platform: ${web.window.navigator.platform}\n'),

View File

@@ -25,5 +25,6 @@ Future<void> main() async {
}
return true;
},
writeResponseOnFailure: true);
writeResponseOnFailure: true,
);
}

View File

@@ -32,8 +32,7 @@ void main() {
// Verify that platform version is retrieved.
await expectLater(
find.byWidgetPredicate(
(Widget widget) =>
widget is Text && widget.data!.startsWith('This should fail'),
(Widget widget) => widget is Text && widget.data!.startsWith('This should fail'),
),
findsOneWidget,
);

View File

@@ -12,8 +12,7 @@ import 'package:test/test.dart';
Future<void> main() async {
test('fails gracefully', () async {
final FlutterDriver driver = await FlutterDriver.connect();
final String jsonResult =
await driver.requestData(null, timeout: const Duration(minutes: 1));
final String jsonResult = await driver.requestData(null, timeout: const Duration(minutes: 1));
final common.Response response = common.Response.fromJson(jsonResult);
await driver.close();
expect(response.allTestsPassed, isFalse);

View File

@@ -29,7 +29,8 @@ import 'dart:convert';
///
/// Since the function is executed on the host driving the test, you can access any environment
/// variable from it.
typedef ScreenshotCallback = Future<bool> Function(String name, List<int> image, [Map<String, Object?>? args]);
typedef ScreenshotCallback =
Future<bool> Function(String name, List<int> image, [Map<String, Object?>? args]);
/// Classes shared between `integration_test.dart` and `flutter drive` based
/// adaptor (ex: `integration_test_driver.dart`).
@@ -38,23 +39,18 @@ typedef ScreenshotCallback = Future<bool> Function(String name, List<int> image,
/// `request_data` command.
class Response {
/// Constructor to use for positive response.
Response.allTestsPassed({this.data})
: _allTestsPassed = true,
_failureDetails = null;
Response.allTestsPassed({this.data}) : _allTestsPassed = true, _failureDetails = null;
/// Constructor for failure response.
Response.someTestsFailed(this._failureDetails, {this.data})
: _allTestsPassed = false;
Response.someTestsFailed(this._failureDetails, {this.data}) : _allTestsPassed = false;
/// Constructor for failure response.
Response.toolException({String? ex})
: _allTestsPassed = false,
_failureDetails = <Failure>[Failure('ToolException', ex)];
: _allTestsPassed = false,
_failureDetails = <Failure>[Failure('ToolException', ex)];
/// Constructor for web driver commands response.
Response.webDriverCommand({this.data})
: _allTestsPassed = false,
_failureDetails = null;
Response.webDriverCommand({this.data}) : _allTestsPassed = false, _failureDetails = null;
final List<Failure>? _failureDetails;
@@ -67,18 +63,17 @@ class Response {
bool get allTestsPassed => _allTestsPassed;
/// If the result are failures get the formatted details.
String get formattedFailureDetails =>
_allTestsPassed ? '' : formatFailures(_failureDetails!);
String get formattedFailureDetails => _allTestsPassed ? '' : formatFailures(_failureDetails!);
/// Failure details as a list.
List<Failure>? get failureDetails => _failureDetails;
/// Serializes this message to a JSON map.
String toJson() => json.encode(<String, dynamic>{
'result': allTestsPassed.toString(),
'failureDetails': _failureDetailsAsString(),
if (data != null) 'data': data,
});
'result': allTestsPassed.toString(),
'failureDetails': _failureDetailsAsString(),
if (data != null) 'data': data,
});
/// Deserializes the result from JSON.
static Response fromJson(String source) {
@@ -139,10 +134,7 @@ class Failure {
/// Serializes the object to JSON.
String toJson() {
return json.encode(<String, String?>{
'methodName': methodName,
'details': details,
});
return json.encode(<String, String?>{'methodName': methodName, 'details': details});
}
@override
@@ -164,20 +156,14 @@ class Failure {
/// the driver side test such as: status pending or tests failed.
class DriverTestMessage {
/// When tests are failed on the driver side.
DriverTestMessage.error()
: _isSuccess = false,
_isPending = false;
DriverTestMessage.error() : _isSuccess = false, _isPending = false;
/// When driver side is waiting on [WebDriverCommand]s to be sent from the
/// app side.
DriverTestMessage.pending()
: _isSuccess = false,
_isPending = true;
DriverTestMessage.pending() : _isSuccess = false, _isPending = true;
/// When driver side successfully completed executing the [WebDriverCommand].
DriverTestMessage.complete()
: _isSuccess = true,
_isPending = false;
DriverTestMessage.complete() : _isSuccess = true, _isPending = false;
final bool _isSuccess;
final bool _isPending;
@@ -213,8 +199,8 @@ class DriverTestMessage {
/// Return a DriverTestMessage depending on `status`.
static DriverTestMessage fromString(String status) {
return switch (status) {
'error' => DriverTestMessage.error(),
'pending' => DriverTestMessage.pending(),
'error' => DriverTestMessage.error(),
'pending' => DriverTestMessage.pending(),
'complete' => DriverTestMessage.complete(),
_ => throw StateError('This type of status does not exist: $status'),
};
@@ -244,17 +230,12 @@ enum WebDriverCommandType {
/// See: https://www.w3.org/TR/webdriver/
class WebDriverCommand {
/// Constructor for [WebDriverCommandType.noop] command.
WebDriverCommand.noop()
: type = WebDriverCommandType.noop,
values = <String, dynamic>{};
WebDriverCommand.noop() : type = WebDriverCommandType.noop, values = <String, dynamic>{};
/// Constructor for [WebDriverCommandType.noop] screenshot.
WebDriverCommand.screenshot(String screenshotName, [Map<String, Object?>? args])
: type = WebDriverCommandType.screenshot,
values = <String, dynamic>{
'screenshot_name': screenshotName,
if (args != null) 'args': args,
};
: type = WebDriverCommandType.screenshot,
values = <String, dynamic>{'screenshot_name': screenshotName, if (args != null) 'args': args};
/// Type of the [WebDriverCommand].
///
@@ -284,11 +265,13 @@ class WebDriverCommand {
abstract class CallbackManager {
/// The callback function to response the driver side input.
Future<Map<String, dynamic>> callback(
Map<String, String> params, IntegrationTestResults testRunner);
Map<String, String> params,
IntegrationTestResults testRunner,
);
/// Takes a screenshot of the application.
/// Returns the data that is sent back to the host.
Future<Map<String, dynamic>> takeScreenshot(String screenshot, [Map<String, Object?>? args]);
Future<Map<String, dynamic>> takeScreenshot(String screenshot, [Map<String, Object?>? args]);
/// Android only. Converts the Flutter surface to an image view.
Future<void> convertFlutterSurfaceToImage();

View File

@@ -40,7 +40,8 @@ const bool _shouldReportResultsToNative = bool.fromEnvironment(
/// A subclass of [LiveTestWidgetsFlutterBinding] that reports tests results
/// on a channel to adapt them to native instrumentation test format.
class IntegrationTestWidgetsFlutterBinding extends LiveTestWidgetsFlutterBinding implements IntegrationTestResults {
class IntegrationTestWidgetsFlutterBinding extends LiveTestWidgetsFlutterBinding
implements IntegrationTestResults {
/// Sets up a listener to report that the tests are finished when everything is
/// torn down.
IntegrationTestWidgetsFlutterBinding() {
@@ -57,17 +58,14 @@ class IntegrationTestWidgetsFlutterBinding extends LiveTestWidgetsFlutterBinding
}
try {
await integrationTestChannel.invokeMethod<void>(
'allTestsFinished',
<String, dynamic>{
'results': results.map<String, dynamic>((String name, Object result) {
if (result is Failure) {
return MapEntry<String, dynamic>(name, result.details);
}
return MapEntry<String, Object>(name, result);
}),
},
);
await integrationTestChannel.invokeMethod<void>('allTestsFinished', <String, dynamic>{
'results': results.map<String, dynamic>((String name, Object result) {
if (result is Failure) {
return MapEntry<String, dynamic>(name, result.details);
}
return MapEntry<String, Object>(name, result);
}),
});
} on MissingPluginException {
debugPrint(r'''
Warning: integration_test plugin was not detected.
@@ -86,8 +84,7 @@ https://docs.flutter.dev/testing/integration-tests
});
final TestExceptionReporter oldTestExceptionReporter = reportTestException;
reportTestException =
(FlutterErrorDetails details, String testDescription) {
reportTestException = (FlutterErrorDetails details, String testDescription) {
results[testDescription] = Failure(testDescription, details.toString());
oldTestExceptionReporter(details, testDescription);
};
@@ -209,8 +206,7 @@ https://docs.flutter.dev/testing/integration-tests
/// The callback function to response the driver side input.
@visibleForTesting
Future<Map<String, dynamic>> callback(Map<String, String> params) async {
return callbackManager.callback(
params, this /* as IntegrationTestResults */);
return callbackManager.callback(params, this /* as IntegrationTestResults */);
}
// Emulates the Flutter driver extension, returning 'pass' or 'fail'.
@@ -232,15 +228,11 @@ https://docs.flutter.dev/testing/integration-tests
String description = '',
@Deprecated(
'This parameter has no effect. Use the `timeout` parameter on `testWidgets` instead. '
'This feature was deprecated after v2.6.0-1.0.pre.'
'This feature was deprecated after v2.6.0-1.0.pre.',
)
Duration? timeout,
}) async {
await super.runTest(
testBody,
invariantTester,
description: description,
);
await super.runTest(testBody, invariantTester, description: description);
results[description] ??= _success;
}
@@ -374,21 +366,17 @@ https://docs.flutter.dev/testing/integration-tests
return const _GarbageCollectionInfo();
}
final vm.Timeline timeline = await traceTimeline(
action,
streams: <String>['GC'],
);
final vm.Timeline timeline = await traceTimeline(action, streams: <String>['GC']);
final int oldGenGCCount = timeline.traceEvents!.where((vm.TimelineEvent event) {
return event.json!['cat'] == 'GC' && event.json!['name'] == 'CollectOldGeneration';
}).length;
final int newGenGCCount = timeline.traceEvents!.where((vm.TimelineEvent event) {
return event.json!['cat'] == 'GC' && event.json!['name'] == 'CollectNewGeneration';
}).length;
return _GarbageCollectionInfo(
oldCount: oldGenGCCount,
newCount: newGenGCCount,
);
final int oldGenGCCount =
timeline.traceEvents!.where((vm.TimelineEvent event) {
return event.json!['cat'] == 'GC' && event.json!['name'] == 'CollectOldGeneration';
}).length;
final int newGenGCCount =
timeline.traceEvents!.where((vm.TimelineEvent event) {
return event.json!['cat'] == 'GC' && event.json!['name'] == 'CollectNewGeneration';
}).length;
return _GarbageCollectionInfo(oldCount: oldGenGCCount, newCount: newGenGCCount);
}
/// Watches the [FrameTiming] during `action` and report it to the binding
@@ -475,10 +463,7 @@ class _GarbageCollectionInfo {
// Copied from vm_service_io so that we can pass a custom [HttpClient] for
// testing. Currently, the WebSocket API reuses an HttpClient that
// is created before the test can change the HttpOverrides.
Future<vm.VmService> _vmServiceConnectUri(
String wsUri, {
HttpClient? httpClient,
}) async {
Future<vm.VmService> _vmServiceConnectUri(String wsUri, {HttpClient? httpClient}) async {
final WebSocket socket = await WebSocket.connect(wsUri, customClient: httpClient);
final StreamController<dynamic> controller = StreamController<dynamic>();
final Completer<void> streamClosedCompleter = Completer<void>();

View File

@@ -31,10 +31,7 @@ Future<void> writeResponseData(
}) async {
destinationDirectory ??= testOutputsDirectory;
await fs.directory(destinationDirectory).create(recursive: true);
final File file = fs.file(path.join(
destinationDirectory,
'$testOutputFilename.json',
));
final File file = fs.file(path.join(destinationDirectory, '$testOutputFilename.json'));
final String resultString = _encodeJson(data, true);
await file.writeAsString(resultString);
}

View File

@@ -31,10 +31,7 @@ Future<void> writeResponseData(
}) async {
destinationDirectory ??= testOutputsDirectory;
await fs.directory(destinationDirectory).create(recursive: true);
final File file = fs.file(path.join(
destinationDirectory,
'$testOutputFilename.json',
));
final File file = fs.file(path.join(destinationDirectory, '$testOutputFilename.json'));
final String resultString = _encodeJson(data, true);
await file.writeAsString(resultString);
}
@@ -104,22 +101,21 @@ Future<void> integrationDriver({
// Use `driver.screenshot()` method to get a screenshot of the web page.
final List<int> screenshotImage = await driver.screenshot();
final String screenshotName = response.data!['screenshot_name']! as String;
final Map<String, Object?>? args = (response.data!['args'] as Map<String, Object?>?)?.cast<String, Object?>();
final Map<String, Object?>? args =
(response.data!['args'] as Map<String, Object?>?)?.cast<String, Object?>();
final bool screenshotSuccess = await onScreenshot!(screenshotName, screenshotImage, args);
onScreenshotResults[screenshotName] = screenshotSuccess;
if (screenshotSuccess) {
jsonResponse = await driver.requestData(DriverTestMessage.complete().toString());
} else {
jsonResponse =
await driver.requestData(DriverTestMessage.error().toString());
jsonResponse = await driver.requestData(DriverTestMessage.error().toString());
}
response = Response.fromJson(jsonResponse);
} else if (webDriverCommand == '${WebDriverCommandType.ack}') {
// Previous command completed ask for a new one.
jsonResponse =
await driver.requestData(DriverTestMessage.pending().toString());
jsonResponse = await driver.requestData(DriverTestMessage.pending().toString());
response = Response.fromJson(jsonResponse);
} else {
@@ -147,7 +143,8 @@ Future<void> integrationDriver({
bool ok = false;
try {
ok = onScreenshotResults[screenshotName] ??
ok =
onScreenshotResults[screenshotName] ??
await onScreenshot(screenshotName, screenshotBytes.cast<int>());
} catch (exception) {
throw StateError(
@@ -160,7 +157,7 @@ Future<void> integrationDriver({
}
}
if (failures.isNotEmpty) {
throw StateError('The following screenshot tests failed: ${failures.join(', ')}');
throw StateError('The following screenshot tests failed: ${failures.join(', ')}');
}
}

View File

@@ -27,29 +27,29 @@ final _IOCallbackManager _singletonCallbackManager = _IOCallbackManager();
class _IOCallbackManager implements CallbackManager {
@override
Future<Map<String, dynamic>> callback(
Map<String, String> params, IntegrationTestResults testRunner) async {
Map<String, String> params,
IntegrationTestResults testRunner,
) async {
final String command = params['command']!;
Map<String, String> response;
switch (command) {
case 'request_data':
final bool allTestsPassed = await testRunner.allTestsPassed.future;
response = <String, String>{
'message': allTestsPassed
? Response.allTestsPassed(data: testRunner.reportData).toJson()
: Response.someTestsFailed(
testRunner.failureMethodsDetails,
data: testRunner.reportData,
).toJson(),
'message':
allTestsPassed
? Response.allTestsPassed(data: testRunner.reportData).toJson()
: Response.someTestsFailed(
testRunner.failureMethodsDetails,
data: testRunner.reportData,
).toJson(),
};
case 'get_health':
response = <String, String>{'status': 'ok'};
default:
throw UnimplementedError('$command is not implemented');
}
return <String, dynamic>{
'isError': false,
'response': response,
};
return <String, dynamic>{'isError': false, 'response': response};
}
@override
@@ -69,22 +69,21 @@ class _IOCallbackManager implements CallbackManager {
return;
}
assert(!_isSurfaceRendered, 'Surface already converted to an image');
await integrationTestChannel.invokeMethod<void>(
'convertFlutterSurfaceToImage',
);
await integrationTestChannel.invokeMethod<void>('convertFlutterSurfaceToImage');
_isSurfaceRendered = true;
addTearDown(() async {
assert(_isSurfaceRendered, 'Surface is not an image');
await integrationTestChannel.invokeMethod<void>(
'revertFlutterImage',
);
await integrationTestChannel.invokeMethod<void>('revertFlutterImage');
_isSurfaceRendered = false;
});
}
@override
Future<Map<String, dynamic>> takeScreenshot(String screenshot, [Map<String, Object?>? args]) async {
Future<Map<String, dynamic>> takeScreenshot(
String screenshot, [
Map<String, Object?>? args,
]) async {
assert(args == null, '[args] handling has not been implemented for this platform');
if (Platform.isAndroid && !_isSurfaceRendered) {
throw StateError('Call convertFlutterSurfaceToImage() before taking a screenshot');
@@ -97,10 +96,7 @@ class _IOCallbackManager implements CallbackManager {
if (rawBytes == null) {
throw StateError('Expected a list of bytes, but instead captureScreenshot returned null');
}
return <String, dynamic>{
'screenshotName': screenshot,
'bytes': rawBytes,
};
return <String, dynamic>{'screenshotName': screenshot, 'bytes': rawBytes};
}
Future<dynamic> _onMethodChannelCall(MethodCall call) async {

View File

@@ -14,8 +14,7 @@ import '../common.dart';
CallbackManager get callbackManager => _singletonWebDriverCommandManager;
/// WebDriverCommandManager singleton.
final _WebCallbackManager _singletonWebDriverCommandManager =
_WebCallbackManager();
final _WebCallbackManager _singletonWebDriverCommandManager = _WebCallbackManager();
/// Manages communication between `integration_tests` and the `driver_tests`.
///
@@ -28,8 +27,7 @@ final _WebCallbackManager _singletonWebDriverCommandManager =
/// See: https://www.w3.org/TR/webdriver/
class _WebCallbackManager implements CallbackManager {
/// App side tests will put the command requests from WebDriver to this pipe.
Completer<WebDriverCommand> _webDriverCommandPipe =
Completer<WebDriverCommand>();
Completer<WebDriverCommand> _webDriverCommandPipe = Completer<WebDriverCommand>();
/// Updated when WebDriver completes the request by the test method.
///
@@ -44,12 +42,15 @@ class _WebCallbackManager implements CallbackManager {
///
/// See: https://www.w3.org/TR/webdriver/#screen-capture.
@override
Future<Map<String, dynamic>> takeScreenshot(String screenshotName, [Map<String, Object?>? args]) async {
Future<Map<String, dynamic>> takeScreenshot(
String screenshotName, [
Map<String, Object?>? args,
]) async {
await _sendWebDriverCommand(WebDriverCommand.screenshot(screenshotName, args));
return <String, dynamic>{
'screenshotName': screenshotName,
// Flutter Web doesn't provide the bytes.
'bytes': <int>[]
'bytes': <int>[],
};
}
@@ -64,8 +65,9 @@ class _WebCallbackManager implements CallbackManager {
final bool awaitCommand = await _driverCommandComplete.future;
if (!awaitCommand) {
throw Exception(
'Web Driver Command ${command.type} failed while waiting for '
'driver side');
'Web Driver Command ${command.type} failed while waiting for '
'driver side',
);
}
} catch (exception) {
throw Exception('Web Driver Command failed: ${command.type} with exception $exception');
@@ -81,7 +83,9 @@ class _WebCallbackManager implements CallbackManager {
/// driver side.
@override
Future<Map<String, dynamic>> callback(
Map<String, String> params, IntegrationTestResults testRunner) async {
Map<String, String> params,
IntegrationTestResults testRunner,
) async {
final String command = params['command']!;
Map<String, String> response;
switch (command) {
@@ -94,18 +98,16 @@ class _WebCallbackManager implements CallbackManager {
default:
throw UnimplementedError('$command is not implemented');
}
return <String, dynamic>{
'isError': false,
'response': response,
};
return <String, dynamic>{'isError': false, 'response': response};
}
Future<Map<String, dynamic>> _requestDataWithMessage(
String extraMessage, IntegrationTestResults testRunner) async {
String extraMessage,
IntegrationTestResults testRunner,
) async {
Map<String, String> response;
// Driver side tests' status is added as an extra message.
final DriverTestMessage message =
DriverTestMessage.fromString(extraMessage);
final DriverTestMessage message = DriverTestMessage.fromString(extraMessage);
// If driver side tests are pending send the first command in the
// `commandPipe` to the tests.
if (message.isPending) {
@@ -113,56 +115,43 @@ class _WebCallbackManager implements CallbackManager {
switch (command.type) {
case WebDriverCommandType.screenshot:
final Map<String, dynamic> data = Map<String, dynamic>.from(command.values);
data.addAll(
WebDriverCommand.typeToMap(WebDriverCommandType.screenshot));
response = <String, String>{
'message': Response.webDriverCommand(data: data).toJson(),
};
data.addAll(WebDriverCommand.typeToMap(WebDriverCommandType.screenshot));
response = <String, String>{'message': Response.webDriverCommand(data: data).toJson()};
case WebDriverCommandType.noop:
final Map<String, dynamic> data = <String, dynamic>{};
data.addAll(WebDriverCommand.typeToMap(WebDriverCommandType.noop));
response = <String, String>{
'message': Response.webDriverCommand(data: data).toJson(),
};
response = <String, String>{'message': Response.webDriverCommand(data: data).toJson()};
case WebDriverCommandType.ack:
throw UnimplementedError('${command.type} is not implemented');
}
} else {
final Map<String, dynamic> data = <String, dynamic>{};
data.addAll(WebDriverCommand.typeToMap(WebDriverCommandType.ack));
response = <String, String>{
'message': Response.webDriverCommand(data: data).toJson(),
};
response = <String, String>{'message': Response.webDriverCommand(data: data).toJson()};
_driverCommandComplete.complete(message.isSuccess);
_webDriverCommandPipe = Completer<WebDriverCommand>();
}
return <String, dynamic>{
'isError': false,
'response': response,
};
return <String, dynamic>{'isError': false, 'response': response};
}
Future<Map<String, dynamic>> _requestData(IntegrationTestResults testRunner) async {
final bool allTestsPassed = await testRunner.allTestsPassed.future;
final Map<String, String> response = <String, String>{
'message': allTestsPassed
? Response.allTestsPassed(data: testRunner.reportData).toJson()
: Response.someTestsFailed(
testRunner.failureMethodsDetails,
data: testRunner.reportData,
).toJson(),
};
return <String, dynamic>{
'isError': false,
'response': response,
'message':
allTestsPassed
? Response.allTestsPassed(data: testRunner.reportData).toJson()
: Response.someTestsFailed(
testRunner.failureMethodsDetails,
data: testRunner.reportData,
).toJson(),
};
return <String, dynamic>{'isError': false, 'response': response};
}
@override
void cleanup() {
if (!_webDriverCommandPipe.isCompleted) {
_webDriverCommandPipe
.complete(Future<WebDriverCommand>.value(WebDriverCommand.noop()));
_webDriverCommandPipe.complete(Future<WebDriverCommand>.value(WebDriverCommand.noop()));
}
if (!_driverCommandComplete.isCompleted) {

View File

@@ -7,7 +7,6 @@
/// See also:
///
/// * `_extension_web.dart`, which has the web implementation
void registerWebServiceExtension(
Future<Map<String, dynamic>> Function(Map<String, String>) call) {
void registerWebServiceExtension(Future<Map<String, dynamic>> Function(Map<String, String>) call) {
throw UnsupportedError('Use registerServiceExtension instead');
}

View File

@@ -18,29 +18,33 @@ external JSObject get _window;
/// See also:
///
/// * `_extension_io.dart`, which has the dart:io implementation
void registerWebServiceExtension(Future<Map<String, dynamic>> Function(Map<String, String>) callback) {
void registerWebServiceExtension(
Future<Map<String, dynamic>> Function(Map<String, String>) callback,
) {
// Define the result variable because packages/flutter_driver/lib/src/driver/web_driver.dart
// checks for this value to become non-null when waiting for the result. If this value is
// undefined at the time of the check, WebDriver throws an exception.
_window.setProperty(r'$flutterDriverResult'.toJS, null);
_window.setProperty(r'$flutterDriver'.toJS, (JSAny message) {
(() async {
try {
final Map<String, dynamic> messageJson = jsonDecode((message as JSString).toDart) as Map<String, dynamic>;
final Map<String, String> params = messageJson.cast<String, String>();
final Map<String, dynamic> result = await callback(params);
_window.setProperty(r'$flutterDriverResult'.toJS, json.encode(result).toJS);
} catch (error, stackTrace) {
// Encode the error in the same format the FlutterDriver extension uses.
// See //packages/flutter_driver/lib/src/extension/extension.dart
_window.setProperty(r'$flutterDriverResult'.toJS,
json.encode(<String, dynamic>{
'isError': true,
'response': '$error\n$stackTrace',
}).toJS
);
}
})();
}.toJS);
_window.setProperty(
r'$flutterDriver'.toJS,
(JSAny message) {
(() async {
try {
final Map<String, dynamic> messageJson =
jsonDecode((message as JSString).toDart) as Map<String, dynamic>;
final Map<String, String> params = messageJson.cast<String, String>();
final Map<String, dynamic> result = await callback(params);
_window.setProperty(r'$flutterDriverResult'.toJS, json.encode(result).toJS);
} catch (error, stackTrace) {
// Encode the error in the same format the FlutterDriver extension uses.
// See //packages/flutter_driver/lib/src/extension/extension.dart
_window.setProperty(
r'$flutterDriverResult'.toJS,
json.encode(<String, dynamic>{'isError': true, 'response': '$error\n$stackTrace'}).toJS,
);
}
})();
}.toJS,
);
}

View File

@@ -5,4 +5,5 @@
import 'dart:async';
// package:flutter_goldens is not used as part of the test process for web.
Future<void> testExecutable(FutureOr<void> Function() testMain, {String? namePrefix}) async => testMain();
Future<void> testExecutable(FutureOr<void> Function() testMain, {String? namePrefix}) async =>
testMain();

View File

@@ -19,18 +19,20 @@ const String _failureExcerpt = r'Expected: <false>\n Actual: <true>';
Future<void> main() async {
group('Integration binding result', () {
test('when multiple tests pass', () async {
final Map<String, dynamic>? results = await _runTest(path.join('test', 'data', 'pass_test_script.dart'));
final Map<String, dynamic>? results = await _runTest(
path.join('test', 'data', 'pass_test_script.dart'),
);
expect(
results,
equals(<String, dynamic>{
'passing test 1': 'success',
'passing test 2': 'success',
}));
results,
equals(<String, dynamic>{'passing test 1': 'success', 'passing test 2': 'success'}),
);
});
test('when multiple tests fail', () async {
final Map<String, dynamic>? results = await _runTest(path.join('test', 'data', 'fail_test_script.dart'));
final Map<String, dynamic>? results = await _runTest(
path.join('test', 'data', 'fail_test_script.dart'),
);
expect(results, hasLength(2));
expect(results, containsPair('failing test 1', contains(_failureExcerpt)));
@@ -38,7 +40,9 @@ Future<void> main() async {
});
test('when one test passes, then another fails', () async {
final Map<String, dynamic>? results = await _runTest(path.join('test', 'data', 'pass_then_fail_test_script.dart'));
final Map<String, dynamic>? results = await _runTest(
path.join('test', 'data', 'pass_then_fail_test_script.dart'),
);
expect(results, hasLength(2));
expect(results, containsPair('passing test', equals('success')));
@@ -46,7 +50,9 @@ Future<void> main() async {
});
test('when one test fails, then another passes', () async {
final Map<String, dynamic>? results = await _runTest(path.join('test', 'data', 'fail_then_pass_test_script.dart'));
final Map<String, dynamic>? results = await _runTest(
path.join('test', 'data', 'fail_then_pass_test_script.dart'),
);
expect(results, hasLength(2));
expect(results, containsPair('failing test', contains(_failureExcerpt)));
@@ -59,8 +65,11 @@ Future<void> main() async {
///
/// [scriptPath] is relative to the package root.
Future<Map<String, dynamic>?> _runTest(String scriptPath) async {
final Process process =
await Process.start(_flutterBin, <String>['test', '--machine', scriptPath]);
final Process process = await Process.start(_flutterBin, <String>[
'test',
'--machine',
scriptPath,
]);
/// In the test [tearDownAll] block, the test results are encoded into JSON and
/// are printed with the [_integrationResultsPrefix] prefix.
@@ -68,28 +77,26 @@ Future<Map<String, dynamic>?> _runTest(String scriptPath) async {
/// See the following for the test event spec which we parse the printed lines
/// out of: https://github.com/dart-lang/test/blob/master/pkgs/test/doc/json_reporter.md
final String testResults = (await process.stdout
.transform(utf8.decoder)
.expand((String text) => text.split('\n'))
.map<dynamic>((String line) {
try {
return jsonDecode(line);
} on FormatException {
// Only interested in test events which are JSON.
}
})
.expand<Map<String, dynamic>>((dynamic json) {
if (json is List<dynamic>) {
return json.cast();
}
return <Map<String, dynamic>>[
if (json != null)
json as Map<String, dynamic>,
];
})
.where((Map<String, dynamic> testEvent) => testEvent['type'] == 'print')
.map((Map<String, dynamic> printEvent) => printEvent['message'] as String)
.firstWhere((String message) => message.startsWith(_integrationResultsPrefix)))
.replaceAll(_integrationResultsPrefix, '');
.transform(utf8.decoder)
.expand((String text) => text.split('\n'))
.map<dynamic>((String line) {
try {
return jsonDecode(line);
} on FormatException {
// Only interested in test events which are JSON.
}
})
.expand<Map<String, dynamic>>((dynamic json) {
if (json is List<dynamic>) {
return json.cast();
}
return <Map<String, dynamic>>[if (json != null) json as Map<String, dynamic>];
})
.where((Map<String, dynamic> testEvent) => testEvent['type'] == 'print')
.map((Map<String, dynamic> printEvent) => printEvent['message'] as String)
.firstWhere(
(String message) => message.startsWith(_integrationResultsPrefix),
)).replaceAll(_integrationResultsPrefix, '');
return jsonDecode(testResults) as Map<String, dynamic>?;
}

View File

@@ -20,23 +20,18 @@ Future<void> main() async {
Future<Map<String, dynamic>>? request;
group('Test Integration binding', () {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
FakeVM? fakeVM;
setUp(() {
request = binding.callback(<String, String>{
'command': 'request_data',
});
fakeVM = FakeVM(
timeline: _kTimelines,
);
request = binding.callback(<String, String>{'command': 'request_data'});
fakeVM = FakeVM(timeline: _kTimelines);
});
testWidgets('Run Integration app', (WidgetTester tester) async {
runApp(const MaterialApp(
home: Text('Test'),
));
runApp(const MaterialApp(home: Text('Test')));
expect(tester.binding, binding);
binding.reportData = <String, dynamic>{'answer': 42};
await tester.pump();
@@ -77,9 +72,7 @@ Future<void> main() async {
testWidgets('setSurfaceSize works', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Center(child: Text('Test'))));
final Size viewCenter = tester.view.physicalSize /
tester.view.devicePixelRatio /
2;
final Size viewCenter = tester.view.physicalSize / tester.view.devicePixelRatio / 2;
final double viewCenterX = viewCenter.width;
final double viewCenterY = viewCenter.height;
@@ -105,10 +98,7 @@ Future<void> main() async {
await binding.traceAction(() async {});
expect(binding.reportData, isNotNull);
expect(binding.reportData!.containsKey('timeline'), true);
expect(
json.encode(binding.reportData!['timeline']),
json.encode(_kTimelines),
);
expect(json.encode(binding.reportData!['timeline']), json.encode(_kTimelines));
});
group('defaultTestTimeout', () {
@@ -140,8 +130,7 @@ Future<void> main() async {
// This part is outside the group so that `request` has been completed as
// part of the `tearDownAll` registered in the group during
// `IntegrationTestWidgetsFlutterBinding` initialization.
final Map<String, dynamic> response =
(await request)!['response'] as Map<String, dynamic>;
final Map<String, dynamic> response = (await request)!['response'] as Map<String, dynamic>;
final String message = response['message'] as String;
final Response result = Response.fromJson(message);
assert(result.data!['answer'] == 42);

View File

@@ -8,7 +8,8 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
Future<void> main() async {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.allTestsPassed.future.then((_) {
// We use this print to communicate with ../binding_fail_test.dart
// ignore: avoid_print

View File

@@ -8,7 +8,8 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
Future<void> main() async {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.allTestsPassed.future.then((_) {
// We use this print to communicate with ../binding_fail_test.dart
// ignore: avoid_print

View File

@@ -8,7 +8,8 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
Future<void> main() async {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.allTestsPassed.future.then((_) {
// We use this print to communicate with ../binding_fail_test.dart
// ignore: avoid_print

View File

@@ -8,7 +8,8 @@ import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
Future<void> main() async {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.allTestsPassed.future.then((_) {
// We use this print to communicate with ../binding_fail_test.dart
// ignore: avoid_print

View File

@@ -15,9 +15,6 @@ void main() {
testWidgets('a screenshot of a Placeholder', (WidgetTester tester) async {
await tester.pumpWidget(const Placeholder());
await expectLater(
find.byType(Placeholder),
matchesGoldenFile('placeholder.png'),
);
await expectLater(find.byType(Placeholder), matchesGoldenFile('placeholder.png'));
});
}

View File

@@ -15,7 +15,8 @@ class SocketExceptionHttpClient extends Fake implements HttpClient {
}
Future<void> main() async {
final IntegrationTestWidgetsFlutterBinding binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
final IntegrationTestWidgetsFlutterBinding binding =
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
test('Prints an appropriate message on socket exception', () async {
bool gotStateError = false;

View File

@@ -17,11 +17,14 @@ external JSObject get _window;
void main() {
IntegrationTestWidgetsFlutterBinding();
test('IntegrationTestWidgetsFlutterBinding on the web should register certain global properties', () {
expect(_window.hasProperty(r'$flutterDriver'.toJS).toDart, true);
expect(_window.getProperty(r'$flutterDriver'.toJS), isNotNull);
test(
'IntegrationTestWidgetsFlutterBinding on the web should register certain global properties',
() {
expect(_window.hasProperty(r'$flutterDriver'.toJS).toDart, true);
expect(_window.getProperty(r'$flutterDriver'.toJS), isNotNull);
expect(_window.hasProperty(r'$flutterDriverResult'.toJS).toDart, true);
expect(_window.getProperty(r'$flutterDriverResult'.toJS), isNull);
});
expect(_window.hasProperty(r'$flutterDriverResult'.toJS).toDart, true);
expect(_window.getProperty(r'$flutterDriverResult'.toJS), isNull);
},
);
}

View File

@@ -7,8 +7,8 @@ import 'package:integration_test/integration_test.dart';
void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.runTest(
() async { },
() { },
() async {},
() {},
// Changes made in https://github.com/flutter/flutter/pull/89952
timeout: Duration(minutes: 30),
);

View File

@@ -7,7 +7,7 @@ import 'package:integration_test/integration_test.dart';
void main() {
final binding = IntegrationTestWidgetsFlutterBinding.ensureInitialized();
binding.runTest(
() async { },
() { },
() async {},
() {},
);
}