Thanks to visit codestin.com
Credit goes to github.com

Skip to content

[flutter_test] Add flag to send device pointer events to the framework #108430

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Aug 3, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 43 additions & 1 deletion packages/flutter_test/lib/src/binding.dart
Original file line number Diff line number Diff line change
Expand Up @@ -494,9 +494,25 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
///
/// When [handlePointerEvent] is called directly, [pointerEventSource]
/// is [TestBindingEventSource.device].
///
/// This means that pointer events triggered by the [WidgetController] (e.g.
/// via [WidgetController.tap]) will result in actual interactions with the
/// UI, but other pointer events such as those from physical taps will be
/// dropped. See also [shouldPropagateDevicePointerEvents] if this is
/// undesired.
TestBindingEventSource get pointerEventSource => _pointerEventSource;
TestBindingEventSource _pointerEventSource = TestBindingEventSource.device;

/// Whether pointer events from [TestBindingEventSource.device] will be
/// propagated to the framework, or dropped.
///
/// Setting this can be useful to interact with the app in some other way
/// besides through the [WidgetController], such as with `adb shell input tap`
/// on Android.
///
/// See also [pointerEventSource].
bool shouldPropagateDevicePointerEvents = false;
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If we land this, we'd need ways to make sure it gets reset after tests.

The frameworks normal solution here would be to subclass the bindings. Is that still not possible in google's testing environment?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can subclass the binding in Google3, just that it adds a bit of complexity and I don't think it's necessary if this is more formally supported through a setting like this.

Is it important for us to reset the value though? I think users should be free to change this value wherever as some sort of "global" - whether it is in a testWidgets() or at the top of their main(), depending on their use case.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in the other comment below

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: maybe drop the should from the name?

Copy link
Member Author

@jiahaog jiahaog Jul 27, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Effective Dart tells us to prefix it with a should though. I don't feel very strongly about this though, happy to remove it.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

How do we make sure this setting doesn't leak between tests?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Not sure I understand, can you elaborate more on what you mean by leaking the setting?

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Basically if you have several tests in a file, and one test changes the value of this, there should be some validation at the end of the test that makes sure it is unset.

If you grep the repo for debugAssertAllPaintingVarsUnset for example, we make sure that these global sorts of things get reset at the end of each testWidgets call.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks, I'll try to add that.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done


/// Dispatch an event to the targets found by a hit test on its position,
/// and remember its source as [pointerEventSource].
///
Expand Down Expand Up @@ -836,6 +852,7 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
final bool autoUpdateGoldensBeforeTest = autoUpdateGoldenFiles && !isBrowser;
final TestExceptionReporter reportTestExceptionBeforeTest = reportTestException;
final ErrorWidgetBuilder errorWidgetBuilderBeforeTest = ErrorWidget.builder;
final bool shouldPropagateDevicePointerEventsBeforeTest = shouldPropagateDevicePointerEvents;

// run the test
await testBody();
Expand All @@ -854,6 +871,7 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
_verifyAutoUpdateGoldensUnset(autoUpdateGoldensBeforeTest && !isBrowser);
_verifyReportTestExceptionUnset(reportTestExceptionBeforeTest);
_verifyErrorWidgetBuilderUnset(errorWidgetBuilderBeforeTest);
_verifyShouldPropagateDevicePointerEventsUnset(shouldPropagateDevicePointerEventsBeforeTest);
_verifyInvariants();
}

Expand Down Expand Up @@ -943,6 +961,21 @@ abstract class TestWidgetsFlutterBinding extends BindingBase
}());
}

void _verifyShouldPropagateDevicePointerEventsUnset(bool valueBeforeTest) {
assert(() {
if (shouldPropagateDevicePointerEvents != valueBeforeTest) {
FlutterError.reportError(FlutterErrorDetails(
exception: FlutterError(
'The value of shouldPropagateDevicePointerEvents was changed by the test.',
),
stack: StackTrace.current,
library: 'Flutter test framework',
));
}
return true;
}());
}

