Catch cases in tests where people try to tap on widgets that aren't reachable. (#74798)

This commit is contained in:
Ian Hickson
2021-02-03 16:11:02 -08:00
committed by GitHub
parent 9278ea984f
commit 824042f9b2
53 changed files with 528 additions and 308 deletions

View File

@@ -42,6 +42,15 @@
/// root of the project.
///
/// If no configuration file is located, the test will be executed like normal.
///
/// See also:
///
/// * [WidgetController.hitTestWarningShouldBeFatal], which can be set
/// in a `flutter_test_config.dart` file to turn warnings printed by
/// [WidgetTester.tap] and similar APIs into fatal errors.
/// * [debugCheckIntrinsicSizes], which can be set in a
/// `flutter_test_config.dart` file to enable deeper [RenderBox]
/// tests of the intrinsic APIs automatically while laying out widgets.
library flutter_test;
export 'dart:async' show Future;

View File

@@ -212,7 +212,11 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
/// change the behavior of [debugPrint]. For example,
/// [AutomatedTestWidgetsFlutterBinding] uses it to make [debugPrint]
/// synchronous, disabling its normal throttling behavior.
@protected
///
/// It is also used by some other parts of the test framework (e.g.
/// [WidgetTester.printToConsole]) to ensure that messages from the
/// test framework are displayed to the developer rather than logged
/// by whatever code is overriding [debugPrint].
DebugPrintCallback get debugPrintOverride => debugPrint;
/// The value to set [debugDisableShadows] to while tests are running.

View File

