Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,5 @@ example/android/fastlane

# code coverage
coverage/
example/ios/Flutter/flutter_export_environment.sh
example/ios/Flutter/Flutter.podspec
17 changes: 17 additions & 0 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Dart",
"program": "../bin/main.dart",
"args": ["-c", "screenshots.yaml"],
"cwd": "example",
"request": "launch",
"type": "dart",

}
]
}
4 changes: 2 additions & 2 deletions example/android/app/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ apply plugin: 'com.android.application'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
compileSdkVersion 27
compileSdkVersion 29

lintOptions {
disable 'InvalidPackage'
Expand All @@ -35,7 +35,7 @@ android {
// TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
applicationId "com.example.example"
minSdkVersion 16
targetSdkVersion 27
targetSdkVersion 29
versionCode flutterVersionCode.toInteger()
versionName flutterVersionName
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
Expand Down
2 changes: 1 addition & 1 deletion example/android/build.gradle
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ buildscript {
}

dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
classpath 'com.android.tools.build:gradle:3.5.3'
}
}

Expand Down
1 change: 1 addition & 0 deletions example/android/gradle.properties
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
org.gradle.jvmargs=-Xmx1536M
android.enableR8=true
4 changes: 2 additions & 2 deletions example/android/gradle/wrapper/gradle-wrapper.properties
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
#Fri Jun 23 08:50:38 CEST 2017
#Mon Dec 23 18:39:35 CET 2019
distributionBase=GRADLE_USER_HOME
distributionPath=wrapper/dists
zipStoreBase=GRADLE_USER_HOME
zipStorePath=wrapper/dists
distributionUrl=https\://services.gradle.org/distributions/gradle-4.10.2-all.zip
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip
42 changes: 22 additions & 20 deletions example/test_driver/main_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -28,27 +28,29 @@ void main() {
});

test('tap on the floating action button; verify counter', () async {
// Finds the floating action button (fab) to tap on
SerializableFinder fab =
find.byTooltip(localizations['counterIncrementButtonTooltip']);

// Wait for the floating action button to appear
await driver.waitFor(fab);

// take screenshot before number is incremented
await screenshot(driver, config, '0');

// Tap on the fab
await driver.tap(fab);

// Wait for text to change to the desired value
await driver.waitFor(find.text('1'));

// take screenshot after number is incremented
await screenshot(driver, config, '1');

// Use unsynchronized FlutterDriver.
// This prevents timeouts when there is an infinite amount of pending frames.
await driver.runUnsynchronized(() async {
// Finds the floating action button (fab) to tap on
SerializableFinder fab =
find.byTooltip(localizations['counterIncrementButtonTooltip']);
// Wait for the floating action button to appear
await driver.waitFor(fab);

// take screenshot before number is incremented
await screenshot(driver, config, '0');

// Tap on the fab
await driver.tap(fab);

// Wait for text to change to the desired value
await driver.waitFor(find.text('1'));

// take screenshot after number is incremented
await screenshot(driver, config, '1');
});
// increase timeout from 30 seconds for testing
// on slow running emulators in cloud
}, timeout: Timeout(Duration(seconds: 120)));
}, timeout: Timeout(Duration(seconds: 120)));
});
}
58 changes: 50 additions & 8 deletions lib/src/capture_screen.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import 'dart:io';

import 'config.dart';
import 'globals.dart';
import 'utils.dart' as utils;

/// Called by integration test to capture images.
Future screenshot(final driver, Config config, String name,
Expand All @@ -11,17 +12,58 @@ Future screenshot(final driver, Config config, String name,
bool waitUntilNoTransientCallbacks = true}) async {
if (config.isScreenShotsAvailable) {
// todo: auto-naming scheme
if (waitUntilNoTransientCallbacks) {
await driver.waitUntilNoTransientCallbacks(timeout: timeout);
final testDir = '${config.stagingDir}/$kTestScreenshotsDir';
final fileLocationAdb = await File('$testDir/$name.adb.$kImageExtension');
final fileLocationDriver = await File('$testDir/$name.driver.$kImageExtension');

final env = await config.screenshotsEnv;
if(env.containsKey('adb_path') && env.containsKey('adb_device_id') && env.containsKey('device_type') && env['device_type'] == 'android'){
try {
await _takeScreenshotUsingAdb(fileLocationAdb, env['adb_path'], env['adb_device_id']);
} catch (e) {
if(!silent) print('Warning: Failed to take screenshot $name using adb. Using FlutterDriver as fallback method.');
if(await fileLocationAdb.exists()) await fileLocationAdb.delete();
await _takeScreenshotUsingFlutterDriver(fileLocationDriver, driver, timeout, waitUntilNoTransientCallbacks);
}
}else{
await _takeScreenshotUsingFlutterDriver(fileLocationDriver, driver, timeout, waitUntilNoTransientCallbacks);
}

final pixels = await driver.screenshot();
final testDir = '${config.stagingDir}/$kTestScreenshotsDir';
final file =
await File('$testDir/$name.$kImageExtension').create(recursive: true);
await file.writeAsBytes(pixels);
if (!silent) print('Screenshot $name created');
if (!silent) print('Screenshot $name created using ${await fileLocationAdb.exists() ? "adb" : "flutter driver"}');
} else {
if (!silent) print('Warning: screenshot $name not created');
}
}

Future _takeScreenshotUsingAdb(File destination, String adbLocation, String deviceId) async {
try {
await destination.create(recursive: true);

// Activate Demo Mode
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'settings', 'put', 'global', 'sysui_demo_allowed', '1'], trace: false);
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'enter'], trace: false);
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'clock', '-e', 'hhmm', '1600'], trace: false);
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'battery', '-e', 'plugged', 'false'], trace: false);
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'battery', '-e', 'level', '100'], trace: false);
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'network', '-e', 'wifi', 'show', '-e', 'level', '4'], trace: false);
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'network', '-e', 'mobile', 'show', '-e', 'datatype', 'none', '-e', 'level', '4'], trace: false);
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'notifications', '-e', 'visible', 'false'], trace: false);
sleep(Duration(milliseconds: 500)); // Wait for statusbar animations to complete

