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:
Matan Lurey
2025-01-08 12:28:38 -08:00
committed by GitHub
parent 04a60d6b27
commit 132e298335
74 changed files with 62 additions and 1051 deletions

View File

@@ -0,0 +1,21 @@
# Android Extensions for Flutter Driver
This a minimal library on top of `flutter_driver` that provides extensions for
interacting with the native Android platform, to otherwise perform actions that
are not possible purely through Flutter Driver, and would want to run as an
_external_ test (run on the host, not on the device):
- Take a screenshot, including of _native_ widgets (platform views, textures)
- Tap on a native widget
- Rotate the device
- Background an app and send a "trim memory" signal to the device
> [!NOTE]
>
> While this library runs on Flutter's own CI, and is used to test Flutter's
> Platform Views, it is not officially supported as an external API, and may
> change or be removed at any time. We recommend you use existing testing
> infrastructure, such as:
>
> - [Integration Test](https://docs.flutter.dev/testing/integration-tests)
> - [Patrol](https://github.com/leancodepl/patrol)

View File

@@ -0,0 +1,110 @@
// 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 'package:flutter/services.dart' as flt;
import 'package:flutter_driver/driver_extension.dart';
import 'package:flutter_driver/flutter_driver.dart';
import 'package:flutter_test/flutter_test.dart';
import 'src/common.dart';
/// An extension that forwards [NativeCommand]s to a registered plugin.
const CommandExtension nativeDriverCommands = NativeDriverCommandExtension(
flt.MethodChannel('native_driver'),
);
/// An extension that forwards [NativeCommand]s to a registered plugin.
///
/// This extension is used to communicate with a platform plugin, and relays
/// [NativeCommand]s to the platform plugin, and resolves the result as a
/// [NativeResult], both thin wrappers around a `Map<String, Object?>` (JSON
/// compatible object).
///
/// A singleton default instance of this class is [nativeDriverCommands].
final class NativeDriverCommandExtension implements CommandExtension {
/// Creates a new [NativeDriverCommandExtension] with the given [channel].
///
/// Can be used in exceptional cases where a custom [MethodChannel] is needed;
/// otherwise, use the singleton [nativeDriverCommands].
const NativeDriverCommandExtension(this._channel);
final flt.MethodChannel _channel;
@override
Future<Result> call(
Command command,
WidgetController prober,
CreateFinderFactory finderFactory,
CommandHandlerFactory handlerFactory,
) async {
if (command is! NativeCommand) {
throw ArgumentError.value(command, 'command', 'Expected a NativeCommand');
}
if (await _builtInCall(command.method) case final Result result) {
return result;
}
final Object? result = await _channel.invokeMethod<Object>(command.method, command.arguments);
if (result == null) {
return const _MethodChannelResult(<String, Object?>{});
}
if (result is! Map<String, Object?>) {
throw ArgumentError.value(result, 'result', 'Expected a Map<String, Object?>');
}
return _MethodChannelResult(result);
}
// While these could have been implemented in native code, they are already
// available as engine-bundled platform plugins, so using them directly
// reduces the amount of code to be written and maintained.
Future<Result?> _builtInCall(String method) async {
switch (method) {
case 'rotate_landscape':
await flt.SystemChrome.setPreferredOrientations(const <flt.DeviceOrientation>[
flt.DeviceOrientation.landscapeLeft,
]);
return Result.empty;
case 'rotate_default':
await flt.SystemChrome.setPreferredOrientations(const <flt.DeviceOrientation>[]);
return Result.empty;
default:
return null;
}
}
@override
String get commandKind => 'native_driver';
@override
NativeCommand deserialize(
Map<String, String> params,
DeserializeFinderFactory finderFactory,
DeserializeCommandFactory commandFactory,
) {
final String? method = params['method'];
if (method == null) {
throw ArgumentError.value(params, 'params', 'Missing method');
}
final String? arguments = params['arguments'];
final Map<String, Object?>? decoded;
if (arguments == null) {
decoded = null;
} else {
final Object? intermediate = json.decode(arguments);
if (intermediate is! Map<String, Object?>) {
throw ArgumentError.value(arguments, 'arguments', 'Expected a Map<String, Object?>');
}
decoded = intermediate;
}
return NativeCommand(method, arguments: decoded);
}
}
final class _MethodChannelResult implements Result {
const _MethodChannelResult(this._json);
final Map<String, Object?> _json;
@override
Map<String, Object?> toJson() => _json;
}

View File

@@ -0,0 +1,26 @@
// 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:async';
import 'dart:io' as io;
import 'dart:typed_data';
import 'package:flutter_driver/flutter_driver.dart';
import 'package:matcher/matcher.dart';
// Similar to `flutter_test`, we ignore the implementation import.
// ignore: implementation_imports
import 'package:matcher/src/expect/async_matcher.dart';
import 'package:path/path.dart' as path;
import 'package:test_api/test_api.dart';
import 'src/common.dart';
export 'src/backend/android.dart' show AndroidDeviceTarget, AndroidNativeDriver;
export 'src/common.dart' show ByNativeAccessibilityLabel, ByNativeIntegerId, NativeFinder;
part 'src/driver.dart';
part 'src/goldens.dart';

View File

@@ -0,0 +1,137 @@
// 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 fork of `package:flutter_goldens/flutter_goldens.dart` without the
/// dependency on `package:flutter_test` or `package:flutter`; this allows
/// the library to be used in a standalone Dart VM context.
library;
import 'dart:async';
import 'dart:io' as io;
import 'dart:typed_data';
import 'package:file/local.dart';
import 'package:flutter_goldens/skia_client.dart';
import 'package:path/path.dart' as path;
import 'package:platform/platform.dart';
import 'package:process/process.dart';
import 'native_driver.dart';
const LocalFileSystem _localFs = LocalFileSystem();
const String _kGoldctlKey = 'GOLDCTL';
const String _kGoldctlPresubmitKey = 'GOLD_TRYJOB';
/// Configures [goldenFileComparator] to use Skia Gold (i.e. on CI).
///
/// Requires that the `GOLDCTL` environment variable is set.
///
/// If the `GOLD_TRYJOB` environment variable is set, the test will be run in
/// presubmit mode; that is, the test will not fail if the comparison fails.
/// See <https://github.com/flutter/flutter/blob/main/docs/contributing/testing/Writing-a-golden-file-test-for-package-flutter.md>
/// for more information.
///
/// May optionally provide a [namePrefix] to be used when uploading images.
Future<void> enableSkiaGoldComparator({String? namePrefix}) async {
assert(
goldenFileComparator is NaiveLocalFileComparator,
'The flutter_goldens_fork library should be used from a *_test.dart file '
'where the "goldenFileComparator" has not yet been set. This is to ensure '
'that the correct comparator is used for the current test environment.',
);
if (!io.Platform.environment.containsKey(_kGoldctlKey)) {
throw StateError(
'Environment variable $_kGoldctlKey is not set. '
'Set it to use Skia Gold.',
);
}
final io.Directory tmpDir = io.Directory.systemTemp.createTempSync('android_driver_test');
final bool isPresubmit = io.Platform.environment.containsKey(_kGoldctlPresubmitKey);
io.stderr.writeln(
'=== Using Skia Gold ===\n'
'Environment variable $_kGoldctlKey is set, using Skia Gold: \n'
' - tmpDir: ${tmpDir.path}\n'
' - namePrefix: $namePrefix\n'
' - isPresubmit: $isPresubmit\n',
);
final SkiaGoldClient skiaGoldClient = SkiaGoldClient(
_localFs.directory(tmpDir.path),
fs: _localFs,
process: const LocalProcessManager(),
platform: const LocalPlatform(),
httpClient: io.HttpClient(),
log: io.stderr.writeln,
);
await skiaGoldClient.auth();
goldenFileComparator = _GoldenFileComparator(
skiaGoldClient,
namePrefix: namePrefix,
isPresubmit: isPresubmit,
);
}
final class _GoldenFileComparator extends GoldenFileComparator {
_GoldenFileComparator(this.skiaClient, {required this.isPresubmit, this.namePrefix, Uri? baseDir})
: baseDir = baseDir ?? Uri.parse(path.dirname(io.Platform.script.path));
final Uri baseDir;
final SkiaGoldClient skiaClient;
final String? namePrefix;
final bool isPresubmit;
@override
Future<bool> compare(Uint8List imageBytes, Uri golden) async {
if (isPresubmit) {
await skiaClient.tryjobInit();
} else {
await skiaClient.imgtestInit();
}
golden = _addPrefix(golden);
final io.File goldenFile = await update(golden, imageBytes);
if (isPresubmit) {
final String? result = await skiaClient.tryjobAdd(
golden.path,
_localFs.file(goldenFile.path),
);
if (result != null) {
io.stderr.writeln('Skia Gold detected an error when comparing "$golden":\n\n$result');
io.stderr.writeln('Still succeeding, will be triaged in Flutter Gold');
} else {
io.stderr.writeln('Skia Gold comparison succeeded comparing "$golden".');
}
return true;
} else {
return skiaClient.imgtestAdd(golden.path, _localFs.file(goldenFile.path));
}
}
@override
Future<io.File> update(Uri golden, Uint8List imageBytes) async {
io.stderr.writeln('Updating golden file: $golden (${imageBytes.length} bytes)...');
final io.File goldenFile = _getGoldenFile(golden);
await goldenFile.parent.create(recursive: true);
await goldenFile.writeAsBytes(imageBytes, flush: true);
return goldenFile;
}
io.File _getGoldenFile(Uri uri) {
return io.File.fromUri(baseDir.resolveUri(uri));
}
Uri _addPrefix(Uri golden) {
assert(
golden.toString().split('.').last == 'png',
'Golden files in the Flutter framework must end with the file extension '
'.png.',
);
return Uri.parse(
<String>[
if (namePrefix != null) namePrefix!,
baseDir.pathSegments[baseDir.pathSegments.length - 2],
golden.toString(),
].join('.'),
);
}
}

View File

@@ -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';

View File

@@ -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,
}

View File

@@ -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;
}

