[flutter_tool] Where possible, catch only subtypes of Exception (#51440)

This commit is contained in:
Zachary Anderson
2020-02-26 21:45:02 -08:00
committed by GitHub
parent 80619f100f
commit f1cd47ef5c
84 changed files with 308 additions and 204 deletions

View File

@@ -7,6 +7,7 @@ import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/build_system/build_system.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/assemble.dart';
import 'package:flutter_tools/src/runner/flutter_command_runner.dart';
import 'package:mockito/mockito.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
@@ -15,6 +16,7 @@ import '../../src/context.dart';
import '../../src/testbed.dart';
void main() {
FlutterCommandRunner.initFlutterRoot();
Cache.disableLocking();
final Testbed testbed = Testbed(overrides: <Type, Generator>{
BuildSystem: () => MockBuildSystem(),

View File

@@ -76,7 +76,7 @@ void main() {
'--show-test-device',
]);
fail('Expect exception');
} catch (e) {
} on Exception catch (e) {
expect(e.toString(), isNot(contains('--fast-start is not supported with --use-application-binary')));
}
}, overrides: <Type, Generator>{
@@ -102,7 +102,7 @@ void main() {
'--no-pub',
]);
fail('Expect exception');
} catch (e) {
} on Exception catch (e) {
expect(e, isInstanceOf<ToolExit>());
}
final BufferLogger bufferLogger = globals.logger as BufferLogger;
@@ -127,7 +127,7 @@ void main() {
'--no-pub',
]);
fail('Expect exception');
} catch (e) {
} on Exception catch (e) {
expect(e, isInstanceOf<ToolExit>());
expect(e.toString(), contains('No pubspec.yaml file found'));
}
@@ -221,8 +221,8 @@ void main() {
} on ToolExit catch (e) {
// We expect a ToolExit because no devices are attached
expect(e.message, null);
} catch (e) {
fail('ToolExit expected');
} on Exception catch (e) {
fail('ToolExit expected, got $e');
}
verifyInOrder(<void>[
@@ -293,8 +293,8 @@ void main() {
} on ToolExit catch (e) {
// We expect a ToolExit because app does not start
expect(e.message, null);
} catch (e) {
fail('ToolExit expected');
} on Exception catch (e) {
fail('ToolExit expected, got $e');
}
final List<dynamic> captures = verify(mockUsage.sendCommand(
captureAny,

View File

@@ -163,7 +163,7 @@ void main() {
try {
await command.getTags();
fail('ToolExit expected');
} catch(e) {
} on Exception catch (e) {
expect(e, isA<ToolExit>());
}
}, overrides: <Type, Generator>{

View File

@@ -584,7 +584,9 @@ flutter:
final AndroidDevice device = AndroidDevice('emulator-5555');
expect(await device.emulatorId, isNull);
}, overrides: <Type, Generator>{
AndroidConsoleSocketFactory: () => (String host, int port) => throw 'Fake socket error',
AndroidConsoleSocketFactory: () {
return (String host, int port) => throw Exception('Fake socket error');
},
ProcessManager: () => mockProcessManager,
});

View File

@@ -80,6 +80,13 @@ void main() {
when(globals.processManager.runSync(<String>[sdk.sdkManagerPath, '--version'],
environment: argThat(isNotNull, named: 'environment')))
.thenReturn(ProcessResult(1, 0, '26.1.1\n', ''));
if (globals.platform.isMacOS) {
when(globals.processManager.runSync(
<String>['/usr/libexec/java_home'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 0, '', ''));
}
expect(sdk.sdkManagerVersion, '26.1.1');
}, overrides: <Type, Generator>{
FileSystem: () => fs,
@@ -112,6 +119,13 @@ void main() {
when(globals.processManager.runSync(<String>[sdk.sdkManagerPath, '--version'],
environment: argThat(isNotNull, named: 'environment')))
.thenReturn(ProcessResult(1, 1, '26.1.1\n', 'Mystery error'));
if (globals.platform.isMacOS) {
when(globals.processManager.runSync(
<String>['/usr/libexec/java_home'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 0, '', ''));
}
expect(sdk.sdkManagerVersion, isNull);
}, overrides: <Type, Generator>{
FileSystem: () => fs,

View File

@@ -70,26 +70,32 @@ $assetsSection
Future<void> buildAndVerifyAssets(
List<String> assets,
List<String> packages,
String expectedAssetManifest,
) async {
String expectedAssetManifest, {
bool expectExists = true,
}) async {
final AssetBundle bundle = AssetBundleFactory.instance.createBundle();
await bundle.build(manifestPath: 'pubspec.yaml');
for (final String packageName in packages) {
for (final String asset in assets) {
final String entryKey = Uri.encodeFull('packages/$packageName/$asset');
expect(bundle.entries.containsKey(entryKey), true, reason: 'Cannot find key on bundle: $entryKey');
expect(
utf8.decode(await bundle.entries[entryKey].contentsAsBytes()),
asset,
);
expect(bundle.entries.containsKey(entryKey), expectExists,
reason: 'Cannot find key on bundle: $entryKey');
if (expectExists) {
expect(
utf8.decode(await bundle.entries[entryKey].contentsAsBytes()),
asset,
);
}
}
}
expect(
utf8.decode(await bundle.entries['AssetManifest.json'].contentsAsBytes()),
expectedAssetManifest,
);
if (expectExists) {
expect(
utf8.decode(await bundle.entries['AssetManifest.json'].contentsAsBytes()),
expectedAssetManifest,
);
}
}
void writeAssets(String path, List<String> assets) {
@@ -660,24 +666,15 @@ $assetsSection
assets: assetOnManifest,
);
try {
await buildAndVerifyAssets(
assetOnManifest,
<String>['test_package'],
null,
);
final Function watchdog = () async {
assert(false, 'Code failed to detect missing directory. Test failed.');
};
watchdog();
} catch (e) {
// Test successful
}
await buildAndVerifyAssets(
assetOnManifest,
<String>['test_package'],
null,
expectExists: false,
);
}, overrides: <Type, Generator>{
FileSystem: () => testFileSystem,
ProcessManager: () => FakeProcessManager.any(),
});
});
}

View File

@@ -197,7 +197,7 @@ void main() {
);
try {
await f;
} catch (e) {
} on String {
caughtByHandler = true;
}
if (!completer.isCompleted) {
@@ -235,7 +235,7 @@ void main() {
);
try {
await f;
} catch (e) {
} on String {
caughtByHandler = true;
}
if (!completer.isCompleted) {
@@ -275,7 +275,7 @@ void main() {
);
try {
await f;
} catch (e) {
} on String {
caughtByHandler = true;
}
if (!completer.isCompleted) {

View File

@@ -249,7 +249,7 @@ void main() {
globals.fs.file('a.dart').createSync();
expect(
() => Fingerprint.fromBuildInputs(<String, String>{}, <String>['a.dart', 'b.dart']),
throwsArgumentError,
throwsException,
);
}, overrides: <Type, Generator>{
FileSystem: () => fs,
@@ -328,7 +328,7 @@ void main() {
'properties': <String, String>{},
'files': <String, String>{},
});
expect(() => Fingerprint.fromJson(jsonString), throwsArgumentError);
expect(() => Fingerprint.fromJson(jsonString), throwsException);
}, overrides: <Type, Generator>{
FlutterVersion: () => mockVersion,
});
@@ -338,7 +338,7 @@ void main() {
'properties': <String, String>{},
'files': <String, String>{},
});
expect(() => Fingerprint.fromJson(jsonString), throwsArgumentError);
expect(() => Fingerprint.fromJson(jsonString), throwsException);
}, overrides: <Type, Generator>{
FlutterVersion: () => mockVersion,
});

