Adds tool warning log level and command line options to fail on warning/error output (#92031)

This commit is contained in:
Greg Spencer
2021-11-10 16:13:04 -08:00
committed by GitHub
parent 02cfbc320e
commit 52ae102f18
60 changed files with 873 additions and 262 deletions

View File

@@ -568,6 +568,20 @@ class StreamLogger extends Logger {
int hangingIndent,
bool wrap,
}) {
hadErrorOutput = true;
_log('[stderr] $message');
}
@override
void printWarning(
String message, {
bool emphasis,
TerminalColor color,
int indent,
int hangingIndent,
bool wrap,
}) {
hadWarningOutput = true;
_log('[stderr] $message');
}

View File

@@ -227,6 +227,8 @@ void main() {
const <String>['build', 'linux', '--debug', '--no-pub']
);
expect(testLogger.statusText, isNot(contains('STDOUT STUFF')));
expect(testLogger.warningText, isNot(contains('STDOUT STUFF')));
expect(testLogger.errorText, isNot(contains('STDOUT STUFF')));
expect(testLogger.traceText, contains('STDOUT STUFF'));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
@@ -308,6 +310,8 @@ ERROR: No file or variants found for asset: images/a_dot_burr.jpeg
);
expect(testLogger.statusText, contains('STDOUT STUFF'));
expect(testLogger.traceText, isNot(contains('STDOUT STUFF')));
expect(testLogger.warningText, isNot(contains('STDOUT STUFF')));
expect(testLogger.errorText, isNot(contains('STDOUT STUFF')));
}, overrides: <Type, Generator>{
FileSystem: () => fileSystem,
ProcessManager: () => processManager,

View File

@@ -3,9 +3,13 @@
// found in the LICENSE file.
// @dart = 2.8
import 'package:args/command_runner.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:meta/meta.dart';
import '../../src/common.dart';
import '../../src/context.dart';
@@ -13,27 +17,97 @@ import '../../src/test_flutter_command_runner.dart';
void main() {
testUsingContext('obfuscate requires split-debug-info', () {
final FakeBuildCommand command = FakeBuildCommand();
final FakeBuildInfoCommand command = FakeBuildInfoCommand();
final CommandRunner<void> commandRunner = createTestCommandRunner(command);
expect(() => commandRunner.run(<String>[
'build',
'fake',
'--obfuscate',
]), throwsToolExit());
]), throwsToolExit(message: '"--${FlutterOptions.kDartObfuscationOption}" can only be used in '
'combination with "--${FlutterOptions.kSplitDebugInfoOption}"'));
});
group('Fatal Logs', () {
FakeBuildCommand command;
MemoryFileSystem fs;
setUp(() {
fs = MemoryFileSystem.test();
fs.file('/package/pubspec.yaml').createSync(recursive: true);
fs.currentDirectory = '/package';
Cache.disableLocking();
});
testUsingContext("doesn't fail if --fatal-warnings specified and no warnings occur", () async {
command = FakeBuildCommand();
try {
await createTestCommandRunner(command).run(<String>[
'build',
'test',
'--${FlutterOptions.kFatalWarnings}',
]);
} on Exception {
fail('Unexpected exception thrown');
}
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext("doesn't fail if --fatal-warnings not specified", () async {
command = FakeBuildCommand();
testLogger.printWarning('Warning: Mild annoyance Will Robinson!');
try {
await createTestCommandRunner(command).run(<String>[
'build',
'test',
]);
} on Exception {
fail('Unexpected exception thrown');
}
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails if --fatal-warnings specified and warnings emitted', () async {
command = FakeBuildCommand();
testLogger.printWarning('Warning: Mild annoyance Will Robinson!');
await expectLater(createTestCommandRunner(command).run(<String>[
'build',
'test',
'--${FlutterOptions.kFatalWarnings}',
]), throwsToolExit(message: 'Logger received warning output during the run, and "--${FlutterOptions.kFatalWarnings}" is enabled.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails if --fatal-warnings specified and errors emitted', () async {
command = FakeBuildCommand();
testLogger.printError('Error: Danger Will Robinson!');
await expectLater(createTestCommandRunner(command).run(<String>[
'build',
'test',
'--${FlutterOptions.kFatalWarnings}',
]), throwsToolExit(message: 'Logger received error output during the run, and "--${FlutterOptions.kFatalWarnings}" is enabled.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
});
}
class FakeBuildCommand extends FlutterCommand {
FakeBuildCommand() {
class FakeBuildInfoCommand extends FlutterCommand {
FakeBuildInfoCommand() : super() {
addSplitDebugInfoOption();
addDartObfuscationOption();
}
@override
String get description => throw UnimplementedError();
String get description => '';
@override
String get name => 'build';
String get name => 'fake';
@override
Future<FlutterCommandResult> runCommand() async {
@@ -41,3 +115,35 @@ class FakeBuildCommand extends FlutterCommand {
return FlutterCommandResult.success();
}
}
class FakeBuildCommand extends BuildCommand {
FakeBuildCommand({bool verboseHelp = false}) : super(verboseHelp: verboseHelp) {
addSubcommand(FakeBuildSubcommand(verboseHelp: verboseHelp));
}
@override
String get description => '';
@override
String get name => 'build';
@override
Future<FlutterCommandResult> runCommand() async {
return FlutterCommandResult.success();
}
}
class FakeBuildSubcommand extends BuildSubCommand {
FakeBuildSubcommand({@required bool verboseHelp}) : super(verboseHelp: verboseHelp);
@override
String get description => '';
@override
String get name => 'test';
@override
Future<FlutterCommandResult> runCommand() async {
return FlutterCommandResult.success();
}
}

View File

@@ -130,6 +130,29 @@ void main() {
Logger: () => notifyingLogger,
});
testUsingContext('printWarning should send daemon.logMessage event', () async {
final StreamController<Map<String, dynamic>> commands = StreamController<Map<String, dynamic>>();
final StreamController<Map<String, dynamic>> responses = StreamController<Map<String, dynamic>>();
daemon = Daemon(
commands.stream,
responses.add,
notifyingLogger: notifyingLogger,
);
globals.printWarning('daemon.logMessage test');
final Map<String, dynamic> response = await responses.stream.firstWhere((Map<String, dynamic> map) {
return map['event'] == 'daemon.logMessage' && (map['params'] as Map<String, dynamic>)['level'] == 'warning';
});
expect(response['id'], isNull);
expect(response['event'], 'daemon.logMessage');
final Map<String, String> logMessage = castStringKeyedMap(response['params']).cast<String, String>();
expect(logMessage['level'], 'warning');
expect(logMessage['message'], 'daemon.logMessage test');
await responses.close();
await commands.close();
}, overrides: <Type, Generator>{
Logger: () => notifyingLogger,
});
testUsingContext('printStatus should log to stdout when logToStdout is enabled', () async {
final StringBuffer buffer = await capturedConsolePrint(() {
final StreamController<Map<String, dynamic>> commands = StreamController<Map<String, dynamic>>();

View File

@@ -294,6 +294,75 @@ void main() {
});
});
group('Fatal Logs', () {
TestRunCommandWithFakeResidentRunner command;
MemoryFileSystem fs;
setUp(() {
command = TestRunCommandWithFakeResidentRunner()
..fakeResidentRunner = FakeResidentRunner();
fs = MemoryFileSystem.test();
});
testUsingContext("doesn't fail if --fatal-warnings specified and no warnings occur", () async {
try {
await createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
'--${FlutterOptions.kFatalWarnings}',
]);
} on Exception {
fail('Unexpected exception thrown');
}
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext("doesn't fail if --fatal-warnings not specified", () async {
testLogger.printWarning('Warning: Mild annoyance Will Robinson!');
try {
await createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
]);
} on Exception {
fail('Unexpected exception thrown');
}
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails if --fatal-warnings specified and warnings emitted', () async {
testLogger.printWarning('Warning: Mild annoyance Will Robinson!');
await expectLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
'--${FlutterOptions.kFatalWarnings}',
]), throwsToolExit(message: 'Logger received warning output during the run, and "--${FlutterOptions.kFatalWarnings}" is enabled.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails if --fatal-warnings specified and errors emitted', () async {
testLogger.printError('Error: Danger Will Robinson!');
await expectLater(createTestCommandRunner(command).run(<String>[
'run',
'--no-pub',
'--no-hot',
'--${FlutterOptions.kFatalWarnings}',
]), throwsToolExit(message: 'Logger received error output during the run, and "--${FlutterOptions.kFatalWarnings}" is enabled.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
});
testUsingContext('should only request artifacts corresponding to connected devices', () async {
mockDeviceManager.devices = <Device>[FakeDevice(targetPlatform: TargetPlatform.android_arm)];
@@ -496,7 +565,7 @@ class FakeDevice extends Fake implements Device {
@override
String get id => 'fake_device';
void _throwToolExit(int code) => throwToolExit(null, exitCode: code);
void _throwToolExit(int code) => throwToolExit('FakeDevice tool exit', exitCode: code);
@override
Future<bool> get isLocalEmulator => Future<bool>.value(_isLocalEmulator);
@@ -504,6 +573,9 @@ class FakeDevice extends Fake implements Device {
@override
bool supportsRuntimeMode(BuildMode mode) => true;
@override
Future<bool> get supportsHardwareRendering async => true;
@override
bool supportsHotReload = false;
@@ -542,7 +614,7 @@ class FakeDevice extends Fake implements Device {
@override
final PlatformType platformType = PlatformType.ios;
bool startAppSuccess = true;
bool startAppSuccess;
@override
DevFSWriter createDevFSWriter(
@@ -564,9 +636,12 @@ class FakeDevice extends Fake implements Device {
bool ipv6 = false,
String userIdentifier,
}) async {
if (!startAppSuccess) {
if (startAppSuccess == false) {
return LaunchResult.failed();
}
if (startAppSuccess == true) {
return LaunchResult.succeeded();
}
final String dartFlags = debuggingOptions.dartFlags;
// In release mode, --dart-flags should be set to the empty string and
// provided flags should be dropped. In debug and profile modes,
@@ -587,18 +662,20 @@ class FakeDevice extends Fake implements Device {
}
class FakeApplicationPackageFactory extends Fake implements ApplicationPackageFactory {
ApplicationPackage package;
FakeApplicationPackageFactory(this.applicationPackage);
ApplicationPackage applicationPackage;
@override
Future<ApplicationPackage> getPackageForPlatform(
TargetPlatform platform, {
BuildInfo buildInfo,
File applicationBinary,
}) async {
return package;
}
TargetPlatform platform, {
BuildInfo buildInfo,
File applicationBinary,
}) async => applicationPackage;
}
class FakeApplicationPackage extends Fake implements ApplicationPackage { }
class TestRunCommandWithFakeResidentRunner extends RunCommand {
FakeResidentRunner fakeResidentRunner;

View File

@@ -16,6 +16,7 @@ import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/test.dart';
import 'package:flutter_tools/src/device.dart';
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/runner/flutter_command.dart';
import 'package:flutter_tools/src/test/runner.dart';
import 'package:flutter_tools/src/test/test_wrapper.dart';
import 'package:flutter_tools/src/test/watcher.dart';
@@ -644,6 +645,60 @@ dev_dependencies:
ProcessManager: () => FakeProcessManager.any(),
DeviceManager: () => _FakeDeviceManager(<Device>[]),
});
group('Fatal Logs', () {
testUsingContext("doesn't fail when --fatal-warnings is set and no warning output", () async {
final FakeFlutterTestRunner testRunner = FakeFlutterTestRunner(0);
final TestCommand testCommand = TestCommand(testRunner: testRunner);
final CommandRunner<void> commandRunner = createTestCommandRunner(testCommand);
try {
await commandRunner.run(const <String>[
'test',
'--no-pub',
'--${FlutterOptions.kFatalWarnings}',
]);
} on Exception {
fail('Unexpected exception thrown');
}
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails if --fatal-warnings specified and warnings emitted', () async {
final FakeFlutterTestRunner testRunner = FakeFlutterTestRunner(0);
final TestCommand testCommand = TestCommand(testRunner: testRunner);
final CommandRunner<void> commandRunner = createTestCommandRunner(testCommand);
testLogger.printWarning('Warning: Mild annoyance, Will Robinson!');
expect(commandRunner.run(const <String>[
'test',
'--no-pub',
'--${FlutterOptions.kFatalWarnings}',
]), throwsToolExit(message: 'Logger received warning output during the run, and "--${FlutterOptions.kFatalWarnings}" is enabled.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
testUsingContext('fails when --fatal-warnings is set and only errors emitted', () async {
final FakeFlutterTestRunner testRunner = FakeFlutterTestRunner(0);
final TestCommand testCommand = TestCommand(testRunner: testRunner);
final CommandRunner<void> commandRunner = createTestCommandRunner(testCommand);
testLogger.printError('Error: Danger Will Robinson!');
expect(commandRunner.run(const <String>[
'test',
'--no-pub',
'--${FlutterOptions.kFatalWarnings}',
]), throwsToolExit(message: 'Logger received error output during the run, and "--${FlutterOptions.kFatalWarnings}" is enabled.'));
}, overrides: <Type, Generator>{
FileSystem: () => fs,
ProcessManager: () => FakeProcessManager.any(),
});
});
}
class FakeFlutterTestRunner implements FlutterTestRunner {

View File

@@ -311,7 +311,7 @@ flutter:
await writeBundle(directory, <String, DevFSContent>{}, loggerOverride: testLogger);
expect(testLogger.errorText, contains('Expected Error Text'));
expect(testLogger.warningText, contains('Expected Error Text'));
});
testUsingContext('does not unnecessarily recreate asset manifest, font manifest, license', () async {

View File

@@ -137,7 +137,7 @@ void main() {
final FakeSimpleArtifact artifact = FakeSimpleArtifact(cache);
await artifact.update(FakeArtifactUpdater(), logger, fileSystem, FakeOperatingSystemUtils());
expect(logger.errorText, contains('stamp write failed'));
expect(logger.warningText, contains('stamp write failed'));
});
testWithoutContext('Continues on missing version file', () async {
@@ -153,7 +153,7 @@ void main() {
final FakeSimpleArtifact artifact = FakeSimpleArtifact(cache);
await artifact.update(FakeArtifactUpdater(), logger, fileSystem, FakeOperatingSystemUtils());
expect(logger.errorText, contains('No known version for the artifact name "fake"'));
expect(logger.warningText, contains('No known version for the artifact name "fake"'));
});
testWithoutContext('Gradle wrapper should not be up to date, if some cached artifact is not available', () {
@@ -725,7 +725,7 @@ void main() {
cache.clearStampFiles();
expect(logger.errorText, contains('Failed to delete some stamp files'));
expect(logger.warningText, contains('Failed to delete some stamp files'));
});
testWithoutContext('FlutterWebSdk fetches web artifacts and deletes previous directory contents', () async {

View File

@@ -83,6 +83,8 @@ void main() {
}
class FakeBuildSubCommand extends BuildSubCommand {
FakeBuildSubCommand() : super(verboseHelp: false);
@override
String get description => throw UnimplementedError();

View File

@@ -432,8 +432,8 @@ void main() {
buildMode: BuildMode.debug,
);
expect(logger.errorText, contains('Warning: Podfile is out of date'));
expect(logger.errorText, contains('rm macos/Podfile'));
expect(logger.warningText, contains('Warning: Podfile is out of date'));
expect(logger.warningText, contains('rm macos/Podfile'));
expect(fakeProcessManager, hasNoRemainingExpectations);
});

View File

@@ -747,7 +747,7 @@ dependencies:
.childFile('GeneratedPluginRegistrant.java');
expect(registrant.readAsStringSync(),
contains('plugin3.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin3.UseOldEmbedding"));'));
expect(testLogger.errorText, equals(
expect(testLogger.warningText, equals(
'The plugin `plugin3` uses a deprecated version of the Android embedding.\n'
'To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. '
'Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.\n'
@@ -827,7 +827,7 @@ dependencies:
await injectPlugins(flutterProject, androidPlatform: true);
expect(testLogger.errorText, equals(
expect(testLogger.warningText, equals(
'This app is using a deprecated version of the Android embedding.\n'
'To avoid unexpected runtime failures, or future build failures, try to migrate this app to the V2 embedding.\n'
'Take a look at the docs for migrating an app: https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects\n'
@@ -854,7 +854,7 @@ dependencies:
contains('plugin3.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin3.UseOldEmbedding"));'));
expect(registrant.readAsStringSync(),
contains('plugin4.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin4.UseOldEmbedding"));'));
expect(testLogger.errorText, equals(
expect(testLogger.warningText, equals(
'The plugins `plugin3, plugin4` use a deprecated version of the Android embedding.\n'
'To avoid unexpected runtime failures, or future build failures, try to see if these plugins support the Android V2 embedding. '
'Otherwise, consider removing them since a future release of Flutter will remove these deprecated APIs.\n'
@@ -882,7 +882,7 @@ dependencies:
contains('plugin3.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin3.UseOldEmbedding"));'));
expect(registrant.readAsStringSync(),
contains('plugin4.UseOldEmbedding.registerWith(shimPluginRegistry.registrarFor("plugin4.UseOldEmbedding"));'));
expect(testLogger.errorText, equals(
expect(testLogger.warningText, equals(
'The plugins `plugin3, plugin4` use a deprecated version of the Android embedding.\n'
'To avoid unexpected runtime failures, or future build failures, try to see if these plugins support the Android V2 embedding. '
'Otherwise, consider removing them since a future release of Flutter will remove these deprecated APIs.\n'

View File

@@ -183,7 +183,7 @@ void main() {
// android:name="flutterEmbedding" android:value="2" />.
await project.regeneratePlatformSpecificTooling();
expect(testLogger.statusText, contains('https://flutter.dev/go/android-project-migration'));
expect(testLogger.warningText, contains('https://github.com/flutter/flutter/wiki/Upgrading-pre-1.12-Android-projects'));
});
_testInMemory('Android plugin without example app does not show a warning', () async {
final FlutterProject project = await aPluginProject();

View File

@@ -87,7 +87,7 @@ void main() {
final CommandRunner<void> runner = createTestCommandRunner(flutterCommand);
await runner.run(<String>['deprecated']);
expect(testLogger.errorText,
expect(testLogger.warningText,
contains('The "deprecated" command is deprecated and will be removed in '
'a future version of Flutter.'));
expect(flutterCommand.usage,

View File

@@ -129,7 +129,7 @@ void main() {
// We get a warning about the unexpected package.
expect(
bufferLogger.errorText,
bufferLogger.warningText,
contains("Unexpected package 'extra' found in packages directory"),
);

View File

@@ -10,12 +10,15 @@ import 'package:file/file.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/base/io.dart';
import 'package:flutter_tools/src/base/logger.dart';
import 'package:flutter_tools/src/base/os.dart';
import 'package:flutter_tools/src/base/terminal.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:process/process.dart';
import 'package:test/fake.dart';
import '../src/common.dart';
import '../src/context.dart';
import '../src/fakes.dart';
import 'test_utils.dart';
final String dart = fileSystem.path
@@ -24,53 +27,122 @@ final String dart = fileSystem.path
void main() {
group('Cache.lock', () {
// Windows locking is too flaky for this to work reliably.
if (!platform.isWindows) {
testWithoutContext(
'should log a message to stderr when lock is not acquired', () async {
final String oldRoot = Cache.flutterRoot;
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('cache_test.');
final BufferLogger logger = BufferLogger(
terminal: Terminal.test(supportsColor: false, supportsEmoji: false),
outputPreferences: OutputPreferences(),
if (platform.isWindows) {
return;
}
testWithoutContext(
'should log a message to stderr when lock is not acquired', () async {
final String oldRoot = Cache.flutterRoot;
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('cache_test.');
final BufferLogger logger = BufferLogger(
terminal: Terminal.test(supportsColor: false, supportsEmoji: false),
outputPreferences: OutputPreferences(),
);
logger.fatalWarnings = true;
try {
Cache.flutterRoot = tempDir.absolute.path;
final Cache cache = Cache.test(
fileSystem: fileSystem,
processManager: FakeProcessManager.any(),
logger: logger,
);
try {
Cache.flutterRoot = tempDir.absolute.path;
final Cache cache = Cache.test(
fileSystem: fileSystem,
processManager: FakeProcessManager.any(),
logger: logger,
);
final File cacheFile = fileSystem.file(fileSystem.path
.join(Cache.flutterRoot, 'bin', 'cache', 'lockfile'))
..createSync(recursive: true);
final File script = fileSystem.file(fileSystem.path
.join(Cache.flutterRoot, 'bin', 'cache', 'test_lock.dart'));
script.writeAsStringSync(r'''
final File cacheFile = fileSystem.file(fileSystem.path
.join(Cache.flutterRoot, 'bin', 'cache', 'lockfile'))
..createSync(recursive: true);
final File script = fileSystem.file(fileSystem.path
.join(Cache.flutterRoot, 'bin', 'cache', 'test_lock.dart'));
script.writeAsStringSync(r'''
import 'dart:async';
import 'dart:io';
Future<void> main(List<String> args) async {
File file = File(args[0]);
RandomAccessFile lock = file.openSync(mode: FileMode.write);
lock.lockSync();
await Future<void>.delayed(const Duration(milliseconds: 1000));
exit(0);
File file = File(args[0]);
RandomAccessFile lock = file.openSync(mode: FileMode.write);
lock.lockSync();
await Future<void>.delayed(const Duration(milliseconds: 1000));
exit(0);
}
''');
final Process process = await const LocalProcessManager().start(
<String>[dart, script.absolute.path, cacheFile.absolute.path],
);
await Future<void>.delayed(const Duration(milliseconds: 500));
await cache.lock();
process.kill(io.ProcessSignal.sigkill);
} finally {
tryToDelete(tempDir);
Cache.flutterRoot = oldRoot;
}
expect(logger.statusText, isEmpty);
expect(logger.errorText,
equals('Waiting for another flutter command to release the startup lock...\n'));
});
}
final Process process = await const LocalProcessManager().start(
<String>[dart, script.absolute.path, cacheFile.absolute.path],
);
await Future<void>.delayed(const Duration(milliseconds: 500));
await cache.lock();
process.kill(io.ProcessSignal.sigkill);
} finally {
tryToDelete(tempDir);
Cache.flutterRoot = oldRoot;
}
expect(logger.statusText, isEmpty);
expect(logger.errorText, isEmpty);
expect(logger.warningText,
equals('Waiting for another flutter command to release the startup lock...\n'));
expect(logger.hadErrorOutput, isFalse);
// Should still be false, since the particular "Waiting..." message above aims to
// avoid triggering failure as a fatal warning.
expect(logger.hadWarningOutput, isFalse);
});
testWithoutContext(
'should log a warning message for unknown version ', () async {
final String oldRoot = Cache.flutterRoot;
final Directory tempDir = fileSystem.systemTempDirectory.createTempSync('cache_test.');
final BufferLogger logger = BufferLogger(
terminal: Terminal.test(supportsColor: false, supportsEmoji: false),
outputPreferences: OutputPreferences(),
);
logger.fatalWarnings = true;
try {
Cache.flutterRoot = tempDir.absolute.path;
final Cache cache = Cache.test(
fileSystem: fileSystem,
processManager: FakeProcessManager.any(),
logger: logger,
);
final FakeVersionlessArtifact artifact = FakeVersionlessArtifact(cache);
cache.registerArtifact(artifact);
await artifact.update(FakeArtifactUpdater(), logger, fileSystem, FakeOperatingSystemUtils());
} finally {
tryToDelete(tempDir);
Cache.flutterRoot = oldRoot;
}
expect(logger.statusText, isEmpty);
expect(logger.warningText, equals('No known version for the artifact name "fake". '
'Flutter can continue, but the artifact may be re-downloaded on '
'subsequent invocations until the problem is resolved.\n'));
expect(logger.hadErrorOutput, isFalse);
expect(logger.hadWarningOutput, isTrue);
});
});
}
class FakeArtifactUpdater extends Fake implements ArtifactUpdater {
void Function(String, Uri, Directory) onDownloadZipArchive;
void Function(String, Uri, Directory) onDownloadZipTarball;
@override
Future<void> downloadZippedTarball(String message, Uri url, Directory location) async {
onDownloadZipTarball?.call(message, url, location);
}
@override
Future<void> downloadZipArchive(String message, Uri url, Directory location) async {
onDownloadZipArchive?.call(message, url, location);
}
@override
void removeDownloadedFiles() { }
}
class FakeVersionlessArtifact extends CachedArtifact {
FakeVersionlessArtifact(Cache cache) : super(
'fake',
cache,
DevelopmentArtifact.universal,
);
@override
String get version => null;
@override
Future<void> updateInner(ArtifactUpdater artifactUpdater, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils) async { }
}

View File

@@ -115,84 +115,66 @@ void main() {
testWithoutContext('flutter test should run a test when its name matches a regexp', () async {
final ProcessResult result = await _runFlutterTest('filtering', automatedTestsDirectory, flutterTestDirectory,
extraArguments: const <String>['--name', 'inc.*de']);
if (!(result.stdout as String).contains('+1: All tests passed')) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
expect(result.stdout, contains(RegExp(r'\+\d+: All tests passed!')));
expect(result.exitCode, 0);
});
testWithoutContext('flutter test should run a test when its name contains a string', () async {
final ProcessResult result = await _runFlutterTest('filtering', automatedTestsDirectory, flutterTestDirectory,
extraArguments: const <String>['--plain-name', 'include']);
if (!(result.stdout as String).contains('+1: All tests passed')) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
expect(result.stdout, contains(RegExp(r'\+\d+: All tests passed!')));
expect(result.exitCode, 0);
});
testWithoutContext('flutter test should run a test with a given tag', () async {
final ProcessResult result = await _runFlutterTest('filtering_tag', automatedTestsDirectory, flutterTestDirectory,
extraArguments: const <String>['--tags', 'include-tag']);
if (!(result.stdout as String).contains('+1: All tests passed')) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
expect(result.stdout, contains(RegExp(r'\+\d+: All tests passed!')));
expect(result.exitCode, 0);
});
testWithoutContext('flutter test should not run a test with excluded tag', () async {
final ProcessResult result = await _runFlutterTest('filtering_tag', automatedTestsDirectory, flutterTestDirectory,
extraArguments: const <String>['--exclude-tags', 'exclude-tag']);
if (!(result.stdout as String).contains('+1: All tests passed')) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
expect(result.stdout, contains(RegExp(r'\+\d+: All tests passed!')));
expect(result.exitCode, 0);
});
testWithoutContext('flutter test should run all tests when tags are unspecified', () async {
final ProcessResult result = await _runFlutterTest('filtering_tag', automatedTestsDirectory, flutterTestDirectory);
if (!(result.stdout as String).contains('+1 -1: Some tests failed')) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
expect(result.stdout, contains(RegExp(r'\+\d+ -1: Some tests failed\.')));
expect(result.exitCode, 1);
});
testWithoutContext('flutter test should run a widgetTest with a given tag', () async {
final ProcessResult result = await _runFlutterTest('filtering_tag_widget', automatedTestsDirectory, flutterTestDirectory,
extraArguments: const <String>['--tags', 'include-tag']);
if (!(result.stdout as String).contains('+1: All tests passed')) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
expect(result.stdout, contains(RegExp(r'\+\d+: All tests passed!')));
expect(result.exitCode, 0);
});
testWithoutContext('flutter test should not run a widgetTest with excluded tag', () async {
final ProcessResult result = await _runFlutterTest('filtering_tag_widget', automatedTestsDirectory, flutterTestDirectory,
extraArguments: const <String>['--exclude-tags', 'exclude-tag']);
if (!(result.stdout as String).contains('+1: All tests passed')) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
expect(result.stdout, contains(RegExp(r'\+\d+: All tests passed!')));
expect(result.exitCode, 0);
});
testWithoutContext('flutter test should run all widgetTest when tags are unspecified', () async {
final ProcessResult result = await _runFlutterTest('filtering_tag_widget', automatedTestsDirectory, flutterTestDirectory);
if (!(result.stdout as String).contains('+1 -1: Some tests failed')) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
expect(result.stdout, contains(RegExp(r'\+\d+ -1: Some tests failed\.')));
expect(result.exitCode, 1);
});
testWithoutContext('flutter test should test runs to completion', () async {
final ProcessResult result = await _runFlutterTest('trivial', automatedTestsDirectory, flutterTestDirectory,
extraArguments: const <String>['--verbose']);
final String stdout = result.stdout as String;
if ((!stdout.contains('+1: All tests passed')) ||
(!stdout.contains('test 0: Starting flutter_tester process with command')) ||
(!stdout.contains('test 0: deleting temporary directory')) ||
(!stdout.contains('test 0: finished')) ||
(!stdout.contains('test package returned with exit code 0'))) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
final String stdout = (result.stdout as String).replaceAll('\r', '\n');
expect(stdout, contains(RegExp(r'\+\d+: All tests passed\!')));
expect(stdout, contains('test 0: Starting flutter_tester process with command'));
expect(stdout, contains('test 0: deleting temporary directory'));
expect(stdout, contains('test 0: finished'));
expect(stdout, contains('test package returned with exit code 0'));
if ((result.stderr as String).isNotEmpty) {
fail('unexpected error output from test:\n\n${result.stderr}\n-- end stderr --\n\n');
}
@@ -202,14 +184,12 @@ void main() {
testWithoutContext('flutter test should run all tests inside of a directory with no trailing slash', () async {
final ProcessResult result = await _runFlutterTest(null, automatedTestsDirectory, '$flutterTestDirectory/child_directory',
extraArguments: const <String>['--verbose']);
final String stdout = result.stdout as String;
if ((!stdout.contains('+2: All tests passed')) ||
(!stdout.contains('test 0: Starting flutter_tester process with command')) ||
(!stdout.contains('test 0: deleting temporary directory')) ||
(!stdout.contains('test 0: finished')) ||
(!stdout.contains('test package returned with exit code 0'))) {
fail('unexpected output from test:\n\n${result.stdout}\n-- end stdout --\n\n');
}
final String stdout = (result.stdout as String).replaceAll('\r', '\n');
expect(result.stdout, contains(RegExp(r'\+\d+: All tests passed\!')));
expect(stdout, contains('test 0: Starting flutter_tester process with command'));
expect(stdout, contains('test 0: deleting temporary directory'));
expect(stdout, contains('test 0: finished'));
expect(stdout, contains('test package returned with exit code 0'));
if ((result.stderr as String).isNotEmpty) {
fail('unexpected error output from test:\n\n${result.stderr}\n-- end stderr --\n\n');
}