From 07161e8267400dab91b00c954016a6def27c23c3 Mon Sep 17 00:00:00 2001 From: Zachary Anderson Date: Wed, 8 Jan 2020 15:20:32 -0800 Subject: [PATCH] [flutter_tool] Don't use context in ProcessUtils (#48444) --- packages/flutter_tools/lib/runner.dart | 2 +- .../flutter_tools/lib/src/android/gradle.dart | 2 +- .../lib/src/application_package.dart | 2 +- .../flutter_tools/lib/src/base/process.dart | 183 +++++++++++------ .../flutter_tools/lib/src/context_runner.dart | 6 +- .../test/general.shard/base/process_test.dart | 190 ++++++++++-------- 6 files changed, 229 insertions(+), 156 deletions(-) diff --git a/packages/flutter_tools/lib/runner.dart b/packages/flutter_tools/lib/runner.dart index c08a004efd..61ae09bd26 100644 --- a/packages/flutter_tools/lib/runner.dart +++ b/packages/flutter_tools/lib/runner.dart @@ -255,7 +255,7 @@ Future _exit(int code) async { } // Run shutdown hooks before flushing logs - await runShutdownHooks(); + await shutdownHooks.runShutdownHooks(); final Completer completer = Completer(); diff --git a/packages/flutter_tools/lib/src/android/gradle.dart b/packages/flutter_tools/lib/src/android/gradle.dart index 82364a1595..c7f7ed82b3 100644 --- a/packages/flutter_tools/lib/src/android/gradle.dart +++ b/packages/flutter_tools/lib/src/android/gradle.dart @@ -907,7 +907,7 @@ Directory _getLocalEngineRepo({ .createTempSync('flutter_tool_local_engine_repo.'); // Remove the local engine repo before the tool exits. - addShutdownHook( + shutdownHooks.addShutdownHook( () => localEngineRepo.deleteSync(recursive: true), ShutdownStage.CLEANUP, ); diff --git a/packages/flutter_tools/lib/src/application_package.dart b/packages/flutter_tools/lib/src/application_package.dart index 034f02d2fd..b8e7ab2824 100644 --- a/packages/flutter_tools/lib/src/application_package.dart +++ b/packages/flutter_tools/lib/src/application_package.dart @@ -288,7 +288,7 @@ abstract class IOSApp extends ApplicationPackage { } else { // Try to unpack as an ipa. final Directory tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_app.'); - addShutdownHook(() async { + shutdownHooks.addShutdownHook(() async { await tempDir.delete(recursive: true); }, ShutdownStage.STILL_RECORDING); os.unzip(globals.fs.file(applicationBinary), tempDir); diff --git a/packages/flutter_tools/lib/src/base/process.dart b/packages/flutter_tools/lib/src/base/process.dart index fb634e8dc6..d8b5d747c7 100644 --- a/packages/flutter_tools/lib/src/base/process.dart +++ b/packages/flutter_tools/lib/src/base/process.dart @@ -4,11 +4,14 @@ import 'dart:async'; +import 'package:meta/meta.dart'; +import 'package:process/process.dart'; + import '../convert.dart'; -import '../globals.dart' as globals; import 'common.dart'; import 'context.dart'; import 'io.dart'; +import 'logger.dart'; import 'utils.dart'; typedef StringConverter = String Function(String string); @@ -51,50 +54,80 @@ class ShutdownStage implements Comparable { int compareTo(ShutdownStage other) => priority.compareTo(other.priority); } -Map> _shutdownHooks = >{}; -bool _shutdownHooksRunning = false; +ShutdownHooks get shutdownHooks => ShutdownHooks.instance; -/// Registers a [ShutdownHook] to be executed before the VM exits. -/// -/// If [stage] is specified, the shutdown hook will be run during the specified -/// stage. By default, the shutdown hook will be run during the -/// [ShutdownStage.CLEANUP] stage. -void addShutdownHook( - ShutdownHook shutdownHook, [ - ShutdownStage stage = ShutdownStage.CLEANUP, -]) { - assert(!_shutdownHooksRunning); - _shutdownHooks.putIfAbsent(stage, () => []).add(shutdownHook); +abstract class ShutdownHooks { + factory ShutdownHooks({ + @required Logger logger, + }) => _DefaultShutdownHooks( + logger: logger, + ); + + static ShutdownHooks get instance => context.get(); + + /// Registers a [ShutdownHook] to be executed before the VM exits. + /// + /// If [stage] is specified, the shutdown hook will be run during the specified + /// stage. By default, the shutdown hook will be run during the + /// [ShutdownStage.CLEANUP] stage. + void addShutdownHook( + ShutdownHook shutdownHook, [ + ShutdownStage stage = ShutdownStage.CLEANUP, + ]); + + /// Runs all registered shutdown hooks and returns a future that completes when + /// all such hooks have finished. + /// + /// Shutdown hooks will be run in groups by their [ShutdownStage]. All shutdown + /// hooks within a given stage will be started in parallel and will be + /// guaranteed to run to completion before shutdown hooks in the next stage are + /// started. + Future runShutdownHooks(); } -/// Runs all registered shutdown hooks and returns a future that completes when -/// all such hooks have finished. -/// -/// Shutdown hooks will be run in groups by their [ShutdownStage]. All shutdown -/// hooks within a given stage will be started in parallel and will be -/// guaranteed to run to completion before shutdown hooks in the next stage are -/// started. -Future runShutdownHooks() async { - globals.printTrace('Running shutdown hooks'); - _shutdownHooksRunning = true; - try { - for (final ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) { - globals.printTrace('Shutdown hook priority ${stage.priority}'); - final List hooks = _shutdownHooks.remove(stage); - final List> futures = >[]; - for (final ShutdownHook shutdownHook in hooks) { - final FutureOr result = shutdownHook(); - if (result is Future) { - futures.add(result); - } - } - await Future.wait(futures); - } - } finally { - _shutdownHooksRunning = false; +class _DefaultShutdownHooks implements ShutdownHooks { + _DefaultShutdownHooks({ + @required Logger logger, + }) : _logger = logger; + + final Logger _logger; + + final Map> _shutdownHooks = >{}; + + bool _shutdownHooksRunning = false; + + @override + void addShutdownHook( + ShutdownHook shutdownHook, [ + ShutdownStage stage = ShutdownStage.CLEANUP, + ]) { + assert(!_shutdownHooksRunning); + _shutdownHooks.putIfAbsent(stage, () => []).add(shutdownHook); + } + + @override + Future runShutdownHooks() async { + _logger.printTrace('Running shutdown hooks'); + _shutdownHooksRunning = true; + try { + for (final ShutdownStage stage in _shutdownHooks.keys.toList()..sort()) { + _logger.printTrace('Shutdown hook priority ${stage.priority}'); + final List hooks = _shutdownHooks.remove(stage); + final List> futures = >[]; + for (final ShutdownHook shutdownHook in hooks) { + final FutureOr result = shutdownHook(); + if (result is Future) { + futures.add(result); + } + } + await Future.wait(futures); + } + } finally { + _shutdownHooksRunning = false; + } + assert(_shutdownHooks.isEmpty); + _logger.printTrace('Shutdown hooks complete'); } - assert(_shutdownHooks.isEmpty); - globals.printTrace('Shutdown hooks complete'); } class ProcessExit implements Exception { @@ -150,7 +183,13 @@ typedef RunResultChecker = bool Function(int); ProcessUtils get processUtils => ProcessUtils.instance; abstract class ProcessUtils { - factory ProcessUtils() => _DefaultProcessUtils(); + factory ProcessUtils({ + @required ProcessManager processManager, + @required Logger logger, + }) => _DefaultProcessUtils( + processManager: processManager, + logger: logger, + ); static ProcessUtils get instance => context.get(); @@ -239,6 +278,16 @@ abstract class ProcessUtils { } class _DefaultProcessUtils implements ProcessUtils { + _DefaultProcessUtils({ + @required ProcessManager processManager, + @required Logger logger, + }) : _processManager = processManager, + _logger = logger; + + final ProcessManager _processManager; + + final Logger _logger; + @override Future run( List cmd, { @@ -259,15 +308,15 @@ class _DefaultProcessUtils implements ProcessUtils { _traceCommand(cmd, workingDirectory: workingDirectory); // When there is no timeout, there's no need to kill a running process, so - // we can just use globals.processManager.run(). + // we can just use _processManager.run(). if (timeout == null) { - final ProcessResult results = await globals.processManager.run( + final ProcessResult results = await _processManager.run( cmd, workingDirectory: workingDirectory, environment: _environment(allowReentrantFlutter, environment), ); final RunResult runResult = RunResult(results, cmd); - globals.printTrace(runResult.toString()); + _logger.printTrace(runResult.toString()); if (throwOnError && runResult.exitCode != 0 && (whiteListFailures == null || !whiteListFailures(runResult.exitCode))) { runResult.throwException('Process exited abnormally:\n$runResult'); @@ -276,7 +325,7 @@ class _DefaultProcessUtils implements ProcessUtils { } // When there is a timeout, we have to kill the running process, so we have - // to use globals.processManager.start() through _runCommand() above. + // to use _processManager.start() through _runCommand() above. while (true) { assert(timeoutRetries >= 0); timeoutRetries = timeoutRetries - 1; @@ -302,7 +351,7 @@ class _DefaultProcessUtils implements ProcessUtils { int exitCode; exitCode = await process.exitCode.timeout(timeout, onTimeout: () { // The process timed out. Kill it. - globals.processManager.killPid(process.pid); + _processManager.killPid(process.pid); return null; }); @@ -331,7 +380,7 @@ class _DefaultProcessUtils implements ProcessUtils { // If the process did not timeout. We are done. if (exitCode != null) { - globals.printTrace(runResult.toString()); + _logger.printTrace(runResult.toString()); if (throwOnError && runResult.exitCode != 0 && (whiteListFailures == null || !whiteListFailures(exitCode))) { runResult.throwException('Process exited abnormally:\n$runResult'); @@ -345,8 +394,10 @@ class _DefaultProcessUtils implements ProcessUtils { } // Log the timeout with a trace message in verbose mode. - globals.printTrace('Process "${cmd[0]}" timed out. $timeoutRetries attempts left:\n' - '$runResult'); + _logger.printTrace( + 'Process "${cmd[0]}" timed out. $timeoutRetries attempts left:\n' + '$runResult', + ); } // Unreachable. @@ -363,14 +414,14 @@ class _DefaultProcessUtils implements ProcessUtils { bool allowReentrantFlutter = false, }) { _traceCommand(cmd, workingDirectory: workingDirectory); - final ProcessResult results = globals.processManager.runSync( + final ProcessResult results = _processManager.runSync( cmd, workingDirectory: workingDirectory, environment: _environment(allowReentrantFlutter, environment), ); final RunResult runResult = RunResult(results, cmd); - globals.printTrace('Exit code ${runResult.exitCode} from: ${cmd.join(' ')}'); + _logger.printTrace('Exit code ${runResult.exitCode} from: ${cmd.join(' ')}'); bool failedExitCode = runResult.exitCode != 0; if (whiteListFailures != null && failedExitCode) { @@ -379,17 +430,17 @@ class _DefaultProcessUtils implements ProcessUtils { if (runResult.stdout.isNotEmpty && !hideStdout) { if (failedExitCode && throwOnError) { - globals.printStatus(runResult.stdout.trim()); + _logger.printStatus(runResult.stdout.trim()); } else { - globals.printTrace(runResult.stdout.trim()); + _logger.printTrace(runResult.stdout.trim()); } } if (runResult.stderr.isNotEmpty) { if (failedExitCode && throwOnError) { - globals.printError(runResult.stderr.trim()); + _logger.printError(runResult.stderr.trim()); } else { - globals.printTrace(runResult.stderr.trim()); + _logger.printTrace(runResult.stderr.trim()); } } @@ -408,7 +459,7 @@ class _DefaultProcessUtils implements ProcessUtils { Map environment, }) { _traceCommand(cmd, workingDirectory: workingDirectory); - return globals.processManager.start( + return _processManager.start( cmd, workingDirectory: workingDirectory, environment: _environment(allowReentrantFlutter, environment), @@ -443,9 +494,9 @@ class _DefaultProcessUtils implements ProcessUtils { if (line != null) { final String message = '$prefix$line'; if (trace) { - globals.printTrace(message); + _logger.printTrace(message); } else { - globals.printStatus(message, wrap: false); + _logger.printStatus(message, wrap: false); } } }); @@ -458,7 +509,7 @@ class _DefaultProcessUtils implements ProcessUtils { line = mapFunction(line); } if (line != null) { - globals.printError('$prefix$line', wrap: false); + _logger.printError('$prefix$line', wrap: false); } }); @@ -487,9 +538,9 @@ class _DefaultProcessUtils implements ProcessUtils { }) { _traceCommand(cli); try { - return globals.processManager.runSync(cli, environment: environment).exitCode == 0; + return _processManager.runSync(cli, environment: environment).exitCode == 0; } catch (error) { - globals.printTrace('$cli failed with $error'); + _logger.printTrace('$cli failed with $error'); return false; } } @@ -501,9 +552,9 @@ class _DefaultProcessUtils implements ProcessUtils { }) async { _traceCommand(cli); try { - return (await globals.processManager.run(cli, environment: environment)).exitCode == 0; + return (await _processManager.run(cli, environment: environment)).exitCode == 0; } catch (error) { - globals.printTrace('$cli failed with $error'); + _logger.printTrace('$cli failed with $error'); return false; } } @@ -525,9 +576,9 @@ class _DefaultProcessUtils implements ProcessUtils { void _traceCommand(List args, { String workingDirectory }) { final String argsText = args.join(' '); if (workingDirectory == null) { - globals.printTrace('executing: $argsText'); + _logger.printTrace('executing: $argsText'); } else { - globals.printTrace('executing: [$workingDirectory${globals.fs.path.separator}] $argsText'); + _logger.printTrace('executing: [$workingDirectory/] $argsText'); } } } diff --git a/packages/flutter_tools/lib/src/context_runner.dart b/packages/flutter_tools/lib/src/context_runner.dart index a24d88deca..92d6ba590b 100644 --- a/packages/flutter_tools/lib/src/context_runner.dart +++ b/packages/flutter_tools/lib/src/context_runner.dart @@ -120,8 +120,12 @@ Future runInContext( OperatingSystemUtils: () => OperatingSystemUtils(), PersistentToolState: () => PersistentToolState(), ProcessInfo: () => ProcessInfo(), - ProcessUtils: () => ProcessUtils(), + ProcessUtils: () => ProcessUtils( + processManager: globals.processManager, + logger: globals.logger, + ), Pub: () => const Pub(), + ShutdownHooks: () => ShutdownHooks(logger: globals.logger), Signals: () => Signals(), SimControl: () => SimControl(), Stdio: () => const Stdio(), diff --git a/packages/flutter_tools/test/general.shard/base/process_test.dart b/packages/flutter_tools/test/general.shard/base/process_test.dart index 668310eca0..605d417ff9 100644 --- a/packages/flutter_tools/test/general.shard/base/process_test.dart +++ b/packages/flutter_tools/test/general.shard/base/process_test.dart @@ -6,6 +6,7 @@ import 'dart:async'; import 'package:platform/platform.dart'; import 'package:flutter_tools/src/base/io.dart'; +import 'package:flutter_tools/src/base/logger.dart'; import 'package:flutter_tools/src/base/process.dart'; import 'package:flutter_tools/src/base/terminal.dart'; import 'package:mockito/mockito.dart'; @@ -15,49 +16,59 @@ import '../../src/common.dart'; import '../../src/context.dart'; import '../../src/mocks.dart' show MockProcess, MockProcessManager, + MockStdio, flakyProcessFactory; +class MockLogger extends Mock implements Logger {} + void main() { group('process exceptions', () { ProcessManager mockProcessManager; + ProcessUtils processUtils; setUp(() { mockProcessManager = PlainMockProcessManager(); + processUtils = ProcessUtils( + processManager: mockProcessManager, + logger: MockLogger(), + ); }); - testUsingContext('runAsync throwOnError: exceptions should be ProcessException objects', () async { + testWithoutContext('runAsync throwOnError: exceptions should be ProcessException objects', () async { when(mockProcessManager.run(['false'])).thenAnswer( (Invocation invocation) => Future.value(ProcessResult(0, 1, '', ''))); expect(() async => await processUtils.run(['false'], throwOnError: true), throwsA(isInstanceOf())); - }, overrides: {ProcessManager: () => mockProcessManager}); + }); }); group('shutdownHooks', () { - testUsingContext('runInExpectedOrder', () async { + testWithoutContext('runInExpectedOrder', () async { int i = 1; int serializeRecording1; int serializeRecording2; int postProcessRecording; int cleanup; - addShutdownHook(() async { + final ShutdownHooks shutdownHooks = ShutdownHooks(logger: MockLogger()); + + shutdownHooks.addShutdownHook(() async { serializeRecording1 = i++; }, ShutdownStage.SERIALIZE_RECORDING); - addShutdownHook(() async { + shutdownHooks.addShutdownHook(() async { cleanup = i++; }, ShutdownStage.CLEANUP); - addShutdownHook(() async { + shutdownHooks.addShutdownHook(() async { postProcessRecording = i++; }, ShutdownStage.POST_PROCESS_RECORDING); - addShutdownHook(() async { + shutdownHooks.addShutdownHook(() async { serializeRecording2 = i++; }, ShutdownStage.SERIALIZE_RECORDING); - await runShutdownHooks(); + await shutdownHooks.runShutdownHooks(); expect(serializeRecording1, lessThanOrEqualTo(2)); expect(serializeRecording2, lessThanOrEqualTo(2)); @@ -68,30 +79,42 @@ void main() { group('output formatting', () { MockProcessManager mockProcessManager; + ProcessUtils processUtils; + BufferLogger mockLogger; setUp(() { mockProcessManager = MockProcessManager(); + mockLogger = BufferLogger( + terminal: AnsiTerminal( + stdio: MockStdio(), + platform: FakePlatform.fromPlatform(const LocalPlatform())..stdoutSupportsAnsi = false, + ), + outputPreferences: OutputPreferences(wrapText: true, wrapColumn: 40), + ); + processUtils = ProcessUtils( + processManager: mockProcessManager, + logger: mockLogger, + ); }); - MockProcess Function(List) processMetaFactory(List stdout, { List stderr = const [] }) { - final Stream> stdoutStream = - Stream>.fromIterable(stdout.map>((String s) => s.codeUnits)); - final Stream> stderrStream = - Stream>.fromIterable(stderr.map>((String s) => s.codeUnits)); + MockProcess Function(List) processMetaFactory(List stdout, { + List stderr = const [], + }) { + final Stream> stdoutStream = Stream>.fromIterable( + stdout.map>((String s) => s.codeUnits, + )); + final Stream> stderrStream = Stream>.fromIterable( + stderr.map>((String s) => s.codeUnits, + )); return (List command) => MockProcess(stdout: stdoutStream, stderr: stderrStream); } - testUsingContext('Command output is not wrapped.', () async { + testWithoutContext('Command output is not wrapped.', () async { final List testString = ['0123456789' * 10]; mockProcessManager.processFactory = processMetaFactory(testString, stderr: testString); await processUtils.stream(['command']); - - expect(testLogger.statusText, equals('${testString[0]}\n')); - expect(testLogger.errorText, equals('${testString[0]}\n')); - }, overrides: { - ProcessManager: () => mockProcessManager, - OutputPreferences: () => OutputPreferences(wrapText: true, wrapColumn: 40), - Platform: () => FakePlatform.fromPlatform(const LocalPlatform())..stdoutSupportsAnsi = false, + expect(mockLogger.statusText, equals('${testString[0]}\n')); + expect(mockLogger.errorText, equals('${testString[0]}\n')); }); }); @@ -99,43 +122,47 @@ void main() { const Duration delay = Duration(seconds: 2); MockProcessManager flakyProcessManager; ProcessManager mockProcessManager; + ProcessUtils processUtils; + ProcessUtils flakyProcessUtils; setUp(() { // MockProcessManager has an implementation of start() that returns the // result of processFactory. flakyProcessManager = MockProcessManager(); mockProcessManager = MockProcessManager(); + processUtils = ProcessUtils( + processManager: mockProcessManager, + logger: MockLogger(), + ); + flakyProcessUtils = ProcessUtils( + processManager: flakyProcessManager, + logger: MockLogger(), + ); }); - testUsingContext(' succeeds on success', () async { + testWithoutContext(' succeeds on success', () async { when(mockProcessManager.run(['whoohoo'])).thenAnswer((_) { return Future.value(ProcessResult(0, 0, '', '')); }); expect((await processUtils.run(['whoohoo'])).exitCode, 0); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' fails on failure', () async { + testWithoutContext(' fails on failure', () async { when(mockProcessManager.run(['boohoo'])).thenAnswer((_) { return Future.value(ProcessResult(0, 1, '', '')); }); expect((await processUtils.run(['boohoo'])).exitCode, 1); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' throws on failure with throwOnError', () async { + testWithoutContext(' throws on failure with throwOnError', () async { when(mockProcessManager.run(['kaboom'])).thenAnswer((_) { return Future.value(ProcessResult(0, 1, '', '')); }); expect(() => processUtils.run(['kaboom'], throwOnError: true), throwsA(isA())); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' does not throw on failure with whitelist', () async { + testWithoutContext(' does not throw on failure with whitelist', () async { when(mockProcessManager.run(['kaboom'])).thenAnswer((_) { return Future.value(ProcessResult(0, 1, '', '')); }); @@ -145,12 +172,11 @@ void main() { throwOnError: true, whiteListFailures: (int c) => c == 1, )).exitCode, - 1); - }, overrides: { - ProcessManager: () => mockProcessManager, + 1, + ); }); - testUsingContext(' throws on failure when not in whitelist', () async { + testWithoutContext(' throws on failure when not in whitelist', () async { when(mockProcessManager.run(['kaboom'])).thenAnswer((_) { return Future.value(ProcessResult(0, 2, '', '')); }); @@ -160,41 +186,36 @@ void main() { throwOnError: true, whiteListFailures: (int c) => c == 1, ), - throwsA(isA())); - }, overrides: { - ProcessManager: () => mockProcessManager, + throwsA(isA()), + ); }); - testUsingContext(' flaky process fails without retry', () async { + testWithoutContext(' flaky process fails without retry', () async { flakyProcessManager.processFactory = flakyProcessFactory( flakes: 1, delay: delay, ); - final RunResult result = await processUtils.run( + final RunResult result = await flakyProcessUtils.run( ['dummy'], timeout: delay + const Duration(seconds: 1), ); expect(result.exitCode, -9); - }, overrides: { - ProcessManager: () => flakyProcessManager, }); - testUsingContext(' flaky process succeeds with retry', () async { + testWithoutContext(' flaky process succeeds with retry', () async { flakyProcessManager.processFactory = flakyProcessFactory( flakes: 1, delay: delay, ); - final RunResult result = await processUtils.run( + final RunResult result = await flakyProcessUtils.run( ['dummy'], timeout: delay - const Duration(milliseconds: 500), timeoutRetries: 1, ); expect(result.exitCode, 0); - }, overrides: { - ProcessManager: () => flakyProcessManager, }); - testUsingContext(' flaky process generates ProcessException on timeout', () async { + testWithoutContext(' flaky process generates ProcessException on timeout', () async { final Completer> flakyStderr = Completer>(); final Completer> flakyStdout = Completer>(); flakyProcessManager.processFactory = flakyProcessFactory( @@ -211,52 +232,57 @@ void main() { flakyStdout.complete([]); return true; }); - expect(() => processUtils.run( + expect(() => flakyProcessUtils.run( ['dummy'], timeout: delay - const Duration(milliseconds: 500), timeoutRetries: 0, ), throwsA(isInstanceOf())); - }, overrides: { - ProcessManager: () => flakyProcessManager, }); }); group('runSync', () { ProcessManager mockProcessManager; + ProcessUtils processUtils; + BufferLogger testLogger; setUp(() { mockProcessManager = MockProcessManager(); + testLogger = BufferLogger( + terminal: AnsiTerminal( + stdio: MockStdio(), + platform: FakePlatform.fromPlatform(const LocalPlatform())..stdoutSupportsAnsi = false, + ), + outputPreferences: OutputPreferences(wrapText: true, wrapColumn: 40), + ); + processUtils = ProcessUtils( + processManager: mockProcessManager, + logger: testLogger, + ); }); - testUsingContext(' succeeds on success', () async { + testWithoutContext(' succeeds on success', () async { when(mockProcessManager.runSync(['whoohoo'])).thenReturn( ProcessResult(0, 0, '', '') ); expect(processUtils.runSync(['whoohoo']).exitCode, 0); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' fails on failure', () async { + testWithoutContext(' fails on failure', () async { when(mockProcessManager.runSync(['boohoo'])).thenReturn( ProcessResult(0, 1, '', '') ); expect(processUtils.runSync(['boohoo']).exitCode, 1); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' throws on failure with throwOnError', () async { + testWithoutContext(' throws on failure with throwOnError', () async { when(mockProcessManager.runSync(['kaboom'])).thenReturn( ProcessResult(0, 1, '', '') ); expect(() => processUtils.runSync(['kaboom'], throwOnError: true), throwsA(isA())); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' does not throw on failure with whitelist', () async { + testWithoutContext(' does not throw on failure with whitelist', () async { when(mockProcessManager.runSync(['kaboom'])).thenReturn( ProcessResult(0, 1, '', '') ); @@ -267,11 +293,9 @@ void main() { whiteListFailures: (int c) => c == 1, ).exitCode, 1); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' throws on failure when not in whitelist', () async { + testWithoutContext(' throws on failure when not in whitelist', () async { when(mockProcessManager.runSync(['kaboom'])).thenReturn( ProcessResult(0, 2, '', '') ); @@ -282,22 +306,18 @@ void main() { whiteListFailures: (int c) => c == 1, ), throwsA(isA())); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' prints stdout and stderr to trace on success', () async { + testWithoutContext(' prints stdout and stderr to trace on success', () async { when(mockProcessManager.runSync(['whoohoo'])).thenReturn( ProcessResult(0, 0, 'stdout', 'stderr') ); expect(processUtils.runSync(['whoohoo']).exitCode, 0); expect(testLogger.traceText, contains('stdout')); expect(testLogger.traceText, contains('stderr')); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' prints stdout to status and stderr to error on failure with throwOnError', () async { + testWithoutContext(' prints stdout to status and stderr to error on failure with throwOnError', () async { when(mockProcessManager.runSync(['kaboom'])).thenReturn( ProcessResult(0, 1, 'stdout', 'stderr') ); @@ -305,71 +325,69 @@ void main() { throwsA(isA())); expect(testLogger.statusText, contains('stdout')); expect(testLogger.errorText, contains('stderr')); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' does not print stdout with hideStdout', () async { + testWithoutContext(' does not print stdout with hideStdout', () async { when(mockProcessManager.runSync(['whoohoo'])).thenReturn( ProcessResult(0, 0, 'stdout', 'stderr') ); expect(processUtils.runSync(['whoohoo'], hideStdout: true).exitCode, 0); expect(testLogger.traceText.contains('stdout'), isFalse); expect(testLogger.traceText, contains('stderr')); - }, overrides: { - ProcessManager: () => mockProcessManager, }); }); group('exitsHappySync', () { ProcessManager mockProcessManager; + ProcessUtils processUtils; setUp(() { mockProcessManager = MockProcessManager(); + processUtils = ProcessUtils( + processManager: mockProcessManager, + logger: MockLogger(), + ); }); - testUsingContext(' succeeds on success', () async { + testWithoutContext(' succeeds on success', () async { when(mockProcessManager.runSync(['whoohoo'])).thenReturn( ProcessResult(0, 0, '', '') ); expect(processUtils.exitsHappySync(['whoohoo']), isTrue); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' fails on failure', () async { + testWithoutContext(' fails on failure', () async { when(mockProcessManager.runSync(['boohoo'])).thenReturn( ProcessResult(0, 1, '', '') ); expect(processUtils.exitsHappySync(['boohoo']), isFalse); - }, overrides: { - ProcessManager: () => mockProcessManager, }); }); group('exitsHappy', () { ProcessManager mockProcessManager; + ProcessUtils processUtils; setUp(() { mockProcessManager = MockProcessManager(); + processUtils = ProcessUtils( + processManager: mockProcessManager, + logger: MockLogger(), + ); }); - testUsingContext(' succeeds on success', () async { + testWithoutContext(' succeeds on success', () async { when(mockProcessManager.run(['whoohoo'])).thenAnswer((_) { return Future.value(ProcessResult(0, 0, '', '')); }); expect(await processUtils.exitsHappy(['whoohoo']), isTrue); - }, overrides: { - ProcessManager: () => mockProcessManager, }); - testUsingContext(' fails on failure', () async { + testWithoutContext(' fails on failure', () async { when(mockProcessManager.run(['boohoo'])).thenAnswer((_) { return Future.value(ProcessResult(0, 1, '', '')); }); expect(await processUtils.exitsHappy(['boohoo']), isFalse); - }, overrides: { - ProcessManager: () => mockProcessManager, }); });