Unverified Commit 74cfc3db authored by Pierre-Louis's avatar Pierre-Louis Committed by GitHub

Use `curly_braces_in_flow_control_structures` for non-`flutter` packages (#104629)

* Use `curly_braces_in_flow_control_structures` for `packages/flutter_driver`

* Use `curly_braces_in_flow_control_structures` for `packages/flutter_goldens`

* Use `curly_braces_in_flow_control_structures` for `packages/flutter_goldens_client`

* Use `curly_braces_in_flow_control_structures` for `packages/flutter_localizations`

* Use `curly_braces_in_flow_control_structures` for `packages/flutter_test`

* Use `curly_braces_in_flow_control_structures` for `packages/flutter_web_plugins`

* fix comments

* Use `curly_braces_in_flow_control_structures` for `packages/integration_test`

* fix indentation
parent a0248ebd
......@@ -21,8 +21,9 @@ class DriverError extends Error {
@override
String toString() {
if (originalError == null)
if (originalError == null) {
return 'DriverError: $message\n';
}
return '''
DriverError: $message
Original error: $originalError
......
......@@ -205,8 +205,9 @@ class ByValueKey extends SerializableFinder {
ByValueKey(this.keyValue)
: keyValueString = '$keyValue',
keyValueType = '${keyValue.runtimeType}' {
if (!_supportedKeyValueTypes.contains(keyValue.runtimeType))
if (!_supportedKeyValueTypes.contains(keyValue.runtimeType)) {
throw _createInvalidKeyValueTypeError('$keyValue.runtimeType');
}
}
/// The true value of the key.
......
......@@ -260,8 +260,9 @@ mixin CommandHandlerFactory {
'This feature was deprecated after v1.9.3.'
)
Future<Result> _waitUntilNoTransientCallbacks(Command command) async {
if (SchedulerBinding.instance.transientCallbackCount != 0)
if (SchedulerBinding.instance.transientCallbackCount != 0) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
return Result.empty;
}
......@@ -310,8 +311,9 @@ mixin CommandHandlerFactory {
node = renderObject.debugSemantics;
renderObject = renderObject.parent as RenderObject?;
}
if (node == null)
if (node == null) {
throw StateError('No semantics data found');
}
return GetSemanticsIdResult(node.id);
}
......@@ -464,26 +466,30 @@ mixin CommandHandlerFactory {
/// Runs `finder` repeatedly until it finds one or more [Element]s.
Future<Finder> waitForElement(Finder finder) async {
if (_frameSync)
if (_frameSync) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
await _waitUntilFrame(() => finder.evaluate().isNotEmpty);
if (_frameSync)
if (_frameSync) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
return finder;
}
/// Runs `finder` repeatedly until it finds zero [Element]s.
Future<Finder> waitForAbsentElement(Finder finder) async {
if (_frameSync)
if (_frameSync) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
await _waitUntilFrame(() => finder.evaluate().isEmpty);
if (_frameSync)
if (_frameSync) {
await _waitUntilFrame(() => SchedulerBinding.instance.transientCallbackCount == 0);
}
return finder;
}
......
......@@ -17,8 +17,9 @@ abstract class Command {
static Duration? _parseTimeout(Map<String, String> json) {
final String? timeout = json['timeout'];
if (timeout == null)
if (timeout == null) {
return null;
}
return Duration(milliseconds: int.parse(timeout));
}
......@@ -52,8 +53,9 @@ abstract class Command {
final Map<String, String> result = <String, String>{
'command': kind,
};
if (timeout != null)
if (timeout != null) {
result['timeout'] = '${timeout!.inMilliseconds}';
}
return result;
}
}
......
......@@ -95,8 +95,9 @@ class NoTransientCallbacks extends SerializableWaitCondition {
/// The [json] argument must not be null.
factory NoTransientCallbacks.deserialize(Map<String, String> json) {
assert(json != null);
if (json['conditionName'] != 'NoTransientCallbacksCondition')
if (json['conditionName'] != 'NoTransientCallbacksCondition') {
throw SerializationException('Error occurred during deserializing the NoTransientCallbacksCondition JSON string: $json');
}
return const NoTransientCallbacks();
}
......@@ -115,8 +116,9 @@ class NoPendingFrame extends SerializableWaitCondition {
/// The [json] argument must not be null.
factory NoPendingFrame.deserialize(Map<String, String> json) {
assert(json != null);
if (json['conditionName'] != 'NoPendingFrameCondition')
if (json['conditionName'] != 'NoPendingFrameCondition') {
throw SerializationException('Error occurred during deserializing the NoPendingFrameCondition JSON string: $json');
}
return const NoPendingFrame();
}
......@@ -135,8 +137,9 @@ class FirstFrameRasterized extends SerializableWaitCondition {
/// The [json] argument must not be null.
factory FirstFrameRasterized.deserialize(Map<String, String> json) {
assert(json != null);
if (json['conditionName'] != 'FirstFrameRasterizedCondition')
if (json['conditionName'] != 'FirstFrameRasterizedCondition') {
throw SerializationException('Error occurred during deserializing the FirstFrameRasterizedCondition JSON string: $json');
}
return const FirstFrameRasterized();
}
......@@ -158,8 +161,9 @@ class NoPendingPlatformMessages extends SerializableWaitCondition {
/// The [json] argument must not be null.
factory NoPendingPlatformMessages.deserialize(Map<String, String> json) {
assert(json != null);
if (json['conditionName'] != 'NoPendingPlatformMessagesCondition')
if (json['conditionName'] != 'NoPendingPlatformMessagesCondition') {
throw SerializationException('Error occurred during deserializing the NoPendingPlatformMessagesCondition JSON string: $json');
}
return const NoPendingPlatformMessages();
}
......@@ -181,8 +185,9 @@ class CombinedCondition extends SerializableWaitCondition {
/// The [jsonMap] argument must not be null.
factory CombinedCondition.deserialize(Map<String, String> jsonMap) {
assert(jsonMap != null);
if (jsonMap['conditionName'] != 'CombinedCondition')
if (jsonMap['conditionName'] != 'CombinedCondition') {
throw SerializationException('Error occurred during deserializing the CombinedCondition JSON string: $jsonMap');
}
if (jsonMap['conditions'] == null) {
return const CombinedCondition(<SerializableWaitCondition>[]);
}
......
......@@ -410,23 +410,26 @@ class TimelineSummary {
}
double _averageInMillis(Iterable<Duration> durations) {
if (durations.isEmpty)
if (durations.isEmpty) {
throw ArgumentError('durations is empty!');
}
final double total = durations.fold<double>(0.0, (double t, Duration duration) => t + duration.inMicroseconds.toDouble() / 1000.0);
return total / durations.length;
}
double _percentileInMillis(Iterable<Duration> durations, double percentile) {
if (durations.isEmpty)
if (durations.isEmpty) {
throw ArgumentError('durations is empty!');
}
assert(percentile >= 0.0 && percentile <= 100.0);
final List<double> doubles = durations.map<double>((Duration duration) => duration.inMicroseconds.toDouble() / 1000.0).toList();
return findPercentile(doubles, percentile);
}
double _maxInMillis(Iterable<Duration> durations) {
if (durations.isEmpty)
if (durations.isEmpty) {
throw ArgumentError('durations is empty!');
}
return durations
.map<double>((Duration duration) => duration.inMicroseconds.toDouble() / 1000.0)
.reduce(math.max);
......
......@@ -321,14 +321,16 @@ class VMServiceFlutterDriver extends FlutterDriver {
stackTrace,
);
}
if ((response['isError'] as bool?) ?? false)
if ((response['isError'] as bool?) ?? false) {
throw DriverError('Error in Flutter application: ${response['response']}');
}
return response['response'] as Map<String, dynamic>;
}
void _logCommunication(String message) {
if (_printCommunication)
if (_printCommunication) {
_log(message);
}
if (_logCommunicationToFile) {
assert(_logFilePathName != null);
final f.File file = fs.file(_logFilePathName);
......@@ -533,8 +535,9 @@ String _getWebSocketUrl(String url) {
if (uri.pathSegments.isNotEmpty) uri.pathSegments.first,
'ws',
];
if (uri.scheme == 'http')
if (uri.scheme == 'http') {
uri = uri.replace(scheme: 'ws', pathSegments: pathSegments);
}
return uri.toString();
}
......
......@@ -377,8 +377,9 @@ class FlutterDriverExtension with DeserializeFinderFactory, CreateFinderFactory,
return _makeResponse(message, isError: true);
} catch (error, stackTrace) {
final String message = 'Uncaught extension error while executing $commandKind: $error\n$stackTrace';
if (!_silenceErrors)
if (!_silenceErrors) {
_log(message);
}
return _makeResponse(message, isError: true);
}
}
......
......@@ -43,8 +43,9 @@ class _InternalNoTransientCallbacksCondition implements WaitCondition {
/// The [condition] argument must not be null.
factory _InternalNoTransientCallbacksCondition.deserialize(SerializableWaitCondition condition) {
assert(condition != null);
if (condition.conditionName != 'NoTransientCallbacksCondition')
if (condition.conditionName != 'NoTransientCallbacksCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
return const _InternalNoTransientCallbacksCondition();
}
......@@ -71,8 +72,9 @@ class _InternalNoPendingFrameCondition implements WaitCondition {
/// The [condition] argument must not be null.
factory _InternalNoPendingFrameCondition.deserialize(SerializableWaitCondition condition) {
assert(condition != null);
if (condition.conditionName != 'NoPendingFrameCondition')
if (condition.conditionName != 'NoPendingFrameCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
return const _InternalNoPendingFrameCondition();
}
......@@ -99,8 +101,9 @@ class _InternalFirstFrameRasterizedCondition implements WaitCondition {
/// The [condition] argument must not be null.
factory _InternalFirstFrameRasterizedCondition.deserialize(SerializableWaitCondition condition) {
assert(condition != null);
if (condition.conditionName != 'FirstFrameRasterizedCondition')
if (condition.conditionName != 'FirstFrameRasterizedCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
return const _InternalFirstFrameRasterizedCondition();
}
......@@ -125,8 +128,9 @@ class _InternalNoPendingPlatformMessagesCondition implements WaitCondition {
/// The [condition] argument must not be null.
factory _InternalNoPendingPlatformMessagesCondition.deserialize(SerializableWaitCondition condition) {
assert(condition != null);
if (condition.conditionName != 'NoPendingPlatformMessagesCondition')
if (condition.conditionName != 'NoPendingPlatformMessagesCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
return const _InternalNoPendingPlatformMessagesCondition();
}
......@@ -161,8 +165,9 @@ class _InternalCombinedCondition implements WaitCondition {
/// The [condition] argument must not be null.
factory _InternalCombinedCondition.deserialize(SerializableWaitCondition condition) {
assert(condition != null);
if (condition.conditionName != 'CombinedCondition')
if (condition.conditionName != 'CombinedCondition') {
throw SerializationException('Error occurred during deserializing from the given condition: ${condition.serialize()}');
}
final CombinedCondition combinedCondition = condition as CombinedCondition;
final List<WaitCondition> conditions = combinedCondition.conditions.map(deserializeCondition).toList();
return _InternalCombinedCondition(conditions);
......
......@@ -314,8 +314,9 @@ class FlutterPreSubmitFileComparator extends FlutterGoldenFileComparator {
suffix: 'flutter_goldens_presubmit.',
);
if (!baseDirectory.existsSync())
if (!baseDirectory.existsSync()) {
baseDirectory.createSync(recursive: true);
}
goldens ??= SkiaGoldClient(baseDirectory);
......@@ -535,8 +536,9 @@ class FlutterLocalFileComparator extends FlutterGoldenFileComparator with LocalC
goldenBytes,
);
if (result.passed)
if (result.passed) {
return true;
}
final String error = await generateFailureOutput(result, golden, basedir);
throw FlutterError(error);
......
......@@ -83,8 +83,9 @@ class SkiaGoldClient {
/// Used by the [FlutterPostSubmitFileComparator] and the
/// [FlutterPreSubmitFileComparator].
Future<void> auth() async {
if (await clientIsAuthorized())
if (await clientIsAuthorized()) {
return;
}
final List<String> authCommand = <String>[
_goldctl,
'auth',
......@@ -124,8 +125,9 @@ class SkiaGoldClient {
/// [FlutterPostSubmitFileComparator].
Future<void> imgtestInit() async {
// This client has already been intialized
if (_initialized)
if (_initialized) {
return;
}
final File keys = workDirectory.childFile('keys.json');
final File failures = workDirectory.childFile('failures.json');
......@@ -234,8 +236,9 @@ class SkiaGoldClient {
/// [FlutterPreSubmitFileComparator].
Future<void> tryjobInit() async {
// This client has already been initialized
if (_tryjobInitialized)
if (_tryjobInitialized) {
return;
}
final File keys = workDirectory.childFile('keys.json');
final File failures = workDirectory.childFile('failures.json');
......@@ -385,8 +388,9 @@ class SkiaGoldClient {
final io.HttpClientResponse response = await request.close();
rawResponse = await utf8.decodeStream(response);
final dynamic jsonResponse = json.decode(rawResponse);
if (jsonResponse is! Map<String, dynamic>)
if (jsonResponse is! Map<String, dynamic>) {
throw const FormatException('Skia gold expectations do not match expected format.');
}
expectation = jsonResponse['digest'] as String?;
} on FormatException catch (error) {
// Ideally we'd use something like package:test's printOnError, but best reliabilty
......
......@@ -436,8 +436,9 @@ abstract class GlobalMaterialLocalizations implements MaterialLocalizations {
@override
TimeOfDayFormat timeOfDayFormat({ bool alwaysUse24HourFormat = false }) {
assert(alwaysUse24HourFormat != null);
if (alwaysUse24HourFormat)
if (alwaysUse24HourFormat) {
return _get24HourVersionOf(timeOfDayFormatRaw);
}
return timeOfDayFormatRaw;
}
......
......@@ -7,8 +7,9 @@ void encodeBundleTranslations(Map<String, dynamic> bundle) {
for (final String key in bundle.keys) {
// The ARB file resource "attributes" for foo are called @foo. Don't need
// to encode them.
if (key.startsWith('@'))
if (key.startsWith('@')) {
continue;
}
final String translation = bundle[key] as String;
// Rewrite the string as a series of unicode characters in JSON format.
// Like "\u0012\u0123\u1234".
......
......@@ -1428,8 +1428,9 @@ void main() {
Locale('de', 'DE'),
],
localeResolutionCallback: (Locale? locale, Iterable<Locale> supportedLocales) {
if (locale == null)
if (locale == null) {
return const Locale('und', 'US');
}
return const Locale('en', 'US');
},
buildContent: (BuildContext context) {
......
......@@ -173,11 +173,12 @@ mixin LocalComparisonOutput {
/// Returns a [ComparisonResult] to describe the pixel differential of the
/// [test] and [master] image bytes provided.
Future<ComparisonResult> compareLists(List<int>? test, List<int>? master) async {
if (identical(test, master))
if (identical(test, master)) {
return ComparisonResult(
passed: true,
diffPercent: 0.0,
);
}
if (test == null || master == null || test.isEmpty || master.isEmpty) {
return ComparisonResult(
......
......@@ -91,8 +91,9 @@ class MatchesGoldenFile extends AsyncMatcher {
throw AssertionError('Future<Image> completed to null');
}
final ByteData? bytes = await image.toByteData(format: ui.ImageByteFormat.png);
if (bytes == null)
if (bytes == null) {
return 'could not encode screenshot.';
}
if (autoUpdateGoldenFiles) {
await goldenFileComparator.update(testNameUri, bytes.buffer.asUint8List());
return null;
......
......@@ -62,8 +62,9 @@ class _DepthFirstChildIterator implements Iterator<Element> {
@override
bool moveNext() {
if (_stack.isEmpty)
if (_stack.isEmpty) {
return false;
}
_current = _stack.removeLast();
_fillChildren(_current);
......
......@@ -500,8 +500,9 @@ class _RenderRootableRepaintBoundary extends RenderRepaintBoundary {
TransformLayer _rootLayer() {
Layer layer = this.layer!;
while (layer.parent != null)
while (layer.parent != null) {
layer = layer.parent!;
}
return layer as TransformLayer;
}
}
......
......@@ -179,8 +179,9 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
_restorationManager = null;
resetGestureBinding();
testTextInput.reset();
if (registerTestTextInput)
if (registerTestTextInput) {
_testTextInput.register();
}
}
@override
......@@ -306,8 +307,9 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
///
/// This is called automatically by [testWidgets].
static TestWidgetsFlutterBinding ensureInitialized([@visibleForTesting Map<String, String>? environment]) {
if (_instance != null)
if (_instance != null) {
return _instance!;
}
return binding.ensureInitialized(environment);
}
......@@ -435,8 +437,9 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
Future<void> setSurfaceSize(Size? size) {
return TestAsyncUtils.guard<void>(() async {
assert(inTest);
if (_surfaceSize == size)
if (_surfaceSize == size) {
return;
}
_surfaceSize = size;
handleMetricsChanged();
});
......@@ -663,8 +666,9 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
reportTestException(_pendingExceptionDetails!, testDescription);
_pendingExceptionDetails = null;
}
if (!completer.isCompleted)
if (!completer.isCompleted) {
completer.complete();
}
};
}
......@@ -714,10 +718,12 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
// information to stack traces, in this case the Trace and Chain classes
// can be present. Because these StackTrace implementations do not follow
// the format the framework expects, we covert them to a vm trace here.
if (stack is stack_trace.Trace)
if (stack is stack_trace.Trace) {
return stack.vmTrace;
if (stack is stack_trace.Chain)
}
if (stack is stack_trace.Chain) {
return stack.toTrace().vmTrace;
}
return stack;
};
final Completer<void> testCompleter = Completer<void>();
......@@ -789,13 +795,15 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
return FlutterError.defaultStackFilter(frames.skip(stackLinesToOmit));
},
informationCollector: () sync* {
if (stackLinesToOmit > 0)
if (stackLinesToOmit > 0) {
yield* omittedFrames;
}
if (showAppDumpInErrors) {
yield DiagnosticsProperty<DiagnosticsNode>('At the time of the failure, the widget tree looked as follows', treeDump, linePrefix: '# ', style: DiagnosticsTreeStyle.flat);
}
if (description.isNotEmpty)
if (description.isNotEmpty) {
yield DiagnosticsProperty<String>('The test description was', description, style: DiagnosticsTreeStyle.errorProperty);
}
},
));
assert(_parentZone != null);
......@@ -839,8 +847,9 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
// alone so that we don't cause more spurious errors.
runApp(Container(key: UniqueKey(), child: _postTestMessage)); // Unmount any remaining widgets.
await pump();
if (registerTestTextInput)
if (registerTestTextInput) {
_testTextInput.unregister();
}
invariantTester();
_verifyAutoUpdateGoldensUnset(autoUpdateGoldensBeforeTest && !isBrowser);
_verifyReportTestExceptionUnset(reportTestExceptionBeforeTest);
......@@ -995,8 +1004,9 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
/// will select the correct test binding implementation
/// automatically.
static AutomatedTestWidgetsFlutterBinding ensureInitialized() {
if (AutomatedTestWidgetsFlutterBinding._instance == null)
if (AutomatedTestWidgetsFlutterBinding._instance == null) {
AutomatedTestWidgetsFlutterBinding();
}
return AutomatedTestWidgetsFlutterBinding.instance;
}
......@@ -1033,8 +1043,9 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
return TestAsyncUtils.guard<void>(() {
assert(inTest);
assert(_clock != null);
if (duration != null)
if (duration != null) {
_currentFakeAsync!.elapse(duration);
}
_phase = newPhase;
if (hasScheduledFrame) {
addTime(const Duration(milliseconds: 500));
......@@ -1057,8 +1068,9 @@ class AutomatedTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
}) {
assert(additionalTime != null);
assert(() {
if (_pendingAsyncTasks == null)
if (_pendingAsyncTasks == null) {
return true;
}
fail(
'Reentrant call to runAsync() denied.\n'
'runAsync() was called, then before its future completed, it '
......@@ -1451,8 +1463,9 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
/// will select the correct test binding implementation
/// automatically.
static LiveTestWidgetsFlutterBinding ensureInitialized() {
if (LiveTestWidgetsFlutterBinding._instance == null)
if (LiveTestWidgetsFlutterBinding._instance == null) {
LiveTestWidgetsFlutterBinding();
}
return LiveTestWidgetsFlutterBinding.instance;
}
......@@ -1499,15 +1512,19 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
@override
void scheduleFrame() {
if (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark)
return; // In benchmark mode, don't actually schedule any engine frames.
if (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark) {
// In benchmark mode, don't actually schedule any engine frames.
return;
}
super.scheduleFrame();
}
@override
void scheduleForcedFrame() {
if (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark)
return; // In benchmark mode, don't actually schedule any engine frames.
if (framePolicy == LiveTestWidgetsFlutterBindingFramePolicy.benchmark) {
// In benchmark mode, don't actually schedule any engine frames.
return;
}
super.scheduleForcedFrame();
}
......@@ -1538,8 +1555,9 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
@override
void handleDrawFrame() {
assert(_doDrawThisFrame != null);
if (_doDrawThisFrame!)
if (_doDrawThisFrame!) {
super.handleDrawFrame();
}
_doDrawThisFrame = null;
_viewNeedsPaint = false;
_expectingFrameToReassemble = false;
......@@ -1595,8 +1613,9 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
final _LiveTestPointerRecord? record = _liveTestRenderView._pointers[event.pointer];
if (record != null) {
record.position = event.position;
if (!event.down)
if (!event.down) {
record.decay = _kPointerDecay;
}
_handleViewNeedsPaint();
} else if (event.down) {
_liveTestRenderView._pointers[event.pointer] = _LiveTestPointerRecord(
......@@ -1630,8 +1649,9 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
case TestBindingEventSource.device:
assert(hitTestResult != null || event is PointerAddedEvent || event is PointerRemovedEvent);
assert(deviceEventDispatcher != null);
if (hitTestResult != null)
if (hitTestResult != null) {
deviceEventDispatcher!.dispatchEvent(event, hitTestResult);
}
break;
}
}
......@@ -1667,8 +1687,9 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
Duration additionalTime = const Duration(milliseconds: 1000),
}) async {
assert(() {
if (!_runningAsyncTasks)
if (!_runningAsyncTasks) {
return true;
}
fail(
'Reentrant call to runAsync() denied.\n'
'runAsync() was called, then before its future completed, it '
......@@ -1890,8 +1911,9 @@ class _LiveTestRenderView extends RenderView {
final _LiveTestPointerRecord record = _pointers[pointer]!;
paint.color = record.color.withOpacity(record.decay < 0 ? (record.decay / (_kPointerDecay - 1)) : 1.0);
canvas.drawPath(path.shift(record.position), paint);
if (record.decay < 0)
if (record.decay < 0) {
dirty = true;
}
record.decay += 1;
}
_pointers
......@@ -1899,8 +1921,9 @@ class _LiveTestRenderView extends RenderView {
.where((int pointer) => _pointers[pointer]!.decay == 0)
.toList()
.forEach(_pointers.remove);
if (dirty && onNeedPaint != null)
if (dirty && onNeedPaint != null) {
scheduleMicrotask(onNeedPaint);
}
}
_label?.paint(context.canvas, offset - const Offset(0.0, 10.0));
}
......
......@@ -182,8 +182,9 @@ abstract class WidgetController {
T _stateOf<T extends State>(Element element, Finder finder) {
TestAsyncUtils.guardSync();
if (element is StatefulElement)
if (element is StatefulElement) {
return element.state as T;
}
throw StateError('Widget of type ${element.widget.runtimeType}, with ${finder.description}, is not a StatefulWidget.');
}
......@@ -1155,8 +1156,9 @@ abstract class WidgetController {
/// Will throw a [StateError] if the finder returns more than one element or
/// if no semantics are found or are not enabled.
SemanticsNode getSemantics(Finder finder) {
if (binding.pipelineOwner.semanticsOwner == null)
if (binding.pipelineOwner.semanticsOwner == null) {
throw StateError('Semantics are not enabled.');
}
final Iterable<Element> candidates = finder.evaluate();
if (candidates.isEmpty) {
throw StateError('Finder returned no matching elements.');
......@@ -1171,8 +1173,9 @@ abstract class WidgetController {
renderObject = renderObject.parent as RenderObject?;
result = renderObject?.debugSemantics;
}
if (result == null)
if (result == null) {
throw StateError('No Semantics data found.');
}
return result;
}
......@@ -1297,8 +1300,9 @@ class LiveWidgetController extends WidgetController {
@override
Future<void> pump([Duration? duration]) async {
if (duration != null)
if (duration != null) {
await Future<void>.delayed(duration);
}
binding.scheduleFrame();
await binding.endOfFrame;
}
......
......@@ -30,8 +30,9 @@ class _WebKeyLocationPair {
String? _keyLabel(LogicalKeyboardKey key) {
final String keyLabel = key.keyLabel;
if (keyLabel.length == 1)
if (keyLabel.length == 1) {
return keyLabel.toLowerCase();
}
return null;
}
......@@ -700,8 +701,9 @@ class KeyEventSimulator {
final Map<String, PhysicalKeyboardKey> result = <String, PhysicalKeyboardKey>{};
for (final PhysicalKeyboardKey key in PhysicalKeyboardKey.knownPhysicalKeys) {
final String? debugName = key.debugName;
if (debugName != null)
if (debugName != null) {
result[debugName] = key;
}
}
return result;
})();
......
......@@ -435,10 +435,11 @@ class CommonFinders {
/// If the `skipOffstage` argument is true (the default), then this skips
/// nodes that are [Offstage] or that are from inactive [Route]s.
Finder bySemanticsLabel(Pattern label, { bool skipOffstage = true }) {
if (WidgetsBinding.instance.pipelineOwner.semanticsOwner == null)
if (WidgetsBinding.instance.pipelineOwner.semanticsOwner == null) {
throw StateError('Semantics are not enabled. '
'Make sure to call tester.ensureSemantics() before using '
'this finder, and call dispose on its return value after.');
}
return byElementPredicate(
(Element element) {
// Multiple elements can have the same renderObject - we want the "owner"
......@@ -550,12 +551,15 @@ abstract class Finder {
final String additional = skipOffstage ? ' (ignoring offstage widgets)' : '';
final List<Element> widgets = evaluate().toList();
final int count = widgets.length;
if (count == 0)
if (count == 0) {
return 'zero widgets with $description$additional';
if (count == 1)
}
if (count == 1) {
return 'exactly one widget with $description$additional: ${widgets.single}';
if (count < 4)
}
if (count < 4) {
return '$count widgets with $description$additional: $widgets';
}
return '$count widgets with $description$additional: ${widgets[0]}, ${widgets[1]}, ${widgets[2]}, ...';
}
}
......@@ -911,8 +915,9 @@ class _DescendantFinder extends Finder {
@override
String get description {
if (matchRoot)
if (matchRoot) {
return '${descendant.description} in the subtree(s) beginning with ${ancestor.description}';
}
return '${descendant.description} that has ancestor(s) with ${ancestor.description}';
}
......@@ -927,8 +932,9 @@ class _DescendantFinder extends Finder {
final List<Element> candidates = ancestorElements.expand<Element>(
(Element element) => collectAllElementsFrom(element, skipOffstage: skipOffstage)
).toSet().toList();
if (matchRoot)
if (matchRoot) {
candidates.insertAll(0, ancestorElements);
}
return candidates;
}
}
......@@ -942,8 +948,9 @@ class _AncestorFinder extends Finder {
@override
String get description {
if (matchRoot)
if (matchRoot) {
return 'ancestor ${ancestor.description} beginning with ${descendant.description}';
}
return '${ancestor.description} which is an ancestor of ${descendant.description}';
}
......@@ -957,8 +964,9 @@ class _AncestorFinder extends Finder {
final List<Element> candidates = <Element>[];
for (final Element root in descendant.evaluate()) {
final List<Element> ancestors = <Element>[];
if (matchRoot)
if (matchRoot) {
ancestors.add(root);
}
root.visitAncestorElements((Element element) {
ancestors.add(element);
return true;
......
......@@ -86,8 +86,9 @@ abstract class GoldenFileComparator {
/// Version numbers are used in golden file tests for package:flutter. You can
/// learn more about these tests [here](https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package:flutter).
Uri getTestUri(Uri key, int? version) {
if (version == null)
if (version == null) {
return key;
}
final String keyString = key.toString();
final String extension = path.extension(keyString);
return Uri.parse('${keyString.split(extension).join()}.$version$extension');
......@@ -193,8 +194,9 @@ abstract class WebGoldenComparator {
/// Version numbers are used in golden file tests for package:flutter. You can
/// learn more about these tests [here](https://github.com/flutter/flutter/wiki/Writing-a-golden-file-test-for-package:flutter).
Uri getTestUri(Uri key, int? version) {
if (version == null)
if (version == null) {
return key;
}
final String keyString = key.toString();
final String extension = path.extension(keyString);
return Uri.parse('${keyString.split(extension).join()}.$version$extension');
......
This diff is collapsed.
......@@ -78,8 +78,9 @@ class TestAsyncUtils {
final List<DiagnosticsNode> information = <DiagnosticsNode>[];
while (_scopeStack.isNotEmpty) {
closedScope = _scopeStack.removeLast();
if (closedScope == scope)
if (closedScope == scope) {
break;
}
if (!leaked) {
information.add(ErrorSummary('Asynchronous call to guarded function leaked.'));
information.add(ErrorHint('You must use "await" with all Future-returning test APIs.'));
......@@ -107,8 +108,9 @@ class TestAsyncUtils {
}
throw FlutterError.fromParts(information);
}
if (error != null)
if (error != null) {
return Future<T>.error(error! as Object, stack);
}
return Future<T>.value(resultValue);
}
return result.then<T>(
......@@ -123,8 +125,9 @@ class TestAsyncUtils {
static Zone? get _currentScopeZone {
Zone? zone = Zone.current;
while (zone != null) {
if (zone[_scopeStack] == true)
if (zone[_scopeStack] == true) {
return zone;
}
zone = zone.parent;
}
return null;
......@@ -174,8 +177,9 @@ class TestAsyncUtils {
skipCount += 1;
scope = candidateScope;
if (skipCount >= _scopeStack.length) {
if (zone == null)
if (zone == null) {
break;
}
// Some people have reported reaching this point, but it's not clear
// why. For now, just silently return.
// TODO(ianh): If we ever get a test case that shows how we reach
......
......@@ -89,11 +89,13 @@ class TestDefaultBinaryMessenger extends BinaryMessenger {
ui.PlatformMessageResponseCallback? callback,
) {
Future<ByteData?>? result;
if (_inboundHandlers.containsKey(channel))
if (_inboundHandlers.containsKey(channel)) {
result = _inboundHandlers[channel]!(data);
}
result ??= Future<ByteData?>.value();
if (callback != null)
if (callback != null) {
result = result.then((ByteData? result) { callback(result); return result; });
}
return result;
}
......
......@@ -36,8 +36,9 @@ void _defaultTestExceptionReporter(FlutterErrorDetails errorDetails, String test
// get the same effect here by calling that error handler directly or indeed just throwing.
// However, we call registerException because that's the semantically correct thing...
String additional = '';
if (testDescription.isNotEmpty)
if (testDescription.isNotEmpty) {
additional = '\nThe test description was: $testDescription';
}
test_package.registerException('Test failed. See exception logs above.$additional', _emptyStackTrace);
}
......
......@@ -98,8 +98,9 @@ class TestPointer {
int? buttons,
}) {
_location = newLocation;
if (buttons != null)
if (buttons != null) {
_buttons = buttons;
}
switch (event.runtimeType) {
case PointerDownEvent:
assert(!isDown);
......@@ -132,8 +133,9 @@ class TestPointer {
assert(!isPanZoomActive);
_isDown = true;
_location = newLocation;
if (buttons != null)
if (buttons != null) {
_buttons = buttons;
}
return PointerDownEvent(
timeStamp: timeStamp,
kind: kind,
......@@ -167,8 +169,9 @@ class TestPointer {
assert(!isPanZoomActive);
final Offset delta = newLocation - location!;
_location = newLocation;
if (buttons != null)
if (buttons != null) {
_buttons = buttons;
}
return PointerMoveEvent(
timeStamp: timeStamp,
kind: kind,
......
......@@ -69,8 +69,9 @@ E? _lastWhereOrNull<E>(Iterable<E> list, bool Function(E) test) {
foundMatching = true;
}
}
if (foundMatching)
if (foundMatching) {
return result;
}
return null;
}
......@@ -414,8 +415,9 @@ Future<void> benchmarkWidgets(
bool semanticsEnabled = false,
}) {
assert(() {
if (mayRunWithAsserts)
if (mayRunWithAsserts) {
return true;
}
debugPrint(kDebugWarning);
return true;
}());
......@@ -499,8 +501,9 @@ Future<void> expectLater(
/// `testWidgets`) can be used as the `vsync` for `AnimationController` objects.
class WidgetTester extends WidgetController implements HitTestDispatcher, TickerProvider {
WidgetTester._(super.binding) {
if (binding is LiveTestWidgetsFlutterBinding)
if (binding is LiveTestWidgetsFlutterBinding) {
(binding as LiveTestWidgetsFlutterBinding).deviceEventDispatcher = this;
}
}
/// The description string of the test currently being run.
......@@ -663,8 +666,9 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
final DateTime endTime = binding.clock.fromNowBy(timeout);
int count = 0;
do {
if (binding.clock.now().isAfter(endTime))
if (binding.clock.now().isAfter(endTime)) {
throw FlutterError('pumpAndSettle timed out');
}
await binding.pump(duration, phase);
count += 1;
} while (binding.hasScheduledFrame);
......@@ -837,8 +841,9 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
int totalNumber = 0;
printToConsole('Some possible finders for the widgets at ${event.position}:');
for (final Element element in candidates) {
if (totalNumber > 13) // an arbitrary number of finders that feels useful without being overwhelming
if (totalNumber > 13) {
break;
}
totalNumber += 1; // optimistically assume we'll be able to describe it
final Widget widget = element.widget;
......@@ -912,8 +917,9 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
totalNumber -= 1; // if we got here, we didn't actually find something to say about it
}
if (totalNumber == 0)
if (totalNumber == 0) {
printToConsole(' <could not come up with any unique finders>');
}
}
}
......
......@@ -569,8 +569,9 @@ class FakeAccessibilityFeatures implements ui.AccessibilityFeatures {
@override
bool operator ==(Object other) {
if (other.runtimeType != runtimeType)
if (other.runtimeType != runtimeType) {
return false;
}
return other is FakeAccessibilityFeatures
&& other.accessibleNavigation == accessibleNavigation
&& other.invertColors == invertColors
......
......@@ -416,12 +416,13 @@ void main() {
const String b = '$kSecondaryMouseButton';
for(int i = 0; i < logs.length; i++) {
if (i == 0)
if (i == 0) {
expect(logs[i], 'down $b');
else if (i != logs.length - 1)
} else if (i != logs.length - 1) {
expect(logs[i], 'move $b');
else
} else {
expect(logs[i], 'up 0');
}
}
},
);
......@@ -472,12 +473,13 @@ void main() {
const String b = '$kSecondaryMouseButton';
for(int i = 0; i < logs.length; i++) {
if (i == 0)
if (i == 0) {
expect(logs[i], 'down $b');
else if (i != logs.length - 1)
} else if (i != logs.length - 1) {
expect(logs[i], 'move $b');
else
} else {
expect(logs[i], 'up 0');
}
}
},
);
......@@ -503,12 +505,13 @@ void main() {
const String b = '$kSecondaryMouseButton';
for(int i = 0; i < logs.length; i++) {
if (i == 0)
if (i == 0) {
expect(logs[i], 'down $b');
else if (i != logs.length - 1)
} else if (i != logs.length - 1) {
expect(logs[i], 'move $b');
else
} else {
expect(logs[i], 'up 0');
}
}
},
);
......@@ -535,12 +538,13 @@ void main() {
const String b = '$kSecondaryMouseButton';
for(int i = 0; i < logs.length; i++) {
if (i == 0)
if (i == 0) {
expect(logs[i], 'down $b');
else if (i != logs.length - 1)
} else if (i != logs.length - 1) {
expect(logs[i], 'move $b');
else
} else {
expect(logs[i], 'up 0');
}
}
},
);
......@@ -599,12 +603,13 @@ void main() {
const String b = '$kSecondaryMouseButton';
for(int i = 0; i < logs.length; i++) {
if (i == 0)
if (i == 0) {
expect(logs[i], 'down $b');
else if (i != logs.length - 1)
} else if (i != logs.length - 1) {
expect(logs[i], 'move $b');
else
} else {
expect(logs[i], 'up 0');
}
}
},
);
......
......@@ -15,8 +15,9 @@ import 'package:flutter_test/flutter_test.dart';
class _MockToStringDeep {
_MockToStringDeep(String str) : _lines = <String>[] {
final List<String> lines = str.split('\n');
for (int i = 0; i < lines.length - 1; ++i)
for (int i = 0; i < lines.length - 1; ++i) {
_lines.add('${lines[i]}\n');
}
// If the last line is empty, that really just means that the previous
// line was terminated with a line break.
......@@ -34,11 +35,13 @@ class _MockToStringDeep {
String toStringDeep({ String prefixLineOne = '', String prefixOtherLines = '' }) {
final StringBuffer sb = StringBuffer();
if (_lines.isNotEmpty)
if (_lines.isNotEmpty) {
sb.write('$prefixLineOne${_lines.first}');
}
for (int i = 1; i < _lines.length; ++i)
for (int i = 1; i < _lines.length; ++i) {
sb.write('$prefixOtherLines${_lines[i]}');
}
return sb.toString();
}
......@@ -560,12 +563,15 @@ void main() {
int actions = 0;
int flags = 0;
const CustomSemanticsAction action = CustomSemanticsAction(label: 'test');
for (final int index in SemanticsAction.values.keys)
for (final int index in SemanticsAction.values.keys) {
actions |= index;
for (final int index in SemanticsFlag.values.keys)
}
for (final int index in SemanticsFlag.values.keys) {
// TODO(mdebbar): Remove this if after https://github.com/flutter/engine/pull/9894
if (SemanticsFlag.values[index] != SemanticsFlag.isMultiline)
if (SemanticsFlag.values[index] != SemanticsFlag.isMultiline) {
flags |= index;
}
}
final SemanticsData data = SemanticsData(
flags: flags,
actions: actions,
......
......@@ -158,10 +158,11 @@ class Registrar extends BinaryMessenger {
@override
void setMessageHandler(String channel, MessageHandler? handler) {
if (handler == null)
if (handler == null) {
_handlers.remove(channel);
else
} else {
_handlers[channel] = handler;
}
}
}
......
......@@ -154,8 +154,9 @@ https://flutter.dev/docs/testing/integration-tests#testing-on-firebase-test-lab
///
/// * [WidgetsFlutterBinding.ensureInitialized], the equivalent in the widgets framework.
static IntegrationTestWidgetsFlutterBinding ensureInitialized() {
if (_instance == null)
if (_instance == null) {
IntegrationTestWidgetsFlutterBinding();
}
return _instance!;
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment