Auto-format Framework (#160545)
This auto-formats all *.dart files in the repository outside of the `engine` subdirectory and enforces that these files stay formatted with a presubmit check. **Reviewers:** Please carefully review all the commits except for the one titled "formatted". The "formatted" commit was auto-generated by running `dev/tools/format.sh -a -f`. The other commits were hand-crafted to prepare the repo for the formatting change. I recommend reviewing the commits one-by-one via the "Commits" tab and avoiding Github's "Files changed" tab as it will likely slow down your browser because of the size of this PR. --------- Co-authored-by: Kate Lovett <katelovett@google.com> Co-authored-by: LongCatIsLooong <31859944+LongCatIsLooong@users.noreply.github.com>
This commit is contained in:
committed by
GitHub
parent
8e0993eda8
commit
5491c8c146
@@ -43,7 +43,8 @@ class FakeAndroidBuilder implements AndroidBuilder {
|
||||
}) async {}
|
||||
|
||||
@override
|
||||
Future<List<String>> getBuildVariants({required FlutterProject project}) async => const <String>[];
|
||||
Future<List<String>> getBuildVariants({required FlutterProject project}) async =>
|
||||
const <String>[];
|
||||
|
||||
@override
|
||||
Future<String> outputsAppLinkSettings(
|
||||
@@ -55,11 +56,8 @@ class FakeAndroidBuilder implements AndroidBuilder {
|
||||
/// Creates a [FlutterProject] in a directory named [flutter_project]
|
||||
/// within [directoryOverride].
|
||||
class FakeFlutterProjectFactory extends FlutterProjectFactory {
|
||||
FakeFlutterProjectFactory(this.directoryOverride) :
|
||||
super(
|
||||
fileSystem: globals.fs,
|
||||
logger: globals.logger,
|
||||
);
|
||||
FakeFlutterProjectFactory(this.directoryOverride)
|
||||
: super(fileSystem: globals.fs, logger: globals.logger);
|
||||
|
||||
final file_system.Directory directoryOverride;
|
||||
|
||||
@@ -120,7 +118,6 @@ const String gradleReplacementString = 'GRADLE_REPLACE_ME';
|
||||
const String flutterCompileSdkString = 'flutter.compileSdkVersion';
|
||||
|
||||
class VersionTuple {
|
||||
|
||||
VersionTuple({
|
||||
required this.agpVersion,
|
||||
required this.gradleVersion,
|
||||
@@ -145,7 +142,8 @@ class VersionTuple {
|
||||
/// ProcessResult.
|
||||
Future<ProcessResult> buildFlutterApkWithSpecifiedDependencyVersions({
|
||||
required VersionTuple versions,
|
||||
required Directory tempDir,}) async {
|
||||
required Directory tempDir,
|
||||
}) async {
|
||||
// Create a new flutter project.
|
||||
final String flutterBin = fileSystem.path.join(getFlutterRoot(), 'bin', 'flutter');
|
||||
ProcessResult result = await processManager.run(<String>[
|
||||
@@ -159,30 +157,32 @@ Future<ProcessResult> buildFlutterApkWithSpecifiedDependencyVersions({
|
||||
final Directory app = Directory(fileSystem.path.join(tempDir.path, 'dependency_checker_app'));
|
||||
|
||||
if (versions.compileSdkVersion != null) {
|
||||
final File appGradleBuild = File(fileSystem.path.join(
|
||||
app.path, 'android', 'app', 'build.gradle.kts'));
|
||||
final String appBuildContent = appGradleBuild.readAsStringSync()
|
||||
.replaceFirst(flutterCompileSdkString, versions.compileSdkVersion!);
|
||||
final File appGradleBuild = File(
|
||||
fileSystem.path.join(app.path, 'android', 'app', 'build.gradle.kts'),
|
||||
);
|
||||
final String appBuildContent = appGradleBuild.readAsStringSync().replaceFirst(
|
||||
flutterCompileSdkString,
|
||||
versions.compileSdkVersion!,
|
||||
);
|
||||
appGradleBuild.writeAsStringSync(appBuildContent);
|
||||
}
|
||||
|
||||
// Modify gradle version to passed in version.
|
||||
final File gradleWrapperProperties = File(fileSystem.path.join(
|
||||
app.path, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties'));
|
||||
final File gradleWrapperProperties = File(
|
||||
fileSystem.path.join(app.path, 'android', 'gradle', 'wrapper', 'gradle-wrapper.properties'),
|
||||
);
|
||||
final String propertyContent = gradleWrapperPropertiesFileContent.replaceFirst(
|
||||
gradleReplacementString,
|
||||
versions.gradleVersion,
|
||||
);
|
||||
await gradleWrapperProperties.writeAsString(propertyContent, flush: true);
|
||||
|
||||
final File gradleSettings = File(fileSystem.path.join(
|
||||
app.path, 'android', 'settings.gradle'));
|
||||
final File gradleSettings = File(fileSystem.path.join(app.path, 'android', 'settings.gradle'));
|
||||
final String settingsContent = gradleSettingsFileContent
|
||||
.replaceFirst(agpReplacementString, versions.agpVersion)
|
||||
.replaceFirst(kgpReplacementString, versions.kotlinVersion);
|
||||
await gradleSettings.writeAsString(settingsContent, flush: true);
|
||||
|
||||
|
||||
// Ensure that gradle files exists from templates.
|
||||
result = await processManager.run(<String>[
|
||||
flutterBin,
|
||||
|
||||
@@ -51,14 +51,19 @@ String getFlutterRoot() {
|
||||
return platform.environment['FLUTTER_ROOT']!;
|
||||
}
|
||||
|
||||
Error invalidScript() => StateError('Could not determine flutter_tools/ path from script URL (${globals.platform.script}); consider setting FLUTTER_ROOT explicitly.');
|
||||
Error invalidScript() => StateError(
|
||||
'Could not determine flutter_tools/ path from script URL (${globals.platform.script}); consider setting FLUTTER_ROOT explicitly.',
|
||||
);
|
||||
|
||||
Uri scriptUri;
|
||||
switch (platform.script.scheme) {
|
||||
case 'file':
|
||||
scriptUri = platform.script;
|
||||
case 'data':
|
||||
final RegExp flutterTools = RegExp(r'(file://[^"]*[/\\]flutter_tools[/\\][^"]+\.dart)', multiLine: true);
|
||||
final RegExp flutterTools = RegExp(
|
||||
r'(file://[^"]*[/\\]flutter_tools[/\\][^"]+\.dart)',
|
||||
multiLine: true,
|
||||
);
|
||||
final Match? match = flutterTools.firstMatch(Uri.decodeFull(platform.script.path));
|
||||
if (match == null) {
|
||||
throw invalidScript();
|
||||
@@ -80,12 +85,17 @@ String getFlutterRoot() {
|
||||
/// Capture console print events into a string buffer.
|
||||
Future<StringBuffer> capturedConsolePrint(Future<void> Function() body) async {
|
||||
final StringBuffer buffer = StringBuffer();
|
||||
await runZoned<Future<void>>(() async {
|
||||
// Service the event loop.
|
||||
await body();
|
||||
}, zoneSpecification: ZoneSpecification(print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
|
||||
buffer.writeln(line);
|
||||
}));
|
||||
await runZoned<Future<void>>(
|
||||
() async {
|
||||
// Service the event loop.
|
||||
await body();
|
||||
},
|
||||
zoneSpecification: ZoneSpecification(
|
||||
print: (Zone self, ZoneDelegate parent, Zone zone, String line) {
|
||||
buffer.writeln(line);
|
||||
},
|
||||
),
|
||||
);
|
||||
return buffer;
|
||||
}
|
||||
|
||||
@@ -95,7 +105,7 @@ final Matcher throwsAssertionError = throwsA(isA<AssertionError>());
|
||||
/// Matcher for functions that throw [ToolExit].
|
||||
///
|
||||
/// [message] is matched using the [contains] matcher.
|
||||
Matcher throwsToolExit({ int? exitCode, Pattern? message }) {
|
||||
Matcher throwsToolExit({int? exitCode, Pattern? message}) {
|
||||
TypeMatcher<ToolExit> result = const TypeMatcher<ToolExit>();
|
||||
|
||||
if (exitCode != null) {
|
||||
@@ -109,7 +119,7 @@ Matcher throwsToolExit({ int? exitCode, Pattern? message }) {
|
||||
}
|
||||
|
||||
/// Matcher for functions that throw [UsageException].
|
||||
Matcher throwsUsageException({Pattern? message }) {
|
||||
Matcher throwsUsageException({Pattern? message}) {
|
||||
Matcher matcher = _isUsageException;
|
||||
if (message != null) {
|
||||
matcher = allOf(matcher, (UsageException e) => e.message.contains(message));
|
||||
@@ -121,7 +131,7 @@ Matcher throwsUsageException({Pattern? message }) {
|
||||
final TypeMatcher<UsageException> _isUsageException = isA<UsageException>();
|
||||
|
||||
/// Matcher for functions that throw [ProcessException].
|
||||
Matcher throwsProcessException({ Pattern? message }) {
|
||||
Matcher throwsProcessException({Pattern? message}) {
|
||||
Matcher matcher = _isProcessException;
|
||||
if (message != null) {
|
||||
matcher = allOf(matcher, (ProcessException e) => e.message.contains(message));
|
||||
@@ -138,8 +148,9 @@ Future<void> expectToolExitLater(Future<dynamic> future, Matcher messageMatcher)
|
||||
fail('ToolExit expected, but nothing thrown');
|
||||
} on ToolExit catch (e) {
|
||||
expect(e.message, messageMatcher);
|
||||
// Catch all exceptions to give a better test failure message.
|
||||
} catch (e, trace) { // ignore: avoid_catches_without_on_clauses
|
||||
// Catch all exceptions to give a better test failure message.
|
||||
} catch (e, trace) {
|
||||
// ignore: avoid_catches_without_on_clauses
|
||||
fail('ToolExit expected, got $e\n$trace');
|
||||
}
|
||||
}
|
||||
@@ -147,26 +158,26 @@ Future<void> expectToolExitLater(Future<dynamic> future, Matcher messageMatcher)
|
||||
Future<void> expectReturnsNormallyLater(Future<dynamic> future) async {
|
||||
try {
|
||||
await future;
|
||||
// Catch all exceptions to give a better test failure message.
|
||||
} catch (e, trace) { // ignore: avoid_catches_without_on_clauses
|
||||
// Catch all exceptions to give a better test failure message.
|
||||
} catch (e, trace) {
|
||||
// ignore: avoid_catches_without_on_clauses
|
||||
fail('Expected to run with no exceptions, got $e\n$trace');
|
||||
}
|
||||
}
|
||||
|
||||
Matcher containsIgnoringWhitespace(String toSearch) {
|
||||
return predicate(
|
||||
(String source) {
|
||||
return collapseWhitespace(source).contains(collapseWhitespace(toSearch));
|
||||
},
|
||||
'contains "$toSearch" ignoring whitespace.',
|
||||
);
|
||||
return predicate((String source) {
|
||||
return collapseWhitespace(source).contains(collapseWhitespace(toSearch));
|
||||
}, 'contains "$toSearch" ignoring whitespace.');
|
||||
}
|
||||
|
||||
/// The tool overrides `test` to ensure that files created under the
|
||||
/// system temporary directory are deleted after each test by calling
|
||||
/// `LocalFileSystem.dispose()`.
|
||||
@isTest
|
||||
void test(String description, FutureOr<void> Function() body, {
|
||||
void test(
|
||||
String description,
|
||||
FutureOr<void> Function() body, {
|
||||
String? testOn,
|
||||
dynamic skip,
|
||||
List<String>? tags,
|
||||
@@ -202,7 +213,9 @@ void test(String description, FutureOr<void> Function() body, {
|
||||
///
|
||||
/// For more information, see https://github.com/flutter/flutter/issues/47161
|
||||
@isTest
|
||||
void testWithoutContext(String description, FutureOr<void> Function() body, {
|
||||
void testWithoutContext(
|
||||
String description,
|
||||
FutureOr<void> Function() body, {
|
||||
String? testOn,
|
||||
dynamic skip,
|
||||
List<String>? tags,
|
||||
@@ -210,10 +223,9 @@ void testWithoutContext(String description, FutureOr<void> Function() body, {
|
||||
int? retry,
|
||||
}) {
|
||||
return test(
|
||||
description, () async {
|
||||
return runZoned(body, zoneValues: <Object, Object>{
|
||||
contextKey: const _NoContext(),
|
||||
});
|
||||
description,
|
||||
() async {
|
||||
return runZoned(body, zoneValues: <Object, Object>{contextKey: const _NoContext()});
|
||||
},
|
||||
skip: skip,
|
||||
tags: tags,
|
||||
@@ -239,7 +251,7 @@ class _NoContext implements AppContext {
|
||||
throw UnsupportedError(
|
||||
'context.get<$T> is not supported in test methods. '
|
||||
'Use Testbed or testUsingContext if accessing Zone injected '
|
||||
'values.'
|
||||
'values.',
|
||||
);
|
||||
}
|
||||
|
||||
@@ -275,7 +287,8 @@ class _NoContext implements AppContext {
|
||||
/// }
|
||||
/// ```
|
||||
class FileExceptionHandler {
|
||||
final Map<String, Map<FileSystemOp, FileSystemException>> _contextErrors = <String, Map<FileSystemOp, FileSystemException>>{};
|
||||
final Map<String, Map<FileSystemOp, FileSystemException>> _contextErrors =
|
||||
<String, Map<FileSystemOp, FileSystemException>>{};
|
||||
final Map<FileSystemOp, FileSystemException> _tempErrors = <FileSystemOp, FileSystemException>{};
|
||||
static final RegExp _tempDirectoryEnd = RegExp('rand[0-9]+');
|
||||
|
||||
|
||||
@@ -62,13 +62,14 @@ void testUsingContext(
|
||||
Map<Type, Generator> overrides = const <Type, Generator>{},
|
||||
bool initializeFlutterRoot = true,
|
||||
String? testOn,
|
||||
bool? skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this
|
||||
bool?
|
||||
skip, // should default to `false`, but https://github.com/dart-lang/test/issues/545 doesn't allow this
|
||||
}) {
|
||||
if (overrides[FileSystem] != null && overrides[ProcessManager] == null) {
|
||||
throw StateError(
|
||||
'If you override the FileSystem context you must also provide a ProcessManager, '
|
||||
'otherwise the processes you launch will not be dealing with the same file system '
|
||||
'that you are dealing with in your test.'
|
||||
'that you are dealing with in your test.',
|
||||
);
|
||||
}
|
||||
if (overrides.containsKey(ProcessUtils)) {
|
||||
@@ -86,105 +87,110 @@ void testUsingContext(
|
||||
});
|
||||
Config buildConfig(FileSystem fs) {
|
||||
configDir ??= globals.fs.systemTempDirectory.createTempSync('flutter_config_dir_test.');
|
||||
return Config.test(
|
||||
name: Config.kFlutterSettings,
|
||||
directory: configDir,
|
||||
logger: globals.logger,
|
||||
);
|
||||
}
|
||||
PersistentToolState buildPersistentToolState(FileSystem fs) {
|
||||
configDir ??= globals.fs.systemTempDirectory.createTempSync('flutter_config_dir_test.');
|
||||
return PersistentToolState.test(
|
||||
directory: configDir!,
|
||||
logger: globals.logger,
|
||||
);
|
||||
return Config.test(name: Config.kFlutterSettings, directory: configDir, logger: globals.logger);
|
||||
}
|
||||
|
||||
test(description, () async {
|
||||
await runInContext<dynamic>(() {
|
||||
return context.run<dynamic>(
|
||||
name: 'mocks',
|
||||
overrides: <Type, Generator>{
|
||||
AnsiTerminal: () => AnsiTerminal(platform: globals.platform, stdio: globals.stdio),
|
||||
Config: () => buildConfig(globals.fs),
|
||||
DeviceManager: () => FakeDeviceManager(),
|
||||
Doctor: () => FakeDoctor(globals.logger),
|
||||
FlutterVersion: () => FakeFlutterVersion(),
|
||||
HttpClient: () => FakeHttpClient.any(),
|
||||
IOSSimulatorUtils: () => const NoopIOSSimulatorUtils(),
|
||||
OutputPreferences: () => OutputPreferences.test(),
|
||||
Logger: () => BufferLogger.test(),
|
||||
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
|
||||
PersistentToolState: () => buildPersistentToolState(globals.fs),
|
||||
Usage: () => TestUsage(),
|
||||
XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(),
|
||||
FileSystem: () => LocalFileSystemBlockingSetCurrentDirectory(),
|
||||
PlistParser: () => FakePlistParser(),
|
||||
Signals: () => FakeSignals(),
|
||||
Pub: () => const ThrowingPub(), // prevent accidentally using pub.
|
||||
CrashReporter: () => const NoopCrashReporter(),
|
||||
TemplateRenderer: () => const MustacheTemplateRenderer(),
|
||||
BuildTargets: () => const BuildTargetsImpl(),
|
||||
Analytics: () => const NoOpAnalytics(),
|
||||
Stdio: () => FakeStdio(),
|
||||
},
|
||||
body: () {
|
||||
// To catch all errors thrown by the test, even uncaught async errors, we use a zone.
|
||||
//
|
||||
// Zones introduce their own event loop, so we do not await futures created inside
|
||||
// the zone from outside the zone. Instead, we create a Completer outside the zone,
|
||||
// and have the test complete it when the test ends (in success or failure), and we
|
||||
// await that.
|
||||
final Completer<void> completer = Completer<void>();
|
||||
runZonedGuarded<Future<dynamic>>(() async {
|
||||
try {
|
||||
return await context.run<dynamic>(
|
||||
// Apply the overrides to the test context in the zone since their
|
||||
// instantiation may reference items already stored on the context.
|
||||
overrides: overrides,
|
||||
name: 'test-specific overrides',
|
||||
body: () async {
|
||||
if (initializeFlutterRoot) {
|
||||
// Provide a sane default for the flutterRoot directory. Individual
|
||||
// tests can override this either in the test or during setup.
|
||||
Cache.flutterRoot ??= getFlutterRoot();
|
||||
PersistentToolState buildPersistentToolState(FileSystem fs) {
|
||||
configDir ??= globals.fs.systemTempDirectory.createTempSync('flutter_config_dir_test.');
|
||||
return PersistentToolState.test(directory: configDir!, logger: globals.logger);
|
||||
}
|
||||
|
||||
test(
|
||||
description,
|
||||
() async {
|
||||
await runInContext<dynamic>(
|
||||
() {
|
||||
return context.run<dynamic>(
|
||||
name: 'mocks',
|
||||
overrides: <Type, Generator>{
|
||||
AnsiTerminal: () => AnsiTerminal(platform: globals.platform, stdio: globals.stdio),
|
||||
Config: () => buildConfig(globals.fs),
|
||||
DeviceManager: () => FakeDeviceManager(),
|
||||
Doctor: () => FakeDoctor(globals.logger),
|
||||
FlutterVersion: () => FakeFlutterVersion(),
|
||||
HttpClient: () => FakeHttpClient.any(),
|
||||
IOSSimulatorUtils: () => const NoopIOSSimulatorUtils(),
|
||||
OutputPreferences: () => OutputPreferences.test(),
|
||||
Logger: () => BufferLogger.test(),
|
||||
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
|
||||
PersistentToolState: () => buildPersistentToolState(globals.fs),
|
||||
Usage: () => TestUsage(),
|
||||
XcodeProjectInterpreter: () => FakeXcodeProjectInterpreter(),
|
||||
FileSystem: () => LocalFileSystemBlockingSetCurrentDirectory(),
|
||||
PlistParser: () => FakePlistParser(),
|
||||
Signals: () => FakeSignals(),
|
||||
Pub: () => const ThrowingPub(), // prevent accidentally using pub.
|
||||
CrashReporter: () => const NoopCrashReporter(),
|
||||
TemplateRenderer: () => const MustacheTemplateRenderer(),
|
||||
BuildTargets: () => const BuildTargetsImpl(),
|
||||
Analytics: () => const NoOpAnalytics(),
|
||||
Stdio: () => FakeStdio(),
|
||||
},
|
||||
body: () {
|
||||
// To catch all errors thrown by the test, even uncaught async errors, we use a zone.
|
||||
//
|
||||
// Zones introduce their own event loop, so we do not await futures created inside
|
||||
// the zone from outside the zone. Instead, we create a Completer outside the zone,
|
||||
// and have the test complete it when the test ends (in success or failure), and we
|
||||
// await that.
|
||||
final Completer<void> completer = Completer<void>();
|
||||
runZonedGuarded<Future<dynamic>>(
|
||||
() async {
|
||||
try {
|
||||
return await context.run<dynamic>(
|
||||
// Apply the overrides to the test context in the zone since their
|
||||
// instantiation may reference items already stored on the context.
|
||||
overrides: overrides,
|
||||
name: 'test-specific overrides',
|
||||
body: () async {
|
||||
if (initializeFlutterRoot) {
|
||||
// Provide a sane default for the flutterRoot directory. Individual
|
||||
// tests can override this either in the test or during setup.
|
||||
Cache.flutterRoot ??= getFlutterRoot();
|
||||
}
|
||||
return await testMethod();
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
// We do not need a catch { ... } block because the error zone
|
||||
// will catch all errors and send them to the completer below.
|
||||
//
|
||||
// See https://github.com/flutter/flutter/pull/141821/files#r1462288131.
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete();
|
||||
}
|
||||
}
|
||||
return await testMethod();
|
||||
},
|
||||
(Object error, StackTrace stackTrace) {
|
||||
// When things fail, it's ok to print to the console!
|
||||
print(error); // ignore: avoid_print
|
||||
print(stackTrace); // ignore: avoid_print
|
||||
_printBufferedErrors(context);
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(error, stackTrace);
|
||||
}
|
||||
throw error; //ignore: only_throw_errors
|
||||
},
|
||||
);
|
||||
} finally {
|
||||
// We do not need a catch { ... } block because the error zone
|
||||
// will catch all errors and send them to the completer below.
|
||||
//
|
||||
// See https://github.com/flutter/flutter/pull/141821/files#r1462288131.
|
||||
if (!completer.isCompleted) {
|
||||
completer.complete();
|
||||
}
|
||||
}
|
||||
}, (Object error, StackTrace stackTrace) {
|
||||
// When things fail, it's ok to print to the console!
|
||||
print(error); // ignore: avoid_print
|
||||
print(stackTrace); // ignore: avoid_print
|
||||
_printBufferedErrors(context);
|
||||
if (!completer.isCompleted) {
|
||||
completer.completeError(error, stackTrace);
|
||||
}
|
||||
throw error; //ignore: only_throw_errors
|
||||
});
|
||||
return completer.future;
|
||||
return completer.future;
|
||||
},
|
||||
);
|
||||
},
|
||||
overrides: <Type, Generator>{
|
||||
// This has to go here so that runInContext will pick it up when it tries
|
||||
// to do bot detection before running the closure. This is important
|
||||
// because the test may be giving us a fake HttpClientFactory, which may
|
||||
// throw in unexpected/abnormal ways.
|
||||
// If a test needs a BotDetector that does not always return true, it
|
||||
// can provide the AlwaysFalseBotDetector in the overrides, or its own
|
||||
// BotDetector implementation in the overrides.
|
||||
BotDetector: overrides[BotDetector] ?? () => const FakeBotDetector(true),
|
||||
},
|
||||
);
|
||||
}, overrides: <Type, Generator>{
|
||||
// This has to go here so that runInContext will pick it up when it tries
|
||||
// to do bot detection before running the closure. This is important
|
||||
// because the test may be giving us a fake HttpClientFactory, which may
|
||||
// throw in unexpected/abnormal ways.
|
||||
// If a test needs a BotDetector that does not always return true, it
|
||||
// can provide the AlwaysFalseBotDetector in the overrides, or its own
|
||||
// BotDetector implementation in the overrides.
|
||||
BotDetector: overrides[BotDetector] ?? () => const FakeBotDetector(true),
|
||||
});
|
||||
}, testOn: testOn, skip: skip);
|
||||
},
|
||||
testOn: testOn,
|
||||
skip: skip,
|
||||
);
|
||||
// We don't support "timeout"; see ../../dart_test.yaml which
|
||||
// configures all tests to have a 15 minute timeout which should
|
||||
// definitely be enough.
|
||||
@@ -230,9 +236,8 @@ class FakeDeviceManager implements DeviceManager {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<List<Device>> getAllDevices({
|
||||
DeviceDiscoveryFilter? filter,
|
||||
}) async => filteredDevices(filter);
|
||||
Future<List<Device>> getAllDevices({DeviceDiscoveryFilter? filter}) async =>
|
||||
filteredDevices(filter);
|
||||
|
||||
@override
|
||||
Future<List<Device>> refreshAllDevices({
|
||||
@@ -309,8 +314,7 @@ class FakeAndroidLicenseValidator extends Fake implements AndroidLicenseValidato
|
||||
}
|
||||
|
||||
class FakeDoctor extends Doctor {
|
||||
FakeDoctor(Logger logger, {super.clock = const SystemClock()})
|
||||
: super(logger: logger);
|
||||
FakeDoctor(Logger logger, {super.clock = const SystemClock()}) : super(logger: logger);
|
||||
|
||||
// True for testing.
|
||||
@override
|
||||
@@ -369,23 +373,20 @@ class FakeXcodeProjectInterpreter implements XcodeProjectInterpreter {
|
||||
|
||||
@override
|
||||
Future<String> pluginsBuildSettingsOutput(
|
||||
Directory podXcodeProject, {
|
||||
Duration timeout = const Duration(minutes: 1),
|
||||
}) async {
|
||||
Directory podXcodeProject, {
|
||||
Duration timeout = const Duration(minutes: 1),
|
||||
}) async {
|
||||
return '';
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> cleanWorkspace(String workspacePath, String scheme, { bool verbose = false }) async { }
|
||||
Future<void> cleanWorkspace(String workspacePath, String scheme, {bool verbose = false}) async {}
|
||||
|
||||
@override
|
||||
Future<XcodeProjectInfo> getInfo(String projectPath, {String? projectFilename}) async {
|
||||
return XcodeProjectInfo(
|
||||
<String>['Runner'],
|
||||
<String>['Debug', 'Release'],
|
||||
<String>['Runner'],
|
||||
BufferLogger.test(),
|
||||
);
|
||||
return XcodeProjectInfo(<String>['Runner'], <String>['Debug', 'Release'], <String>[
|
||||
'Runner',
|
||||
], BufferLogger.test());
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -397,7 +398,7 @@ class NoopCrashReporter implements CrashReporter {
|
||||
const NoopCrashReporter();
|
||||
|
||||
@override
|
||||
Future<void> informUser(CrashDetails details, File crashFile) async { }
|
||||
Future<void> informUser(CrashDetails details, File crashFile) async {}
|
||||
}
|
||||
|
||||
class LocalFileSystemBlockingSetCurrentDirectory extends LocalFileSystem {
|
||||
@@ -407,10 +408,12 @@ class LocalFileSystemBlockingSetCurrentDirectory extends LocalFileSystem {
|
||||
|
||||
@override
|
||||
set currentDirectory(dynamic value) {
|
||||
throw Exception('globals.fs.currentDirectory should not be set on the local file system during '
|
||||
'tests as this can cause race conditions with concurrent tests. '
|
||||
'Consider using a MemoryFileSystem for testing if possible or refactor '
|
||||
'code to not require setting globals.fs.currentDirectory.');
|
||||
throw Exception(
|
||||
'globals.fs.currentDirectory should not be set on the local file system during '
|
||||
'tests as this can cause race conditions with concurrent tests. '
|
||||
'Consider using a MemoryFileSystem for testing if possible or refactor '
|
||||
'code to not require setting globals.fs.currentDirectory.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,18 +9,19 @@ import 'package:flutter_tools/src/custom_devices/custom_device_config.dart';
|
||||
void writeCustomDevicesConfigFile(
|
||||
Directory dir, {
|
||||
List<CustomDeviceConfig>? configs,
|
||||
dynamic json
|
||||
dynamic json,
|
||||
}) {
|
||||
dir.createSync(recursive: true);
|
||||
|
||||
final File file = dir.childFile('.flutter_custom_devices.json');
|
||||
file.writeAsStringSync(jsonEncode(
|
||||
<String, dynamic>{
|
||||
'custom-devices': configs != null ?
|
||||
configs.map<dynamic>((CustomDeviceConfig c) => c.toJson()).toList() :
|
||||
json,
|
||||
},
|
||||
));
|
||||
file.writeAsStringSync(
|
||||
jsonEncode(<String, dynamic>{
|
||||
'custom-devices':
|
||||
configs != null
|
||||
? configs.map<dynamic>((CustomDeviceConfig c) => c.toJson()).toList()
|
||||
: json,
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
final CustomDeviceConfig testConfig = CustomDeviceConfig(
|
||||
@@ -35,7 +36,7 @@ final CustomDeviceConfig testConfig = CustomDeviceConfig(
|
||||
uninstallCommand: const <String>['testuninstall'],
|
||||
runDebugCommand: const <String>['testrundebug'],
|
||||
forwardPortCommand: const <String>['testforwardport'],
|
||||
forwardPortSuccessRegex: RegExp('testforwardportsuccess')
|
||||
forwardPortSuccessRegex: RegExp('testforwardportsuccess'),
|
||||
);
|
||||
|
||||
const Map<String, dynamic> testConfigJson = <String, dynamic>{
|
||||
|
||||
@@ -33,13 +33,13 @@ List<FakeDeviceJsonData> fakeDevices = <FakeDeviceJsonData>[
|
||||
'hardwareRendering': true,
|
||||
'startPaused': true,
|
||||
},
|
||||
}
|
||||
},
|
||||
),
|
||||
FakeDeviceJsonData(
|
||||
FakeDevice('webby', 'webby')
|
||||
..targetPlatform = Future<TargetPlatform>.value(TargetPlatform.web_javascript)
|
||||
..sdkNameAndVersion = Future<String>.value('Web SDK (1.2.4)'),
|
||||
<String,Object>{
|
||||
<String, Object>{
|
||||
'name': 'webby',
|
||||
'id': 'webby',
|
||||
'isSupported': true,
|
||||
@@ -80,18 +80,18 @@ List<FakeDeviceJsonData> fakeDevices = <FakeDeviceJsonData>[
|
||||
'hardwareRendering': true,
|
||||
'startPaused': true,
|
||||
},
|
||||
}
|
||||
},
|
||||
),
|
||||
FakeDeviceJsonData(
|
||||
FakeDevice(
|
||||
'wireless ios',
|
||||
'wireless-ios',
|
||||
type:PlatformType.ios,
|
||||
connectionInterface: DeviceConnectionInterface.wireless,
|
||||
)
|
||||
'wireless ios',
|
||||
'wireless-ios',
|
||||
type: PlatformType.ios,
|
||||
connectionInterface: DeviceConnectionInterface.wireless,
|
||||
)
|
||||
..targetPlatform = Future<TargetPlatform>.value(TargetPlatform.ios)
|
||||
..sdkNameAndVersion = Future<String>.value('iOS 16'),
|
||||
<String,Object>{
|
||||
<String, Object>{
|
||||
'name': 'wireless ios',
|
||||
'id': 'wireless-ios',
|
||||
'isSupported': true,
|
||||
@@ -113,7 +113,9 @@ List<FakeDeviceJsonData> fakeDevices = <FakeDeviceJsonData>[
|
||||
|
||||
/// Fake device to test `devices` command.
|
||||
class FakeDevice extends Device {
|
||||
FakeDevice(this.name, String id, {
|
||||
FakeDevice(
|
||||
this.name,
|
||||
String id, {
|
||||
bool ephemeral = true,
|
||||
bool isSupported = true,
|
||||
bool isSupportedForProject = true,
|
||||
@@ -124,16 +126,16 @@ class FakeDevice extends Device {
|
||||
this.deviceLogReader,
|
||||
bool supportsFlavors = false,
|
||||
}) : _isSupported = isSupported,
|
||||
_isSupportedForProject = isSupportedForProject,
|
||||
_launchResult = launchResult ?? LaunchResult.succeeded(),
|
||||
_supportsFlavors = supportsFlavors,
|
||||
super(
|
||||
id,
|
||||
platformType: type,
|
||||
category: Category.mobile,
|
||||
ephemeral: ephemeral,
|
||||
logger: FakeLogger(),
|
||||
);
|
||||
_isSupportedForProject = isSupportedForProject,
|
||||
_launchResult = launchResult ?? LaunchResult.succeeded(),
|
||||
_supportsFlavors = supportsFlavors,
|
||||
super(
|
||||
id,
|
||||
platformType: type,
|
||||
category: Category.mobile,
|
||||
ephemeral: ephemeral,
|
||||
logger: FakeLogger(),
|
||||
);
|
||||
|
||||
final bool _isSupported;
|
||||
final bool _isSupportedForProject;
|
||||
@@ -145,7 +147,8 @@ class FakeDevice extends Device {
|
||||
final String name;
|
||||
|
||||
@override
|
||||
Future<LaunchResult> startApp(ApplicationPackage? package, {
|
||||
Future<LaunchResult> startApp(
|
||||
ApplicationPackage? package, {
|
||||
String? mainPath,
|
||||
String? route,
|
||||
DebuggingOptions? debuggingOptions,
|
||||
@@ -156,15 +159,10 @@ class FakeDevice extends Device {
|
||||
}) async => _launchResult;
|
||||
|
||||
@override
|
||||
Future<bool> stopApp(ApplicationPackage? app, {
|
||||
String? userIdentifier,
|
||||
}) async => true;
|
||||
Future<bool> stopApp(ApplicationPackage? app, {String? userIdentifier}) async => true;
|
||||
|
||||
@override
|
||||
Future<bool> uninstallApp(
|
||||
ApplicationPackage app, {
|
||||
String? userIdentifier,
|
||||
}) async => true;
|
||||
Future<bool> uninstallApp(ApplicationPackage app, {String? userIdentifier}) async => true;
|
||||
|
||||
@override
|
||||
Future<void> dispose() async {}
|
||||
@@ -197,10 +195,8 @@ class FakeDevice extends Device {
|
||||
Future<String> sdkNameAndVersion = Future<String>.value('Test SDK (1.2.3)');
|
||||
|
||||
@override
|
||||
FutureOr<DeviceLogReader> getLogReader({
|
||||
ApplicationPackage? app,
|
||||
bool includePastLogs = false,
|
||||
}) => deviceLogReader ?? FakeDeviceLogReader();
|
||||
FutureOr<DeviceLogReader> getLogReader({ApplicationPackage? app, bool includePastLogs = false}) =>
|
||||
deviceLogReader ?? FakeDeviceLogReader();
|
||||
}
|
||||
|
||||
/// Combines fake device with its canonical JSON representation.
|
||||
@@ -212,16 +208,15 @@ class FakeDeviceJsonData {
|
||||
}
|
||||
|
||||
class FakePollingDeviceDiscovery extends PollingDeviceDiscovery {
|
||||
FakePollingDeviceDiscovery({
|
||||
this.requiresExtendedWirelessDeviceDiscovery = false,
|
||||
}) : super('mock');
|
||||
FakePollingDeviceDiscovery({this.requiresExtendedWirelessDeviceDiscovery = false})
|
||||
: super('mock');
|
||||
|
||||
final List<Device> _devices = <Device>[];
|
||||
final StreamController<Device> _onAddedController = StreamController<Device>.broadcast();
|
||||
final StreamController<Device> _onRemovedController = StreamController<Device>.broadcast();
|
||||
|
||||
@override
|
||||
Future<List<Device>> pollingGetDevices({ Duration? timeout }) async {
|
||||
Future<List<Device>> pollingGetDevices({Duration? timeout}) async {
|
||||
lastPollingTimeout = timeout;
|
||||
return _devices;
|
||||
}
|
||||
@@ -257,10 +252,7 @@ class FakePollingDeviceDiscovery extends PollingDeviceDiscovery {
|
||||
bool discoverDevicesCalled = false;
|
||||
|
||||
@override
|
||||
Future<List<Device>> discoverDevices({
|
||||
Duration? timeout,
|
||||
DeviceDiscoveryFilter? filter,
|
||||
}) {
|
||||
Future<List<Device>> discoverDevices({Duration? timeout, DeviceDiscoveryFilter? filter}) {
|
||||
discoverDevicesCalled = true;
|
||||
return super.discoverDevices(timeout: timeout);
|
||||
}
|
||||
@@ -288,12 +280,12 @@ class FakeDeviceLogReader extends DeviceLogReader {
|
||||
bool disposed = false;
|
||||
|
||||
final List<String> _lineQueue = <String>[];
|
||||
late final StreamController<String> _linesController =
|
||||
StreamController<String>
|
||||
.broadcast(onListen: () {
|
||||
late final StreamController<String> _linesController = StreamController<String>.broadcast(
|
||||
onListen: () {
|
||||
_lineQueue.forEach(_linesController.add);
|
||||
_lineQueue.clear();
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
@override
|
||||
Stream<String> get logLines => _linesController.stream;
|
||||
@@ -314,5 +306,5 @@ class FakeDeviceLogReader extends DeviceLogReader {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> provideVmService(FlutterVmService? connectedVmService) async { }
|
||||
Future<void> provideVmService(FlutterVmService? connectedVmService) async {}
|
||||
}
|
||||
|
||||
@@ -10,23 +10,16 @@ import 'dart:io';
|
||||
import 'package:collection/collection.dart';
|
||||
|
||||
/// The HTTP verb for a [FakeRequest].
|
||||
enum HttpMethod {
|
||||
get,
|
||||
put,
|
||||
delete,
|
||||
post,
|
||||
patch,
|
||||
head,
|
||||
}
|
||||
enum HttpMethod { get, put, delete, post, patch, head }
|
||||
|
||||
HttpMethod _fromMethodString(String value) {
|
||||
return switch (value.toLowerCase()) {
|
||||
'get' => HttpMethod.get,
|
||||
'put' => HttpMethod.put,
|
||||
'get' => HttpMethod.get,
|
||||
'put' => HttpMethod.put,
|
||||
'delete' => HttpMethod.delete,
|
||||
'post' => HttpMethod.post,
|
||||
'patch' => HttpMethod.patch,
|
||||
'head' => HttpMethod.head,
|
||||
'post' => HttpMethod.post,
|
||||
'patch' => HttpMethod.patch,
|
||||
'head' => HttpMethod.head,
|
||||
_ => throw StateError('Unrecognized HTTP method $value'),
|
||||
};
|
||||
}
|
||||
@@ -38,7 +31,7 @@ String _toMethodString(HttpMethod method) {
|
||||
HttpMethod.delete => 'DELETE',
|
||||
HttpMethod.post => 'POST',
|
||||
HttpMethod.patch => 'PATCH',
|
||||
HttpMethod.head => 'HEAD'
|
||||
HttpMethod.head => 'HEAD',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -49,7 +42,8 @@ String _toMethodString(HttpMethod method) {
|
||||
/// empty response. If [responseError] is non-null, will throw this instead
|
||||
/// of returning the response when closing the request.
|
||||
class FakeRequest {
|
||||
const FakeRequest(this.uri, {
|
||||
const FakeRequest(
|
||||
this.uri, {
|
||||
this.method = HttpMethod.get,
|
||||
this.response = FakeResponse.empty,
|
||||
this.responseError,
|
||||
@@ -92,8 +86,7 @@ class FakeHttpClient implements HttpClient {
|
||||
///
|
||||
/// This does not enforce any order on the requests, but if multiple
|
||||
/// requests match then the first will be selected;
|
||||
FakeHttpClient.list(List<FakeRequest> requests)
|
||||
: _requests = requests.toList();
|
||||
FakeHttpClient.list(List<FakeRequest> requests) : _requests = requests.toList();
|
||||
|
||||
/// Creates an HTTP client that always returns an empty 200 request.
|
||||
FakeHttpClient.any() : _any = true, _requests = <FakeRequest>[];
|
||||
@@ -127,7 +120,8 @@ class FakeHttpClient implements HttpClient {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<ConnectionTask<Socket>> Function(Uri url, String? proxyHost, int? proxyPort)? connectionFactory;
|
||||
Future<ConnectionTask<Socket>> Function(Uri url, String? proxyHost, int? proxyPort)?
|
||||
connectionFactory;
|
||||
|
||||
@override
|
||||
Future<bool> Function(Uri url, String scheme, String realm)? authenticate;
|
||||
@@ -142,7 +136,7 @@ class FakeHttpClient implements HttpClient {
|
||||
void Function(String line)? keyLog;
|
||||
|
||||
@override
|
||||
void close({bool force = false}) { }
|
||||
void close({bool force = false}) {}
|
||||
|
||||
@override
|
||||
Future<HttpClientRequest> delete(String host, int port, String path) {
|
||||
@@ -235,14 +229,7 @@ class FakeHttpClient implements HttpClient {
|
||||
}
|
||||
final String methodString = _toMethodString(method);
|
||||
if (_any) {
|
||||
return _FakeHttpClientRequest(
|
||||
FakeResponse.empty,
|
||||
uri,
|
||||
methodString,
|
||||
null,
|
||||
null,
|
||||
stackTrace,
|
||||
);
|
||||
return _FakeHttpClientRequest(FakeResponse.empty, uri, methodString, null, null, stackTrace);
|
||||
}
|
||||
FakeRequest? matchedRequest;
|
||||
for (final FakeRequest request in _requests) {
|
||||
@@ -254,7 +241,7 @@ class FakeHttpClient implements HttpClient {
|
||||
if (matchedRequest == null) {
|
||||
throw StateError(
|
||||
'Unexpected request for $method to $uri after $_requestCount requests.\n'
|
||||
'Pending requests: ${_requests.join(',')}'
|
||||
'Pending requests: ${_requests.join(',')}',
|
||||
);
|
||||
}
|
||||
_requestCount += 1;
|
||||
@@ -271,7 +258,14 @@ class FakeHttpClient implements HttpClient {
|
||||
}
|
||||
|
||||
class _FakeHttpClientRequest implements HttpClientRequest {
|
||||
_FakeHttpClientRequest(this._response, this._uri, this._method, this._responseError, this._expectedBody, this._stackTrace);
|
||||
_FakeHttpClientRequest(
|
||||
this._response,
|
||||
this._uri,
|
||||
this._method,
|
||||
this._responseError,
|
||||
this._expectedBody,
|
||||
this._stackTrace,
|
||||
);
|
||||
|
||||
final FakeResponse _response;
|
||||
final String _method;
|
||||
@@ -310,7 +304,7 @@ class _FakeHttpClientRequest implements HttpClientRequest {
|
||||
}
|
||||
|
||||
@override
|
||||
void addError(Object error, [StackTrace? stackTrace]) { }
|
||||
void addError(Object error, [StackTrace? stackTrace]) {}
|
||||
|
||||
@override
|
||||
Future<void> addStream(Stream<List<int>> stream) async {
|
||||
@@ -324,9 +318,12 @@ class _FakeHttpClientRequest implements HttpClientRequest {
|
||||
final Completer<void> completer = Completer<void>();
|
||||
Timer.run(() {
|
||||
if (_expectedBody != null && !const ListEquality<int>().equals(_expectedBody, _body)) {
|
||||
completer.completeError(StateError(
|
||||
'Expected a request with the following body:\n$_expectedBody\n but found:\n$_body'
|
||||
), _stackTrace);
|
||||
completer.completeError(
|
||||
StateError(
|
||||
'Expected a request with the following body:\n$_expectedBody\n but found:\n$_body',
|
||||
),
|
||||
_stackTrace,
|
||||
);
|
||||
} else {
|
||||
completer.complete();
|
||||
}
|
||||
@@ -348,7 +345,7 @@ class _FakeHttpClientRequest implements HttpClientRequest {
|
||||
Future<HttpClientResponse> get done => throw UnimplementedError();
|
||||
|
||||
@override
|
||||
Future<void> flush() async { }
|
||||
Future<void> flush() async {}
|
||||
|
||||
@override
|
||||
final HttpHeaders headers = _FakeHttpHeaders(<String, List<String>>{});
|
||||
@@ -382,7 +379,7 @@ class _FakeHttpClientRequest implements HttpClientRequest {
|
||||
|
||||
class _FakeHttpClientResponse extends Stream<List<int>> implements HttpClientResponse {
|
||||
_FakeHttpClientResponse(this._response)
|
||||
: headers = _FakeHttpHeaders(Map<String, List<String>>.from(_response.headers));
|
||||
: headers = _FakeHttpHeaders(Map<String, List<String>>.from(_response.headers));
|
||||
|
||||
final FakeResponse _response;
|
||||
|
||||
@@ -419,9 +416,7 @@ class _FakeHttpClientResponse extends Stream<List<int>> implements HttpClientRes
|
||||
void Function()? onDone,
|
||||
bool? cancelOnError,
|
||||
}) {
|
||||
final Stream<List<int>> response = Stream<List<int>>.fromIterable(<List<int>>[
|
||||
_response.body,
|
||||
]);
|
||||
final Stream<List<int>> response = Stream<List<int>>.fromIterable(<List<int>>[_response.body]);
|
||||
return response.listen(onData, onError: onError, onDone: onDone, cancelOnError: cancelOnError);
|
||||
}
|
||||
|
||||
@@ -478,13 +473,13 @@ class _FakeHttpHeaders implements HttpHeaders {
|
||||
DateTime? expires;
|
||||
|
||||
@override
|
||||
void forEach(void Function(String name, List<String> values) action) { }
|
||||
void forEach(void Function(String name, List<String> values) action) {}
|
||||
|
||||
@override
|
||||
String? host;
|
||||
|
||||
@override
|
||||
void noFolding(String name) { }
|
||||
void noFolding(String name) {}
|
||||
|
||||
@override
|
||||
void remove(String name, Object value) {
|
||||
|
||||
@@ -118,7 +118,8 @@ class FakeCommand {
|
||||
Encoding? encoding,
|
||||
io.ProcessStartMode? mode,
|
||||
) {
|
||||
final List<dynamic> matchers = this.command.map((Pattern x) => x is String ? x : matches(x)).toList();
|
||||
final List<dynamic> matchers =
|
||||
this.command.map((Pattern x) => x is String ? x : matches(x)).toList();
|
||||
expect(command, matchers);
|
||||
if (processStartMode != null) {
|
||||
expect(mode, processStartMode);
|
||||
@@ -160,25 +161,27 @@ class FakeProcess implements io.Process {
|
||||
}
|
||||
return exitCode;
|
||||
}),
|
||||
_stderr = stderr,
|
||||
stdin = stdin ??
|
||||
IOSink(
|
||||
StreamController<List<int>>()
|
||||
..stream.listen((_) {})
|
||||
..sink,
|
||||
),
|
||||
_stdout = stdout,
|
||||
_completer = completer
|
||||
{
|
||||
_stderr = stderr,
|
||||
stdin =
|
||||
stdin ??
|
||||
IOSink(
|
||||
StreamController<List<int>>()
|
||||
..stream.listen((_) {})
|
||||
..sink,
|
||||
),
|
||||
_stdout = stdout,
|
||||
_completer = completer {
|
||||
if (_stderr.isEmpty) {
|
||||
this.stderr = const Stream<List<int>>.empty();
|
||||
} else if (outputFollowsExit) {
|
||||
// Wait for the process to exit before emitting stderr.
|
||||
this.stderr = Stream<List<int>>.fromFuture(this.exitCode.then((_) {
|
||||
// Return a Future so stderr isn't immediately available to those who
|
||||
// await exitCode, but is available asynchronously later.
|
||||
return Future<List<int>>(() => _stderr);
|
||||
}));
|
||||
this.stderr = Stream<List<int>>.fromFuture(
|
||||
this.exitCode.then((_) {
|
||||
// Return a Future so stderr isn't immediately available to those who
|
||||
// await exitCode, but is available asynchronously later.
|
||||
return Future<List<int>>(() => _stderr);
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
this.stderr = Stream<List<int>>.value(_stderr);
|
||||
}
|
||||
@@ -187,11 +190,13 @@ class FakeProcess implements io.Process {
|
||||
this.stdout = const Stream<List<int>>.empty();
|
||||
} else if (outputFollowsExit) {
|
||||
// Wait for the process to exit before emitting stdout.
|
||||
this.stdout = Stream<List<int>>.fromFuture(this.exitCode.then((_) {
|
||||
// Return a Future so stdout isn't immediately available to those who
|
||||
// await exitCode, but is available asynchronously later.
|
||||
return Future<List<int>>(() => _stdout);
|
||||
}));
|
||||
this.stdout = Stream<List<int>>.fromFuture(
|
||||
this.exitCode.then((_) {
|
||||
// Return a Future so stdout isn't immediately available to those who
|
||||
// await exitCode, but is available asynchronously later.
|
||||
return Future<List<int>>(() => _stdout);
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
this.stdout = Stream<List<int>>.value(_stdout);
|
||||
}
|
||||
@@ -407,7 +412,8 @@ abstract class FakeProcessManager implements ProcessManager {
|
||||
|
||||
/// Returns false if executable in [excludedExecutables].
|
||||
@override
|
||||
bool canRun(dynamic executable, {String? workingDirectory}) => !excludedExecutables.contains(executable);
|
||||
bool canRun(dynamic executable, {String? workingDirectory}) =>
|
||||
!excludedExecutables.contains(executable);
|
||||
|
||||
Set<String> excludedExecutables = <String>{};
|
||||
|
||||
@@ -447,7 +453,7 @@ class _FakeAnyProcessManager extends FakeProcessManager {
|
||||
}
|
||||
|
||||
@override
|
||||
void addCommand(FakeCommand command) { }
|
||||
void addCommand(FakeCommand command) {}
|
||||
|
||||
@override
|
||||
bool get hasRemainingExpectations => true;
|
||||
@@ -469,9 +475,12 @@ class _SequenceProcessManager extends FakeProcessManager {
|
||||
Encoding? encoding,
|
||||
io.ProcessStartMode? mode,
|
||||
) {
|
||||
expect(_commands, isNotEmpty,
|
||||
reason: 'ProcessManager was told to execute $command (in $workingDirectory) '
|
||||
'but the FakeProcessManager.list expected no more processes.'
|
||||
expect(
|
||||
_commands,
|
||||
isNotEmpty,
|
||||
reason:
|
||||
'ProcessManager was told to execute $command (in $workingDirectory) '
|
||||
'but the FakeProcessManager.list expected no more processes.',
|
||||
);
|
||||
_commands.first._matches(command, workingDirectory, environment, encoding, mode);
|
||||
return _commands.removeAt(0);
|
||||
@@ -506,13 +515,14 @@ class _HasNoRemainingExpectations extends Matcher {
|
||||
|
||||
@override
|
||||
Description describeMismatch(
|
||||
dynamic item,
|
||||
Description description,
|
||||
Map<dynamic, dynamic> matchState,
|
||||
bool verbose,
|
||||
) {
|
||||
dynamic item,
|
||||
Description description,
|
||||
Map<dynamic, dynamic> matchState,
|
||||
bool verbose,
|
||||
) {
|
||||
final FakeProcessManager fakeProcessManager = item as FakeProcessManager;
|
||||
return description.add(
|
||||
'has remaining expectations:\n${fakeProcessManager._remainingExpectations.map((FakeCommand command) => command.command).join('\n')}');
|
||||
'has remaining expectations:\n${fakeProcessManager._remainingExpectations.map((FakeCommand command) => command.command).join('\n')}',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -26,17 +26,10 @@ final class FakePubWithPrimedDeps implements Pub {
|
||||
<String, Object?>{
|
||||
'name': rootPackageName,
|
||||
'kind': 'root',
|
||||
'dependencies': <String>[
|
||||
...dependencies.keys,
|
||||
...devDependencies,
|
||||
]..sort(),
|
||||
'directDependencies': <String>[
|
||||
...?dependencies[rootPackageName],
|
||||
...devDependencies,
|
||||
]..sort(),
|
||||
'devDependencies': <String>[
|
||||
...devDependencies,
|
||||
],
|
||||
'dependencies': <String>[...dependencies.keys, ...devDependencies]..sort(),
|
||||
'directDependencies': <String>[...?dependencies[rootPackageName], ...devDependencies]
|
||||
..sort(),
|
||||
'devDependencies': <String>[...devDependencies],
|
||||
},
|
||||
];
|
||||
|
||||
@@ -46,12 +39,8 @@ final class FakePubWithPrimedDeps implements Pub {
|
||||
packages.add(<String, Object?>{
|
||||
'name': packageName,
|
||||
'kind': direct ? 'direct' : 'transitive',
|
||||
'dependencies': <String>[
|
||||
...?dependencies[packageName],
|
||||
],
|
||||
'directDependencies': <String>[
|
||||
...?dependencies[packageName],
|
||||
],
|
||||
'dependencies': <String>[...?dependencies[packageName]],
|
||||
'directDependencies': <String>[...?dependencies[packageName]],
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -19,10 +19,11 @@ class FakeVmServiceHost {
|
||||
Uri? httpAddress,
|
||||
Uri? wsAddress,
|
||||
}) : _requests = requests {
|
||||
_vmService = FlutterVmService(vm_service.VmService(
|
||||
_input.stream,
|
||||
_output.add,
|
||||
), httpAddress: httpAddress, wsAddress: wsAddress);
|
||||
_vmService = FlutterVmService(
|
||||
vm_service.VmService(_input.stream, _output.add),
|
||||
httpAddress: httpAddress,
|
||||
wsAddress: wsAddress,
|
||||
);
|
||||
_applyStreamListen();
|
||||
_output.stream.listen((String data) {
|
||||
final Map<String, Object?> request = json.decode(data) as Map<String, Object?>;
|
||||
@@ -30,9 +31,15 @@ class FakeVmServiceHost {
|
||||
throw Exception('Unexpected request: $request');
|
||||
}
|
||||
final FakeVmServiceRequest fakeRequest = _requests.removeAt(0) as FakeVmServiceRequest;
|
||||
expect(request, isA<Map<String, Object?>>()
|
||||
.having((Map<String, Object?> request) => request['method'], 'method', fakeRequest.method)
|
||||
.having((Map<String, Object?> request) => request['params'], 'args', fakeRequest.args)
|
||||
expect(
|
||||
request,
|
||||
isA<Map<String, Object?>>()
|
||||
.having(
|
||||
(Map<String, Object?> request) => request['method'],
|
||||
'method',
|
||||
fakeRequest.method,
|
||||
)
|
||||
.having((Map<String, Object?> request) => request['params'], 'args', fakeRequest.args),
|
||||
);
|
||||
if (fakeRequest.close) {
|
||||
unawaited(_vmService.dispose());
|
||||
@@ -40,20 +47,24 @@ class FakeVmServiceHost {
|
||||
return;
|
||||
}
|
||||
if (fakeRequest.error == null) {
|
||||
_input.add(json.encode(<String, Object?>{
|
||||
'jsonrpc': '2.0',
|
||||
'id': request['id'],
|
||||
'result': fakeRequest.jsonResponse ?? <String, Object>{'type': 'Success'},
|
||||
}));
|
||||
_input.add(
|
||||
json.encode(<String, Object?>{
|
||||
'jsonrpc': '2.0',
|
||||
'id': request['id'],
|
||||
'result': fakeRequest.jsonResponse ?? <String, Object>{'type': 'Success'},
|
||||
}),
|
||||
);
|
||||
} else {
|
||||
_input.add(json.encode(<String, Object?>{
|
||||
'jsonrpc': '2.0',
|
||||
'id': request['id'],
|
||||
'error': <String, Object?>{
|
||||
'code': fakeRequest.error!.code,
|
||||
'message': fakeRequest.error!.error,
|
||||
},
|
||||
}));
|
||||
_input.add(
|
||||
json.encode(<String, Object?>{
|
||||
'jsonrpc': '2.0',
|
||||
'id': request['id'],
|
||||
'error': <String, Object?>{
|
||||
'code': fakeRequest.error!.code,
|
||||
'message': fakeRequest.error!.error,
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
_applyStreamListen();
|
||||
});
|
||||
@@ -66,22 +77,24 @@ class FakeVmServiceHost {
|
||||
FlutterVmService get vmService => _vmService;
|
||||
late final FlutterVmService _vmService;
|
||||
|
||||
|
||||
bool get hasRemainingExpectations => _requests.isNotEmpty;
|
||||
|
||||
// remove FakeStreamResponse objects from _requests until it is empty
|
||||
// or until we hit a FakeRequest
|
||||
void _applyStreamListen() {
|
||||
while (_requests.isNotEmpty && !_requests.first.isRequest) {
|
||||
final FakeVmServiceStreamResponse response = _requests.removeAt(0) as FakeVmServiceStreamResponse;
|
||||
_input.add(json.encode(<String, Object>{
|
||||
'jsonrpc': '2.0',
|
||||
'method': 'streamNotify',
|
||||
'params': <String, Object>{
|
||||
'streamId': response.streamId,
|
||||
'event': response.event.toJson(),
|
||||
},
|
||||
}));
|
||||
final FakeVmServiceStreamResponse response =
|
||||
_requests.removeAt(0) as FakeVmServiceStreamResponse;
|
||||
_input.add(
|
||||
json.encode(<String, Object>{
|
||||
'jsonrpc': '2.0',
|
||||
'method': 'streamNotify',
|
||||
'params': <String, Object>{
|
||||
'streamId': response.streamId,
|
||||
'event': response.event.toJson(),
|
||||
},
|
||||
}),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -91,10 +104,7 @@ abstract class VmServiceExpectation {
|
||||
}
|
||||
|
||||
class FakeRPCError {
|
||||
const FakeRPCError({
|
||||
required this.code,
|
||||
this.error = 'error',
|
||||
});
|
||||
const FakeRPCError({required this.code, this.error = 'error'});
|
||||
|
||||
final int code;
|
||||
final String error;
|
||||
@@ -125,10 +135,7 @@ class FakeVmServiceRequest implements VmServiceExpectation {
|
||||
}
|
||||
|
||||
class FakeVmServiceStreamResponse implements VmServiceExpectation {
|
||||
const FakeVmServiceStreamResponse({
|
||||
required this.event,
|
||||
required this.streamId,
|
||||
});
|
||||
const FakeVmServiceStreamResponse({required this.event, required this.streamId});
|
||||
|
||||
final vm_service.Event event;
|
||||
final String streamId;
|
||||
|
||||
@@ -40,8 +40,13 @@ class FakeDyldEnvironmentArtifact extends ArtifactSet {
|
||||
String get name => 'fake';
|
||||
|
||||
@override
|
||||
Future<void> update(ArtifactUpdater artifactUpdater, Logger logger, FileSystem fileSystem, OperatingSystemUtils operatingSystemUtils, {bool offline = false}) async {
|
||||
}
|
||||
Future<void> update(
|
||||
ArtifactUpdater artifactUpdater,
|
||||
Logger logger,
|
||||
FileSystem fileSystem,
|
||||
OperatingSystemUtils operatingSystemUtils, {
|
||||
bool offline = false,
|
||||
}) async {}
|
||||
}
|
||||
|
||||
/// A fake process implementation which can be provided all necessary values.
|
||||
@@ -78,9 +83,7 @@ class FakeProcess implements Process {
|
||||
|
||||
/// An IOSink that completes a future with the first line written to it.
|
||||
class CompleterIOSink extends MemoryIOSink {
|
||||
CompleterIOSink({
|
||||
this.throwOnAdd = false,
|
||||
});
|
||||
CompleterIOSink({this.throwOnAdd = false});
|
||||
|
||||
final bool throwOnAdd;
|
||||
|
||||
@@ -122,8 +125,9 @@ class MemoryIOSink implements IOSink {
|
||||
(List<int> data) {
|
||||
try {
|
||||
add(data);
|
||||
// Catches all exceptions to propagate them to the completer.
|
||||
} catch (err, stack) { // ignore: avoid_catches_without_on_clauses
|
||||
// Catches all exceptions to propagate them to the completer.
|
||||
} catch (err, stack) {
|
||||
// ignore: avoid_catches_without_on_clauses
|
||||
sub.cancel();
|
||||
completer.completeError(err, stack);
|
||||
}
|
||||
@@ -146,12 +150,12 @@ class MemoryIOSink implements IOSink {
|
||||
}
|
||||
|
||||
@override
|
||||
void writeln([ Object? obj = '' ]) {
|
||||
void writeln([Object? obj = '']) {
|
||||
add(encoding.encode('$obj\n'));
|
||||
}
|
||||
|
||||
@override
|
||||
void writeAll(Iterable<dynamic> objects, [ String separator = '' ]) {
|
||||
void writeAll(Iterable<dynamic> objects, [String separator = '']) {
|
||||
bool addSeparator = false;
|
||||
for (final dynamic object in objects) {
|
||||
if (addSeparator) {
|
||||
@@ -163,7 +167,7 @@ class MemoryIOSink implements IOSink {
|
||||
}
|
||||
|
||||
@override
|
||||
void addError(dynamic error, [ StackTrace? stackTrace ]) {
|
||||
void addError(dynamic error, [StackTrace? stackTrace]) {
|
||||
throw UnimplementedError();
|
||||
}
|
||||
|
||||
@@ -171,10 +175,10 @@ class MemoryIOSink implements IOSink {
|
||||
Future<void> get done => close();
|
||||
|
||||
@override
|
||||
Future<void> close() async { }
|
||||
Future<void> close() async {}
|
||||
|
||||
@override
|
||||
Future<void> flush() async { }
|
||||
Future<void> flush() async {}
|
||||
|
||||
void clear() {
|
||||
writes.clear();
|
||||
@@ -193,6 +197,7 @@ class MemoryStdout extends MemoryIOSink implements io.Stdout {
|
||||
set hasTerminal(bool value) {
|
||||
_hasTerminal = value;
|
||||
}
|
||||
|
||||
bool _hasTerminal = true;
|
||||
|
||||
@override
|
||||
@@ -212,6 +217,7 @@ class MemoryStdout extends MemoryIOSink implements io.Stdout {
|
||||
set supportsAnsiEscapes(bool value) {
|
||||
_supportsAnsiEscapes = value;
|
||||
}
|
||||
|
||||
bool _supportsAnsiEscapes = true;
|
||||
|
||||
@override
|
||||
@@ -221,6 +227,7 @@ class MemoryStdout extends MemoryIOSink implements io.Stdout {
|
||||
}
|
||||
throw const io.StdoutException('unspecified mock value');
|
||||
}
|
||||
|
||||
set terminalColumns(int value) => _terminalColumns = value;
|
||||
int? _terminalColumns;
|
||||
|
||||
@@ -231,6 +238,7 @@ class MemoryStdout extends MemoryIOSink implements io.Stdout {
|
||||
}
|
||||
throw const io.StdoutException('unspecified mock value');
|
||||
}
|
||||
|
||||
set terminalLines(int value) => _terminalLines = value;
|
||||
int? _terminalLines;
|
||||
}
|
||||
@@ -307,8 +315,8 @@ class FakeStdin extends Fake implements Stdin {
|
||||
}
|
||||
|
||||
class FakePlistParser implements PlistParser {
|
||||
FakePlistParser([Map<String, Object>? underlyingValues]):
|
||||
_underlyingValues = underlyingValues ?? <String, Object>{};
|
||||
FakePlistParser([Map<String, Object>? underlyingValues])
|
||||
: _underlyingValues = underlyingValues ?? <String, Object>{};
|
||||
|
||||
final Map<String, Object> _underlyingValues;
|
||||
|
||||
@@ -346,8 +354,7 @@ class FakePlistParser implements PlistParser {
|
||||
}
|
||||
|
||||
class FakeBotDetector implements BotDetector {
|
||||
const FakeBotDetector(bool isRunningOnBot)
|
||||
: _isRunningOnBot = isRunningOnBot;
|
||||
const FakeBotDetector(bool isRunningOnBot) : _isRunningOnBot = isRunningOnBot;
|
||||
|
||||
@override
|
||||
Future<bool> get isRunningOnBot async => _isRunningOnBot;
|
||||
@@ -382,9 +389,7 @@ class FakeFlutterVersion implements FlutterVersion {
|
||||
final FlutterVersion? nextFlutterVersion;
|
||||
|
||||
@override
|
||||
FlutterVersion fetchTagsAndGetVersion({
|
||||
SystemClock clock = const SystemClock(),
|
||||
}) {
|
||||
FlutterVersion fetchTagsAndGetVersion({SystemClock clock = const SystemClock()}) {
|
||||
_didFetchTagsAndUpdate = true;
|
||||
return nextFlutterVersion ?? this;
|
||||
}
|
||||
@@ -445,11 +450,13 @@ class FakeFlutterVersion implements FlutterVersion {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<void> ensureVersionFile() async { }
|
||||
Future<void> ensureVersionFile() async {}
|
||||
|
||||
@override
|
||||
String getBranchName({bool redactUnknownBranches = false}) {
|
||||
if (!redactUnknownBranches || kOfficialChannels.contains(branch) || kObsoleteBranches.containsKey(branch)) {
|
||||
if (!redactUnknownBranches ||
|
||||
kOfficialChannels.contains(branch) ||
|
||||
kObsoleteBranches.containsKey(branch)) {
|
||||
return branch;
|
||||
}
|
||||
return kUserBranch;
|
||||
@@ -549,7 +556,7 @@ class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils {
|
||||
final List<List<String>> chmods = <List<String>>[];
|
||||
|
||||
@override
|
||||
void makeExecutable(File file) { }
|
||||
void makeExecutable(File file) {}
|
||||
|
||||
@override
|
||||
HostPlatform hostPlatform = HostPlatform.linux_x64;
|
||||
@@ -569,10 +576,10 @@ class FakeOperatingSystemUtils extends Fake implements OperatingSystemUtils {
|
||||
int? getDirectorySize(Directory directory) => 10000000; // 10 MB / 9.5 MiB
|
||||
|
||||
@override
|
||||
void unzip(File file, Directory targetDirectory) { }
|
||||
void unzip(File file, Directory targetDirectory) {}
|
||||
|
||||
@override
|
||||
void unpack(File gzippedTarFile, Directory targetDirectory) { }
|
||||
void unpack(File gzippedTarFile, Directory targetDirectory) {}
|
||||
|
||||
@override
|
||||
Stream<List<int>> gzipLevel1Stream(Stream<List<int>> stream) => stream;
|
||||
@@ -624,13 +631,11 @@ class FakeStopwatch implements Stopwatch {
|
||||
}
|
||||
|
||||
class FakeStopwatchFactory implements StopwatchFactory {
|
||||
FakeStopwatchFactory({
|
||||
Stopwatch? stopwatch,
|
||||
Map<String, Stopwatch>? stopwatches
|
||||
}) : stopwatches = <String, Stopwatch>{
|
||||
if (stopwatches != null) ...stopwatches,
|
||||
if (stopwatch != null) '': stopwatch,
|
||||
};
|
||||
FakeStopwatchFactory({Stopwatch? stopwatch, Map<String, Stopwatch>? stopwatches})
|
||||
: stopwatches = <String, Stopwatch>{
|
||||
if (stopwatches != null) ...stopwatches,
|
||||
if (stopwatch != null) '': stopwatch,
|
||||
};
|
||||
|
||||
Map<String, Stopwatch> stopwatches;
|
||||
|
||||
@@ -651,7 +656,6 @@ class FakeFlutterProjectFactory implements FlutterProjectFactory {
|
||||
}
|
||||
|
||||
class FakeAndroidSdk extends Fake implements AndroidSdk {
|
||||
|
||||
@override
|
||||
late bool platformToolsAvailable;
|
||||
|
||||
@@ -674,13 +678,13 @@ class FakeJava extends Fake implements Java {
|
||||
String binary = '/android-studio/jbr/bin/java',
|
||||
Version? version,
|
||||
bool canRun = true,
|
||||
}): binaryPath = binary,
|
||||
version = version ?? const Version.withText(19, 0, 2, 'openjdk 19.0.2 2023-01-17'),
|
||||
_environment = <String, String>{
|
||||
if (javaHome != null) Java.javaHomeEnvironmentVariable: javaHome,
|
||||
'PATH': '/android-studio/jbr/bin',
|
||||
},
|
||||
_canRun = canRun;
|
||||
}) : binaryPath = binary,
|
||||
version = version ?? const Version.withText(19, 0, 2, 'openjdk 19.0.2 2023-01-17'),
|
||||
_environment = <String, String>{
|
||||
if (javaHome != null) Java.javaHomeEnvironmentVariable: javaHome,
|
||||
'PATH': '/android-studio/jbr/bin',
|
||||
},
|
||||
_canRun = canRun;
|
||||
|
||||
@override
|
||||
String? javaHome;
|
||||
@@ -706,13 +710,8 @@ class FakeJava extends Fake implements Java {
|
||||
}
|
||||
}
|
||||
|
||||
class FakeDartDevelopmentServiceLauncher extends Fake
|
||||
implements DartDevelopmentServiceLauncher {
|
||||
FakeDartDevelopmentServiceLauncher({
|
||||
required this.uri,
|
||||
this.devToolsUri,
|
||||
this.dtdUri,
|
||||
});
|
||||
class FakeDartDevelopmentServiceLauncher extends Fake implements DartDevelopmentServiceLauncher {
|
||||
FakeDartDevelopmentServiceLauncher({required this.uri, this.devToolsUri, this.dtdUri});
|
||||
|
||||
@override
|
||||
final Uri uri;
|
||||
@@ -733,8 +732,7 @@ class FakeDartDevelopmentServiceLauncher extends Fake
|
||||
}
|
||||
|
||||
class FakeDevtoolsLauncher extends Fake implements DevtoolsLauncher {
|
||||
FakeDevtoolsLauncher({DevToolsServerAddress? serverAddress})
|
||||
: _serverAddress = serverAddress;
|
||||
FakeDevtoolsLauncher({DevToolsServerAddress? serverAddress}) : _serverAddress = serverAddress;
|
||||
|
||||
@override
|
||||
Future<void> get processStart => _processStarted.future;
|
||||
@@ -785,7 +783,8 @@ class FakeLogger implements Logger {
|
||||
|
||||
class ClosedStdinController extends Fake implements StreamSink<List<int>> {
|
||||
@override
|
||||
Future<Object?> addStream(Stream<List<int>> stream) async => throw const SocketException('Bad pipe');
|
||||
Future<Object?> addStream(Stream<List<int>> stream) async =>
|
||||
throw const SocketException('Bad pipe');
|
||||
|
||||
@override
|
||||
Future<Object?> close() async {
|
||||
|
||||
@@ -17,8 +17,7 @@ import 'package:flutter_tools/src/base/file_system.dart';
|
||||
/// The only safe delegate types are those that do not call out to `dart:io`,
|
||||
/// like the [MemoryFileSystem].
|
||||
class FlutterIOOverrides extends io.IOOverrides {
|
||||
FlutterIOOverrides({ FileSystem? fileSystem })
|
||||
: _fileSystemDelegate = fileSystem;
|
||||
FlutterIOOverrides({FileSystem? fileSystem}) : _fileSystemDelegate = fileSystem;
|
||||
|
||||
final FileSystem? _fileSystemDelegate;
|
||||
|
||||
@@ -39,8 +38,8 @@ class FlutterIOOverrides extends io.IOOverrides {
|
||||
|
||||
@override
|
||||
Stream<FileSystemEvent> fsWatch(String path, int events, bool recursive) {
|
||||
return _fileSystemDelegate?.file(path).watch(events: events, recursive: recursive)
|
||||
?? super.fsWatch(path, events, recursive);
|
||||
return _fileSystemDelegate?.file(path).watch(events: events, recursive: recursive) ??
|
||||
super.fsWatch(path, events, recursive);
|
||||
}
|
||||
|
||||
@override
|
||||
@@ -50,14 +49,14 @@ class FlutterIOOverrides extends io.IOOverrides {
|
||||
|
||||
@override
|
||||
Future<FileSystemEntityType> fseGetType(String path, bool followLinks) {
|
||||
return _fileSystemDelegate?.type(path, followLinks: followLinks)
|
||||
?? super.fseGetType(path, followLinks);
|
||||
return _fileSystemDelegate?.type(path, followLinks: followLinks) ??
|
||||
super.fseGetType(path, followLinks);
|
||||
}
|
||||
|
||||
@override
|
||||
FileSystemEntityType fseGetTypeSync(String path, bool followLinks) {
|
||||
return _fileSystemDelegate?.typeSync(path, followLinks: followLinks)
|
||||
?? super.fseGetTypeSync(path, followLinks);
|
||||
return _fileSystemDelegate?.typeSync(path, followLinks: followLinks) ??
|
||||
super.fseGetTypeSync(path, followLinks);
|
||||
}
|
||||
|
||||
@override
|
||||
|
||||
@@ -11,12 +11,28 @@ class LoggingLogger extends BufferLogger {
|
||||
List<String> messages = <String>[];
|
||||
|
||||
@override
|
||||
void printError(String message, {StackTrace? stackTrace, bool? emphasis, TerminalColor? color, int? indent, int? hangingIndent, bool? wrap}) {
|
||||
void printError(
|
||||
String message, {
|
||||
StackTrace? stackTrace,
|
||||
bool? emphasis,
|
||||
TerminalColor? color,
|
||||
int? indent,
|
||||
int? hangingIndent,
|
||||
bool? wrap,
|
||||
}) {
|
||||
messages.add(message);
|
||||
}
|
||||
|
||||
@override
|
||||
void printStatus(String message, {bool? emphasis, TerminalColor? color, bool? newline, int? indent, int? hangingIndent, bool? wrap}) {
|
||||
void printStatus(
|
||||
String message, {
|
||||
bool? emphasis,
|
||||
TerminalColor? color,
|
||||
bool? newline,
|
||||
int? indent,
|
||||
int? hangingIndent,
|
||||
bool? wrap,
|
||||
}) {
|
||||
messages.add(message);
|
||||
}
|
||||
|
||||
|
||||
@@ -20,7 +20,11 @@ void validatePubspecForPlugin({
|
||||
}) {
|
||||
assert(pluginClass != null || ffiPlugin);
|
||||
final FlutterManifest manifest =
|
||||
FlutterManifest.createFromPath('$projectDir/pubspec.yaml', fileSystem: globals.fs, logger: globals.logger)!;
|
||||
FlutterManifest.createFromPath(
|
||||
'$projectDir/pubspec.yaml',
|
||||
fileSystem: globals.fs,
|
||||
logger: globals.logger,
|
||||
)!;
|
||||
final YamlMap platformMaps = YamlMap.wrap(manifest.supportedPlatforms!);
|
||||
for (final String platform in expectedPlatforms) {
|
||||
expect(platformMaps[platform], isNotNull);
|
||||
|
||||
@@ -8,9 +8,7 @@ import 'package:flutter_tools/src/build_system/build_system.dart';
|
||||
|
||||
class TestBuildSystem implements BuildSystem {
|
||||
/// Create a [BuildSystem] instance that returns the provided results in order.
|
||||
TestBuildSystem.list(this._results, [this._onRun])
|
||||
: _exception = null,
|
||||
_singleResult = null;
|
||||
TestBuildSystem.list(this._results, [this._onRun]) : _exception = null, _singleResult = null;
|
||||
|
||||
/// Create a [BuildSystem] instance that returns the provided result for every build
|
||||
/// and buildIncremental request.
|
||||
@@ -32,7 +30,11 @@ class TestBuildSystem implements BuildSystem {
|
||||
int _nextResult = 0;
|
||||
|
||||
@override
|
||||
Future<BuildResult> build(Target target, Environment environment, {BuildSystemConfig buildSystemConfig = const BuildSystemConfig()}) async {
|
||||
Future<BuildResult> build(
|
||||
Target target,
|
||||
Environment environment, {
|
||||
BuildSystemConfig buildSystemConfig = const BuildSystemConfig(),
|
||||
}) async {
|
||||
if (_onRun != null) {
|
||||
_onRun.call(target, environment);
|
||||
}
|
||||
@@ -49,7 +51,11 @@ class TestBuildSystem implements BuildSystem {
|
||||
}
|
||||
|
||||
@override
|
||||
Future<BuildResult> buildIncremental(Target target, Environment environment, BuildResult? previousBuild) async {
|
||||
Future<BuildResult> buildIncremental(
|
||||
Target target,
|
||||
Environment environment,
|
||||
BuildResult? previousBuild,
|
||||
) async {
|
||||
if (_onRun != null) {
|
||||
_onRun.call(target, environment);
|
||||
}
|
||||
|
||||
@@ -18,7 +18,7 @@ import 'package:flutter_tools/src/runner/flutter_command_runner.dart';
|
||||
|
||||
export 'package:test/test.dart' hide isInstanceOf, test;
|
||||
|
||||
CommandRunner<void> createTestCommandRunner([ FlutterCommand? command ]) {
|
||||
CommandRunner<void> createTestCommandRunner([FlutterCommand? command]) {
|
||||
final FlutterCommandRunner runner = TestFlutterCommandRunner();
|
||||
if (command != null) {
|
||||
runner.addCommand(command);
|
||||
@@ -29,7 +29,7 @@ CommandRunner<void> createTestCommandRunner([ FlutterCommand? command ]) {
|
||||
/// Creates a flutter project in the [temp] directory using the
|
||||
/// [arguments] list if specified, or `--no-pub` if not.
|
||||
/// Returns the path to the flutter project.
|
||||
Future<String> createProject(Directory temp, { List<String>? arguments }) async {
|
||||
Future<String> createProject(Directory temp, {List<String>? arguments}) async {
|
||||
arguments ??= <String>['--no-pub'];
|
||||
final String projectPath = globals.fs.path.join(temp.path, 'flutter_project');
|
||||
final CreateCommand command = CreateCommand();
|
||||
@@ -43,8 +43,7 @@ class TestFlutterCommandRunner extends FlutterCommandRunner {
|
||||
Future<void> runCommand(ArgResults topLevelResults) async {
|
||||
final Logger topLevelLogger = globals.logger;
|
||||
final Map<Type, dynamic> contextOverrides = <Type, dynamic>{
|
||||
if (topLevelResults['verbose'] as bool)
|
||||
Logger: VerboseLogger(topLevelLogger),
|
||||
if (topLevelResults['verbose'] as bool) Logger: VerboseLogger(topLevelLogger),
|
||||
};
|
||||
return context.run<void>(
|
||||
overrides: contextOverrides.map<Type, Generator>((Type type, dynamic value) {
|
||||
@@ -59,7 +58,7 @@ class TestFlutterCommandRunner extends FlutterCommandRunner {
|
||||
// For compatibility with tests that set this to a relative path.
|
||||
Cache.flutterRoot = globals.fs.path.normalize(globals.fs.path.absolute(Cache.flutterRoot!));
|
||||
return super.runCommand(topLevelResults);
|
||||
}
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,18 +32,26 @@ export 'package:flutter_tools/src/base/context.dart' show Generator;
|
||||
// this provider. For example, [BufferLogger], [MemoryFileSystem].
|
||||
final Map<Type, Generator> _testbedDefaults = <Type, Generator>{
|
||||
// Keeps tests fast by avoiding the actual file system.
|
||||
FileSystem: () => MemoryFileSystem(style: globals.platform.isWindows ? FileSystemStyle.windows : FileSystemStyle.posix),
|
||||
FileSystem:
|
||||
() => MemoryFileSystem(
|
||||
style: globals.platform.isWindows ? FileSystemStyle.windows : FileSystemStyle.posix,
|
||||
),
|
||||
ProcessManager: () => FakeProcessManager.any(),
|
||||
Logger: () => BufferLogger(
|
||||
terminal: AnsiTerminal(stdio: globals.stdio, platform: globals.platform), // Danger, using real stdio.
|
||||
outputPreferences: OutputPreferences.test(),
|
||||
), // Allows reading logs and prevents stdout.
|
||||
Logger:
|
||||
() => BufferLogger(
|
||||
terminal: AnsiTerminal(
|
||||
stdio: globals.stdio,
|
||||
platform: globals.platform,
|
||||
), // Danger, using real stdio.
|
||||
outputPreferences: OutputPreferences.test(),
|
||||
), // Allows reading logs and prevents stdout.
|
||||
OperatingSystemUtils: () => FakeOperatingSystemUtils(),
|
||||
OutputPreferences: () => OutputPreferences.test(), // configures BufferLogger to avoid color codes.
|
||||
OutputPreferences:
|
||||
() => OutputPreferences.test(), // configures BufferLogger to avoid color codes.
|
||||
Usage: () => TestUsage(), // prevent addition of analytics from burdening test mocks
|
||||
Analytics: () => const NoOpAnalytics(),
|
||||
FlutterVersion: () => FakeFlutterVersion(), // prevent requirement to mock git for test runner.
|
||||
Signals: () => FakeSignals(), // prevent registering actual signal handlers.
|
||||
Signals: () => FakeSignals(), // prevent registering actual signal handlers.
|
||||
Pub: () => const ThrowingPub(), // prevent accidental invocations of pub.
|
||||
};
|
||||
|
||||
@@ -82,8 +90,8 @@ class Testbed {
|
||||
/// `setup` may be provided to apply mocks within the tool managed zone,
|
||||
/// including any specified overrides.
|
||||
Testbed({FutureOr<void> Function()? setup, Map<Type, Generator>? overrides})
|
||||
: _setup = setup,
|
||||
_overrides = overrides;
|
||||
: _setup = setup,
|
||||
_overrides = overrides;
|
||||
|
||||
final FutureOr<void> Function()? _setup;
|
||||
final Map<Type, Generator>? _overrides;
|
||||
@@ -114,12 +122,24 @@ class Testbed {
|
||||
name: 'testbed',
|
||||
overrides: testOverrides,
|
||||
zoneSpecification: ZoneSpecification(
|
||||
createTimer: (Zone self, ZoneDelegate parent, Zone zone, Duration duration, void Function() timer) {
|
||||
createTimer: (
|
||||
Zone self,
|
||||
ZoneDelegate parent,
|
||||
Zone zone,
|
||||
Duration duration,
|
||||
void Function() timer,
|
||||
) {
|
||||
final Timer result = parent.createTimer(zone, duration, timer);
|
||||
timers[result] = StackTrace.current;
|
||||
return result;
|
||||
},
|
||||
createPeriodicTimer: (Zone self, ZoneDelegate parent, Zone zone, Duration period, void Function(Timer) timer) {
|
||||
createPeriodicTimer: (
|
||||
Zone self,
|
||||
ZoneDelegate parent,
|
||||
Zone zone,
|
||||
Duration period,
|
||||
void Function(Timer) timer,
|
||||
) {
|
||||
final Timer result = parent.createPeriodicTimer(zone, period, timer);
|
||||
timers[result] = StackTrace.current;
|
||||
return result;
|
||||
@@ -138,7 +158,8 @@ class Testbed {
|
||||
}
|
||||
}
|
||||
return null;
|
||||
});
|
||||
},
|
||||
);
|
||||
});
|
||||
}, createHttpClient: (SecurityContext? c) => FakeHttpClient.any());
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user