Implement golden-file matching for integration_test on Android and iOS devices (#160484)

Work towards https://github.com/flutter/flutter/issues/143299.
Work towards https://github.com/flutter/flutter/issues/160043.

---

This PR implements, end-to-end, support for `matchesGoldenFile` when (a)
running with `package:integration_test` (b) on a device, such as an
Android emulator, Android device, iOS simulator, or iOS device, where
the _runner_ of a test file does not have process and local-file system
access.

There are multiple parts to this PR; I could make it smaller than 1K
lines, but the bulk of that is tests, and it would mean landing PRs that
are incomplete and unused, which does not seem useful - so instead here
is a quick overview of the PR's contents - questions/feedback welcome,
and I am willing to break code out or land incremental refactors if
requested.

1. Augmented `flutter_platform.dart` (used for iOS and Android), similar
to
[`flutter_web_platform.dart`](1398dc7eec/packages/flutter_tools/lib/src/test/flutter_web_platform.dart (L117-L128)),
now creates and uses
[`test_golden_comparator.dart`](https://github.com/flutter/flutter/blob/master/packages/flutter_tools/lib/src/test/test_golden_comparator.dart)
to proxy calls (coming from the VM service protocol) for golden-file
updates and comparisons to a `flutter_tester` process. A full
explanation of how (or why) it works this way is too hard to include
here, but see https://github.com/flutter/flutter/pull/160215 for more
details.
1. Added `VmServiceProxyGoldenFileComparator`, which is a currently
unused (outside of a single e2e test) comparator that forwards calls to
`compare` and `update` to the VM service protocol (of which, the other
side of this is implemented above, in `flutter_platform.dart`. The idea
is that this comparator would be used automatically when running in an
integration test on a device that requires it (similar to how web works
today), but that is **not** wired up yet and requires additional work in
`flutter_tools`.
1. Added two unit tests (of both the client and server), and a full
e2e-test using it to run `matchesGoldenFile`.
This commit is contained in:
Matan Lurey
2024-12-28 11:48:20 -08:00
committed by GitHub
parent b15625ca92
commit 4cd0e33013
9 changed files with 958 additions and 22 deletions

View File

@@ -0,0 +1,43 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
@Tags(<String>['reduced-test-set'])
library;
import 'package:flutter/material.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart';
import 'package:integration_test_example/main.dart' as app;
/// To run:
///
/// ```sh
/// # Be in this directory
/// cd dev/packages/integration_test/example
///
/// flutter test integration_test/matches_golden_test.dart
/// ```
///
/// To run on a particular device, see `flutter -d`.
void main() {
IntegrationTestWidgetsFlutterBinding.ensureInitialized();
// TODO(matanlurey): Make this automatic as part of the bootstrap.
VmServiceProxyGoldenFileComparator.useIfRunningOnDevice();
testWidgets('can use matchesGoldenFile with integration_test', (WidgetTester tester) async {
// Build our app and trigger a frame.
app.main();
// TODO(matanlurey): Is this necessary?
await tester.pumpAndSettle();
// Take a screenshot.
await expectLater(
find.byType(MaterialApp),
matchesGoldenFile('integration_test_matches_golden_file.png'),
);
});
}

View File

@@ -24,6 +24,8 @@ import 'src/callback.dart' as driver_actions;
import 'src/channel.dart';
import 'src/extension.dart';
export 'src/vm_service_golden_client.dart';
const String _success = 'success';
/// Whether results should be reported to the native side over the method

View File

@@ -0,0 +1,226 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Examples can assume:
// import 'dart:developer' as dev;
import 'dart:async';
import 'dart:convert';
import 'dart:developer' as dev;
import 'dart:io' as io;
import 'package:flutter/foundation.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:meta/meta.dart';
/// Compares image pixels against a golden image file on the host system.
///
/// This comparator will send a request, using the VM service protocol, to a
/// host script (i.e. the _driver_ script, running in a Dart VM on the host
/// desktop OS), which will then forward the comparison to a concrete
/// [GoldenFileComparator].
///
/// To use, run [useIfRunningOnDevice] in the `main()` of a test file or similar:
///
/// ```dart
/// import 'package:integration_test/integration_test.dart';
///
/// void main() {
/// VmServiceProxyGoldenFileComparator.useIfRunningOnDevice();
///
/// // Actual tests and such below.
/// }
/// ```
///
/// When either [compare] or [update] is called, the following event is sent
/// with [dev.postEvent]:
///
/// ```dart
/// dev.postEvent('compare' /* or 'update' */, <String, Object?>{
/// 'id': 1001, // a valid unique integer, often incrementing;
/// 'path': 'path/to/image.png', // golden key created by matchesGoldenFile;
/// 'bytes': '...base64encoded', // base64 encoded bytes representing the current image.
/// }, stream: 'integration_test.VmServiceProxyGoldenFileComparator');
/// ```
///
/// The comparator expects a response at the service extension
/// `ext.integration_test.VmServiceProxyGoldenFileComparator` that is either
/// of the following formats:
///
/// ```dart
/// <String, Object?>{
/// 'error': 'Description of why the operation failed'
/// }
/// ```
///
/// or:
///
/// ```dart
/// <String, Object?>{
/// 'result': true /* or possibly false, in the case of 'compare' calls */
/// }
/// ```
///
/// See also:
///
/// * [matchesGoldenFile], the function that invokes the comparator.
@experimental
final class VmServiceProxyGoldenFileComparator extends GoldenFileComparator {
VmServiceProxyGoldenFileComparator._() : _postEvent = dev.postEvent {
dev.registerExtension(_kServiceName, (_, Map<String, String> parameters) {
return handleEvent(parameters);
});
}
/// Creates an instance of [VmServiceProxyGoldenFileComparator] for internal testing.
///
/// @nodoc
@visibleForTesting
VmServiceProxyGoldenFileComparator.forTesting(this._postEvent);
static bool get _isRunningOnHost {
if (kIsWeb) {
return false;
}
return !io.Platform.isAndroid && !io.Platform.isIOS;
}
static void _assertNotRunningOnFuchsia() {
if (!kIsWeb && io.Platform.isFuchsia) {
throw UnsupportedError('Golden testing with integration_test does not support Fuchsia.');
}
}
/// Conditionally sets [goldenFileComparator] to [VmServiceProxyGoldenFileComparator].
///
/// If running on a non-mobile non-web platform (i.e. desktop), this method has no effect.
static void useIfRunningOnDevice() {
if (_isRunningOnHost) {
return;
}
_assertNotRunningOnFuchsia();
goldenFileComparator = _kInstance;
}
static final GoldenFileComparator _kInstance = VmServiceProxyGoldenFileComparator._();
static const String _kServiceName = 'ext.$_kEventName';
static const String _kEventName = 'integration_test.VmServiceProxyGoldenFileComparator';
final void Function(String, Map<Object?, Object?>, {String stream}) _postEvent;
/// Handles the received method and parameters as an incoming event.
///
/// Each event is treated as if it were received by the Dart developer
/// extension protocol; this method is public only to be able to write unit
/// tests that do not have to bring up and use a VM service.
///
/// @nodoc
@visibleForTesting
Future<dev.ServiceExtensionResponse> handleEvent(Map<String, String> parameters) async {
// Treat the method as the ID number of the pending request.
final String? methodIdString = parameters['id'];
if (methodIdString == null) {
return dev.ServiceExtensionResponse.error(
dev.ServiceExtensionResponse.extensionError,
'Required parameter "id" not present in response.',
);
}
final int? methodId = int.tryParse(methodIdString);
if (methodId == null) {
return dev.ServiceExtensionResponse.error(
dev.ServiceExtensionResponse.extensionError,
'Required parameter "id" not a valid integer: "$methodIdString".',
);
}
final Completer<_Result>? completer = _pendingRequests[methodId];
if (completer == null) {
return dev.ServiceExtensionResponse.error(
dev.ServiceExtensionResponse.extensionError,
'No pending request with method ID "$methodIdString".',
);
}
assert(!completer.isCompleted, 'Can never occur, as the completer should be removed');
final String? error = parameters['error'];
if (error != null) {
completer.complete(_Failure(error));
return dev.ServiceExtensionResponse.result('{}');
}
final String? result = parameters['result'];
if (result == null) {
return dev.ServiceExtensionResponse.error(
dev.ServiceExtensionResponse.invalidParams,
'Required parameter "result" not present in response.',
);
}
if (bool.tryParse(result) case final bool result) {
completer.complete(_Success(result));
return dev.ServiceExtensionResponse.result('{}');
} else {
return dev.ServiceExtensionResponse.error(
dev.ServiceExtensionResponse.invalidParams,
'Required parameter "result" not a valid boolean: "$result".',
);
}
}
int _nextId = 0;
final Map<int, Completer<_Result>> _pendingRequests = <int, Completer<_Result>>{};
Future<_Result> _postAndWait(
Uint8List imageBytes,
Uri golden, {
required String operation,
}) async {
final int nextId = ++_nextId;
assert(!_pendingRequests.containsKey(nextId));
final Completer<_Result> completer = Completer<_Result>();
_postEvent(operation, <String, Object?>{
'id': nextId,
'path': '$golden',
'bytes': base64.encode(imageBytes),
}, stream: _kEventName);
_pendingRequests[nextId] = completer;
completer.future.whenComplete(() {
_pendingRequests.remove(nextId);
});
return completer.future;
}
@override
Future<bool> compare(Uint8List imageBytes, Uri golden) async {
return switch (await _postAndWait(imageBytes, golden, operation: 'compare')) {
_Success(:final bool result) => result,
_Failure(:final String error) => Future<bool>.error(error),
};
}
@override
Future<void> update(Uri golden, Uint8List imageBytes) async {
final _Result result = await _postAndWait(imageBytes, golden, operation: 'update');
if (result is _Failure) {
return Future<void>.error(result.error);
}
}
}
// These wrapper classes allow us to use a Completer to indicate both a failed
// response and a successful response, without making a call of completeError
// within handleEvent, which is difficult or impossible to use correctly because
// of the semantics of error zones.
//
// Of course, this is a private implementation detail, others are welcome to try
// an alternative approach that might simplify the code above, but it's probably
// not worth it.
sealed class _Result {}
final class _Success implements _Result {
_Success(this.result);
final bool result;
}
final class _Failure implements _Result {
_Failure(this.error);
final String error;
}

View File

@@ -0,0 +1,297 @@
// Copyright 2014 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
import 'dart:convert';
import 'dart:developer' as dev;
import 'dart:typed_data';
import 'package:flutter_test/flutter_test.dart';
import 'package:integration_test/integration_test.dart' as integration_test;
void main() {
setUp(() {
// Ensure that we reset to a throwing comparator by default.
goldenFileComparator = const _NullGoldenFileComparator();
});
group('useIfRunningOnDevice', () {
test('is skipped on the web', () {
integration_test.VmServiceProxyGoldenFileComparator.useIfRunningOnDevice();
expect(goldenFileComparator, isInstanceOf<_NullGoldenFileComparator>());
}, testOn: 'js');
test('is skipped on desktop platforms', () {
integration_test.VmServiceProxyGoldenFileComparator.useIfRunningOnDevice();
expect(goldenFileComparator, isInstanceOf<_NullGoldenFileComparator>());
}, testOn: 'windows || mac-os || linux');
test('is set on mobile platforms', () {
integration_test.VmServiceProxyGoldenFileComparator.useIfRunningOnDevice();
expect(
goldenFileComparator,
isInstanceOf<integration_test.VmServiceProxyGoldenFileComparator>(),
);
}, testOn: 'ios || android');
});
group('handleEvent', () {
late integration_test.VmServiceProxyGoldenFileComparator goldenFileComparator;
setUp(() {
goldenFileComparator = integration_test.VmServiceProxyGoldenFileComparator.forTesting(
(String operation, Map<Object?, Object?> params, {String stream = ''}) {},
);
});
test('"id" must be provided', () async {
final dev.ServiceExtensionResponse response = await goldenFileComparator.handleEvent(
<String, String>{'result': 'true'},
);
expect(response.errorDetail, contains('Required parameter "id" not present in response'));
});
test('"id" must be an integer', () async {
final dev.ServiceExtensionResponse response = await goldenFileComparator.handleEvent(
<String, String>{'id': 'not-an-integer', 'result': 'true'},
);
expect(
response.errorDetail,
stringContainsInOrder(<String>[
'Required parameter "id" not a valid integer',
'not-an-integer',
]),
);
});
test('"id" must match a pending request (never occurred)', () async {
final dev.ServiceExtensionResponse response = await goldenFileComparator.handleEvent(
<String, String>{'id': '12345', 'result': 'true'},
);
expect(
response.errorDetail,
stringContainsInOrder(<String>['No pending request with method ID', '12345']),
);
});
test('"id" must match a pending request (already occurred)', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
goldenFileComparator.update(Uri(path: 'some-file'), Uint8List(0));
dev.ServiceExtensionResponse response;
response = await goldenFileComparator.handleEvent(<String, String>{
'id': '$nextId',
'result': 'true',
});
expect(response.errorDetail, isNull);
response = await goldenFileComparator.handleEvent(<String, String>{
'id': '$nextId',
'result': 'true',
});
expect(
response.errorDetail,
stringContainsInOrder(<String>['No pending request with method ID', '1']),
);
});
test('requests that contain "error" completes it as an error', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
expect(
goldenFileComparator.compare(Uint8List(0), Uri(path: 'some-file')),
throwsA(contains('We did a bad')),
);
final dev.ServiceExtensionResponse response = await goldenFileComparator.handleEvent(
<String, String>{'id': '$nextId', 'error': 'We did a bad'},
);
expect(response.errorDetail, isNull);
expect(response.result, '{}');
});
test('requests that do not contain "error" return an empty response', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
goldenFileComparator.update(Uri(path: 'some-file'), Uint8List(0));
final dev.ServiceExtensionResponse response = await goldenFileComparator.handleEvent(
<String, String>{'id': '$nextId', 'result': 'true'},
);
expect(response.errorDetail, isNull);
expect(response.result, '{}');
});
test('"result" must be provided if "error" is omitted', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
goldenFileComparator.update(Uri(path: 'some-file'), Uint8List(0));
final dev.ServiceExtensionResponse response = await goldenFileComparator.handleEvent(
<String, String>{'id': '$nextId'},
);
expect(response.errorDetail, contains('Required parameter "result" not present in response'));
});
test('"result" must be a boolean', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
goldenFileComparator.update(Uri(path: 'some-file'), Uint8List(0));
final dev.ServiceExtensionResponse response = await goldenFileComparator.handleEvent(
<String, String>{'id': '$nextId', 'result': 'not-a-boolean'},
);
expect(
response.errorDetail,
stringContainsInOrder(<String>[
'Required parameter "result" not a valid boolean',
'not-a-boolean',
]),
);
});
group('compare', () {
late integration_test.VmServiceProxyGoldenFileComparator goldenFileComparator;
late List<(String, Map<Object?, Object?>)> postedEvents;
setUp(() {
postedEvents = <(String, Map<Object?, Object?>)>[];
goldenFileComparator = integration_test.VmServiceProxyGoldenFileComparator.forTesting((
String operation,
Map<Object?, Object?> params, {
String stream = '',
}) {
postedEvents.add((operation, params));
});
});
test('posts an event and returns true', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
final Uint8List bytes = Uint8List.fromList(<int>[1, 2, 3, 4, 5]);
expect(goldenFileComparator.compare(bytes, Uri(path: 'golden-path')), completion(true));
await goldenFileComparator.handleEvent(<String, String>{'id': '$nextId', 'result': 'true'});
final (String event, Map<Object?, Object?> params) = postedEvents.single;
expect(event, 'compare');
expect(params, <Object?, Object?>{
'id': nextId,
'path': 'golden-path',
'bytes': base64.encode(bytes),
});
});
test('posts an event and returns false', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
final Uint8List bytes = Uint8List.fromList(<int>[1, 2, 3, 4, 5]);
expect(goldenFileComparator.compare(bytes, Uri(path: 'golden-path')), completion(false));
await goldenFileComparator.handleEvent(<String, String>{
'id': '$nextId',
'result': 'false',
});
final (String event, Map<Object?, Object?> params) = postedEvents.single;
expect(event, 'compare');
expect(params, <Object?, Object?>{
'id': nextId,
'path': 'golden-path',
'bytes': base64.encode(bytes),
});
});
test('posts an event and returns an error', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
final Uint8List bytes = Uint8List.fromList(<int>[1, 2, 3, 4, 5]);
expect(
goldenFileComparator.compare(bytes, Uri(path: 'golden-path')),
throwsA(contains('We did a bad')),
);
await goldenFileComparator.handleEvent(<String, String>{
'id': '$nextId',
'error': 'We did a bad',
});
final (String event, Map<Object?, Object?> params) = postedEvents.single;
expect(event, 'compare');
expect(params, <Object?, Object?>{
'id': nextId,
'path': 'golden-path',
'bytes': base64.encode(bytes),
});
});
});
group('update', () {
late integration_test.VmServiceProxyGoldenFileComparator goldenFileComparator;
late List<(String, Map<Object?, Object?>)> postedEvents;
setUp(() {
postedEvents = <(String, Map<Object?, Object?>)>[];
goldenFileComparator = integration_test.VmServiceProxyGoldenFileComparator.forTesting((
String operation,
Map<Object?, Object?> params, {
String stream = '',
}) {
postedEvents.add((operation, params));
});
});
test('posts an event and returns', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
final Uint8List bytes = Uint8List.fromList(<int>[1, 2, 3, 4, 5]);
expect(goldenFileComparator.update(Uri(path: 'golden-path'), bytes), completes);
await goldenFileComparator.handleEvent(<String, String>{'id': '$nextId', 'result': 'true'});
final (String event, Map<Object?, Object?> params) = postedEvents.single;
expect(event, 'update');
expect(params, <Object?, Object?>{
'id': nextId,
'path': 'golden-path',
'bytes': base64.encode(bytes),
});
});
test('posts an event and returns an error', () async {
// This is based on an implementation detail of knowing how IDs are generated.
const int nextId = 1;
final Uint8List bytes = Uint8List.fromList(<int>[1, 2, 3, 4, 5]);
expect(
goldenFileComparator.update(Uri(path: 'golden-path'), bytes),
throwsA(contains('We did a bad')),
);
await goldenFileComparator.handleEvent(<String, String>{
'id': '$nextId',
'error': 'We did a bad',
});
final (String event, Map<Object?, Object?> params) = postedEvents.single;
expect(event, 'update');
expect(params, <Object?, Object?>{
'id': nextId,
'path': 'golden-path',
'bytes': base64.encode(bytes),
});
});
});
});
}
final class _NullGoldenFileComparator with Fake implements GoldenFileComparator {
const _NullGoldenFileComparator();
}