// Take Screenshot
final screenshotResult = await Process.run(adbLocation, ['-s', deviceId, 'exec-out', 'screencap', '-p'], stdoutEncoding: null);
await destination.writeAsBytes(screenshotResult.stdout);
} finally {
// Deactivate Demo Mode
utils.cmd([adbLocation, '-s', deviceId, 'shell', 'am', 'broadcast', '-a', 'com.android.systemui.demo', '-e', 'command', 'exit'], trace: false);
}
}

Future _takeScreenshotUsingFlutterDriver(File destination, driver, Duration timeout, bool waitUntilNoTransientCallbacks) async {
await destination.create(recursive: true);
if (waitUntilNoTransientCallbacks) {
await driver.waitUntilNoTransientCallbacks(timeout: timeout);
}
final pixels = await driver.screenshot();
await destination.writeAsBytes(pixels);
}
4 changes: 3 additions & 1 deletion lib/src/config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -123,13 +123,15 @@ class Config {
/// (called by screenshots)
@visibleForTesting
Future<void> storeEnv(Screens screens, String emulatorName, String locale,
DeviceType deviceType, Orientation orientation) async {
DeviceType deviceType, Orientation orientation, String adbPath, String adbDeviceId) async {
// store env for later use by tests
final screenProps = screens.getScreen(emulatorName);
final screenSize = screenProps == null ? null : screenProps['size'];
final currentEnv = {
'screen_size': screenSize,
'locale': locale,
'adb_path': adbPath,
'adb_device_id': adbDeviceId,
'device_name': emulatorName,
'device_type': utils.getStringFromEnum(deviceType),
'orientation': utils.getStringFromEnum(orientation)
Expand Down
16 changes: 9 additions & 7 deletions lib/src/image_processor.dart
Original file line number Diff line number Diff line change
Expand Up @@ -66,14 +66,16 @@ class ImageProcessor {
printStatus('Warning: no screenshots found in $screenshotsDir');
}
for (final screenshotPath in screenshotPaths) {
// add status bar for each screenshot
await overlay(
_config.stagingDir, screenResources, screenshotPath.path);

if (deviceType == DeviceType.android) {
// add nav bar for each screenshot
await append(
if(!p.basenameWithoutExtension(screenshotPath.path).endsWith('.adb')){
// add status bar for each screenshot
await overlay(
_config.stagingDir, screenResources, screenshotPath.path);

if (deviceType == DeviceType.android) {
// add nav bar for each screenshot
await append(
_config.stagingDir, screenResources, screenshotPath.path);
}
}

await frame(_config.stagingDir, screenProps, screenshotPath.path,
Expand Down
2 changes: 1 addition & 1 deletion lib/src/orientation.dart
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ void changeDeviceOrientation(DeviceType deviceType, Orientation orientation,
'system',
'user_rotation',
androidOrientations[_orientation]
]);
], retry: true);
break;
case DeviceType.ios:
// requires permission when run for first time
Expand Down
16 changes: 15 additions & 1 deletion lib/src/run.dart
Original file line number Diff line number Diff line change
Expand Up @@ -347,7 +347,13 @@ class Screenshots {
// store env for later use by tests
// ignore: invalid_use_of_visible_for_testing_member
await config.storeEnv(
screens, configDeviceName, locale, deviceType, orientation);
screens,
configDeviceName,
locale,
deviceType,
orientation,
getAdbPath(androidSdk),
deviceId);

// run tests and process images
await runProcessTests(
Expand All @@ -359,6 +365,14 @@ class Screenshots {
);
}
} else {
await config.storeEnv(
screens,
configDeviceName,
locale,
deviceType,
null,
getAdbPath(androidSdk),
deviceId);
await runProcessTests(
configDeviceName,
locale,
Expand Down
34 changes: 22 additions & 12 deletions lib/src/utils.dart
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert' as cnv;
import 'dart:convert';
import 'dart:io';

import 'package:path/path.dart' as p;
import 'package:process/process.dart';
Expand Down Expand Up @@ -131,7 +132,7 @@ Future prefixFilesInDir(String dirPath, String prefix) async {
await for (final file
in fs.directory(dirPath).list(recursive: false, followLinks: false)) {
await file
.rename(p.dirname(file.path) + '/' + prefix + p.basename(file.path));
.rename(p.dirname(file.path) + '/' + prefix + p.basenameWithoutExtension(p.basenameWithoutExtension(file.path)) + '.$kImageExtension');
}
}

Expand Down Expand Up @@ -416,18 +417,27 @@ Future<bool> isEmulatorPath() async {

/// Run command and return stdout as [string].
String cmd(List<String> cmd,
{String workingDirectory, bool silent = true}) {
final result = processManager.runSync(cmd,
workingDirectory: workingDirectory, runInShell: true);
_traceCommand(cmd, workingDirectory: workingDirectory);
if (!silent) printStatus(result.stdout);
if (result.exitCode != 0) {
if (silent) printError(result.stdout);
printError(result.stderr);
throw 'command failed: exitcode=${result.exitCode}, cmd=\'${cmd.join(" ")}\', workingDir=$workingDirectory';
{String workingDirectory, bool silent = true, bool trace = true, bool retry = false, int retryAttempts = 5 }) {

StdoutException error = StdoutException('');
for (var i = 0; i < retryAttempts; i++) {
try {
final result = processManager.runSync(cmd, workingDirectory: workingDirectory, runInShell: true);
if(trace) _traceCommand(cmd, workingDirectory: workingDirectory);
if (result.exitCode != 0) {
throw StdoutException(result.stdout, OSError(result.stderr, result.exitCode));
}
// return stdout
return result.stdout;
} on StdoutException catch (e) {
error = e;
if(!retry) rethrow;
sleep(Duration(seconds: 5));
}
}
// return stdout
return result.stdout;
if (silent) printError(error.message);
printError(error.osError.message);
throw 'command failed: exitcode=${error.osError.errorCode}, cmd=\'${cmd.join(" ")}\', workingDir=$workingDirectory';
}

/// Run command and return exit code as [int].
Expand Down
19 changes: 7 additions & 12 deletions pubspec.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -5,35 +5,30 @@ homepage: https://github.com/mmcc007/screenshots
author: Maurice McCabe <mmcc007@gmail.com>

environment:
sdk: '>=2.2.2 <3.0.0'
sdk: '>=2.10.0 <3.0.0'

dependencies:
args: ^1.5.1
yaml: ^2.1.15
resource: ^2.1.5
path: ^1.6.2
file: ^5.0.7
file: ^6.0.0-nullsafety.2
archive: ^2.0.9
platform: ^2.2.0
process: ^3.0.9
platform: ^3.0.0-nullsafety.2
process: ^4.0.0-nullsafety.2
meta: ^1.1.6
intl: ">=0.15.0 <1.0.0"
tool_mobile: ^1.9.5
# tool_mobile:
# path: ../tool_mobile
tool_mobile: ^2.0.0

dev_dependencies:
test: ^1.5.1+1
test_api: ^0.2.5
mockito: ^4.1.0
pedantic: ^1.8.0+1
quiver: '>=2.0.0 <3.0.0'
fake_process_manager: ^0.1.0
fake_process_manager: ^0.2.0
# path: ../fake_process_manager
tool_base_test:
git: https://github.com/mmcc007/tool_base_test.git
# path: ../tool_base_test
collection: any

executables:
screenshots: main
screenshots: main
6 changes: 5 additions & 1 deletion test/config_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,8 @@ main() {
final env = {
'screen_size': '1440x2560',
'locale': 'en_US',
'adb_path': 'adb',
'adb_device_id': 'emulator-000',
'device_name': 'Nexus 6P',
'device_type': 'android',
'orientation': orientation
Expand All @@ -199,7 +201,9 @@ main() {
env['device_name'],
env['locale'],
getEnumFromString(DeviceType.values, env['device_type']),
getEnumFromString(Orientation.values, orientation));
getEnumFromString(Orientation.values, orientation),
env['adb_path'],
env['adb_device_id']);

// called by test
// simulate no screenshots available
Expand Down
Loading