@@ -3,6 +3,7 @@
// found in the LICENSE file.
import 'package:clock/clock.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/rendering.dart';
import 'package:flutter/services.dart';
@@ -251,10 +252,23 @@ abstract class WidgetController {
/// Dispatch a pointer down / pointer up sequence at the center of
/// the given widget, assuming it is exposed.
///
/// If the center of the widget is not exposed, this might send events to
/// another object.
Future<void> tap(Finder finder, {int? pointer, int buttons = kPrimaryButton}) {
return tapAt(getCenter(finder), pointer: pointer, buttons: buttons);
/// {@template flutter.flutter_test.WidgetController.tap.warnIfMissed}
/// The `warnIfMissed` argument, if true (the default), causes a warning to be
/// displayed on the console if the specified [Finder] indicates a widget and
/// location that, were a pointer event to be sent to that location, would not
/// actually send any events to the widget (e.g. because the widget is
/// obscured, or the location is off-screen, or the widget is transparent to
/// pointer events).
///
/// Set the argument to false to silence that warning if you intend to not
/// actually hit the specified element.
/// {@endtemplate}
///
/// For example, a test that verifies that tapping a disabled button does not
/// trigger the button would set `warnIfMissed` to false, because the button
/// would ignore the tap.
Future<void> tap(Finder finder, {int? pointer, int buttons = kPrimaryButton, bool warnIfMissed = true}) {
return tapAt(getCenter(finder, warnIfMissed: warnIfMissed, callee: 'tap'), pointer: pointer, buttons: buttons);
}
/// Dispatch a pointer down / pointer up sequence at the given location.
@@ -268,11 +282,19 @@ abstract class WidgetController {
/// Dispatch a pointer down at the center of the given widget, assuming it is
/// exposed.
///
/// If the center of the widget is not exposed, this might send events to
/// another object.
Future<TestGesture> press(Finder finder, {int? pointer, int buttons = kPrimaryButton}) {
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// The return value is a [TestGesture] object that can be used to continue the
/// gesture (e.g. moving the pointer or releasing it).
///
/// See also:
///
/// * [tap], which presses and releases a pointer at the given location.
/// * [longPress], which presses and releases a pointer with a gap in
/// between long enough to trigger the long-press gesture.
Future<TestGesture> press(Finder finder, {int? pointer, int buttons = kPrimaryButton, bool warnIfMissed = true}) {
return TestAsyncUtils.guard<TestGesture>(() {
return startGesture(getCenter(finder), pointer: pointer, buttons: buttons);
return startGesture(getCenter(finder, warnIfMissed: warnIfMissed, callee: 'press'), pointer: pointer, buttons: buttons);
});
}
@@ -280,10 +302,16 @@ abstract class WidgetController {
/// [kLongPressTimeout] + [kPressTimeout] between the two events) at the
/// center of the given widget, assuming it is exposed.
///
/// If the center of the widget is not exposed, this might send events to
/// another object.
Future<void> longPress(Finder finder, {int? pointer, int buttons = kPrimaryButton}) {
return longPressAt(getCenter(finder), pointer: pointer, buttons: buttons);
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// For example, consider a widget that, when long-pressed, shows an overlay
/// that obscures the original widget. A test for that widget might first
/// long-press that widget with `warnIfMissed` at its default value true, then
/// later verify that long-pressing the same location (using the same finder)
/// has no effect (since the widget is now obscured), setting `warnIfMissed`
/// to false on that second call.
Future<void> longPress(Finder finder, {int? pointer, int buttons = kPrimaryButton, bool warnIfMissed = true}) {
return longPressAt(getCenter(finder, warnIfMissed: warnIfMissed, callee: 'longPress'), pointer: pointer, buttons: buttons);
}
/// Dispatch a pointer down / pointer up sequence at the given location with
@@ -299,8 +327,7 @@ abstract class WidgetController {
/// Attempts a fling gesture starting from the center of the given
/// widget, moving the given distance, reaching the given speed.
///
/// If the middle of the widget is not exposed, this might send
/// events to another object.
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// {@template flutter.flutter_test.WidgetController.fling}
/// This can pump frames.
@@ -342,9 +369,10 @@ abstract class WidgetController {
Duration frameInterval = const Duration(milliseconds: 16),
Offset initialOffset = Offset.zero,
Duration initialOffsetDelay = const Duration(seconds: 1),
bool warnIfMissed = true,
}) {
return flingFrom(
getCenter(finder),
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'fling'),
offset,
speed,
pointer: pointer,
@@ -467,8 +495,7 @@ abstract class WidgetController {
/// Attempts to drag the given widget by the given offset, by
/// starting a drag in the middle of the widget.
///
/// If the middle of the widget is not exposed, this might send
/// events to another object.
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// If you want the drag to end with a speed so that the gesture recognition
/// system identifies the gesture as a fling, consider using [fling] instead.
@@ -500,9 +527,10 @@ abstract class WidgetController {
int buttons = kPrimaryButton,
double touchSlopX = kDragSlopDefault,
double touchSlopY = kDragSlopDefault,
bool warnIfMissed = true,
}) {
return dragFrom(
getCenter(finder),
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'drag'),
offset,
pointer: pointer,
buttons: buttons,
@@ -606,8 +634,7 @@ abstract class WidgetController {
/// Attempts to drag the given widget by the given offset in the `duration`
/// time, starting in the middle of the widget.
///
/// If the middle of the widget is not exposed, this might send
/// events to another object.
/// {@macro flutter.flutter_test.WidgetController.tap.warnIfMissed}
///
/// This is the timed version of [drag]. This may or may not result in a
/// [fling] or ballistic animation, depending on the speed from
@@ -629,9 +656,10 @@ abstract class WidgetController {
int? pointer,
int buttons = kPrimaryButton,
double frequency = 60.0,
bool warnIfMissed = true,
}) {
return timedDragFrom(
getCenter(finder),
getCenter(finder, warnIfMissed: warnIfMissed, callee: 'timedDrag'),
offset,
duration,
pointer: pointer,
@@ -779,41 +807,157 @@ abstract class WidgetController {
});
}
/// Calls [debugPrint] with the given message.
///
/// This is overridden by the WidgetTester subclass to use the test binding's
/// [TestWidgetsFlutterBinding.debugPrintOverride], so that it appears on the
/// console even if the test is logging output from the application.
@protected
void printToConsole(String message) {
debugPrint(message);
}
// GEOMETRY
/// Returns the point at the center of the given widget.
Offset getCenter(Finder finder) {
return _getElementPoint(finder, (Size size) => size.center(Offset.zero));
///
/// {@template flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
/// If `warnIfMissed` is true (the default is false), then the returned
/// coordinate is checked to see if a hit test at the returned location would
/// actually include the specified element in the [HitTestResult], and if not,
/// a warning is printed to the console.
///
/// The `callee` argument is used to identify the method that should be
/// referenced in messages regarding `warnIfMissed`. It can be ignored unless
/// this method is being called from another that is forwarding its own
/// `warnIfMissed` parameter (see e.g. the implementation of [tap]).
/// {@endtemplate}
Offset getCenter(Finder finder, { bool warnIfMissed = false, String callee = 'getCenter' }) {
return _getElementPoint(finder, (Size size) => size.center(Offset.zero), warnIfMissed: warnIfMissed, callee: callee);
}
/// Returns the point at the top left of the given widget.
Offset getTopLeft(Finder finder) {
return _getElementPoint(finder, (Size size) => Offset.zero);
///
/// {@macro flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
Offset getTopLeft(Finder finder, { bool warnIfMissed = false, String callee = 'getTopLeft' }) {
return _getElementPoint(finder, (Size size) => Offset.zero, warnIfMissed: warnIfMissed, callee: callee);
}
/// Returns the point at the top right of the given widget. This
/// point is not inside the object's hit test area.
Offset getTopRight(Finder finder) {
return _getElementPoint(finder, (Size size) => size.topRight(Offset.zero));
///
/// {@macro flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
Offset getTopRight(Finder finder, { bool warnIfMissed = false, String callee = 'getTopRight' }) {
return _getElementPoint(finder, (Size size) => size.topRight(Offset.zero), warnIfMissed: warnIfMissed, callee: callee);
}
/// Returns the point at the bottom left of the given widget. This
/// point is not inside the object's hit test area.
Offset getBottomLeft(Finder finder) {
return _getElementPoint(finder, (Size size) => size.bottomLeft(Offset.zero));
///
/// {@macro flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
Offset getBottomLeft(Finder finder, { bool warnIfMissed = false, String callee = 'getBottomLeft' }) {
return _getElementPoint(finder, (Size size) => size.bottomLeft(Offset.zero), warnIfMissed: warnIfMissed, callee: callee);
}
/// Returns the point at the bottom right of the given widget. This
/// point is not inside the object's hit test area.
Offset getBottomRight(Finder finder) {
return _getElementPoint(finder, (Size size) => size.bottomRight(Offset.zero));
///
/// {@macro flutter.flutter_test.WidgetController.getCenter.warnIfMissed}
Offset getBottomRight(Finder finder, { bool warnIfMissed = false, String callee = 'getBottomRight' }) {
return _getElementPoint(finder, (Size size) => size.bottomRight(Offset.zero), warnIfMissed: warnIfMissed, callee: callee);
}
Offset _getElementPoint(Finder finder, Offset sizeToPoint(Size size)) {
/// Whether warnings relating to hit tests not hitting their mark should be
/// fatal (cause the test to fail).
///
/// Some methods, e.g. [tap], have an argument `warnIfMissed` which causes a
/// warning to be displayed if the specified [Finder] indicates a widget and
/// location that, were a pointer event to be sent to that location, would not
/// actually send any events to the widget (e.g. because the widget is
/// obscured, or the location is off-screen, or the widget is transparent to
/// pointer events).
///
/// This warning was added in 2021. In ordinary operation this warning is
/// non-fatal since making it fatal would be a significantly breaking change
/// for anyone who already has tests relying on the ability to target events
/// using finders where the events wouldn't reach the widgets specified by the
/// finders in question.
///
/// However, doing this is usually unintentional. To make the warning fatal,
/// thus failing any tests where it occurs, this property can be set to true.
///
/// Typically this is done using a `flutter_test_config.dart` file, as described
/// in the documentation for the [flutter_test] library.
static bool hitTestWarningShouldBeFatal = false;
Offset _getElementPoint(Finder finder, Offset sizeToPoint(Size size), { required bool warnIfMissed, required String callee }) {
TestAsyncUtils.guardSync();
final Element element = finder.evaluate().single;
final Iterable<Element> elements = finder.evaluate();
if (elements.isEmpty) {
throw FlutterError('The finder "$finder" (used in a call to "$callee()") could not find any matching widgets.');
}
if (elements.length > 1) {
throw FlutterError('The finder "$finder" (used in a call to "$callee()") ambiguously found multiple matching widgets. The "$callee()" method needs a single target.');
}
final Element element = elements.single;
final RenderObject? renderObject = element.renderObject;
if (renderObject == null) {
throw FlutterError(
'The finder "$finder" (used in a call to "$callee()") found an element, but it does not have a corresponding render object. '
'Maybe the element has not yet been rendered?'
);
}
if (renderObject is! RenderBox) {
throw FlutterError(
'The finder "$finder" (used in a call to "$callee()") found an element whose corresponding render object is not a RenderBox (it is a ${renderObject.runtimeType}: "$renderObject"). '
'Unfortunately "$callee()" only supports targetting widgets that correspond to RenderBox objects in the rendering.'
);
}
final RenderBox box = element.renderObject! as RenderBox;
return box.localToGlobal(sizeToPoint(box.size));
final Offset location = box.localToGlobal(sizeToPoint(box.size));
if (warnIfMissed) {
final HitTestResult result = HitTestResult();
binding.hitTest(result, location);
bool found = false;
for (final HitTestEntry entry in result.path) {
if (entry.target == box) {
found = true;
break;
}
}
if (!found) {
bool outOfBounds = false;
if (binding.renderView != null && binding.renderView.size != null) {
outOfBounds = !(Offset.zero & binding.renderView.size).contains(location);
}
if (hitTestWarningShouldBeFatal) {
throw FlutterError.fromParts(<DiagnosticsNode>[
ErrorSummary('Finder specifies a widget that would not receive pointer events.'),
ErrorDescription('A call to $callee() with finder "$finder" derived an Offset ($location) that would not hit test on the specified widget.'),
ErrorHint('Maybe the widget is actually off-screen, or another widget is obscuring it, or the widget cannot receive pointer events.'),
if (outOfBounds)
ErrorHint('Indeed, $location is outside the bounds of the root of the render tree, ${binding.renderView.size}.'),
box.toDiagnosticsNode(name: 'The finder corresponds to this RenderBox', style: DiagnosticsTreeStyle.singleLine),
ErrorDescription('The hit test result at that offset is: $result'),
ErrorDescription('If you expected this target not to be able to receive pointer events, pass "warnIfMissed: false" to "$callee()".'),
ErrorDescription('To make this error into a non-fatal warning, set WidgetController.hitTestWarningShouldBeFatal to false.'),
]);
}
printToConsole(
'\n'
'Warning: A call to $callee() with finder "$finder" derived an Offset ($location) that would not hit test on the specified widget.\n'
'Maybe the widget is actually off-screen, or another widget is obscuring it, or the widget cannot receive pointer events.\n'
'${outOfBounds ? "Indeed, $location is outside the bounds of the root of the render tree, ${binding.renderView.size}.\n" : ""}'
'The finder corresponds to this RenderBox: $box\n'
'The hit test result at that offset is: $result\n'
'${StackTrace.current}'
'To silence this warning, pass "warnIfMissed: false" to "$callee()".\n'
'To make this warning fatal, set WidgetController.hitTestWarningShouldBeFatal to true.\n'
''
);
}
}
return location;
}
/// Returns the size of the given widget. This is only valid once

View File

@@ -797,7 +797,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
orElse: () => null,
);
if (innerTargetElement == null) {
debugPrint('No widgets found at ${binding.globalToLocal(event.position)}.');
printToConsole('No widgets found at ${binding.globalToLocal(event.position)}.');
return;
}
final List<Element> candidates = <Element>[];
@@ -810,7 +810,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
int numberOfWithTexts = 0;
int numberOfTypes = 0;
int totalNumber = 0;
debugPrint('Some possible finders for the widgets at ${binding.globalToLocal(event.position)}:');
printToConsole('Some possible finders for the widgets at ${binding.globalToLocal(event.position)}:');
for (final Element element in candidates) {
if (totalNumber > 13) // an arbitrary number of finders that feels useful without being overwhelming
break;
@@ -820,7 +820,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
if (widget is Tooltip) {
final Iterable<Element> matches = find.byTooltip(widget.message).evaluate();
if (matches.length == 1) {
debugPrint(" find.byTooltip('${widget.message}')");
printToConsole(" find.byTooltip('${widget.message}')");
continue;
}
}
@@ -832,7 +832,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
final Iterable<Element> matches = find.text(text).evaluate();
descendantText = widget.data;
if (matches.length == 1) {
debugPrint(" find.text('$text')");
printToConsole(" find.text('$text')");
continue;
}
}
@@ -850,7 +850,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
if (keyLabel != null) {
final Iterable<Element> matches = find.byKey(key).evaluate();
if (matches.length == 1) {
debugPrint(' find.byKey($keyLabel)');
printToConsole(' find.byKey($keyLabel)');
continue;
}
}
@@ -860,7 +860,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
if (numberOfTypes < 5) {
final Iterable<Element> matches = find.byType(widget.runtimeType).evaluate();
if (matches.length == 1) {
debugPrint(' find.byType(${widget.runtimeType})');
printToConsole(' find.byType(${widget.runtimeType})');
numberOfTypes += 1;
continue;
}
@@ -869,7 +869,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
if (descendantText != null && numberOfWithTexts < 5) {
final Iterable<Element> matches = find.widgetWithText(widget.runtimeType, descendantText).evaluate();
if (matches.length == 1) {
debugPrint(" find.widgetWithText(${widget.runtimeType}, '$descendantText')");
printToConsole(" find.widgetWithText(${widget.runtimeType}, '$descendantText')");
numberOfWithTexts += 1;
continue;
}
@@ -879,7 +879,7 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
if (!_isPrivate(element.runtimeType)) {
final Iterable<Element> matches = find.byElementType(element.runtimeType).evaluate();
if (matches.length == 1) {
debugPrint(' find.byElementType(${element.runtimeType})');
printToConsole(' find.byElementType(${element.runtimeType})');
continue;
}
}
@@ -887,7 +887,7 @@ 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)
debugPrint(' <could not come up with any unique finders>');
printToConsole(' <could not come up with any unique finders>');
}
}
@@ -1061,6 +1061,11 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
await tap(backButton);
});
}
@override
void printToConsole(String message) {
binding.debugPrintOverride(message);
}
}
typedef _TickerDisposeCallback = void Function(_TestTicker ticker);