Skip to content

Commit

Permalink
[flutter_tools] migrate more unit tests to null safety (#106153)
Browse files Browse the repository at this point in the history
  • Loading branch information
jonahwilliams authored Jun 18, 2022
1 parent 2af8250 commit db829c1
Show file tree
Hide file tree
Showing 70 changed files with 798 additions and 950 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -210,10 +210,10 @@ DevFSContent? processSkSLBundle(String? bundlePath, {
}

// Step 2: validate top level bundle structure.
Map<String, Object>? bundle;
Map<String, Object?>? bundle;
try {
final Object? rawBundle = json.decode(skSLBundleFile.readAsStringSync());
if (rawBundle is Map<String, Object>) {
if (rawBundle is Map<String, Object?>) {
bundle = rawBundle;
} else {
logger.printError('"$bundle" was not a JSON object: $rawBundle');
Expand Down
6 changes: 3 additions & 3 deletions packages/flutter_tools/lib/src/cache.dart
Original file line number Diff line number Diff line change
Expand Up @@ -389,10 +389,10 @@ class Cache {
throw Exception('Could not find file at $versionFilePath');
}
final dynamic data = jsonDecode(versionFile.readAsStringSync());
if (data is! Map<String, Object>) {
throw Exception("Expected object of type 'Map<String, Object>' but got one of type '${data.runtimeType}'");
if (data is! Map<String, Object?>) {
throw Exception("Expected object of type 'Map<String, Object?>' but got one of type '${data.runtimeType}'");
}
final dynamic version = data['version'];
final Object? version = data['version'];
if (version == null) {
throw Exception('Could not parse DevTools version from $version');
}
Expand Down
6 changes: 3 additions & 3 deletions packages/flutter_tools/lib/src/commands/create_base.dart
Original file line number Diff line number Diff line change
Expand Up @@ -668,11 +668,11 @@ abstract class CreateBase extends FlutterCommand {
'templates',
'template_manifest.json',
);
final Map<String, Object> manifest = json.decode(
final Map<String, Object?> manifest = json.decode(
globals.fs.file(manifestPath).readAsStringSync(),
) as Map<String, Object>;
) as Map<String, Object?>;
return Set<Uri>.from(
(manifest['files']! as List<Object>).cast<String>().map<Uri>(
(manifest['files']! as List<Object?>).cast<String>().map<Uri>(
(String path) =>
Uri.file(globals.fs.path.join(flutterToolsAbsolutePath, path))),
);
Expand Down
4 changes: 2 additions & 2 deletions packages/flutter_tools/lib/src/macos/application_package.dart
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,8 @@ abstract class MacOSApp extends ApplicationPackage {
return null;
}
final Map<String, dynamic> propertyValues = globals.plistParser.parseFile(plistPath);
final String id = propertyValues[PlistParser.kCFBundleIdentifierKey] as String;
final String executableName = propertyValues[PlistParser.kCFBundleExecutable] as String;
final String? id = propertyValues[PlistParser.kCFBundleIdentifierKey] as String?;
final String? executableName = propertyValues[PlistParser.kCFBundleExecutable] as String?;
if (id == null) {
globals.printError('Invalid prebuilt macOS app. Info.plist does not contain bundle identifier');
return null;
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter_tools/lib/src/runner/flutter_command.dart
Original file line number Diff line number Diff line change
Expand Up @@ -1534,7 +1534,7 @@ abstract class FlutterCommand extends Command<void> {
if (!argParser.options.containsKey(name)) {
return null;
}
return argResults![name] as String;
return argResults![name] as String?;
}

/// Gets the parsed command-line option named [name] as an `int`.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -117,7 +117,7 @@ class CoverageCollector extends TestWatcher {
);

final Future<void> collectionComplete = testDevice.observatoryUri
.then((Uri observatoryUri) {
.then((Uri? observatoryUri) {
_logMessage('collecting coverage data from $testDevice at $observatoryUri...');
return collect(observatoryUri, libraryNames)
.then<void>((Map<String, dynamic> result) {
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter_tools/lib/src/test/flutter_platform.dart
Original file line number Diff line number Diff line change
Expand Up @@ -494,7 +494,7 @@ class FlutterPlatform extends PlatformPlugin {
await Future.any<void>(<Future<void>>[
testDevice.finished,
() async {
final Uri processObservatoryUri = await testDevice.observatoryUri;
final Uri? processObservatoryUri = await testDevice.observatoryUri;
if (processObservatoryUri != null) {
globals.printTrace('test $ourTestCount: Observatory uri is available at $processObservatoryUri');
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,7 @@ class FlutterTesterTestDevice extends TestDevice {
}) : assert(shellPath != null), // Please provide the path to the shell in the SKY_SHELL environment variable.
assert(!debuggingOptions.startPaused || enableObservatory),
_gotProcessObservatoryUri = enableObservatory
// ignore: null_argument_to_non_null_type
? Completer<Uri>() : (Completer<Uri>()..complete()),
? Completer<Uri?>() : (Completer<Uri?>()..complete()),
_operatingSystemUtils = OperatingSystemUtils(
fileSystem: fileSystem,
logger: logger,
Expand All @@ -73,7 +72,7 @@ class FlutterTesterTestDevice extends TestDevice {
final CompileExpression? compileExpression;
final FontConfigManager fontConfigManager;

final Completer<Uri> _gotProcessObservatoryUri;
final Completer<Uri?> _gotProcessObservatoryUri;
final Completer<int> _exitCode = Completer<int>();

Process? _process;
Expand Down Expand Up @@ -209,7 +208,7 @@ class FlutterTesterTestDevice extends TestDevice {
}

@override
Future<Uri> get observatoryUri {
Future<Uri?> get observatoryUri {
assert(_gotProcessObservatoryUri != null);
return _gotProcessObservatoryUri.future;
}
Expand Down
4 changes: 2 additions & 2 deletions packages/flutter_tools/lib/src/test/test_compiler.dart
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ class TestCompiler {
late File outputDill;

Future<String?> compile(Uri mainDart) {
final Completer<String> completer = Completer<String>();
final Completer<String?> completer = Completer<String?>();
if (compilerController.isClosed) {
return Future<String?>.value();
}
Expand Down Expand Up @@ -175,7 +175,7 @@ class TestCompiler {
// compiler to avoid reusing compiler that might have gotten into
// a weird state.
if (outputPath == null || compilerOutput!.errorCount > 0) {
request.result.complete(null);
request.result.complete();
await _shutdown();
} else {
if (shouldCopyDillFile) {
Expand Down
2 changes: 1 addition & 1 deletion packages/flutter_tools/lib/src/test/test_device.dart
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ abstract class TestDevice {
Future<StreamChannel<String>> start(String entrypointPath);

/// Should complete with null if the observatory is not enabled.
Future<Uri> get observatoryUri;
Future<Uri?> get observatoryUri;

/// Terminates the test device.
Future<void> kill();
Expand Down
36 changes: 17 additions & 19 deletions packages/flutter_tools/test/general.shard/analytics_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// @dart = 2.8

import 'package:args/command_runner.dart';
import 'package:file/memory.dart';
import 'package:flutter_tools/src/android/android_workflow.dart';
Expand Down Expand Up @@ -37,8 +35,8 @@ void main() {
});

group('analytics', () {
Directory tempDir;
Config testConfig;
late Directory tempDir;
late Config testConfig;

setUp(() {
Cache.flutterRoot = '../..';
Expand Down Expand Up @@ -108,7 +106,7 @@ void main() {
});

testUsingContext('Usage records one feature in experiment setting', () async {
testConfig.setValue(flutterWebFeature.configSetting, true);
testConfig.setValue(flutterWebFeature.configSetting!, true);
final Usage usage = Usage(runningOnBot: true);
usage.sendCommand('test');

Expand All @@ -126,9 +124,9 @@ void main() {
});

testUsingContext('Usage records multiple features in experiment setting', () async {
testConfig.setValue(flutterWebFeature.configSetting, true);
testConfig.setValue(flutterLinuxDesktopFeature.configSetting, true);
testConfig.setValue(flutterMacOSDesktopFeature.configSetting, true);
testConfig.setValue(flutterWebFeature.configSetting!, true);
testConfig.setValue(flutterLinuxDesktopFeature.configSetting!, true);
testConfig.setValue(flutterMacOSDesktopFeature.configSetting!, true);
final Usage usage = Usage(runningOnBot: true);
usage.sendCommand('test');

Expand All @@ -150,11 +148,11 @@ void main() {
});

group('analytics with fakes', () {
MemoryFileSystem memoryFileSystem;
FakeStdio fakeStdio;
TestUsage testUsage;
FakeClock fakeClock;
FakeDoctor doctor;
late MemoryFileSystem memoryFileSystem;
late FakeStdio fakeStdio;
late TestUsage testUsage;
late FakeClock fakeClock;
late FakeDoctor doctor;

setUp(() {
memoryFileSystem = MemoryFileSystem.test();
Expand Down Expand Up @@ -211,7 +209,7 @@ void main() {

testUsingContext('compound command usage path', () async {
final BuildCommand buildCommand = BuildCommand();
final FlutterCommand buildApkCommand = buildCommand.subcommands['apk'] as FlutterCommand;
final FlutterCommand buildApkCommand = buildCommand.subcommands['apk']! as FlutterCommand;

expect(await buildApkCommand.usagePath, 'build/apk');
}, overrides: <Type, Generator>{
Expand Down Expand Up @@ -280,7 +278,7 @@ void main() {
});

group('analytics bots', () {
Directory tempDir;
late Directory tempDir;

setUp(() {
tempDir = globals.fs.systemTempDirectory.createTempSync('flutter_tools_analytics_bots_test.');
Expand Down Expand Up @@ -341,8 +339,8 @@ Analytics throwingAnalyticsIOFactory(
String trackingId,
String applicationName,
String applicationVersion, {
String analyticsUrl,
Directory documentDirectory,
String? analyticsUrl,
Directory? documentDirectory,
}) {
throw const FileSystemException('Could not create file');
}
Expand All @@ -368,9 +366,9 @@ class FakeDoctor extends Fake implements Doctor {
bool androidLicenses = false,
bool verbose = true,
bool showColor = true,
AndroidLicenseValidator androidLicenseValidator,
AndroidLicenseValidator? androidLicenseValidator,
bool showPii = true,
List<ValidatorTask> startedValidatorTasks,
List<ValidatorTask>? startedValidatorTasks,
bool sendEvent = true,
}) async {
return diagnoseSucceeds;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,6 @@
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

// @dart = 2.8

import 'package:archive/archive.dart';
import 'package:file/memory.dart';
import 'package:file_testing/file_testing.dart';
Expand All @@ -27,10 +25,10 @@ import '../../src/fake_process_manager.dart';

void main() {
group('gradle build', () {
BufferLogger logger;
TestUsage testUsage;
FileSystem fileSystem;
FakeProcessManager processManager;
late BufferLogger logger;
late TestUsage testUsage;
late FileSystem fileSystem;
late FakeProcessManager processManager;

setUp(() {
processManager = FakeProcessManager.empty();
Expand Down Expand Up @@ -99,10 +97,10 @@ void main() {
return line.contains('Some gradle message');
},
handler: ({
String line,
FlutterProject project,
bool usesAndroidX,
bool multidexEnabled
String? line,
FlutterProject? project,
bool? usesAndroidX,
bool? multidexEnabled
}) async {
handlerCalled = true;
return GradleBuildStatus.exit;
Expand Down Expand Up @@ -263,10 +261,10 @@ void main() {
return false;
},
handler: ({
String line,
FlutterProject project,
bool usesAndroidX,
bool multidexEnabled
String? line,
FlutterProject? project,
bool? usesAndroidX,
bool? multidexEnabled
}) async {
return GradleBuildStatus.retry;
},
Expand Down Expand Up @@ -351,10 +349,10 @@ void main() {
return line.contains('Some gradle message');
},
handler: ({
String line,
FlutterProject project,
bool usesAndroidX,
bool multidexEnabled
String? line,
FlutterProject? project,
bool? usesAndroidX,
bool? multidexEnabled
}) async {
handlerCalled = true;
return GradleBuildStatus.exit;
Expand Down Expand Up @@ -517,10 +515,10 @@ void main() {
return line.contains('Some gradle message');
},
handler: ({
String line,
FlutterProject project,
bool usesAndroidX,
bool multidexEnabled
String? line,
FlutterProject? project,
bool? usesAndroidX,
bool? multidexEnabled
}) async {
return GradleBuildStatus.retry;
},
Expand Down Expand Up @@ -595,7 +593,7 @@ void main() {
.childDirectory('flutter-apk')
.childFile('app-release.apk')
..createSync(recursive: true)
..writeAsBytesSync(ZipEncoder().encode(archive));
..writeAsBytesSync(ZipEncoder().encode(archive)!);

fileSystem.file('foo/snapshot.arm64-v8a.json')
..createSync(recursive: true)
Expand Down
Loading

0 comments on commit db829c1

Please sign in to comment.