Rename native_driver to android_{driver_extensions|engine_test} (#161263)
Towards https://github.com/flutter/flutter/issues/161261 (before I add more tests). This is a 1:1 move, with massaging of `run_flutter_driver_android_tests.dart` to be more automated as tests are added. /cc @reidbaker
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
// 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.
|
||||
|
||||
export 'android/adb.dart';
|
||||
export 'android/driver.dart';
|
||||
@@ -0,0 +1,289 @@
|
||||
// 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:io' as io;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:process/process.dart';
|
||||
|
||||
/// A minimal wrapper around the `adb` command-line tool.
|
||||
@internal
|
||||
class Adb {
|
||||
const Adb._(this._prefixArgs, this._process);
|
||||
|
||||
/// Creates a new `adb` command runner that uses the `adb` command-line tool.
|
||||
///
|
||||
/// If [adbPath] is not provided, the `adb` command is assumed to be in the
|
||||
/// system's PATH.
|
||||
///
|
||||
/// If [target] is not provided, the target is assumed to be the only running
|
||||
/// emulator or connected device.
|
||||
///
|
||||
/// For testing, [processManager] can be provided to mock the process manager.
|
||||
static Future<Adb> create({
|
||||
String? adbPath,
|
||||
AndroidDeviceTarget? target,
|
||||
@visibleForTesting ProcessManager? processManager,
|
||||
}) async {
|
||||
target ??= const AndroidDeviceTarget.onlyEmulatorOrDevice();
|
||||
final String tool = adbPath ?? 'adb';
|
||||
final Adb adb = Adb._(<String>[
|
||||
tool,
|
||||
...target._toAdbArgs(),
|
||||
], processManager ?? const LocalProcessManager());
|
||||
final (bool connected, String? error) = await adb.isDeviceConnected();
|
||||
if (!connected) {
|
||||
throw StateError('No device connected: $error');
|
||||
}
|
||||
return adb;
|
||||
}
|
||||
|
||||
Future<AdbStringResult> _runString(List<String> args) async {
|
||||
final io.ProcessResult result = await _process.run(<String>[..._prefixArgs, ...args]);
|
||||
return AdbStringResult(
|
||||
result.stdout as String,
|
||||
exitCode: result.exitCode,
|
||||
stderr: result.stderr as String,
|
||||
);
|
||||
}
|
||||
|
||||
Future<AdbBinaryResult> _runBinary(List<String> args) async {
|
||||
final io.ProcessResult result = await _process.run(<String>[
|
||||
..._prefixArgs,
|
||||
...args,
|
||||
], stdoutEncoding: null);
|
||||
return AdbBinaryResult(
|
||||
result.stdout as Uint8List,
|
||||
exitCode: result.exitCode,
|
||||
stderr: result.stderr as String,
|
||||
);
|
||||
}
|
||||
|
||||
final List<String> _prefixArgs;
|
||||
final ProcessManager _process;
|
||||
|
||||
/// Returns whether the device is currently connected.
|
||||
///
|
||||
/// Returns a tuple of a boolean indicating whether the device is connected
|
||||
/// and an error message if the device is not connected. If the device is
|
||||
/// connected, the error message is `null`.
|
||||
Future<(bool connected, String? error)> isDeviceConnected() async {
|
||||
final AdbStringResult result = await _runString(<String>['shell', 'echo', 'connected']);
|
||||
if (result.exitCode != 0) {
|
||||
return (false, result.stderr);
|
||||
} else {
|
||||
return (true, null);
|
||||
}
|
||||
}
|
||||
|
||||
/// Takes a screenshot of the device.
|
||||
Future<Uint8List> screencap() async {
|
||||
final AdbBinaryResult result = await _runBinary(<String>['exec-out', 'screencap', '-p']);
|
||||
if (result.exitCode != 0) {
|
||||
throw StateError('Failed to take screenshot: ${result.stderr}');
|
||||
}
|
||||
return result.stdout;
|
||||
}
|
||||
|
||||
/// Taps on the screen at the given [x] and [y] coordinates.
|
||||
Future<void> tap(int x, int y) async {
|
||||
final AdbStringResult result = await _runString(<String>['shell', 'input', 'tap', '$x', '$y']);
|
||||
if (result.exitCode != 0) {
|
||||
throw StateError('Failed to tap at $x, $y: ${result.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends the device to the home screen.
|
||||
Future<void> sendToHome() async {
|
||||
final AdbStringResult result = await _runString(<String>[
|
||||
'shell',
|
||||
'input',
|
||||
'keyevent',
|
||||
'KEYCODE_HOME',
|
||||
]);
|
||||
if (result.exitCode != 0) {
|
||||
throw StateError('Failed to send to home: ${result.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
/// Simulate low memory conditions on the device.
|
||||
Future<void> trimMemory({required String appName}) async {
|
||||
final AdbStringResult result = await _runString(<String>[
|
||||
'shell',
|
||||
'am',
|
||||
'send-trim-memory',
|
||||
appName,
|
||||
'MODERATE',
|
||||
]);
|
||||
if (result.exitCode != 0) {
|
||||
throw StateError('Failed to simulate low memory: ${result.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
/// Resume a backgrounded app (i.e. after [sendToHome]).
|
||||
Future<void> resumeApp({required String appName, String activityName = '.MainActivity'}) async {
|
||||
final AdbStringResult result = await _runString(<String>[
|
||||
'shell',
|
||||
'am',
|
||||
'start',
|
||||
'-n',
|
||||
'$appName/$activityName',
|
||||
]);
|
||||
if (result.exitCode != 0) {
|
||||
throw StateError('Failed to resume app: ${result.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
/// Disable confirmations for immersive mode.
|
||||
Future<void> disableImmersiveModeConfirmations() async {
|
||||
final AdbStringResult result = await _runString(<String>[
|
||||
'shell',
|
||||
'settings',
|
||||
'put',
|
||||
'secure',
|
||||
'immersive_mode_confirmations',
|
||||
'confirmed',
|
||||
]);
|
||||
if (result.exitCode != 0) {
|
||||
throw StateError('Failed to disable immersive mode confirmations: ${result.stderr}');
|
||||
}
|
||||
}
|
||||
|
||||
/// Disable animations on the device.
|
||||
Future<void> disableAnimations() async {
|
||||
const Map<String, String> settings = <String, String>{
|
||||
'show_surface_updates': '1',
|
||||
'transition_animation_scale': '0',
|
||||
'window_animation_scale': '0',
|
||||
'animator_duration_scale': '0',
|
||||
};
|
||||
for (final MapEntry<String, String> entry in settings.entries) {
|
||||
final AdbStringResult result = await _runString(<String>[
|
||||
'shell',
|
||||
'settings',
|
||||
'put',
|
||||
'global',
|
||||
entry.key,
|
||||
entry.value,
|
||||
]);
|
||||
if (result.exitCode != 0) {
|
||||
throw StateError('Failed to disable animations: ${result.stderr}');
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Possible results of an `adb` command.
|
||||
@internal
|
||||
sealed class AdbResult {
|
||||
/// Creates a new `adb` result.
|
||||
const AdbResult._({this.exitCode = 0, this.stderr = ''});
|
||||
|
||||
/// The exit code of the `adb` command.
|
||||
final int exitCode;
|
||||
|
||||
/// The standard error output of the `adb` command.
|
||||
final String stderr;
|
||||
}
|
||||
|
||||
@internal
|
||||
final class AdbStringResult extends AdbResult {
|
||||
AdbStringResult(this.stdout, {super.stderr, super.exitCode}) : super._();
|
||||
|
||||
/// The standard output of the `adb` command.
|
||||
final String stdout;
|
||||
}
|
||||
|
||||
@internal
|
||||
final class AdbBinaryResult extends AdbResult {
|
||||
AdbBinaryResult(this.stdout, {super.stderr, super.exitCode}) : super._();
|
||||
|
||||
/// The standard output of the `adb` command.
|
||||
final Uint8List stdout;
|
||||
}
|
||||
|
||||
/// Represents a target device running Android.
|
||||
sealed class AndroidDeviceTarget {
|
||||
/// Represents a device with the given [serialNumber].
|
||||
///
|
||||
/// This is the recommended way to target a specific device, and uses the
|
||||
/// device's serial number, as reported by `adb devices`, to identify the
|
||||
/// device:
|
||||
///
|
||||
/// ```sh
|
||||
/// $ adb devices
|
||||
/// List of devices attached
|
||||
/// emulator-5554 device
|
||||
/// ```
|
||||
///
|
||||
/// In this example, the serial number is `emulator-5554`:
|
||||
///
|
||||
/// ```dart
|
||||
/// const AndroidDeviceTarget target = AndroidDeviceTarget.bySerial('emulator-5554');
|
||||
/// ```
|
||||
const factory AndroidDeviceTarget.bySerial(String serialNumber) = _SerialDeviceTarget;
|
||||
|
||||
/// Represents the only running emulator _or_ connected device.
|
||||
///
|
||||
/// This is equivalent to using `adb` without `-e`, `-d`, or `-s`.
|
||||
const factory AndroidDeviceTarget.onlyEmulatorOrDevice() = _SingleAnyTarget;
|
||||
|
||||
/// Represents the only running emulator on the host machine.
|
||||
///
|
||||
/// This is equivalent to using `adb -e`, a _single_ emulator must be running.
|
||||
const factory AndroidDeviceTarget.onlyEmulator() = _SingleEmulatorTarget;
|
||||
|
||||
/// Represents the only connected device on the host machine.
|
||||
///
|
||||
/// This is equivalent to using `adb -d`, a _single_ device must be connected.
|
||||
const factory AndroidDeviceTarget.onlyDevice() = _SingleDeviceTarget;
|
||||
|
||||
/// Returns the arguments to pass to `adb` to target this device.
|
||||
List<String> _toAdbArgs();
|
||||
}
|
||||
|
||||
final class _SerialDeviceTarget implements AndroidDeviceTarget {
|
||||
const _SerialDeviceTarget(this.serialNumber);
|
||||
final String serialNumber;
|
||||
|
||||
@override
|
||||
List<String> _toAdbArgs() => <String>['-s', serialNumber];
|
||||
}
|
||||
|
||||
final class _SingleEmulatorTarget implements AndroidDeviceTarget {
|
||||
const _SingleEmulatorTarget();
|
||||
|
||||
@override
|
||||
List<String> _toAdbArgs() => const <String>['-e'];
|
||||
}
|
||||
|
||||
final class _SingleDeviceTarget implements AndroidDeviceTarget {
|
||||
const _SingleDeviceTarget();
|
||||
|
||||
@override
|
||||
List<String> _toAdbArgs() => const <String>['-d'];
|
||||
}
|
||||
|
||||
final class _SingleAnyTarget implements AndroidDeviceTarget {
|
||||
const _SingleAnyTarget();
|
||||
|
||||
@override
|
||||
List<String> _toAdbArgs() => const <String>[];
|
||||
}
|
||||
|
||||
/// Represents the possible screen orientations on Android.
|
||||
enum AdbUserRotation {
|
||||
/// Portrait orientation.
|
||||
portrait,
|
||||
|
||||
/// Landscape orientation.
|
||||
landscape,
|
||||
|
||||
/// Reverse portrait orientation, i.e., portrait upside down.
|
||||
reversePortrait,
|
||||
|
||||
/// Reverse landscape orientation, i.e., landscape upside down.
|
||||
reverseLandscape,
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
// 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:io' as io;
|
||||
import 'dart:typed_data';
|
||||
|
||||
import 'package:flutter_driver/flutter_driver.dart';
|
||||
import 'package:meta/meta.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import '../../../native_driver.dart';
|
||||
import '../../common.dart';
|
||||
import 'adb.dart';
|
||||
|
||||
/// Drives an Android device or emulator that is running a Flutter application.
|
||||
final class AndroidNativeDriver implements NativeDriver {
|
||||
/// Assumes a connected device or emulator via [adb].
|
||||
///
|
||||
/// This constructor is intended for testing purposes only.
|
||||
@visibleForTesting
|
||||
AndroidNativeDriver.forTesting({
|
||||
required Adb adb,
|
||||
required FlutterDriver driver,
|
||||
required io.Directory tempDirectory,
|
||||
}) : this._(adb, driver, tempDirectory);
|
||||
|
||||
AndroidNativeDriver._(this._adb, this._driver, this._tmpDir);
|
||||
final Adb _adb;
|
||||
final FlutterDriver _driver;
|
||||
final io.Directory _tmpDir;
|
||||
|
||||
/// Connects to a device or emulator identified by [target], which defaults to
|
||||
/// the only running emulator or connected device.
|
||||
///
|
||||
/// If [adbPath] is not provided, the `adb` command is assumed to be in the
|
||||
/// system's PATH.
|
||||
///
|
||||
/// If [tempDirectory] is not provided, a temporary directory will be created
|
||||
/// in the system's temporary directory.
|
||||
static Future<AndroidNativeDriver> connect(
|
||||
FlutterDriver driver, {
|
||||
AndroidDeviceTarget? target,
|
||||
String? adbPath,
|
||||
io.Directory? tempDirectory,
|
||||
}) async {
|
||||
final Adb adb = await Adb.create(adbPath: adbPath, target: target);
|
||||
tempDirectory ??= io.Directory.systemTemp.createTempSync('native_driver.');
|
||||
final AndroidNativeDriver nativeDriver = AndroidNativeDriver.forTesting(
|
||||
adb: adb,
|
||||
driver: driver,
|
||||
tempDirectory: tempDirectory,
|
||||
);
|
||||
await nativeDriver.ping();
|
||||
return nativeDriver;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> close() async {
|
||||
await _tmpDir.delete(recursive: true);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> configureForScreenshotTesting() async {
|
||||
await _adb.disableImmersiveModeConfirmations();
|
||||
await _adb.disableAnimations();
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> tap(NativeFinder finder) async {
|
||||
await _driver.sendCommand(NativeCommand.tap(finder));
|
||||
}
|
||||
|
||||
/// Waits for 2 seconds before completing.
|
||||
///
|
||||
/// There is no perfect way, outside of polling, to know when the device is
|
||||
/// "stable" or has "stabilized" after a state change. The way that commands
|
||||
/// such as [FlutterDriver.screenshot] handle this is to wait for 2 seconds
|
||||
/// as a baseline, and then proceed with the command.
|
||||
static Future<void> _waitFor2s() async {
|
||||
await Future<void>.delayed(const Duration(seconds: 2));
|
||||
}
|
||||
|
||||
@override
|
||||
Future<NativeScreenshot> screenshot() async {
|
||||
// Identical wait to what `FlutterDriver.screenshot` does.
|
||||
await _waitFor2s();
|
||||
return _AdbScreencap(await _adb.screencap(), _tmpDir);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Duration> ping() async {
|
||||
final Stopwatch stopwatch = Stopwatch()..start();
|
||||
await _driver.sendCommand(NativeCommand.ping);
|
||||
return stopwatch.elapsed;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> rotateToLandscape() async {
|
||||
_driver.sendCommand(NativeCommand.rotateLandscape);
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> rotateResetDefault() async {
|
||||
_driver.sendCommand(NativeCommand.rotateDefault);
|
||||
}
|
||||
|
||||
/// Background the app by pressing the home button.
|
||||
Future<void> backgroundApp() async {
|
||||
await _adb.sendToHome();
|
||||
await _waitFor2s();
|
||||
}
|
||||
|
||||
/// Resumes the app by selecting it from the recent apps list.
|
||||
Future<void> resumeApp({required String appName}) async {
|
||||
await _adb.resumeApp(appName: appName);
|
||||
await _waitFor2s();
|
||||
}
|
||||
|
||||
/// Send a trim memory signal to the app to force it to release memory.
|
||||
Future<void> simulateLowMemory({required String appName}) async {
|
||||
await _adb.trimMemory(appName: appName);
|
||||
await _waitFor2s();
|
||||
}
|
||||
}
|
||||
|
||||
final class _AdbScreencap implements NativeScreenshot {
|
||||
const _AdbScreencap(this._bytes, this._tmpDir);
|
||||
|
||||
/// Raw bytes of the screenshot in PNG format.
|
||||
final Uint8List _bytes;
|
||||
|
||||
/// Temporary directory to use as a default location for saving.
|
||||
final io.Directory _tmpDir;
|
||||
|
||||
static int _lastScreenshotId = 0;
|
||||
|
||||
@override
|
||||
Future<String> saveAs([String? path]) async {
|
||||
final int id = _lastScreenshotId++;
|
||||
path ??= p.join(_tmpDir.path, 'screenshot_$id.png');
|
||||
await io.File(path).writeAsBytes(_bytes);
|
||||
return path;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Uint8List> readAsBytes() async => _bytes;
|
||||
}
|
||||
119
dev/tools/android_driver_extensions/lib/src/common.dart
Normal file
119
dev/tools/android_driver_extensions/lib/src/common.dart
Normal file
@@ -0,0 +1,119 @@
|
||||
// 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';
|
||||
|
||||
// This code has to be available in both the Flutter app and Dart VM test.
|
||||
// ignore: implementation_imports
|
||||
import 'package:flutter_driver/src/common/message.dart';
|
||||
|
||||
/// A command that is forwarded to a registered plugin.
|
||||
final class NativeCommand extends Command {
|
||||
/// Creates a new [NativeCommand] with the given [method].
|
||||
const NativeCommand(this.method, {this.arguments, super.timeout});
|
||||
|
||||
/// Tries to tap a native view by a selector.
|
||||
factory NativeCommand.tap(NativeFinder finder) {
|
||||
return NativeCommand('tap_view', arguments: finder);
|
||||
}
|
||||
|
||||
/// Requests that the device be rotated to landscape mode.
|
||||
static const NativeCommand rotateLandscape = NativeCommand('rotate_landscape');
|
||||
|
||||
/// Requests that the device reset its rotation to the default orientation.
|
||||
static const NativeCommand rotateDefault = NativeCommand('rotate_default');
|
||||
|
||||
/// Pings the device to ensure it is responsive.
|
||||
static const NativeCommand ping = NativeCommand('ping');
|
||||
|
||||
/// The method to call on the plugin.
|
||||
final String method;
|
||||
|
||||
/// What arguments to pass when invoking the [method].
|
||||
final Object? arguments;
|
||||
|
||||
@override
|
||||
String get kind => 'native_driver';
|
||||
|
||||
@override
|
||||
Map<String, String> serialize() {
|
||||
final Map<String, String> serialized = super.serialize();
|
||||
serialized['method'] = method;
|
||||
if (arguments != null) {
|
||||
serialized['arguments'] = jsonEncode(arguments);
|
||||
}
|
||||
return serialized;
|
||||
}
|
||||
}
|
||||
|
||||
/// A result from a [NativeCommand].
|
||||
final class NativeResult extends Result {
|
||||
/// Creates a new [NativeResult].
|
||||
const NativeResult();
|
||||
|
||||
@override
|
||||
Map<String, dynamic> toJson() => const <String, Object?>{};
|
||||
}
|
||||
|
||||
/// An object that describes searching for _native_ elements.
|
||||
sealed class NativeFinder {
|
||||
const NativeFinder();
|
||||
|
||||
/// Serializes to JSON.
|
||||
Map<String, Object?> toJson() => const <String, Object?>{};
|
||||
}
|
||||
|
||||
/// Finds a native element by its native accessibility label.
|
||||
final class ByNativeAccessibilityLabel extends NativeFinder {
|
||||
/// Creates a new [ByNativeSemanticsLabel] finder.
|
||||
const ByNativeAccessibilityLabel(this.label);
|
||||
|
||||
/// The label to search for.
|
||||
///
|
||||
/// ## Android
|
||||
///
|
||||
/// On Android, this label is the `contentDescription` of the view:
|
||||
///
|
||||
/// ```java
|
||||
/// view.setContentDescription("My Label");
|
||||
/// ```
|
||||
final String label;
|
||||
|
||||
@override
|
||||
Map<String, String> toJson() {
|
||||
return <String, String>{'kind': 'byNativeAccessibilityLabel', 'label': label};
|
||||
}
|
||||
|
||||
/// Deserializes this finder from the value generated by [serialize].
|
||||
static ByNativeAccessibilityLabel deserialize(Map<String, String> params) {
|
||||
return ByNativeAccessibilityLabel(params['label']!);
|
||||
}
|
||||
}
|
||||
|
||||
/// Finds a native element by its native integer-based ID.
|
||||
final class ByNativeIntegerId extends NativeFinder {
|
||||
/// Creates a new [ByNativeIntegerId] finder.
|
||||
const ByNativeIntegerId(this.id);
|
||||
|
||||
/// The integer ID to search for.
|
||||
///
|
||||
/// ## Android
|
||||
///
|
||||
/// On Android, this ID is the `View.getId()` of the view:
|
||||
///
|
||||
/// ```java
|
||||
/// view.setId(42);
|
||||
/// ```
|
||||
final int id;
|
||||
|
||||
@override
|
||||
Map<String, String> toJson() {
|
||||
return <String, String>{'kind': 'byNativeIntegerId', 'id': id.toString()};
|
||||
}
|
||||
|
||||
/// Deserializes this finder from the value generated by [serialize].
|
||||
static ByNativeIntegerId deserialize(Map<String, String> params) {
|
||||
return ByNativeIntegerId(int.parse(params['id']!));
|
||||
}
|
||||
}
|
||||
86
dev/tools/android_driver_extensions/lib/src/driver.dart
Normal file
86
dev/tools/android_driver_extensions/lib/src/driver.dart
Normal file
@@ -0,0 +1,86 @@
|
||||
// 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.
|
||||
|
||||
part of '../native_driver.dart';
|
||||
|
||||
/// Drives a native device or emulator that is running a Flutter application.
|
||||
///
|
||||
/// Unlike [FlutterDriver], a [NativeDriver] is backed by a platform specific
|
||||
/// implementation that might interact with out-of-process services, such as
|
||||
/// `adb` for Android and might require additional setup (e.g., adding test-only
|
||||
/// plugins to the application under test) for full functionality.
|
||||
///
|
||||
/// API that is available directly on [NativeDriver] is considered _lowest
|
||||
/// common denominator_ and is guaranteed to work on all platforms supported by
|
||||
/// Flutter Driver unless otherwise noted. Platform-specific functionality that
|
||||
/// _cannot_ be exposed through this interface is available through
|
||||
/// platform-specific extensions.
|
||||
abstract interface class NativeDriver {
|
||||
/// Closes the native driver and releases any resources associated with it.
|
||||
///
|
||||
/// After calling this method, the driver is no longer usable.
|
||||
Future<void> close();
|
||||
|
||||
/// Configures the device for (more) deterministic screenshots if possible.
|
||||
///
|
||||
/// This method should be called during `setUpAll` if tests are going to
|
||||
/// compare screenshots to golden files.
|
||||
///
|
||||
/// Not all platforms support this method, and it is a no-op on platforms that
|
||||
/// do not.
|
||||
Future<void> configureForScreenshotTesting();
|
||||
|
||||
/// Pings the device to ensure it is responsive.
|
||||
///
|
||||
/// The implementation should return a future that completes when a command
|
||||
/// is passed to the device (from the driver script), and to the native driver
|
||||
/// plugin (if applicable), and back to the driver script.
|
||||
///
|
||||
/// The duration of the round trip is returned, typically calculated as:
|
||||
/// ```dart
|
||||
/// final Stopwatch stopwatch = Stopwatch()..start();
|
||||
/// await doPing();
|
||||
/// return stopwatch.elapsed;
|
||||
/// ```
|
||||
Future<Duration> ping();
|
||||
|
||||
/// Take a screenshot using a platform-specific mechanism.
|
||||
///
|
||||
/// The image is returned as an opaque handle that can be used to retrieve
|
||||
/// the screenshot data or to compare it with another screenshot, and may
|
||||
/// include platform-specific system UI elements, such as the status bar or
|
||||
/// navigation bar.
|
||||
Future<NativeScreenshot> screenshot();
|
||||
|
||||
/// Rotates the device to landscape orientation.
|
||||
Future<void> rotateToLandscape();
|
||||
|
||||
/// Returns the device to its default orientation.
|
||||
Future<void> rotateResetDefault();
|
||||
|
||||
/// Taps on a native view found by a selector.
|
||||
///
|
||||
/// The [finder] is a platform-specific object that describes how to search
|
||||
/// for a view to tap on. The method completes when the tap is complete,
|
||||
/// or throws if a view cannot be found or tapped.
|
||||
Future<void> tap(NativeFinder finder);
|
||||
}
|
||||
|
||||
/// An opaque handle to a screenshot taken on a native device.
|
||||
///
|
||||
/// Unlike [FlutterDriver.screenshot], the screenshot represented by this handle
|
||||
/// is generated by a platform-specific mechanism and is often already stored
|
||||
/// on disk. The handle can be used to retrieve the screenshot data or to
|
||||
/// compare it with another screenshot.
|
||||
abstract interface class NativeScreenshot {
|
||||
/// Saves the screenshot to a file at the specified [path].
|
||||
///
|
||||
/// If [path] is not provided, a temporary file will be created.
|
||||
///
|
||||
/// Returns the path to the saved file.
|
||||
Future<String> saveAs([String? path]);
|
||||
|
||||
/// Reads the screenshot as a PNG-formatted list of bytes.
|
||||
Future<Uint8List> readAsBytes();
|
||||
}
|
||||
221
dev/tools/android_driver_extensions/lib/src/goldens.dart
Normal file
221
dev/tools/android_driver_extensions/lib/src/goldens.dart
Normal file
@@ -0,0 +1,221 @@
|
||||
// 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.
|
||||
|
||||
// A partial copy of [flutter_test.matchesGoldenFile] and supporting code.
|
||||
//
|
||||
// Flutter driver runs in the standalone Dart VM, which does not have access to
|
||||
// the Flutter test library or `dart:ui`. This file provides a subset of the
|
||||
// functionality of `flutter_test`'s `matchesGoldenFile` function, and we can
|
||||
// consider refactoring this code to be shared between the two libraries
|
||||
// (https://github.com/flutter/flutter/issues/152257).
|
||||
part of '../native_driver.dart';
|
||||
|
||||
/// Whether golden files should be automatically updated during tests rather
|
||||
/// than compared to the image bytes recorded by the tests.
|
||||
///
|
||||
/// When this is `true`, [matchesGoldenFile] will always report a successful
|
||||
/// match, because the bytes being tested implicitly become the new golden.
|
||||
bool autoUpdateGoldenFiles = false;
|
||||
|
||||
/// Compares pixels against those of a golden image file.
|
||||
///
|
||||
/// This comparator is used as the backend for [matchesGoldenFile].
|
||||
///
|
||||
/// By default, an exact pixel match to a local golden file is used.
|
||||
GoldenFileComparator goldenFileComparator = const NaiveLocalFileComparator._();
|
||||
|
||||
/// Compares image pixels against a golden image file.
|
||||
///
|
||||
/// Instances of this comparator will be used as the backend for
|
||||
/// [matchesGoldenFile].
|
||||
abstract class GoldenFileComparator {
|
||||
/// @nodoc
|
||||
const GoldenFileComparator();
|
||||
|
||||
/// Compares the pixels of decoded png [imageBytes] against the golden file
|
||||
/// identified by [golden].
|
||||
///
|
||||
/// The returned future completes with a boolean value that indicates whether
|
||||
/// the pixels decoded from [imageBytes] match the golden file's pixels.
|
||||
///
|
||||
/// In the case of comparison mismatch, the comparator may choose to throw a
|
||||
/// [TestFailure] if it wants to control the failure message, often in the
|
||||
/// form of a [ComparisonResult] that provides detailed information about the
|
||||
/// mismatch.
|
||||
///
|
||||
/// The method by which [golden] is located and by which its bytes are loaded
|
||||
/// is left up to the implementation class. For instance, some implementations
|
||||
/// may load files from the local file system, whereas others may load files
|
||||
/// over the network or from a remote repository.
|
||||
Future<bool> compare(Uint8List imageBytes, Uri golden);
|
||||
|
||||
/// Updates the golden file identified by [golden] with [imageBytes].
|
||||
///
|
||||
/// This will be invoked in lieu of [compare] when [autoUpdateGoldenFiles]
|
||||
/// is `true` (which gets set automatically by the test framework when the
|
||||
/// user runs `flutter drive --update-goldens`).
|
||||
///
|
||||
/// The method by which [golden] is located and by which its bytes are written
|
||||
/// is left up to the implementation class.
|
||||
Future<void> update(Uri golden, Uint8List imageBytes);
|
||||
|
||||
/// Returns a new golden file [Uri] to incorporate any [version] number with
|
||||
/// the [key].
|
||||
///
|
||||
/// The [version] is an optional int that can be used to differentiate
|
||||
/// historical golden files.
|
||||
///
|
||||
/// Version numbers are used in golden file tests for package:flutter. You can
|
||||
/// learn more about these tests [here](https://github.com/flutter/flutter/blob/main/docs/contributing/testing/Writing-a-golden-file-test-for-package-flutter.md).
|
||||
Uri getTestUri(Uri key, int? version) {
|
||||
if (version == null) {
|
||||
return key;
|
||||
}
|
||||
final String keyString = key.toString();
|
||||
final String extension = path.extension(keyString);
|
||||
return Uri.parse('${keyString.split(extension).join()}.$version$extension');
|
||||
}
|
||||
}
|
||||
|
||||
/// The default [GoldenFileComparator] implementation for `flutter drive`.
|
||||
///
|
||||
/// This comparator performs a pixel-for-pixel comparison of the decoded PNGs,
|
||||
/// returning true only if there's an exact match. In cases where the captured
|
||||
/// test image does not match the golden file, this comparator will provide a
|
||||
/// fairly unhelpful error message, which could be improved in the future.
|
||||
final class NaiveLocalFileComparator extends GoldenFileComparator {
|
||||
const NaiveLocalFileComparator._();
|
||||
|
||||
@override
|
||||
Future<bool> compare(Uint8List imageBytes, Uri golden) async {
|
||||
final io.File goldenFile = _getTestFilePath(golden);
|
||||
final Uint8List goldenBytes;
|
||||
try {
|
||||
goldenBytes = await goldenFile.readAsBytes();
|
||||
} on io.PathNotFoundException {
|
||||
throw TestFailure('Golden file not found: ${goldenFile.path}');
|
||||
}
|
||||
|
||||
if (goldenBytes.length != imageBytes.length) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (int i = 0; i < goldenBytes.length; i++) {
|
||||
if (goldenBytes[i] != imageBytes[i]) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> update(Uri golden, Uint8List imageBytes) async {
|
||||
final io.File goldenFile = _getTestFilePath(golden);
|
||||
await goldenFile.parent.create(recursive: true);
|
||||
await goldenFile.writeAsBytes(imageBytes);
|
||||
}
|
||||
|
||||
/// Returns a path relative to the test script.
|
||||
///
|
||||
/// This is hacky and unreliable, but it's the best we can do until we have
|
||||
/// more integration with the `flutter` CLI (which does all the heavy lifting
|
||||
/// for us in `flutter_test`).
|
||||
io.File _getTestFilePath(Uri golden) {
|
||||
final String testScriptPath = io.Platform.script.toFilePath();
|
||||
final String testScriptDir = path.dirname(testScriptPath);
|
||||
return io.File(path.join(testScriptDir, golden.path));
|
||||
}
|
||||
}
|
||||
|
||||
// Examples can assume:
|
||||
// import 'package:flutter_driver/src/native/driver.dart';
|
||||
// import 'package:flutter_driver/src/native/goldens.dart';
|
||||
// import 'package:test/test.dart';
|
||||
// late NativeDriver nativeDriver;
|
||||
|
||||
/// Asserts that a [NativeScreenshot], [Future<NativeScreenshot>], or
|
||||
/// [List<int>] matches the golden image file identified by [key], with an
|
||||
/// optional [version] number].
|
||||
///
|
||||
/// The [key] may be either a [Uri] or a [String] representation of a URL.
|
||||
///
|
||||
/// The [version] is a number that can be used to differentiate historical
|
||||
/// golden files. This parameter is optional.
|
||||
///
|
||||
/// This is an asynchronous matcher, meaning that callers should use
|
||||
/// [flutter_test.expectLater] when using this matcher and await the future
|
||||
/// returned by [flutter_test.expectLater].
|
||||
///
|
||||
/// ## Golden File Testing
|
||||
///
|
||||
/// The term __golden file__ refers to a master image that is considered the
|
||||
/// true rendering of a given widget, state, application, or other visual
|
||||
/// representation you have chosen to capture.
|
||||
///
|
||||
/// The master golden image files are tested against can be created or updated
|
||||
/// by running `flutter drive --update-goldens` on the test.
|
||||
///
|
||||
/// {@tool snippet}
|
||||
/// Sample invocations of [matchesGoldenFile].
|
||||
///
|
||||
/// ```dart
|
||||
/// await expectLater(
|
||||
/// nativeDriver.screenshot(),
|
||||
/// matchesGoldenFile('save.png'),
|
||||
/// );
|
||||
/// ```
|
||||
/// {@end-tool}
|
||||
AsyncMatcher matchesGoldenFile(Object key, {int? version}) {
|
||||
return switch (key) {
|
||||
Uri() => _MatchesGoldenFile(key, version),
|
||||
String() => _MatchesGoldenFile.forStringPath(key, version),
|
||||
_ => throw ArgumentError('Unexpected type for golden file: ${key.runtimeType}'),
|
||||
};
|
||||
}
|
||||
|
||||
/// The matcher created by [matchesGoldenFile].
|
||||
final class _MatchesGoldenFile extends AsyncMatcher {
|
||||
/// Creates an instance of [MatchesGoldenFile].
|
||||
const _MatchesGoldenFile(this.key, this.version);
|
||||
|
||||
/// Creates an instance of [MatchesGoldenFile] from a [String] path.
|
||||
_MatchesGoldenFile.forStringPath(String path, this.version) : key = Uri.parse(path);
|
||||
|
||||
/// The [key] to the golden image.
|
||||
final Uri key;
|
||||
|
||||
/// The [version] of the golden image.
|
||||
final int? version;
|
||||
|
||||
@override
|
||||
Future<String?> matchAsync(Object? item) async {
|
||||
final Uri testNameUri = goldenFileComparator.getTestUri(key, version);
|
||||
|
||||
final Uint8List buffer;
|
||||
if (item is FutureOr<List<int>>) {
|
||||
buffer = Uint8List.fromList(await item);
|
||||
} else if (item is FutureOr<NativeScreenshot>) {
|
||||
buffer = await (await item).readAsBytes();
|
||||
} else {
|
||||
throw ArgumentError('Unexpected type for golden file: ${item.runtimeType}');
|
||||
}
|
||||
|
||||
if (autoUpdateGoldenFiles) {
|
||||
await goldenFileComparator.update(testNameUri, buffer);
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
final bool success = await goldenFileComparator.compare(buffer, testNameUri);
|
||||
return success ? null : 'does not match';
|
||||
} on TestFailure catch (e) {
|
||||
return e.message;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
Description describe(Description description) {
|
||||
return description.add('app screenshot image matches golden file "$key"');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user