View 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']!));
}
}

View 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();
}

View 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"');
}
}

View File

@@ -0,0 +1,79 @@
name: android_driver_extensions
environment:
sdk: ^3.7.0-0
dependencies:
flutter:
sdk: flutter
flutter_driver:
sdk: flutter
flutter_goldens:
sdk: flutter
flutter_test:
sdk: flutter
matcher: 0.12.17
meta: 1.16.0
path: 1.9.1
platform: 3.1.6
process: 5.0.3
test_api: 0.7.4
async: 2.12.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
boolean_selector: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
characters: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
clock: 1.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
collection: 1.19.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
crypto: 3.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
fake_async: 1.3.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
file: 7.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker: 10.0.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_flutter_testing: 3.0.9 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
leak_tracker_testing: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
material_color_utilities: 0.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_span: 1.10.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stack_trace: 1.12.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
stream_channel: 2.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
string_scanner: 1.4.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
sync_http: 0.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
term_glyph: 1.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
typed_data: 1.4.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vector_math: 2.1.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
vm_service: 14.3.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webdriver: 3.0.4 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
dev_dependencies:
test: 1.25.14
_fe_analyzer_shared: 76.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
analyzer: 6.11.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
args: 2.6.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
convert: 3.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
coverage: 1.11.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
frontend_server_client: 4.0.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
glob: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_multi_server: 3.2.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
http_parser: 4.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
io: 1.0.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
js: 0.7.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
logging: 1.3.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
mime: 1.0.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
node_preamble: 2.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
package_config: 2.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pool: 1.5.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
pub_semver: 2.1.5 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf: 1.4.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_packages_handler: 3.0.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_static: 1.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
shelf_web_socket: 2.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_map_stack_trace: 2.1.2 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
source_maps: 0.10.13 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
test_core: 0.6.8 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
watcher: 1.1.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web: 1.1.0 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web_socket: 0.1.6 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
web_socket_channel: 3.0.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
webkit_inspection_protocol: 1.2.1 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
yaml: 3.1.3 # THIS LINE IS AUTOGENERATED - TO UPDATE USE "flutter update-packages --force-upgrade"
# PUBSPEC CHECKSUM: 9a31