/// Called by the [testWidgets] function after a test is executed.
void postTest() {
assert(inTest);
Expand Down Expand Up @@ -1595,7 +1628,8 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
///
/// Normally, device events are silently dropped. However, if this property is
/// set to a non-null value, then the events will be routed to its
/// [HitTestDispatcher.dispatchEvent] method instead.
/// [HitTestDispatcher.dispatchEvent] method instead, unless
/// [shouldPropagateDevicePointerEvents] is true.
///
/// Events dispatched by [TestGesture] are not affected by this.
HitTestDispatcher? deviceEventDispatcher;
Expand Down Expand Up @@ -1630,6 +1664,10 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
super.handlePointerEvent(event);
break;
case TestBindingEventSource.device:
if (shouldPropagateDevicePointerEvents) {
super.handlePointerEvent(event);
break;
}
if (deviceEventDispatcher != null) {
// The pointer events received with this source has a global position
// (see [handlePointerEventForSource]). Transform it to the local
Expand All @@ -1651,6 +1689,10 @@ class LiveTestWidgetsFlutterBinding extends TestWidgetsFlutterBinding {
break;
case TestBindingEventSource.device:
assert(hitTestResult != null || event is PointerAddedEvent || event is PointerRemovedEvent);
if (shouldPropagateDevicePointerEvents) {
super.dispatchEvent(event, hitTestResult);
break;
}
assert(deviceEventDispatcher != null);
if (hitTestResult != null) {
deviceEventDispatcher!.dispatchEvent(event, hitTestResult);
Expand Down
8 changes: 8 additions & 0 deletions packages/flutter_test/lib/src/widget_tester.dart
Original file line number Diff line number Diff line change
Expand Up @@ -502,6 +502,10 @@ Future<void> expectLater(
///
/// For convenience, instances of this class (such as the one provided by
/// `testWidgets`) can be used as the `vsync` for `AnimationController` objects.
///
/// When the binding is [LiveTestWidgetsFlutterBinding], events from
/// [LiveTestWidgetsFlutterBinding.deviceEventDispatcher] will be handled in
/// [dispatchEvent].
class WidgetTester extends WidgetController implements HitTestDispatcher, TickerProvider {
WidgetTester._(super.binding) {
if (binding is LiveTestWidgetsFlutterBinding) {
Expand Down Expand Up @@ -817,6 +821,10 @@ class WidgetTester extends WidgetController implements HitTestDispatcher, Ticker
}

/// Handler for device events caught by the binding in live test mode.
///
/// [PointerDownEvent]s received here will only print a diagnostic message
/// showing possible [Finder]s that can be used to interact with the widget at
/// the location of [result].
@override
void dispatchEvent(PointerEvent event, HitTestResult result) {
if (event is PointerDownEvent) {
Expand Down
55 changes: 54 additions & 1 deletion packages/flutter_test/test/live_binding_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import 'package:flutter_test/flutter_test.dart';

// This file is for testings that require a `LiveTestWidgetsFlutterBinding`
void main() {
LiveTestWidgetsFlutterBinding();
final LiveTestWidgetsFlutterBinding binding = LiveTestWidgetsFlutterBinding();
testWidgets('Input PointerAddedEvent', (WidgetTester tester) async {
await tester.pumpWidget(const MaterialApp(home: Text('Test')));
await tester.pump();
Expand Down Expand Up @@ -99,4 +99,57 @@ void main() {

await expectLater(tester.binding.reassembleApplication(), completes);
}, timeout: const Timeout(Duration(seconds: 30)));

testWidgets('shouldPropagateDevicePointerEvents can override events from ${TestBindingEventSource.device}', (WidgetTester tester) async {
binding.shouldPropagateDevicePointerEvents = true;

await tester.pumpWidget(_ShowNumTaps());

final Offset position = tester.getCenter(find.text('0'));

// Simulates a real device tap.
//
// `handlePointerEventForSource defaults to sending events using
// TestBindingEventSource.device. This will not be forwarded to the actual
// gesture handlers, unless `shouldPropagateDevicePointerEvents` is true.
binding.handlePointerEventForSource(
PointerDownEvent(position: position),
);
binding.handlePointerEventForSource(
PointerUpEvent(position: position),
);

await tester.pump();

expect(find.text('1'), findsOneWidget);

// Reset the value, otherwise the test will fail when it checks that this
// has not been changed as an invariant.
binding.shouldPropagateDevicePointerEvents = false;
});
}

/// A widget that shows the number of times it has been tapped.
class _ShowNumTaps extends StatefulWidget {
@override
_ShowNumTapsState createState() => _ShowNumTapsState();
}

class _ShowNumTapsState extends State<_ShowNumTaps> {
int _counter = 0;

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: () {
setState(() {
_counter++;
});
},
child: Directionality(
textDirection: TextDirection.ltr,
child: Text(_counter.toString()),
),
);
}
}