View File

@@ -61,8 +61,9 @@ void main() {
});
testUsingContext('signal handler error goes on error stream', () async {
final Exception exn = Exception('Error');
signals.addHandler(signalUnderTest, (ProcessSignal s) {
throw 'Error';
throw exn;
});
final Completer<void> completer = Completer<void>();
@@ -75,7 +76,7 @@ void main() {
controller.add(mockSignal);
await completer.future;
await errSub.cancel();
expect(errList, <Object>['Error']);
expect(errList, contains(exn));
}, overrides: <Type, Generator>{
Signals: () => Signals(),
});

View File

@@ -91,6 +91,6 @@ void main() {
expect(getIOSArchForName('arm64'), DarwinArch.arm64);
expect(getIOSArchForName('arm64e'), DarwinArch.arm64);
expect(getIOSArchForName('x86_64'), DarwinArch.x86_64);
expect(() => getIOSArchForName('bogus'), throwsAssertionError);
expect(() => getIOSArchForName('bogus'), throwsException);
});
}

View File

@@ -231,7 +231,7 @@ void main() {
null,
});
fail('Mock thrown exception expected');
} catch (e) {
} on Exception {
verify(artifact1.update());
// Don't continue when retrieval fails.
verifyNever(artifact2.update());

View File

@@ -152,6 +152,26 @@ void main() {
.thenAnswer((_) => Future<Process>.value(process));
when(mockProcessManager.canRun(any)).thenReturn(false);
when(mockProcessManager.runSync(
argThat(contains(contains('gen_snapshot'))),
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 255, '', ''));
when(mockProcessManager.runSync(
<String>['/usr/bin/xcode-select', '--print-path'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 0, '', ''));
when(mockProcessManager.run(
<String>['which', 'pod'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenAnswer((_) {
return Future<ProcessResult>.value(ProcessResult(0, 0, '', ''));
});
mockAndroidSdk = MockAndroidSdk();
when(mockAndroidSdk.directory).thenReturn('irrelevant');
});

View File

@@ -9,12 +9,11 @@ import 'package:flutter_tools/src/android/android_builder.dart';
import 'package:flutter_tools/src/android/android_sdk.dart';
import 'package:flutter_tools/src/base/context.dart';
import 'package:flutter_tools/src/base/file_system.dart';
import 'package:flutter_tools/src/cache.dart';
import 'package:flutter_tools/src/commands/build_appbundle.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:flutter_tools/src/project.dart';
import 'package:flutter_tools/src/reporting/reporting.dart';
import 'package:flutter_tools/src/globals.dart' as globals;
import 'package:mockito/mockito.dart';
import 'package:process/process.dart';
@@ -135,6 +134,26 @@ void main() {
.thenAnswer((_) => Future<Process>.value(process));
when(mockProcessManager.canRun(any)).thenReturn(false);
when(mockProcessManager.runSync(
argThat(contains(contains('gen_snapshot'))),
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 255, '', ''));
when(mockProcessManager.runSync(
<String>['/usr/bin/xcode-select', '--print-path'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenReturn(ProcessResult(0, 0, '', ''));
when(mockProcessManager.run(
<String>['which', 'pod'],
workingDirectory: anyNamed('workingDirectory'),
environment: anyNamed('environment'),
)).thenAnswer((_) {
return Future<ProcessResult>.value(ProcessResult(0, 0, '', ''));
});
mockAndroidSdk = MockAndroidSdk();
when(mockAndroidSdk.validateSdkWellFormed()).thenReturn(const <String>[]);
when(mockAndroidSdk.directory).thenReturn('irrelevant');

View File

@@ -327,8 +327,7 @@ void main() {
try {
await pub.get(context: PubContext.flutterTests, checkLastModified: true);
expect(true, isFalse, reason: 'pub.get did not throw');
} catch (error) {
expect(error, isA<Exception>());
} on ToolExit catch (error) {
expect(error.message, '/: unexpected concurrent modification of pubspec.yaml while running pub.');
}
expect(testLogger.statusText, 'Running "flutter pub get" in /...\n');

View File

@@ -136,7 +136,7 @@ void main() {
const int kFailedAttempts = 5;
when(httpRequest.close()).thenAnswer((Invocation invocation) {
if (nRequest++ < kFailedAttempts) {
throw 'Connection resert by peer';
throw Exception('Connection resert by peer');
}
return Future<HttpClientResponse>.value(httpClientResponse);
});

View File

@@ -46,8 +46,17 @@ void main() {
Future<Map<String, String>> captureEnvironment() async {
flutterPlatform.loadChannel('test1.dart', MockSuitePlatform());
when(mockProcessManager.start(
any,
environment: anyNamed('environment')),
).thenAnswer((_) {
return Future<Process>.value(MockProcess());
});
await untilCalled(mockProcessManager.start(any, environment: anyNamed('environment')));
final VerificationResult toVerify = verify(mockProcessManager.start(any, environment: captureAnyNamed('environment')));
final VerificationResult toVerify = verify(mockProcessManager.start(
any,
environment: captureAnyNamed('environment'),
));
expect(toVerify.captured, hasLength(1));
expect(toVerify.captured.first, isA<Map<String, String>>());
return toVerify.captured.first as Map<String, String>;
@@ -146,6 +155,8 @@ class MockSuitePlatform extends Mock implements SuitePlatform {}
class MockProcessManager extends Mock implements ProcessManager {}
class MockProcess extends Mock implements Process {}
class MockPlatform extends Mock implements Platform {}
class MockHttpServer extends Mock implements HttpServer {}

View File

@@ -476,7 +476,7 @@ void main() {
try {
await device.takeScreenshot(globals.fs.file('file.ppm'));
} catch (_) {
} on Exception {
assert(false);
}
expect(
@@ -534,8 +534,8 @@ void main() {
try {
await device.takeScreenshot(globals.fs.file('file.ppm'));
} catch (_) {
assert(false);
} on Exception catch (e) {
fail('Unexpected exception: $e');
}
}, overrides: <Type, Generator>{
ProcessManager: () => mockProcessManager,

View File

@@ -229,9 +229,9 @@ void main() {
Map<String, String> signingConfigs;
try {
signingConfigs = await getCodeSigningIdentityDevelopmentTeam(iosApp: app);
} catch (e) {
} on Exception catch (e) {
// This should not throw
expect(true, false);
fail('Code signing threw: $e');
}
expect(testLogger.statusText, contains('Apple Development: Profile 1 (1111AAAA11)'));

View File

@@ -54,7 +54,7 @@ void main() {
expect(portForwarder.forwardedPorts.length, 2);
try {
await portForwarder.dispose();
} catch (e) {
} on Exception catch (e) {
fail('Encountered exception: $e');
}
expect(portForwarder.forwardedPorts.length, 0);

View File

@@ -355,7 +355,7 @@ void main() {
engineDir: 'engine/path',
);
fail('ToolExit expected');
} catch(e) {
} on Exception catch (e) {
expect(e, isA<ToolExit>());
verifyNever(mockProcessManager.run(
argThat(containsAllInOrder(<String>['pod', 'install'])),
@@ -404,7 +404,7 @@ Note: as of CocoaPods 1.0, `pod repo update` does not happen on `pod install` by
engineDir: 'engine/path',
);
fail('ToolExit expected');
} catch (e) {
} on Exception catch (e) {
expect(e, isA<ToolExit>());
expect(
testLogger.errorText,

View File

@@ -528,7 +528,7 @@ class FlutterRunTestDriver extends FlutterTestDriver {
// have already completed.
_currentRunningAppId = (await started)['params']['appId'] as String;
prematureExitGuard.complete();
} catch (error, stackTrace) {
} on Exception catch (error, stackTrace) {
prematureExitGuard.completeError(error, stackTrace);
}
}());
@@ -732,7 +732,7 @@ class FlutterTestTestDriver extends FlutterTestDriver {
Map<String, dynamic> _parseJsonResponse(String line) {
try {
return castStringKeyedMap(json.decode(line));
} catch (e) {
} on Exception {
// Not valid JSON, so likely some other output.
return null;
}
@@ -771,7 +771,7 @@ Map<String, dynamic> parseFlutterResponse(String line) {
try {
final Map<String, dynamic> response = castStringKeyedMap(json.decode(line)[0]);
return response;
} catch (e) {
} on Exception {
// Not valid JSON, so likely some other output that was surrounded by [brackets]
return null;
}

View File

@@ -139,7 +139,8 @@ Future<void> expectToolExitLater(Future<dynamic> future, Matcher messageMatcher)
fail('ToolExit expected, but nothing thrown');
} on ToolExit catch(e) {
expect(e.message, messageMatcher);
} catch(e, trace) {
// 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');
}
}

View File

@@ -148,7 +148,8 @@ void testUsingContext(
return await testMethod();
},
);
} catch (error) {
// This catch rethrows, so doesn't need to catch only Exception.
} catch (error) { // ignore: avoid_catches_without_on_clauses
_printBufferedErrors(context);
rethrow;
}

View File

@@ -398,7 +398,8 @@ class MemoryIOSink implements IOSink {
(List<int> data) {
try {
add(data);
} catch (err, stack) {
// Catches all exceptions to propagate them to the completer.
} catch (err, stack) { // ignore: avoid_catches_without_on_clauses
sub.cancel();
completer.completeError(err, stack);
}