View File

@@ -0,0 +1,125 @@
// 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:typed_data';
import 'package:android_driver_extensions/src/backend/android/adb.dart';
import 'package:process/process.dart';
import 'package:test/test.dart';
import 'src/fake_process_manager.dart';
// These tests are fake IO tests, so they don't actually run any commands.
void main() {
group('AndroidDeviceTarget', () {
late List<String> caughtArgs;
late FakeProcessManager processManager;
setUp(() {
caughtArgs = <String>[];
processManager = FakeProcessManager((String exec, List<String> args) async {
assert(caughtArgs.isEmpty, 'Should only catch one call to run');
caughtArgs = args;
return FakeProcessManager.ok();
});
});
test('bySerial emits "-s <number>"', () async {
await Adb.create(
target: const AndroidDeviceTarget.bySerial('1234'),
processManager: processManager,
);
expect(caughtArgs.take(2), <String>['-s', '1234']);
});
test('onlyEmulatorOrDevice emits no arguments', () async {
await Adb.create(
target: const AndroidDeviceTarget.onlyEmulatorOrDevice(),
processManager: processManager,
);
expect(caughtArgs, <String>['shell', 'echo', 'connected']);
});
test('onlyEmulator emits "-e"', () async {
await Adb.create(
target: const AndroidDeviceTarget.onlyEmulator(),
processManager: processManager,
);
expect(caughtArgs.take(1), <String>['-e']);
});
test('onlyDevice emits "-d"', () async {
await Adb.create(
target: const AndroidDeviceTarget.onlyDevice(),
processManager: processManager,
);
expect(caughtArgs.take(1), <String>['-d']);
});
});
test('if isDeviceConnected fails, bootstrap fails', () async {
final ProcessManager processManager = FakeProcessManager((
String exec,
List<String> args,
) async {
return FakeProcessManager.error('error');
});
expect(
Adb.create(processManager: processManager),
throwsA(
isA<StateError>().having(
(StateError e) => e.message,
'message',
'No device connected: error',
),
),
);
});
test('screencap invokes "exec-out screencap -p"', () async {
final FakeProcessManager processManager = FakeProcessManager((
String exec,
List<String> args,
) async {
switch (args) {
case ['shell', 'echo', 'connected']:
return FakeProcessManager.ok('connected');
case ['exec-out', 'screencap', '-p']:
return FakeProcessManager.okBinary(<int>[0, 1, 2, 3]);
default:
throw UnsupportedError('Unknown command: $args');
}
});
final Adb adb = await Adb.create(processManager: processManager);
final Uint8List result = await adb.screencap();
expect(result, <int>[0, 1, 2, 3]);
});
test('tap invokes "shell input tap"', () async {
final FakeProcessManager processManager = FakeProcessManager((
String exec,
List<String> args,
) async {
switch (args) {
case ['shell', 'echo', 'connected']:
return FakeProcessManager.ok('connected');
case ['shell', 'input', 'tap', '1', '2']:
return FakeProcessManager.ok();
default:
throw UnsupportedError('Unknown command: $args');
}
});
final Adb adb = await Adb.create(processManager: processManager);
await adb.tap(1, 2);
});
}

