From 8ea5f7b318373c27dda667d8b821af1df35cd751 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jonas=20Badst=C3=BCbner?= Date: Wed, 30 Aug 2023 22:52:01 +0200 Subject: [PATCH] chore: some linting --- lib/screenshots.dart | 9 +- lib/src/archive.dart | 5 +- lib/src/base/process_common.dart | 22 ++--- lib/src/context_runner.dart | 12 +-- lib/src/daemon_client.dart | 48 +++++------ lib/src/fastlane.dart | 23 ++--- lib/src/image_magick.dart | 16 ++-- lib/src/image_processor.dart | 10 +-- lib/src/orientation.dart | 14 ++-- lib/src/run.dart | 5 +- lib/src/screens.dart | 4 +- lib/src/utils.dart | 15 ++-- lib/src/validate.dart | 13 +-- test/all_tests.dart | 20 ++--- test/config_test.dart | 55 ++++++------ test/daemon_client_test.dart | 140 +++++++++++++++---------------- test/daemon_test.dart | 40 +++++---- test/fastlane_test.dart | 8 +- test/frame_test.dart | 10 +-- test/image_magick_test.dart | 5 +- test/image_processor_test.dart | 32 +++---- test/resources/frame.dart | 14 ++-- test/resources_test.dart | 5 +- test/run_test.dart | 129 ++++++++++++++-------------- test/screenshots_test.dart | 12 +-- test/screenshots_yaml_test.dart | 2 +- test/src/common.dart | 10 +-- test/src/common_tools.dart | 6 +- test/src/context.dart | 12 +-- test/src/context_test.dart | 42 +++++----- test/src/mocks.dart | 39 ++++----- 31 files changed, 380 insertions(+), 397 deletions(-) diff --git a/lib/screenshots.dart b/lib/screenshots.dart index 4c96e5d1..2b8d727d 100644 --- a/lib/screenshots.dart +++ b/lib/screenshots.dart @@ -1,9 +1,8 @@ -library screenshots; -export 'src/run.dart' show screenshots; -export 'src/config.dart'; +export 'src/base/process_common.dart'; export 'src/capture_screen.dart'; +export 'src/config.dart'; export 'src/globals.dart' show DeviceType, kConfigFileName; -export 'src/utils.dart' show isAdbPath, isEmulatorPath; -export 'src/base/process_common.dart'; export 'src/image_magick.dart' show isImageMagicInstalled; +export 'src/run.dart' show screenshots; +export 'src/utils.dart' show isAdbPath, isEmulatorPath; diff --git a/lib/src/archive.dart b/lib/src/archive.dart index 60e2ab2a..13ec2372 100644 --- a/lib/src/archive.dart +++ b/lib/src/archive.dart @@ -3,11 +3,10 @@ import 'utils.dart' as utils; /// Archive screenshots generated by a run. class Archive { + Archive(String archiveDir) : archiveDirPrefix = '$archiveDir/$_timeStamp'; static final _timeStamp = getTimestamp(); - final archiveDirPrefix; - - Archive(String archiveDir) : archiveDirPrefix = '$archiveDir/$_timeStamp'; + final String archiveDirPrefix; String dstDir(DeviceType deviceType, String locale) => '$archiveDirPrefix/${utils.getStringFromEnum(deviceType)}/$locale'; diff --git a/lib/src/base/process_common.dart b/lib/src/base/process_common.dart index 7ff83ea6..4188f91a 100644 --- a/lib/src/base/process_common.dart +++ b/lib/src/base/process_common.dart @@ -57,28 +57,28 @@ String? getExecutablePath( assert(_osToPathStyle[platform.operatingSystem] == fs.path.style.name); workingDirectory ??= fs.currentDirectory.path; - Context context = Context(style: fs.path.style, current: workingDirectory); + final context = Context(style: fs.path.style, current: workingDirectory); // TODO(goderbauer): refactor when github.com/google/platform.dart/issues/2 // is available. - String pathSeparator = platform.isWindows ? ';' : ':'; + final pathSeparator = platform.isWindows ? ';' : ':'; - List extensions = []; + var extensions = []; if (platform.isWindows && context.extension(command).isEmpty) { extensions = platform.environment['PATHEXT']!.split(pathSeparator); } - List candidates = []; + var candidates = []; if (command.contains(context.separator)) { candidates = _getCandidatePaths( command, [workingDirectory], extensions, context); } else { - List searchPath = + final searchPath = platform.environment['PATH']!.split(pathSeparator); candidates = _getCandidatePaths(command, searchPath, extensions, context); } return candidates.map((e) => e).firstWhere( - (String? path) => fs.file(path).existsSync(), + (path) => fs.file(path).existsSync(), orElse: () => null); } @@ -95,16 +95,16 @@ List _getCandidatePaths( List extensions, Context context, ) { - List withExtensions = extensions.isNotEmpty - ? extensions.map((String ext) => '$command$ext').toList() + final withExtensions = extensions.isNotEmpty + ? extensions.map((ext) => '$command$ext').toList() : [command]; if (context.isAbsolute(command)) { return withExtensions; } return searchPaths - .map((String path) => - withExtensions.map((String command) => context.join(path, command))) - .expand((Iterable e) => e) + .map((path) => + withExtensions.map((command) => context.join(path, command))) + .expand((e) => e) .toList() .cast(); } diff --git a/lib/src/context_runner.dart b/lib/src/context_runner.dart index ccfea529..daf1d207 100644 --- a/lib/src/context_runner.dart +++ b/lib/src/context_runner.dart @@ -11,7 +11,7 @@ import 'package:tool_base/tool_base.dart'; import 'package:tool_mobile/tool_mobile.dart'; Future runInContext( - FutureOr runner(), { + FutureOr Function() runner, { Map? overrides, }) async { return await context.run( @@ -21,12 +21,12 @@ Future runInContext( fallbacks: { AndroidSdk: AndroidSdk.locateAndroidSdk, BotDetector: () => const BotDetector(), - Config: () => Config(), - DaemonClient: () => DaemonClient(), - ImageMagick: () => ImageMagick(), + Config: Config.new, + DaemonClient: DaemonClient.new, + ImageMagick: ImageMagick.new, Logger: () => platform.isWindows ? WindowsStdoutLogger() : StdoutLogger(), - OperatingSystemUtils: () => OperatingSystemUtils(), - ProcessManager: () => LocalProcessManager(), + OperatingSystemUtils: OperatingSystemUtils.new, + ProcessManager: LocalProcessManager.new, Stdio: () => const Stdio(), TimeoutConfiguration: () => const TimeoutConfiguration(), }, diff --git a/lib/src/daemon_client.dart b/lib/src/daemon_client.dart index bee28652..d1e7b4d3 100644 --- a/lib/src/daemon_client.dart +++ b/lib/src/daemon_client.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:convert'; import 'package:meta/meta.dart'; import 'package:screenshots/src/utils.dart'; @@ -22,9 +21,10 @@ class DaemonClient { Completer? _waitForConnection; Completer? _waitForResponse; Completer _waitForEvent = Completer(); - List? _iosDevices; // contains model of device, used by screenshots - StreamSubscription? _stdOutListener; - StreamSubscription? _stdErrListener; + List>? + _iosDevices; // contains model of device, used by screenshots + StreamSubscription? _stdOutListener; + StreamSubscription>? _stdErrListener; /// Start flutter tools daemon. Future get start async { @@ -37,7 +37,7 @@ class DaemonClient { // maybe should check if iOS run type is active if (platform.isMacOS) _iosDevices = getIosDevices(); // wait for device discovery - await Future.delayed(Duration(milliseconds: 100)); + await Future.delayed(const Duration(milliseconds: 100)); } } @@ -213,7 +213,7 @@ class DaemonClient { /// Get attached ios devices with id and model. List> getIosDevices() { final regExp = RegExp(r'Found (\w+) \(\w+, (.*), \w+, \w+\)'); - final noAttachedDevices = 'no attached devices'; + const noAttachedDevices = 'no attached devices'; final iosDeployDevices = cmd(['sh', '-c', 'ios-deploy -c || echo "$noAttachedDevices"']) .trim() @@ -247,19 +247,18 @@ Future waitForEmulatorToStart(DaemonClient daemonClient, orElse: () => null); started = device != null; if (started) deviceId = device.id; - await Future.delayed(Duration(milliseconds: 1000)); + await Future.delayed(const Duration(milliseconds: 1000)); } return deviceId!; } abstract class BaseDevice { + BaseDevice(this.id, this.name, this.category, this.platformType); final String id; final String name; final String category; final String platformType; - BaseDevice(this.id, this.name, this.category, this.platformType); - @override bool operator ==(other) { return other is BaseDevice && @@ -278,34 +277,35 @@ abstract class BaseDevice { /// Describe an emulator. class DaemonEmulator extends BaseDevice { DaemonEmulator( - String id, - String name, - String category, - String platformType, - ) : super(id, name, category, platformType); + super.id, + super.name, + super.category, + super.platformType, + ); } /// Describe a device. class DaemonDevice extends BaseDevice { - final String platform; - final bool emulator; - final bool ephemeral; - final String? emulatorId; - final String? iosModel; // iOS model + // iOS model DaemonDevice( - String id, - String name, - String category, - String platformType, + super.id, + super.name, + super.category, + super.platformType, this.platform, this.emulator, this.ephemeral, this.emulatorId, { this.iosModel, - }) : super(id, name, category, platformType) { + }) { // debug check in CI if (emulator && emulatorId == null) throw 'Emulator id is null'; } + final String platform; + final bool emulator; + final bool ephemeral; + final String? emulatorId; + final String? iosModel; @override bool operator ==(other) { diff --git a/lib/src/fastlane.dart b/lib/src/fastlane.dart index 7b3fc231..d5d7ae82 100644 --- a/lib/src/fastlane.dart +++ b/lib/src/fastlane.dart @@ -1,18 +1,18 @@ import 'dart:async'; +import 'package:path/path.dart' as p; import 'package:screenshots/src/image_magick.dart'; import 'package:tool_base/tool_base.dart' hide Config; import 'config.dart'; -import 'screens.dart'; -import 'package:path/path.dart' as p; import 'globals.dart'; +import 'screens.dart'; /// clear configured fastlane directories. -Future clearFastlaneDirs( +Future clearFastlaneDirs( ScreenshotsConfig config, Screens screens, RunMode runMode) async { if (config.isRunTypeActive(DeviceType.android)) { - for (ConfigDevice device in config.androidDevices) { + for (final device in config.androidDevices) { for (final locale in config.locales) { await _clearFastlaneDir( screens, device.name, locale, DeviceType.android, runMode); @@ -20,7 +20,7 @@ Future clearFastlaneDirs( } } if (config.isRunTypeActive(DeviceType.ios)) { - for (ConfigDevice device in config.iosDevices) { + for (final device in config.iosDevices) { for (final locale in config.locales) { await _clearFastlaneDir( screens, device.name, locale, DeviceType.ios, runMode); @@ -30,10 +30,10 @@ Future clearFastlaneDirs( } /// Clear images destination. -Future _clearFastlaneDir(Screens screens, String deviceName, String locale, - DeviceType deviceType, RunMode runMode) async { - final Map? screenProps = screens.getScreen(deviceName); - String? androidModelType = getAndroidModelType(screenProps, deviceName); +Future _clearFastlaneDir(Screens screens, String deviceName, + String locale, DeviceType deviceType, RunMode runMode) async { + final screenProps = screens.getScreen(deviceName); + final androidModelType = getAndroidModelType(screenProps, deviceName); final dirPath = getDirPath(deviceType, locale, androidModelType); @@ -77,13 +77,14 @@ String getDirPath( } /// Get android model type (phone or tablet screen size). -String? getAndroidModelType(Map? screenProps, String deviceName) { +String? getAndroidModelType( + Map? screenProps, String deviceName) { String? androidDeviceType = kFastlanePhone; if (screenProps == null) { printStatus( 'Warning: using default value \'$kFastlanePhone\' in \'$deviceName\' fastlane directory.'); } else { - androidDeviceType = screenProps['destName'] as String?; + androidDeviceType = screenProps['destName']?.toString(); } return androidDeviceType; } diff --git a/lib/src/image_magick.dart b/lib/src/image_magick.dart index 35562ef0..0c4801e0 100644 --- a/lib/src/image_magick.dart +++ b/lib/src/image_magick.dart @@ -14,16 +14,16 @@ final ImageMagick _kImageMagick = ImageMagick(); ImageMagick get im => context.get() ?? _kImageMagick; class ImageMagick { + factory ImageMagick() { + return _imageMagick; + } + ImageMagick._internal(); static const _kThreshold = 0.76; static const kDiffSuffix = '-diff'; //const kThreshold = 0.5; // singleton static final ImageMagick _imageMagick = ImageMagick._internal(); - factory ImageMagick() { - return _imageMagick; - } - ImageMagick._internal(); /// /// ImageMagick calls. @@ -110,7 +110,7 @@ class ImageMagick { bool compare(String? comparisonImage, String? recordedImage) { final diffImage = getDiffImagePath(comparisonImage); - int returnCode = _imageMagickCmd('compare', [ + final returnCode = _imageMagickCmd('compare', [ '-metric', 'mae', recordedImage!, @@ -127,11 +127,7 @@ class ImageMagick { /// Append diff suffix [kDiffSuffix] to [imagePath]. String getDiffImagePath(String? imagePath) { - final diffName = p.dirname(imagePath!) + - '/' + - p.basenameWithoutExtension(imagePath) + - kDiffSuffix + - p.extension(imagePath); + final diffName = '${p.dirname(imagePath!)}/${p.basenameWithoutExtension(imagePath)}$kDiffSuffix${p.extension(imagePath)}'; return diffName; } diff --git a/lib/src/image_processor.dart b/lib/src/image_processor.dart index bc42cec7..9e4c7af5 100644 --- a/lib/src/image_processor.dart +++ b/lib/src/image_processor.dart @@ -15,6 +15,10 @@ import 'screens.dart'; import 'utils.dart' as utils; class ImageProcessor { + + ImageProcessor(Screens screens, ScreenshotsConfig config) + : _screens = screens, + _config = config; static const _kDefaultIosBackground = 'xc:white'; @visibleForTesting // for now static const kDefaultAndroidBackground = 'xc:none'; // transparent @@ -24,10 +28,6 @@ class ImageProcessor { final Screens _screens; final ScreenshotsConfig _config; - ImageProcessor(Screens screens, ScreenshotsConfig config) - : _screens = screens, - _config = config; - /// Process screenshots. /// /// If android, screenshot is overlaid with a status bar and appended with @@ -136,7 +136,7 @@ class ImageProcessor { @visibleForTesting static Future>> compareImages( String deviceName, String recordingDir, String comparisonDir) async { - var failedCompare = >{}; + final failedCompare = >{}; final recordedImages = fs.directory(recordingDir).listSync(); fs .directory(comparisonDir) diff --git a/lib/src/orientation.dart b/lib/src/orientation.dart index f88f38f2..25844282 100644 --- a/lib/src/orientation.dart +++ b/lib/src/orientation.dart @@ -26,8 +26,8 @@ void changeDeviceOrientation(DeviceType deviceType, Orientation orientation, 'LandscapeLeft': 'Landscape Left' }; const sim_orientation_script = 'sim_orientation.scpt'; - final _orientation = utils.getStringFromEnum(orientation); - printStatus('Setting orientation to $_orientation'); + final orientation0 = utils.getStringFromEnum(orientation); + printStatus('Setting orientation to $orientation0'); switch (deviceType) { case DeviceType.android: cmd([ @@ -39,7 +39,7 @@ void changeDeviceOrientation(DeviceType deviceType, Orientation orientation, 'put', 'system', 'user_rotation', - androidOrientations[_orientation]! + androidOrientations[orientation0]! ]); break; case DeviceType.ios: @@ -47,7 +47,7 @@ void changeDeviceOrientation(DeviceType deviceType, Orientation orientation, cmd([ 'osascript', '$scriptDir/$sim_orientation_script', - iosOrientations[_orientation]! + iosOrientations[orientation0]! ]); break; case DeviceType.web: @@ -56,10 +56,10 @@ void changeDeviceOrientation(DeviceType deviceType, Orientation orientation, } Orientation getOrientationEnum(String orientation) { - final _orientation = + final orientation0 = utils.getEnumFromString(Orientation.values, orientation); - _orientation == null + orientation0 == null ? throw 'Error: orientation \'$orientation\' not found' : null; - return _orientation; + return orientation0; } diff --git a/lib/src/run.dart b/lib/src/run.dart index 00d915f0..f9b5505f 100644 --- a/lib/src/run.dart +++ b/lib/src/run.dart @@ -171,7 +171,7 @@ class Screenshots { } void _printScreenshotDirs(String? dirPrefix) { - final prefix = dirPrefix == null ? '' : '${dirPrefix}/'; + final prefix = dirPrefix == null ? '' : '$dirPrefix/'; if (config.isRunTypeActive(DeviceType.ios)) { printStatus(' ${prefix}ios/fastlane/screenshots'); } @@ -252,8 +252,9 @@ class Screenshots { // a device is now found // (and running if not ios simulator pending locale change) - if (deviceId == null) + if (deviceId == null) { throw 'Error: device \'$configDeviceName\' not found'; + } // todo: make a backup of GlobalPreferences.plist if changing iOS locale // set locale and run tests diff --git a/lib/src/screens.dart b/lib/src/screens.dart index db92fbcb..6a2e17d5 100644 --- a/lib/src/screens.dart +++ b/lib/src/screens.dart @@ -68,8 +68,8 @@ class Screens { }); // sort iPhone devices first deviceNames.sort((v1, v2) { - if ('$v1'.contains('iPhone') && '$v2'.contains('iPad')) return -1; - if ('$v1'.contains('iPad') && '$v2'.contains('iPhone')) return 1; + if (v1.contains('iPhone') && v2.contains('iPad')) return -1; + if (v1.contains('iPad') && v2.contains('iPhone')) return 1; return v1.compareTo(v2); }); diff --git a/lib/src/utils.dart b/lib/src/utils.dart index 41a13cd7..26ae7618 100644 --- a/lib/src/utils.dart +++ b/lib/src/utils.dart @@ -1,6 +1,5 @@ import 'dart:async'; import 'dart:convert' as cnv; -import 'dart:convert'; import 'package:path/path.dart' as p; import 'package:process/process.dart'; @@ -95,7 +94,7 @@ Map? getHighestIosSimulator( final iosVersionSims = iosSims[simName]![iOSVersionName]! as List; if (iosVersionSims.isEmpty) { - throw "Error: no simulators found for \'$simName\'"; + throw "Error: no simulators found for '$simName'"; } // use the first device found for the iOS version return iosVersionSims[0] as Map; @@ -137,12 +136,12 @@ 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.basename(file.path)}'); } } -/// Converts [_enum] value to [String]. -String getStringFromEnum(dynamic _enum) => _enum.toString().split('.').last; +/// Converts [enum] value to [String]. +String getStringFromEnum(dynamic e) => e.toString().split('.').last; /// Converts [String] to [enum]. T? getEnumFromString(List values, String value, @@ -365,7 +364,7 @@ Future waitSysLogMsg( final process = ProcessWrapper(delegate); return await process.stdout // .transform(cnv.Utf8Decoder(reportErrors: false)) // from flutter tools - .transform(cnv.Utf8Decoder(allowMalformed: true)) + .transform(const cnv.Utf8Decoder(allowMalformed: true)) .transform(const cnv.LineSplitter()) .map((e) => e) .firstWhere((line) { @@ -456,7 +455,7 @@ int runCmd(List cmd) { /// Trace a command. void _traceCommand(List args, {String? workingDirectory}) { - final String argsText = args.join(' '); + final argsText = args.join(' '); if (workingDirectory == null) { printTrace('executing: $argsText'); } else { @@ -473,7 +472,7 @@ Future streamCmd( Map? environment, }) async { if (mode == ProcessStartMode.normal) { - final int exitCode = await runCommandAndStreamOutput(cmd, + final exitCode = await runCommandAndStreamOutput(cmd, workingDirectory: workingDirectory, environment: environment); if (exitCode != 0) { throw 'command failed: exitcode=$exitCode, cmd=\'${cmd.join(" ")}\', workingDirectory=$workingDirectory, mode=$mode, environment=$environment'; diff --git a/lib/src/validate.dart b/lib/src/validate.dart index f43b3979..eb1e2e6c 100644 --- a/lib/src/validate.dart +++ b/lib/src/validate.dart @@ -16,14 +16,14 @@ Future isValidConfig(ScreenshotsConfig config, Screens screens, final configPath = config.configPath; // validate tests - for (var test in config.tests) { + for (final test in config.tests) { if (!isValidTestPaths(test)) { printError('Invalid config: \'$test\' in $configPath'); isValid = false; } } - final isDeviceAttached = (DaemonDevice? device) => device != null; + bool isDeviceAttached(dynamic device) => device != null; // validate android device if (config.isRunTypeActive(DeviceType.android)) { @@ -247,7 +247,7 @@ void _printAttachedDevices(List devices) { device.platform == 'ios' ? printStatus(' ${device.iosModel} (${device.id})') : printStatus( - ' ${device.emulator ? '${device.emulatorId}' : '${device.name}'} (${device.id})'); + ' ${device.emulator ? '${device.emulatorId}' : device.name} (${device.id})'); // } } } @@ -261,13 +261,14 @@ void _printEmulators(List emulators, String platformType) { void _printSimulators() { final simulatorNames = utils.getIosSimulators().keys.toList(); simulatorNames.sort((thisSim, otherSim) => - '$thisSim'.contains('iPhone') && !'$otherSim'.contains('iPhone') + thisSim.contains('iPhone') && !otherSim.contains('iPhone') ? -1 : thisSim.compareTo(otherSim)); if (simulatorNames.isNotEmpty) { printStatus('\n Installed simulators:'); - simulatorNames - .forEach((simulatorName) => printStatus(' $simulatorName')); + for (final simulatorName in simulatorNames) { + printStatus(' $simulatorName'); + } } } diff --git a/test/all_tests.dart b/test/all_tests.dart index 351442eb..c4a09842 100644 --- a/test/all_tests.dart +++ b/test/all_tests.dart @@ -1,21 +1,21 @@ -import 'screenshots_test.dart' as screenshots_test; +import 'base/all_tests.dart' as base_all_tests; +import 'config_test.dart' as config_test; +import 'daemon_client_test.dart' as daemon_client_test; import 'daemon_test.dart' as daemon_test; +import 'fastlane_test.dart' as fastlane_test; import 'frame_test.dart' as frame_test; +import 'image_magick_test.dart' as image_magick_test; import 'image_processor_test.dart' as image_processor_test; -import 'screenshots_yaml_test.dart' as screenshots_yaml_test; import 'regression/issue_29.dart' as regression_issue_29_test; import 'regression/regression_test.dart' as regression_regression_test; -import 'run_test.dart' as run_test; -import 'src/all_tests.dart' as src_all_tests; -import 'image_magick_test.dart' as image_magick_test; import 'resources_test.dart' as resources_test; -import 'fastlane_test.dart' as fastlane_test; -import 'daemon_client_test.dart' as daemon_client_test; -import 'config_test.dart' as config_test; +import 'run_test.dart' as run_test; import 'screens_test.dart' as screens_test; -import 'validate_test.dart' as validate_test; +import 'screenshots_test.dart' as screenshots_test; +import 'screenshots_yaml_test.dart' as screenshots_yaml_test; +import 'src/all_tests.dart' as src_all_tests; import 'utils_test.dart' as utils_test; -import 'base/all_tests.dart' as base_all_tests; +import 'validate_test.dart' as validate_test; void main() { diff --git a/test/config_test.dart b/test/config_test.dart index e8772822..e09a3669 100644 --- a/test/config_test.dart +++ b/test/config_test.dart @@ -1,7 +1,6 @@ import 'dart:io' as io; import 'package:screenshots/screenshots.dart'; -import 'package:screenshots/src/config.dart'; import 'package:screenshots/src/orientation.dart'; import 'package:screenshots/src/screens.dart'; import 'package:screenshots/src/utils.dart'; @@ -12,12 +11,12 @@ import 'src/common.dart'; main() { group('config', () { test('getters', () { - final expectedTest = 'test_driver/main.dart'; - final expectedStaging = '/tmp/screenshots'; - final expectedLocale = 'en-US'; - final expectedIosName = 'iPhone XS Max'; - final expectedIosFrame = false; - final expectedOrientation = 'LandscapeRight'; + const expectedTest = 'test_driver/main.dart'; + const expectedStaging = '/tmp/screenshots'; + const expectedLocale = 'en-US'; + const expectedIosName = 'iPhone XS Max'; + const expectedIosFrame = false; + const expectedOrientation = 'LandscapeRight'; final orientation = getEnumFromString(Orientation.values, expectedOrientation); final expectedIosDevice = ConfigDevice( @@ -27,8 +26,8 @@ main() { [orientation!], true, ); - final expectedAndroidName = 'Nexus 6P'; - final expectedGlobalFrame = true; + const expectedAndroidName = 'Nexus 6P'; + const expectedGlobalFrame = true; final expectedAndroidDevice = ConfigDevice( expectedAndroidName, DeviceType.android, @@ -36,9 +35,9 @@ main() { [orientation], true, ); - final expectedRecording = '/tmp/screenshots_record'; - final expectedArchive = '/tmp/screenshots_archive'; - final configStr = ''' + const expectedRecording = '/tmp/screenshots_record'; + const expectedArchive = '/tmp/screenshots_archive'; + const configStr = ''' tests: - $expectedTest staging: $expectedStaging @@ -75,7 +74,7 @@ main() { }); test('backward compatible orientation', () { - String configStr = ''' + var configStr = ''' devices: android: device name: @@ -83,7 +82,7 @@ main() { - Portrait frame: true '''; - ScreenshotsConfig config = ScreenshotsConfig(configStr: configStr); + var config = ScreenshotsConfig(configStr: configStr); expect(config.devices[0].orientations![0], Orientation.Portrait); configStr = ''' devices: @@ -97,31 +96,31 @@ main() { }); test('active run type', () { - final configIosOnly = ''' + const configIosOnly = ''' devices: ios: iPhone X: '''; - final configAndroidOnly = ''' + const configAndroidOnly = ''' devices: ios: # check for empty devices android: Nexus 6P: '''; - final configBoth = ''' + const configBoth = ''' devices: ios: iPhone X: android: Nexus 6P: '''; - final configNeither = ''' + const configNeither = ''' devices: ios: android: '''; // Map config = utils.parseYamlStr(configIosOnly); - ScreenshotsConfig config = ScreenshotsConfig(configStr: configIosOnly); + var config = ScreenshotsConfig(configStr: configIosOnly); expect(config.isRunTypeActive(DeviceType.ios), isTrue); expect(config.isRunTypeActive(DeviceType.android), isFalse); @@ -139,14 +138,14 @@ main() { }); test('isFrameRequired', () { - final deviceName = 'Nexus 6P'; - String configStr = ''' + const deviceName = 'Nexus 6P'; + var configStr = ''' devices: android: $deviceName: frame: true '''; - ScreenshotsConfig config = ScreenshotsConfig(configStr: configStr); + var config = ScreenshotsConfig(configStr: configStr); expect(config.isFrameRequired(deviceName, null), isTrue); configStr = ''' devices: @@ -175,15 +174,15 @@ main() { }); test('store and retrieve environment', () async { - final tmpDir = '/tmp/screenshots_test_env'; + const tmpDir = '/tmp/screenshots_test_env'; clearDirectory(tmpDir); - String configStr = ''' + const configStr = ''' staging: $tmpDir '''; final config = ScreenshotsConfig(configStr: configStr); - final screens = await Screens(); + final screens = Screens(); await screens.init(); - final orientation = 'Portrait'; + const orientation = 'Portrait'; final env = { 'screen_size': '1440x2560', @@ -203,11 +202,11 @@ main() { // called by test // simulate no screenshots available - ScreenshotsConfig testConfig = ScreenshotsConfig(configStr: configStr); + var testConfig = ScreenshotsConfig(configStr: configStr); expect(await testConfig.screenshotsEnv, {}); // simulate screenshots available - final configPath = '$tmpDir/screenshots.yaml'; + const configPath = '$tmpDir/screenshots.yaml'; await io.File(configPath).writeAsString(configStr); testConfig = ScreenshotsConfig(configPath: configPath); expect(await testConfig.screenshotsEnv, env); diff --git a/test/daemon_client_test.dart b/test/daemon_client_test.dart index 546c318d..06f18d36 100644 --- a/test/daemon_client_test.dart +++ b/test/daemon_client_test.dart @@ -1,8 +1,6 @@ -import 'dart:convert'; import 'package:fake_process_manager/fake_process_manager.dart'; import 'package:mockito/mockito.dart'; -import 'package:platform/platform.dart'; import 'package:process/process.dart'; import 'package:screenshots/src/daemon_client.dart'; import 'package:test/test.dart'; @@ -11,49 +9,49 @@ import 'package:tool_base/tool_base.dart'; import 'src/context.dart'; main() { - final String kEmulatorsJson = jsonEncode([ + final kEmulatorsJson = jsonEncode([ { - "id": "Nexus_6P_API_28", - "name": "Nexus 6P", - "category": "mobile", - "platformType": "android" + 'id': 'Nexus_6P_API_28', + 'name': 'Nexus 6P', + 'category': 'mobile', + 'platformType': 'android' }, { - "id": "apple_ios_simulator", - "name": "iOS Simulator", - "category": "mobile", - "platformType": "ios" + 'id': 'apple_ios_simulator', + 'name': 'iOS Simulator', + 'category': 'mobile', + 'platformType': 'ios' } ]); - final String kRunningAndroidEmulatorJson = jsonEncode({ - "id": "emulator-5554", - "name": "Android SDK built for x86", - "platform": "android-x86", - "emulator": true, - "category": "mobile", - "platformType": "android", - "ephemeral": true + final kRunningAndroidEmulatorJson = jsonEncode({ + 'id': 'emulator-5554', + 'name': 'Android SDK built for x86', + 'platform': 'android-x86', + 'emulator': true, + 'category': 'mobile', + 'platformType': 'android', + 'ephemeral': true }); - const String kIPhoneUuid = '3b3455019e329e007e67239d9b897148244b5053'; - final String kRunningRealIosDeviceJson = jsonEncode({ - "id": "$kIPhoneUuid", - "name": "My iPhone", - "platform": "ios", - "emulator": false, - "category": "mobile", - "platformType": "ios", - "ephemeral": true + const kIPhoneUuid = '3b3455019e329e007e67239d9b897148244b5053'; + final kRunningRealIosDeviceJson = jsonEncode({ + 'id': kIPhoneUuid, + 'name': 'My iPhone', + 'platform': 'ios', + 'emulator': false, + 'category': 'mobile', + 'platformType': 'ios', + 'ephemeral': true }); - final String kRunningRealAndroidDeviceJson = jsonEncode({ - "id": "someandroiddeviceid", - "name": "My Android Phone", - "platform": "android", - "emulator": false, - "category": "mobile", - "platformType": "android", - "ephemeral": true + final kRunningRealAndroidDeviceJson = jsonEncode({ + 'id': 'someandroiddeviceid', + 'name': 'My Android Phone', + 'platform': 'android', + 'emulator': false, + 'category': 'mobile', + 'platformType': 'android', + 'ephemeral': true }); - final String kRealDevicesJson = jsonEncode([ + final kRealDevicesJson = jsonEncode([ jsonDecode(kRunningRealAndroidDeviceJson), jsonDecode(kRunningRealIosDeviceJson) ]); @@ -72,13 +70,13 @@ main() { setUp(() async { mockProcessManager = FakeProcessManager(customStart: () { - final MockStdIn mockStdIn = MockStdIn(); + final mockStdIn = MockStdIn(); when(mockProcess.stdin).thenReturn(mockStdIn); when(mockProcess.stderr).thenAnswer( - (Invocation invocation) => const Stream>.empty()); + (invocation) => const Stream>.empty()); // Delay return of exitCode until after stdout stream data, since it terminates the logger. - when(mockProcess.exitCode).thenAnswer((Invocation invocation) => + when(mockProcess.exitCode).thenAnswer((invocation) => Future.delayed(Duration.zero, () => 0)); return Future.value(mockProcess); }); @@ -88,7 +86,7 @@ main() { tearDown(() {}); testUsingContext('start/stop', () async { - DaemonClient daemonClient = DaemonClient(); + final daemonClient = DaemonClient(); fakePlatform = fakePlatform.copyWith(operatingSystem: 'linux'); List getLine(int i) { @@ -104,7 +102,7 @@ main() { when(mockProcess.stdout).thenAnswer((_) { return Stream>.periodic( - Duration(milliseconds: streamPeriod), getLine); + const Duration(milliseconds: streamPeriod), getLine); }); await daemonClient.start; @@ -147,7 +145,7 @@ main() { when(mockProcess.stdout).thenAnswer((_) { return Stream>.periodic( - Duration(milliseconds: streamPeriod), getLine); + const Duration(milliseconds: streamPeriod), getLine); }); await daemonClient.start; @@ -182,7 +180,7 @@ main() { group('faked processes', () { late FakeProcessManager fakeProcessManager; - final List stdinCaptured = []; + final stdinCaptured = []; void _captureStdin(String item) { stdinCaptured.add(item); @@ -211,8 +209,8 @@ main() { return lines[i]; } - final iosModel = 'iPhone 5c (GSM)'; - final iosPhoneName = 'My iPhone'; + const iosModel = 'iPhone 5c (GSM)'; + const iosPhoneName = 'My iPhone'; fakeProcessManager.calls = [ Call( 'flutter daemon', @@ -220,7 +218,7 @@ main() { 0, 0, Stream>.periodic( - Duration(milliseconds: streamPeriod), getLine), + const Duration(milliseconds: streamPeriod), getLine), '')), Call( 'sh -c ios-deploy -c || echo "no attached devices"', @@ -258,7 +256,7 @@ main() { group('in CI', () { late FakeProcessManager fakeProcessManager; late FakePlatform fakePlatform; - final List stdinCaptured = []; + final stdinCaptured = []; void _captureStdin(String item) { stdinCaptured.add(item); @@ -275,23 +273,23 @@ main() { environment: {'CI': 'true'}, operatingSystem: 'linux', ); - final id = 'device id'; - final name = 'device name'; - final emulator = false; - final emulatorId = null; + const id = 'device id'; + const name = 'device name'; + const emulator = false; + const emulatorId = null; final bogusRealAndroidDevice = [ { - "id": 1, - "result": [ + 'id': 1, + 'result': [ { - "id": id, - "name": name, - "platform": "android-arm", - "emulator": emulator, - "category": "mobile", - "platformType": "android", - "ephemeral": true, - "emulatorId": emulatorId, + 'id': id, + 'name': name, + 'platform': 'android-arm', + 'emulator': emulator, + 'category': 'mobile', + 'platformType': 'android', + 'ephemeral': true, + 'emulatorId': emulatorId, } ] } @@ -320,7 +318,7 @@ main() { 0, 0, Stream>.periodic( - Duration(milliseconds: streamPeriod), getLine), + const Duration(milliseconds: streamPeriod), getLine), '')), ]; @@ -351,9 +349,9 @@ main() { test('daemon emulators', () { final List emulators = jsonDecode(kEmulatorsJson); final daemonEmulators = []; - emulators.forEach((emulator) { + for (final emulator in emulators) { daemonEmulators.add(loadDaemonEmulator(emulator)); - }); + } expect(daemonEmulators.length, emulators.length); expect(daemonEmulators[0].id, emulators[0]['id']); }); @@ -361,9 +359,9 @@ main() { test('daemon devices', () { final List devices = jsonDecode(kRealDevicesJson); final daemonDevices = []; - devices.forEach((device) { + for (final device in devices) { daemonDevices.add(loadDaemonDevice(device)); - }); + } expect(daemonDevices.length, devices.length); expect(daemonDevices[0].id, devices[0]['id']); }); @@ -371,16 +369,16 @@ main() { group('devices', () { test('equality', () { - DaemonEmulator emulator1 = + final emulator1 = loadDaemonEmulator(jsonDecode(kEmulatorsJson)[0]); - DaemonEmulator emulator2 = + var emulator2 = loadDaemonEmulator(jsonDecode(kEmulatorsJson)[0]); expect(emulator1, equals(emulator2)); emulator2 = loadDaemonEmulator(jsonDecode(kEmulatorsJson)[1]); expect(emulator1, isNot(equals(emulator2))); - DaemonDevice device1 = loadDaemonDevice(jsonDecode(kRealDevicesJson)[0]); - DaemonDevice device2 = loadDaemonDevice(jsonDecode(kRealDevicesJson)[0]); + final device1 = loadDaemonDevice(jsonDecode(kRealDevicesJson)[0]); + var device2 = loadDaemonDevice(jsonDecode(kRealDevicesJson)[0]); expect(device1, equals(device2)); device2 = loadDaemonDevice(jsonDecode(kRealDevicesJson)[1]); expect(device1, isNot(equals(device2))); diff --git a/test/daemon_test.dart b/test/daemon_test.dart index 9f59ecb0..3c6790cd 100644 --- a/test/daemon_test.dart +++ b/test/daemon_test.dart @@ -2,22 +2,20 @@ import 'dart:convert'; import 'dart:io'; import 'package:path/path.dart'; +import 'package:screenshots/src/config.dart'; import 'package:screenshots/src/daemon_client.dart'; import 'package:screenshots/src/fastlane.dart' as fastlane; import 'package:screenshots/src/globals.dart'; import 'package:screenshots/src/resources.dart' as resources; import 'package:screenshots/src/run.dart'; import 'package:screenshots/src/screens.dart'; -import 'package:screenshots/src/config.dart'; import 'package:screenshots/src/utils.dart' as utils; import 'package:test/test.dart'; -import 'src/common.dart'; - main() { group('daemon test', () { test('start shipped daemon client', () async { - final flutterHome = dirname(dirname((utils.cmd(['which', 'flutter'])))); + final flutterHome = dirname(dirname(utils.cmd(['which', 'flutter']))); final flutterToolsHome = '$flutterHome/packages/flutter_tools'; // print('flutterToolsHome=$flutterToolsHome'); final daemonClient = await Process.start( @@ -25,12 +23,12 @@ main() { workingDirectory: flutterToolsHome); // print('shipped daemon client process started, pid: ${daemonClient.pid}'); - bool connected = false; - bool waitingForResponse = false; + var connected = false; + var waitingForResponse = false; daemonClient.stdout .transform(utf8.decoder) .transform(const LineSplitter()) - .listen((String line) async { + .listen((line) async { // print('<<< $line'); if (line.contains('daemon.connected')) { // print('connected'); @@ -61,9 +59,9 @@ main() { }, skip: true); test('parse daemon result response', () { - final expected = + const expected = '[{"id":"Nexus_5X_API_27","name":"Nexus 5X"},{"id":"Nexus_6P_API_28","name":"Nexus 6P"},{"id":"Nexus_9_API_28","name":"Nexus 9"},{"id":"apple_ios_simulator","name":"iOS Simulator"}]'; - final response = '[{"id":0,"result":$expected}]'; + const response = '[{"id":0,"result":$expected}]'; final respExp = RegExp(r'result":(.*)}\]'); final match = respExp.firstMatch(response)!.group(1); // print('match=${jsonDecode(match)}'); @@ -82,11 +80,11 @@ main() { } } ]; - final eventType = 'device.added'; - final deviceId = 'emulator-5554'; - final params = + const eventType = 'device.added'; + const deviceId = 'emulator-5554'; + const params = '{"id":"$deviceId","name":"Android SDK built for x86","platform":"android-x86","emulator":true}'; - final response = '[{"event":"$eventType","params":$params}]'; + const response = '[{"event":"$eventType","params":$params}]'; final responseInfo = jsonDecode(response); expect(responseInfo, expected); expect(responseInfo[0]['event'], eventType); @@ -104,8 +102,8 @@ main() { }, skip: true); test('launch android emulator via daemon and shutdown', () async { - final expected = 'emulator-5554'; - final emulatorId = 'Nexus_6P_API_28'; + const expected = 'emulator-5554'; + const emulatorId = 'Nexus_6P_API_28'; final daemonClient = DaemonClient(); await daemonClient.start; final deviceId = await daemonClient.launchEmulator(emulatorId); @@ -114,10 +112,10 @@ main() { }, skip: true); test('parse ios-deploy response', () { - final expectedDeviceId = '3b3455019e329e007e67239d9b897148244b5053'; - final expectedModel = 'iPhone 5c (GSM)'; + const expectedDeviceId = '3b3455019e329e007e67239d9b897148244b5053'; + const expectedModel = 'iPhone 5c (GSM)'; final regExp = RegExp(r'Found (\w+) \(\w+, (.*), \w+, \w+\)'); - final response = + const response = "[....] Found $expectedDeviceId (N48AP, $expectedModel, iphoneos, armv7s) a.k.a. 'Maurice’s iPhone' connected through USB."; final deviceId = regExp.firstMatch(response)!.group(1); @@ -181,7 +179,7 @@ main() { // }); test('run test on matching devices or emulators', () async { - final configPath = 'test/screenshots_test.yaml'; + const configPath = 'test/screenshots_test.yaml'; final screens = Screens(); await screens.init(); @@ -189,7 +187,7 @@ main() { // init final stagingDir = config.stagingDir; - await Directory(stagingDir + '/$kTestScreenshotsDir') + await Directory('$stagingDir/$kTestScreenshotsDir') .create(recursive: true); await resources.unpackScripts(stagingDir); await fastlane.clearFastlaneDirs(config, screens, RunMode.normal); @@ -212,6 +210,6 @@ main() { await screenshots.runTestsOnAll(); // allow other tests to continue Directory.current = origDir; - }, timeout: Timeout(Duration(minutes: 4)), skip: true); + }, timeout: const Timeout(Duration(minutes: 4)), skip: true); }); } diff --git a/test/fastlane_test.dart b/test/fastlane_test.dart index 26d650ad..f813151b 100644 --- a/test/fastlane_test.dart +++ b/test/fastlane_test.dart @@ -11,7 +11,7 @@ import 'src/context.dart'; main() { group('fastlane', () { - final dirPath = 'test/$kTestScreenshotsDir'; + const dirPath = 'test/$kTestScreenshotsDir'; late MemoryFileSystem memoryFileSystem; setUp(() { @@ -30,7 +30,7 @@ main() { }); testUsingContext('prefix files and delete matching files', () async { - final prefix = 'my_prefix'; + const prefix = 'my_prefix'; expect(memoryFileSystem.directory(dirPath).listSync().length, 2); await for (final file in memoryFileSystem.directory(dirPath).list()) { expect(file.path.contains(prefix), isFalse); @@ -45,7 +45,7 @@ main() { }, overrides: {FileSystem: () => memoryFileSystem}); testUsingContext('clear fastlane dirs', () async { - final configStr = ''' + const configStr = ''' devices: android: android device1: @@ -63,7 +63,7 @@ main() { for (final locale in config.locales) { for (final device in config.devices) { // create files - int i = 0; + const i = 0; final path = getDirPath(device.deviceType, locale, getAndroidModelType(screens.getScreen(device.name), device.name)); expect(memoryFileSystem.directory(path).existsSync(), isFalse); diff --git a/test/frame_test.dart b/test/frame_test.dart index a85c744b..e53b0f52 100644 --- a/test/frame_test.dart +++ b/test/frame_test.dart @@ -10,16 +10,16 @@ import 'package:test/test.dart'; main() { group('frame test', () { test('frame Nexus 9', () async { - final Screens screens = Screens(); + final screens = Screens(); await screens.init(); - Map screen = screens.getScreen('Nexus 9')!; - final ScreenshotsConfig config = + final Map screen = screens.getScreen('Nexus 9')!; + final config = ScreenshotsConfig(configPath: 'test/screenshots_test.yaml'); final Map ScreenResources = screen['resources']; await resources.unpackImages(ScreenResources, '/tmp/screenshots'); - final screenshotPath = './test/resources/nexus_9_0.png'; + const screenshotPath = './test/resources/nexus_9_0.png'; final statusbarPath = '${config.stagingDir}/${ScreenResources['statusbar']}'; @@ -41,7 +41,7 @@ main() { await runInContext(() async { return im.convert('append', options); }); - final framePath = config.stagingDir + '/' + ScreenResources['frame']; + final framePath = '${config.stagingDir}/' + ScreenResources['frame']; final size = screen['size']; final resize = screen['resize']; final offset = screen['offset']; diff --git a/test/image_magick_test.dart b/test/image_magick_test.dart index 2b679446..210cb6ba 100644 --- a/test/image_magick_test.dart +++ b/test/image_magick_test.dart @@ -2,7 +2,6 @@ import 'package:fake_process_manager/fake_process_manager.dart'; import 'package:mockito/mockito.dart'; import 'package:process/process.dart'; import 'package:screenshots/src/context_runner.dart'; -import 'package:screenshots/src/globals.dart'; import 'package:screenshots/src/image_magick.dart'; import 'package:screenshots/src/image_processor.dart'; import 'package:screenshots/src/utils.dart'; @@ -55,8 +54,8 @@ main() { test('threshold exceeded', () async { final imagePath = toPlatformPath('./test/resources/0.png'); - final cropSizeOffset = '1242x42+0+0'; - bool isThresholdExceeded = await runInContext(() async { + const cropSizeOffset = '1242x42+0+0'; + var isThresholdExceeded = await runInContext(() async { return im.isThresholdExceeded(imagePath, cropSizeOffset, 0.5); }); expect(isThresholdExceeded, isTrue); diff --git a/test/image_processor_test.dart b/test/image_processor_test.dart index c81f3c1d..0168e329 100644 --- a/test/image_processor_test.dart +++ b/test/image_processor_test.dart @@ -20,10 +20,10 @@ import 'src/context.dart'; main() { test('process screenshots for iPhone X and iPhone XS Max', () async { - final imageDir = 'test/resources'; - final Screens screens = Screens(); + const imageDir = 'test/resources'; + final screens = Screens(); await screens.init(); - final ScreenshotsConfig config = + final config = ScreenshotsConfig(configPath: 'test/screenshots_test.yaml'); final Map devices = { @@ -36,7 +36,7 @@ main() { for (final String deviceName in devices.keys) { final screenshotName = devices[deviceName]; // print('deviceName=$deviceName, screenshotName=$screenshotName'); - Map screen = screens.getScreen(deviceName)!; + final Map screen = screens.getScreen(deviceName)!; final Map screenResources = screen['resources']; await resources.unpackImages(screenResources, '/tmp/screenshots'); @@ -52,7 +52,7 @@ main() { await runInContext(() async { return im.convert('overlay', options); }); - final framePath = config.stagingDir + '/' + screenResources['frame']; + final framePath = '${config.stagingDir}/' + screenResources['frame']; final size = screen['size']; final resize = screen['resize']; final offset = screen['offset']; @@ -68,7 +68,7 @@ main() { return im.convert('frame', options); }); } - for (var deviceName in devices.values) { + for (final deviceName in devices.values) { await runInContext(() async { cmd(['git', 'checkout', '$imageDir/$deviceName']); }); @@ -87,16 +87,16 @@ main() { }); testUsingContext('process', () async { - final stagingDir = '/tmp/screenshots'; + const stagingDir = '/tmp/screenshots'; // copy a screenshot to memory file system - final imagePath = 'test/resources/screenshot_Nexus_6P.png'; + const imagePath = 'test/resources/screenshot_Nexus_6P.png'; copyFileToMemory(imagePath, stagingDir); final screens = Screens(); await screens.init(); - final deviceName = 'Nexus 6P'; - final locale = 'en-US'; - final configStr = ''' + const deviceName = 'Nexus 6P'; + const locale = 'en-US'; + const configStr = ''' staging: $stagingDir devices: android: @@ -136,9 +136,9 @@ main() { }); testUsingContext('compare images', () async { - final comparisonDir = 'test/resources/comparison'; - final recordingDir = 'test/resources/recording'; - final deviceName = 'Nexus 6P'; + const comparisonDir = 'test/resources/comparison'; + const recordingDir = 'test/resources/recording'; + const deviceName = 'Nexus 6P'; final expected = { 'Nexus 6P-0.png': { 'recording': 'test/resources/recording/Nexus 6P-0.png', @@ -161,11 +161,11 @@ main() { expect(failedCompare, expected); // show diffs ImageProcessor.showFailedCompare(failedCompare); - final BufferLogger logger = context.get() as BufferLogger; + final logger = context.get() as BufferLogger; expect(logger.errorText, contains('Comparison failed:')); }, overrides: { // ProcessManager: () => fakeProcessManager, - Logger: () => BufferLogger(), + Logger: BufferLogger.new, // FileSystem: () => memoryFileSystem, ImageMagick: () => mockImageMagick, }); diff --git a/test/resources/frame.dart b/test/resources/frame.dart index cd079bbb..5d973919 100644 --- a/test/resources/frame.dart +++ b/test/resources/frame.dart @@ -18,10 +18,10 @@ const kRunMode = RunMode.normal; main(List arguments) async { late ArgResults argResults; - final screenshotArg = 'screenshot'; - final deviceArg = 'device'; - final helpArg = 'help'; - final ArgParser argParser = ArgParser(allowTrailingOptions: false) + const screenshotArg = 'screenshot'; + const deviceArg = 'device'; + const helpArg = 'help'; + final argParser = ArgParser(allowTrailingOptions: false) ..addOption(screenshotArg, abbr: 's', defaultsTo: 'screenshot.png', @@ -46,7 +46,7 @@ main(List arguments) async { // validate args if (!await File(argResults[screenshotArg]).exists()) { - _handleError(argParser, "File not found: ${argResults[screenshotArg]}"); + _handleError(argParser, 'File not found: ${argResults[screenshotArg]}'); } final screenshotPath = argResults[screenshotArg]; @@ -72,7 +72,7 @@ Future runFrame(String screenshotPath, String deviceName) async { clearDirectory(kFrameTestTmpDir); - final framedScreenshotPath = '$kFrameTestTmpDir/framed_screenshot.png'; + const framedScreenshotPath = '$kFrameTestTmpDir/framed_screenshot.png'; await File(screenshotPath).copy(framedScreenshotPath); final screenResources = screen['resources']; @@ -102,7 +102,7 @@ void _handleError(ArgParser argParser, String msg) { } void _showUsage(ArgParser argParser) { - print('$usage'); + print(usage); print('\n$sampleUsage\n'); print(argParser.usage); exit(2); diff --git a/test/resources_test.dart b/test/resources_test.dart index f07bc1e7..1ea74419 100644 --- a/test/resources_test.dart +++ b/test/resources_test.dart @@ -1,5 +1,4 @@ import 'package:fake_process_manager/fake_process_manager.dart'; -import 'package:mockito/mockito.dart'; import 'package:process/process.dart'; import 'package:screenshots/src/resources.dart'; import 'package:screenshots/src/screens.dart'; @@ -11,7 +10,7 @@ import 'src/context.dart'; main() { group('resources', () { - final tmpDir = '/tmp/screenshots_test'; + const tmpDir = '/tmp/screenshots_test'; group('in context', () { late ProcessManager mockProcessManager; @@ -29,7 +28,7 @@ main() { group('no context', () { test('unpack screen resource images', () async { - final Screens screens = Screens(); + final screens = Screens(); await screens.init(); final screen = screens.getScreen('iPhone 7 Plus'); final Map screenResources = screen!['resources']; diff --git a/test/run_test.dart b/test/run_test.dart index d54ebce6..23b507fe 100644 --- a/test/run_test.dart +++ b/test/run_test.dart @@ -3,7 +3,6 @@ import 'package:fake_process_manager/fake_process_manager.dart'; import 'package:file/memory.dart'; import 'package:mockito/mockito.dart'; -import 'package:platform/platform.dart'; import 'package:process/process.dart'; import 'package:screenshots/src/daemon_client.dart'; import 'package:screenshots/src/run.dart'; @@ -15,11 +14,11 @@ import 'package:tool_base_test/tool_base_test.dart'; import 'src/mocks.dart'; main() { - final stagingDir = '/tmp/screenshots'; - final configAndroidDeviceName = 'Nexus 6P'; - final configIosDeviceName = 'iPhone X'; - final emulatorId = 'NEXUS_6P_API_28'; - final List stdinCaptured = []; + const stagingDir = '/tmp/screenshots'; + const configAndroidDeviceName = 'Nexus 6P'; + const configIosDeviceName = 'iPhone X'; + const emulatorId = 'NEXUS_6P_API_28'; + final stdinCaptured = []; Directory? sdkDir; @@ -69,7 +68,7 @@ main() { group('run', () { group('with running android emulator', () { - final deviceId = 'emulator-5554'; + const deviceId = 'emulator-5554'; final runningDaemonDevice = loadDaemonDevice({ 'id': deviceId, 'name': 'Android SDK built for x86', @@ -89,7 +88,7 @@ main() { testUsingContext('no frames, no locales', () async { // screenshots config - final configStr = ''' + const configStr = ''' tests: - example/test_driver/main.dart staging: $stagingDir @@ -100,12 +99,12 @@ main() { $configAndroidDeviceName: frame: false '''; - String adbPath = initAdbPath(); + final adbPath = initAdbPath(); final androidUSLocaleCall = Call( '$adbPath -s $deviceId shell getprop persist.sys.locale', ProcessResult(0, 0, 'en-US', '')); // fake process responses - final List calls = [ + final calls = [ ...unpackScriptsCalls, // Call('$adbPath -s emulator-5554 emu avd name', // ProcessResult(0, 0, 'Nexus_6P_API_28', '')), @@ -116,7 +115,7 @@ main() { fakeProcessManager.calls = calls; final result = await screenshots(configStr: configStr); expect(result, isTrue); - final BufferLogger logger = context.get() as BufferLogger; + final logger = context.get() as BufferLogger; expect(logger.statusText, isNot(contains('Starting $configAndroidDeviceName...'))); expect(logger.statusText, isNot(contains('Changing locale'))); @@ -129,13 +128,13 @@ main() { ProcessManager: () => fakeProcessManager, // Platform: () => FakePlatform.fromPlatform(const LocalPlatform()) // ..environment = {'CI': 'false'}, - Logger: () => BufferLogger(), + Logger: BufferLogger.new, }); testUsingContext('change orientation', () async { - final emulatorName = 'Nexus 6P'; + const emulatorName = 'Nexus 6P'; // screenshots config - final configStr = ''' + const configStr = ''' tests: - example/test_driver/main.dart staging: $stagingDir @@ -147,12 +146,12 @@ main() { orientation: LandscapeRight frame: true '''; - String adbPath = initAdbPath(); + final adbPath = initAdbPath(); final androidUSLocaleCall = Call( '$adbPath -s $deviceId shell getprop persist.sys.locale', ProcessResult(0, 0, 'en-US', '')); // fake process responses - final List calls = [ + final calls = [ ...unpackScriptsCalls, // Call('$adbPath -s emulator-5554 emu avd name', // ProcessResult(0, 0, 'Nexus_6P_API_28', '')), @@ -166,7 +165,7 @@ main() { fakeProcessManager.calls = calls; final result = await screenshots(configStr: configStr); expect(result, isTrue); - final BufferLogger logger = context.get() as BufferLogger; + final logger = context.get() as BufferLogger; expect(logger.statusText, contains('Setting orientation to LandscapeRight')); expect(logger.statusText, contains('Warning: framing is not enabled')); @@ -178,7 +177,7 @@ main() { ProcessManager: () => fakeProcessManager, // Platform: () => FakePlatform.fromPlatform(const LocalPlatform()) // ..environment = {'CI': 'false'}, - Logger: () => BufferLogger(), + Logger: BufferLogger.new, }); }); @@ -191,7 +190,7 @@ main() { testUsingContext(', android run, no frames, no locales', () async { // screenshots config - final configStr = ''' + const configStr = ''' tests: - example/test_driver/main.dart staging: $stagingDir @@ -202,13 +201,13 @@ main() { $configAndroidDeviceName: frame: false '''; - String adbPath = initAdbPath(); - final deviceId = 'emulator-5554'; + final adbPath = initAdbPath(); + const deviceId = 'emulator-5554'; final androidUSLocaleCall = Call( '$adbPath -s $deviceId shell getprop persist.sys.locale', ProcessResult(0, 0, 'en-US', '')); // fake process responses - final List calls = [ + final calls = [ ...unpackScriptsCalls, androidUSLocaleCall, androidUSLocaleCall, @@ -226,7 +225,7 @@ main() { final result = await screenshots(configStr: configStr); expect(result, isTrue); - final BufferLogger logger = context.get() as BufferLogger; + final logger = context.get() as BufferLogger; expect(logger.statusText, contains('Starting $configAndroidDeviceName...')); expect(logger.statusText, contains('Warning: framing is not enabled')); @@ -241,20 +240,20 @@ main() { ProcessManager: () => fakeProcessManager, // Platform: () => FakePlatform.fromPlatform(const LocalPlatform()) // ..environment = {'CI': 'false'}, - Logger: () => BufferLogger(), + Logger: BufferLogger.new, }); testUsingContext( ', android and ios run, no frames, multiple locales, orientation', () async { - final locale1 = 'en-US'; - final locale1Lower = 'en_US'; - final locale2 = 'fr-CA'; - final locale2Lower = 'fr_CA'; - final orientation1 = 'LandscapeRight'; - final orientation2 = 'LandscapeLeft'; - final deviceId = 'emulator-5554'; - final configStr = ''' + const locale1 = 'en-US'; + const locale1Lower = 'en_US'; + const locale2 = 'fr-CA'; + const locale2Lower = 'fr_CA'; + const orientation1 = 'LandscapeRight'; + const orientation2 = 'LandscapeLeft'; + const deviceId = 'emulator-5554'; + const configStr = ''' tests: - example/test_driver/main.dart staging: $stagingDir @@ -270,7 +269,7 @@ main() { orientation: $orientation2 frame: false '''; - final simulatorID = '6B3B1AD9-EFD3-49AB-9CE9-D43CE1A47446'; + const simulatorID = '6B3B1AD9-EFD3-49AB-9CE9-D43CE1A47446'; // fake process responses final callListIosDevices = Call( @@ -307,14 +306,14 @@ main() { final callPlutilFrCA = Call( 'plutil -convert json -o - //Library/Developer/CoreSimulator/Devices/$simulatorID/data/Library/Preferences/.GlobalPreferences.plist', ProcessResult(0, 0, '{"AppleLocale":"$locale2"}', '')); - String adbPath = initAdbPath(); + final adbPath = initAdbPath(); final androidEnUSLocaleCall = Call( '$adbPath -s $deviceId shell getprop persist.sys.locale', - ProcessResult(0, 0, '$locale1', '')); + ProcessResult(0, 0, locale1, '')); final androidFrCALocaleCall = Call( '$adbPath -s $deviceId shell getprop persist.sys.locale', - ProcessResult(0, 0, '$locale2', '')); - final List calls = [ + ProcessResult(0, 0, locale2, '')); + final calls = [ callListIosDevices, ...unpackScriptsCalls, androidEnUSLocaleCall, @@ -388,7 +387,7 @@ main() { ]; fakeProcessManager.calls = calls; - final runningEmulatorDeviceId = 'emulator-5554'; + const runningEmulatorDeviceId = 'emulator-5554'; final devices = [ { 'id': runningEmulatorDeviceId, @@ -398,7 +397,7 @@ main() { 'category': 'mobile', 'platformType': 'android', 'ephemeral': true, - "emulatorId": emulatorId, + 'emulatorId': emulatorId, }, { 'id': simulatorID, @@ -409,13 +408,13 @@ main() { 'platformType': 'ios', 'ephemeral': true, 'model': 'iPhone 5c (GSM)', - "emulatorId": simulatorID, + 'emulatorId': simulatorID, } ]; final daemonDevices = - devices.map((device) => loadDaemonDevice(device)).toList(); + devices.map(loadDaemonDevice).toList(); - final List> devicesResponses = [ + final devicesResponses = >[ [], daemonDevices, daemonDevices, @@ -443,7 +442,7 @@ main() { final screenshots = Screenshots(configStr: configStr); final result = await screenshots.run(); expect(result, isTrue); - final BufferLogger logger = context.get() as BufferLogger; + final logger = context.get() as BufferLogger; expect(logger.errorText, ''); // print(logger.statusText); expect(logger.statusText, @@ -489,14 +488,14 @@ main() { // 'HOME': LocalPlatform().environment['HOME'] 'HOME': memoryFileSystem.currentDirectory.path }, operatingSystem: 'macos'), - Logger: () => BufferLogger(), + Logger: BufferLogger.new, FileSystem: () => memoryFileSystem, }); }); }); group('hack in CI', () { - final deviceId = 'emulator-5554'; + const deviceId = 'emulator-5554'; final runningEmulatorDaemonDevice = loadDaemonDevice({ 'id': deviceId, 'name': 'Android SDK built for x86', @@ -518,7 +517,7 @@ main() { testUsingContext('on android', () async { // screenshots config - final configStr = ''' + const configStr = ''' tests: - example/test_driver/main.dart staging: $stagingDir @@ -532,11 +531,11 @@ main() { - LandscapeRight frame: false '''; - String adbPath = initAdbPath(); + final adbPath = initAdbPath(); final androidUSLocaleCall = Call( '$adbPath -s $deviceId shell getprop persist.sys.locale', ProcessResult(0, 0, 'en-US', '')); - final List calls = [ + final calls = [ ...unpackScriptsCalls, androidUSLocaleCall, androidUSLocaleCall, @@ -557,7 +556,7 @@ main() { fakeProcessManager.verifyCalls(); verify(mockDaemonClient.devices).called(3); verify(mockDaemonClient.emulators).called(1); - final BufferLogger logger = context.get() as BufferLogger; + final logger = context.get() as BufferLogger; expect(logger.errorText, ''); expect( logger.statusText, @@ -573,16 +572,16 @@ main() { ProcessManager: () => fakeProcessManager, Platform: () => FakePlatform.fromPlatform(const LocalPlatform()) .copyWith(environment: {'CI': 'true'}), - Logger: () => BufferLogger(), + Logger: BufferLogger.new, }); }); group('utils', () { testUsingContext('change android locale of real device', () { - String adbPath = initAdbPath(); - final deviceId = 'deviceId'; - final deviceLocale = 'en-US'; - final testLocale = 'fr-CA'; + final adbPath = initAdbPath(); + const deviceId = 'deviceId'; + const deviceLocale = 'en-US'; + const testLocale = 'fr-CA'; fakeProcessManager.calls = [ Call( @@ -594,7 +593,7 @@ main() { null), ]; changeAndroidLocale(deviceId, deviceLocale, testLocale); - final BufferLogger logger = context.get() as BufferLogger; + final logger = context.get() as BufferLogger; expect( logger.errorText, contains( @@ -602,12 +601,12 @@ main() { fakeProcessManager.verifyCalls(); }, skip: false, overrides: { ProcessManager: () => fakeProcessManager, - Logger: () => BufferLogger(), + Logger: BufferLogger.new, }); test('find running emulator', () async { final runningEmulator = loadDaemonDevice({ - 'id': '$emulatorId', + 'id': emulatorId, 'name': 'sdk phone armv7', 'platform': 'android-arm', 'emulator': true, @@ -628,12 +627,12 @@ main() { }); testUsingContext('multiple tests (on iOS)', () async { - final deviceName = 'device name'; - final deviceId = 'deviceId'; - final locale = 'locale'; - final test1 = 'test_driver/main.dart'; - final test2 = 'test_driver/main2.dart'; - final configStr = ''' + const deviceName = 'device name'; + const deviceId = 'deviceId'; + const locale = 'locale'; + const test1 = 'test_driver/main.dart'; + const test2 = 'test_driver/main2.dart'; + const configStr = ''' tests: - $test1 - $test2 @@ -662,7 +661,7 @@ main() { usePatrol: false, ); expect(result, isNull); - final BufferLogger logger = context.get() as BufferLogger; + final logger = context.get() as BufferLogger; expect(logger.errorText, ''); expect(logger.statusText, contains('Running $test1 on \'$deviceName\' in locale $locale...')); @@ -673,7 +672,7 @@ main() { fakeProcessManager.verifyCalls(); }, skip: false, overrides: { ProcessManager: () => fakeProcessManager, - Logger: () => BufferLogger(), + Logger: BufferLogger.new, }); }); } diff --git a/test/screenshots_test.dart b/test/screenshots_test.dart index d3ac808a..e7821621 100644 --- a/test/screenshots_test.dart +++ b/test/screenshots_test.dart @@ -386,7 +386,7 @@ void main() { test('get ios simulator locale', () async { const udId = '03D4FC12-3927-4C8B-A226-17DE34AE9C18'; - var locale = utils.getIosSimulatorLocale(udId); + final locale = utils.getIosSimulatorLocale(udId); expect(locale, 'en-US'); }, skip: true); @@ -435,7 +435,7 @@ void main() { var deviceName = 'iPhone 5c'; var device = utils.getDevice([expected], deviceName); expect(device, expected); - final isDeviceAttached = (device) => device != null; + bool isDeviceAttached(device) => device != null; expect(isDeviceAttached(device), true); deviceName = 'iPhone X'; device = utils.getDevice([expected], deviceName); @@ -456,7 +456,7 @@ void main() { '''; final configInfo = ScreenshotsConfig(configStr: config); - var deviceType = run.getDeviceType(configInfo, deviceName); + final deviceType = run.getDeviceType(configInfo, deviceName); expect(deviceType, expected); }); @@ -476,7 +476,7 @@ void main() { // start emulator final deviceId = await daemonClient.launchEmulator(emulatorId); - var props = getDeviceProps(deviceId); + final props = getDeviceProps(deviceId); final newProps = Map.from(props); newProps['xmpp.auto-presence'] = false; //changed newProps['xxx'] = 'yyy'; // added @@ -510,7 +510,7 @@ void main() { await daemonClient.start; const emulatorId = 'Nexus_6P_API_28'; final deviceId = await daemonClient.launchEmulator(emulatorId); - var actual = await utils.waitSysLogMsg(deviceId, expected, toLocale); + final actual = await utils.waitSysLogMsg(deviceId, expected, toLocale); // print('actual=$actual'); expect(actual?.contains(expected), isTrue); expect(await run.shutdownAndroidEmulator(daemonClient, deviceId), @@ -562,7 +562,7 @@ void main() { pairs.forEach((behave, pair) async { final recordedImage = pair['recorded']!; final comparisonImage = pair['comparison']!; - var doCompare = await runInContext(() async { + final doCompare = await runInContext(() async { return im.compare(comparisonImage, recordedImage); }); behave == 'good' diff --git a/test/screenshots_yaml_test.dart b/test/screenshots_yaml_test.dart index 739cd552..d2bff487 100644 --- a/test/screenshots_yaml_test.dart +++ b/test/screenshots_yaml_test.dart @@ -2,11 +2,11 @@ import 'dart:io'; import 'package:screenshots/src/config.dart'; import 'package:screenshots/src/daemon_client.dart'; +import 'package:screenshots/src/fastlane.dart' as fastlane; import 'package:screenshots/src/globals.dart'; import 'package:screenshots/src/screens.dart'; import 'package:screenshots/src/validate.dart'; import 'package:test/test.dart'; -import 'package:screenshots/src/fastlane.dart' as fastlane; import 'package:yaml/yaml.dart'; const screenshotsYaml = ''' diff --git a/test/src/common.dart b/test/src/common.dart index 0fdeb171..fe454f0c 100644 --- a/test/src/common.dart +++ b/test/src/common.dart @@ -1,9 +1,7 @@ import 'dart:async'; import 'dart:io'; -import 'package:meta/meta.dart'; import 'package:path/path.dart' as p; -import 'package:platform/platform.dart'; import 'package:screenshots/src/utils.dart'; ///// Test for CI environment. @@ -94,7 +92,7 @@ class Poller { /// Show differences between maps Map diffMaps(Map orig, Map diff, {bool verbose = false}) { - Map diffs = { + final Map diffs = { 'added': {}, 'removed': {}, 'changed': {'orig': {}, 'new': {}} @@ -124,9 +122,9 @@ Map diffMaps(Map orig, Map diff, {bool verbose = false}) { /// Returns a future that completes with a path suitable for ANDROID_HOME /// or with null, if ANDROID_HOME cannot be found. Future findAndroidHome() async { - final Iterable hits = grep( + final hits = grep( 'ANDROID_HOME = ', - from: await cmd(['flutter', 'doctor', '-v']), + from: cmd(['flutter', 'doctor', '-v']), ); if (hits.isEmpty) return null; return hits.first.split('= ').last; @@ -134,7 +132,7 @@ Future findAndroidHome() async { /// Splits [from] into lines and selects those that contain [pattern]. Iterable grep(Pattern pattern, {required String from}) { - return from.split('\n').where((String line) { + return from.split('\n').where((line) { return line.contains(pattern); }); } diff --git a/test/src/common_tools.dart b/test/src/common_tools.dart index 8e8fc707..05692543 100644 --- a/test/src/common_tools.dart +++ b/test/src/common_tools.dart @@ -25,12 +25,12 @@ void tryToDelete(Directory directory) { /// Matcher for functions that throw [ToolExit]. Matcher throwsToolExit({int? exitCode, Pattern? message}) { - Matcher matcher = isToolExit; + var matcher = isToolExit; if (exitCode != null) { - matcher = allOf(matcher, (ToolExit e) => e.exitCode == exitCode); + matcher = allOf(matcher, (e) => e.exitCode == exitCode); } if (message != null) { - matcher = allOf(matcher, (ToolExit e) => e.message.contains(message)); + matcher = allOf(matcher, (e) => e.message.contains(message)); } return throwsA(matcher); } diff --git a/test/src/context.dart b/test/src/context.dart index b701f149..3709f775 100644 --- a/test/src/context.dart +++ b/test/src/context.dart @@ -15,7 +15,7 @@ typedef ContextInitializer = void Function(AppContext testContext); @isTest void testUsingContext( String description, - dynamic testMethod(), { + dynamic Function() testMethod, { Timeout? timeout, Map overrides = const {}, bool initializeFlutterRoot = true, @@ -35,7 +35,7 @@ void testUsingContext( Config buildConfig(FileSystem fs) { configDir = fs.systemTempDirectory.createTempSync('flutter_config_dir_test.'); - final File settingsFile = + final settingsFile = fs.file(fs.path.join(configDir!.path, '.flutter_settings')); return Config(settingsFile); } @@ -46,11 +46,11 @@ void testUsingContext( name: 'mocks', overrides: { Config: () => buildConfig(fs), - Logger: () => BufferLogger(), - OperatingSystemUtils: () => MockOperatingSystemUtils(), + Logger: BufferLogger.new, + OperatingSystemUtils: MockOperatingSystemUtils.new, OutputPreferences: () => OutputPreferences(showColor: false), // ProcessManager: () => FakeProcessManager(), - FileSystem: () => LocalFileSystemBlockingSetCurrentDirectory(), + FileSystem: LocalFileSystemBlockingSetCurrentDirectory.new, TimeoutConfiguration: () => const TimeoutConfiguration(), }, body: () { @@ -77,7 +77,7 @@ void testUsingContext( // _printBufferedErrors(context); rethrow; } - }, onError: (dynamic error, StackTrace stackTrace) { + }, onError: (dynamic error, stackTrace) { stdout.writeln(error); stdout.writeln(stackTrace); // _printBufferedErrors(context); diff --git a/test/src/context_test.dart b/test/src/context_test.dart index 755bd74d..34da536e 100644 --- a/test/src/context_test.dart +++ b/test/src/context_test.dart @@ -25,8 +25,8 @@ void main() { test( 'returns root context in child of root zone if zone was manually created', () { - final Zone rootZone = Zone.current; - final AppContext rootContext = context; + final rootZone = Zone.current; + final rootContext = context; runZoned(() { expect(Zone.current, isNot(rootZone)); expect(Zone.current.parent, rootZone); @@ -37,7 +37,7 @@ void main() { }); test('returns child context after run', () async { - final AppContext rootContext = context; + final rootContext = context; await rootContext.run( name: 'child', body: () { @@ -49,11 +49,11 @@ void main() { }); test('returns grandchild context after nested run', () async { - final AppContext rootContext = context; + final rootContext = context; await rootContext.run( name: 'child', body: () async { - final AppContext childContext = context; + final childContext = context; await childContext.run( name: 'grandchild', body: () { @@ -67,11 +67,11 @@ void main() { }); test('scans up zone hierarchy for first context', () async { - final AppContext rootContext = context; + final rootContext = context; await rootContext.run( name: 'child', body: () { - final AppContext childContext = context; + final childContext = context; runZoned(() { expect(context, isNot(rootContext)); expect(context, same(childContext)); @@ -86,8 +86,8 @@ void main() { group('operator[]', () { test('still finds values if async code runs after body has finished', () async { - final Completer outer = Completer(); - final Completer inner = Completer(); + final outer = Completer(); + final inner = Completer(); String? value; await context.run( body: () { @@ -107,11 +107,11 @@ void main() { }); test('caches generated override values', () async { - int consultationCount = 0; + var consultationCount = 0; String? value; await context.run( body: () async { - final StringBuffer buf = StringBuffer(context.get()!); + final buf = StringBuffer(context.get()!); buf.write(context.get()); await context.run(body: () { buf.write(context.get()); @@ -130,11 +130,11 @@ void main() { }); test('caches generated fallback values', () async { - int consultationCount = 0; + var consultationCount = 0; String? value; await context.run( body: () async { - final StringBuffer buf = StringBuffer(context.get()!); + final buf = StringBuffer(context.get()!); buf.write(context.get()); await context.run(body: () { buf.write(context.get()); @@ -153,7 +153,7 @@ void main() { }); test('returns null if generated value is null', () async { - final String? value = await context.run( + final value = await context.run( body: () => context.get(), overrides: { String: () => null, @@ -163,7 +163,7 @@ void main() { }); test('throws if generator has dependency cycle', () async { - final Future value = context.run( + final value = context.run( body: () async { return context.get()!; }, @@ -207,7 +207,7 @@ void main() { }); test('are applied after parent context is consulted', () async { - final String value = await context.run( + final value = await context.run( body: () { return context.run( body: () { @@ -225,8 +225,8 @@ void main() { }); test('are not applied if parent context supplies value', () async { - bool childConsulted = false; - final String value = await context.run( + var childConsulted = false; + final value = await context.run( body: () { return context.run( body: () { @@ -251,7 +251,7 @@ void main() { }); test('may depend on one another', () async { - final String value = await context.run( + final value = await context.run( body: () { return context.get()!; }, @@ -266,8 +266,8 @@ void main() { group('overrides', () { test('intercept consultation of parent context', () async { - bool parentConsulted = false; - final String value = await context.run( + var parentConsulted = false; + final value = await context.run( body: () { return context.run( body: () => context.get()!, diff --git a/test/src/mocks.dart b/test/src/mocks.dart index 0791b787..b9f5d3d6 100644 --- a/test/src/mocks.dart +++ b/test/src/mocks.dart @@ -1,5 +1,4 @@ import 'dart:async'; -import 'dart:convert'; import 'dart:io' as io show IOSink; import 'package:mockito/mockito.dart'; @@ -18,10 +17,10 @@ class MockAndroidSdk extends Mock implements AndroidSdk { bool withPlatformTools = true, bool withBuildTools = true, }) { - final Directory dir = + final dir = fs.systemTempDirectory.createTempSync('flutter_mock_android_sdk.'); - final String exe = platform.isWindows ? '.exe' : ''; - final String bat = platform.isWindows ? '.bat' : ''; + final exe = platform.isWindows ? '.exe' : ''; + final bat = platform.isWindows ? '.bat' : ''; _createDir(dir, 'licenses'); @@ -49,7 +48,7 @@ class MockAndroidSdk extends Mock implements AndroidSdk { if (withSdkManager) _createSdkFile(dir, 'tools/bin/sdkmanager$bat'); if (withNdkDir != null) { - final String ndkToolchainBin = fs.path.join( + final ndkToolchainBin = fs.path.join( 'ndk-bundle', 'toolchains', 'arm-linux-androideabi-4.9', @@ -57,11 +56,11 @@ class MockAndroidSdk extends Mock implements AndroidSdk { withNdkDir, 'bin', ); - final String ndkCompiler = fs.path.join( + final ndkCompiler = fs.path.join( ndkToolchainBin, 'arm-linux-androideabi-gcc', ); - final String ndkLinker = fs.path.join( + final ndkLinker = fs.path.join( ndkToolchainBin, 'arm-linux-androideabi-ld', ); @@ -75,7 +74,7 @@ Pkg.Revision = $ndkVersion.1.5063045 '''); } if (withNdkSysroot) { - final String armPlatform = fs.path.join( + final armPlatform = fs.path.join( 'ndk-bundle', 'platforms', 'android-9', @@ -89,7 +88,7 @@ Pkg.Revision = $ndkVersion.1.5063045 static void _createSdkFile(Directory dir, String filePath, {String? contents}) { - final File file = dir.childFile(filePath); + final file = dir.childFile(filePath); file.createSync(recursive: true); if (contents != null) { file.writeAsStringSync(contents, flush: true); @@ -97,7 +96,7 @@ Pkg.Revision = $ndkVersion.1.5063045 } static void _createDir(Directory dir, String path) { - final Directory directory = fs.directory(fs.path.join(dir.path, path)); + final directory = fs.directory(fs.path.join(dir.path, path)); directory.createSync(recursive: true); } @@ -113,7 +112,7 @@ typedef ProcessFactory = Process Function(List command); /// A ProcessManager that starts Processes by delegating to a ProcessFactory. class MockProcessManager implements ProcessManager { - ProcessFactory processFactory = (List commands) => MockProcess(); + ProcessFactory processFactory = (commands) => MockProcess(); bool succeed = true; List commands = []; @@ -132,8 +131,8 @@ class MockProcessManager implements ProcessManager { assert(command is List); command = command as List; if (!succeed) { - final String executable = command[0]; - final List arguments = + final executable = command[0]; + final arguments = command.length > 1 ? command.sublist(1) : []; throw ProcessException(executable, arguments); } @@ -148,7 +147,6 @@ class MockProcessManager implements ProcessManager { /// A process that exits successfully with no output and ignores all input. class MockProcess extends Mock implements Process { - late MemoryIOSink _stdin; MockProcess({ this.pid = 1, @@ -158,6 +156,7 @@ class MockProcess extends Mock implements Process { this.stderr = const Stream>.empty(), }) : exitCode = exitCode ?? Future.value(0), _stdin = stdin ?? MemoryIOSink(); + late final MemoryIOSink _stdin; @override final int pid; @@ -189,10 +188,8 @@ class MemoryIOSink implements IOSink { @override Future addStream(Stream> stream) { - final Completer completer = Completer(); - stream.listen((List data) { - add(data); - }).onDone(() => completer.complete()); + final completer = Completer(); + stream.listen(add).onDone(completer.complete); return completer.future; } @@ -207,14 +204,14 @@ class MemoryIOSink implements IOSink { } @override - void writeln([Object? object = ""]) { + void writeln([Object? object = '']) { add(encoding.encode('$object\n')); } @override void writeAll(Iterable objects, [String separator = '']) { - bool addSeparator = false; - for (dynamic object in objects) { + var addSeparator = false; + for (final dynamic object in objects) { if (addSeparator) { write(separator); }