View File

@@ -0,0 +1,47 @@
// 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:android_driver_extensions/native_driver.dart';
import 'package:test/test.dart';
import 'src/fake_adb.dart';
import 'src/fake_driver.dart';
void main() async {
test('screenshot calls ADB screencap', () async {
final FakeAdb adb = FakeAdb(screencap: () async => Uint8List.fromList(<int>[1, 2, 3, 4]));
final io.Directory tmpDir = io.Directory.systemTemp.createTempSync();
final AndroidNativeDriver driver = AndroidNativeDriver.forTesting(
adb: adb,
driver: const NullFlutterDriver(),
tempDirectory: tmpDir,
);
final NativeScreenshot screenshot = await driver.screenshot();
await expectLater(screenshot.readAsBytes(), completion(<int>[1, 2, 3, 4]));
final String path = await screenshot.saveAs();
final io.File file = io.File(path);
expect(file.readAsBytes(), completion(<int>[1, 2, 3, 4]));
await driver.close();
});
test('closes deletes the temporary directory', () async {
final FakeAdb adb = FakeAdb();
final io.Directory tmpDir = io.Directory.systemTemp.createTempSync();
final AndroidNativeDriver driver = AndroidNativeDriver.forTesting(
adb: adb,
driver: const NullFlutterDriver(),
tempDirectory: tmpDir,
);
expect(tmpDir.existsSync(), isTrue);
await driver.close();
expect(tmpDir.existsSync(), isFalse);
});
}

View 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.
import 'dart:typed_data';
import 'package:android_driver_extensions/src/backend/android.dart';
/// A stub of [Adb] that allows overriding its methods.
///
/// The default implementation of each method is a simple success case.
final class FakeAdb implements Adb {
FakeAdb({
Future<(bool, String?)> Function()? isDeviceConnected,
Future<Uint8List> Function()? screencap,
Future<void> Function(int x, int y)? tap,
Future<void> Function()? disableImmersiveModeConfirmations,
Future<void> Function()? disableAnimations,
Future<void> Function()? sendToHome,
Future<void> Function(String appName, [String? activityName])? resumeApp,
Future<void> Function(String appName)? trimMemory,
}) : _isDeviceConnected = isDeviceConnected,
_screencap = screencap,
_tap = tap,
_disableImmersiveModeConfirmations = disableImmersiveModeConfirmations,
_disableAnimations = disableAnimations,
_sendToHome = sendToHome,
_resumeApp = resumeApp,
_trimMemory = trimMemory;
@override
Future<(bool, String?)> isDeviceConnected() async {
return _isDeviceConnected?.call() ?? (true, null);
}
final Future<(bool, String?)> Function()? _isDeviceConnected;
@override
Future<Uint8List> screencap() {
return _screencap?.call() ?? Future<Uint8List>.value(Uint8List(0));
}
final Future<Uint8List> Function()? _screencap;
@override
Future<void> tap(int x, int y) async {
return _tap?.call(x, y) ?? Future<void>.value();
}
final Future<void> Function(int x, int y)? _tap;
@override
Future<void> disableImmersiveModeConfirmations() {
return _disableImmersiveModeConfirmations?.call() ?? Future<void>.value();
}
final Future<void> Function()? _disableImmersiveModeConfirmations;
@override
Future<void> disableAnimations() {
return _disableAnimations?.call() ?? Future<void>.value();
}
final Future<void> Function()? _disableAnimations;
@override
Future<void> sendToHome() {
return _sendToHome?.call() ?? Future<void>.value();
}
final Future<void> Function()? _sendToHome;
@override
Future<void> resumeApp({required String appName, String? activityName}) {
return _resumeApp?.call(appName, activityName) ?? Future<void>.value();
}
final Future<void> Function(String appName, [String? activityName])? _resumeApp;
@override
Future<void> trimMemory({required String appName}) {
return _trimMemory?.call(appName) ?? Future<void>.value();
}
final Future<void> Function(String appName)? _trimMemory;
}

View File

@@ -0,0 +1,13 @@
// 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 'package:flutter_driver/flutter_driver.dart';
/// A fake [FlutterDriver] that throws [UnimplementedError] for all methods.
final class NullFlutterDriver implements FlutterDriver {
const NullFlutterDriver();
@override
Never noSuchMethod(Invocation invocation) => throw UnimplementedError();
}

View File

@@ -0,0 +1,50 @@
// 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:io';
import 'dart:typed_data';
import 'package:process/process.dart';
/// A stub of [ProcessManager] that allows mocking the [run] method only.
final class FakeProcessManager extends ProcessManager {
/// Creates a new [FakeProcessManager] with the given delegate callback.
FakeProcessManager(this._runDelegate);
final Future<ProcessResult> Function(String executable, List<String> arguments) _runDelegate;
@override
Never noSuchMethod(_) => throw UnimplementedError();
@override
Future<ProcessResult> run(
List<Object> command, {
String? workingDirectory,
Map<String, String>? environment,
bool includeParentEnvironment = true,
bool runInShell = false,
Encoding? stdoutEncoding = systemEncoding,
Encoding? stderrEncoding = systemEncoding,
}) {
final List<String> strings = command.map((Object e) => '$e').toList();
final [String executable, ...List<String> arguments] = strings;
return _runDelegate(executable, arguments);
}
/// Returns a [ProcessResult] with the given [stdout].
static ProcessResult ok([String stdout = '']) {
return ProcessResult(0, 0, stdout, '');
}
/// Returns a [ProcessResult] with the given [stderr].
static ProcessResult error([String stderr = '']) {
return ProcessResult(0, 1, '', stderr);
}
/// Returns a [ProcessResult] with the given [stdout] binary data.
static ProcessResult okBinary(List<int> stdout) {
return ProcessResult(0, 0, Uint8List.fromList(stdout), '');
}
}