Skip to content
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

[flutter_test] A KeyDownEvent is dispatched, but the state shows that the physical key is already pressed #148986

Closed
maheshmnj opened this issue May 23, 2024 · 5 comments
Labels
r: solved Issue is closed as solved

Comments

@maheshmnj
Copy link
Member

maheshmnj commented May 23, 2024

Steps to reproduce

  1. Create a new flutter project
  2. add the test test/flutter_test.dart
  3. Run the test using flutter test test/flutter_test.dart

The test is failing when you simulate multiple simulateKeyDownEvent as per my understanding this used to work in flutter 3.19 (not exactly sure about the version) and below

Note: If you only have only one simulateKeyDownEvent the test will pass.

Expected results

The test should pass without any exception

Actual results

The test fails with exception

Code sample

Code sample
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('simulate consecutive key down', (tester) async {
    await tester.pumpWidget(const SizedBox());
    await simulateKeyDownEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyDownEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyDownEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyDownEvent(LogicalKeyboardKey.enter);
  });
}

Screenshots or Video

Screenshots / Video demonstration

[Upload media here]

Logs

Logs
mahesh@Maheshs-MacBook-Air-M1-3 searchfield % flutter test test/flutter_test.dart
00:03 +0: simulate consecutive key down                                                                                                 
══╡ EXCEPTION CAUGHT BY FLUTTER TEST FRAMEWORK ╞════════════════════════════════════════════════════
The following assertion was thrown running a test:
A KeyDownEvent is dispatched, but the state shows that the physical key is already pressed. If this
occurs in real application, please report this bug to Flutter. If this occurs in unit tests, please
ensure that simulated events follow Flutter's event model as documented in `HardwareKeyboard`. This
was the event: KeyDownEvent#e0d6b(physicalKey: PhysicalKeyboardKey#556a0(usbHidUsage: "0x00070051",
debugName: "Arrow Down"), logicalKey: LogicalKeyboardKey#80d00(keyId: "0x100000301", keyLabel:
"Arrow Down", debugName: "Arrow Down"), character: null, timeStamp: 0:00:00.000000)
'package:flutter/src/services/hardware_keyboard.dart':
Failed assertion: line 505 pos 16: '!_pressedKeys.containsKey(event.physicalKey)'

Either the assertion indicates an error in the framework itself, or we should provide substantially
more information in this error message to help you determine and fix the underlying cause.
In either case, please report this assertion by filing a bug on GitHub:
  https://github.com/flutter/flutter/issues/new?template=2_bug.yml

When the exception was thrown, this was the stack:
#2      HardwareKeyboard._assertEventIsRegular.<anonymous closure> (package:flutter/src/services/hardware_keyboard.dart:505:16)
#3      HardwareKeyboard._assertEventIsRegular (package:flutter/src/services/hardware_keyboard.dart:520:6)
#4      HardwareKeyboard.handleKeyEvent (package:flutter/src/services/hardware_keyboard.dart:643:5)
#5      KeyEventManager.handleRawKeyMessage (package:flutter/src/services/hardware_keyboard.dart:1164:37)
#6      BasicMessageChannel.setMessageHandler.<anonymous closure> (package:flutter/src/services/platform_channel.dart:235:49)
#7      TestDefaultBinaryMessenger.handlePlatformMessage (package:flutter_test/src/test_default_binary_messenger.dart:99:42)
#8      KeyEventSimulator._simulateKeyEventByRawEvent.<anonymous closure> (package:flutter_test/src/event_simulation.dart:655:79)
#11     TestAsyncUtils.guard (package:flutter_test/src/test_async_utils.dart:71:41)
#12     KeyEventSimulator._simulateKeyEventByRawEvent (package:flutter_test/src/event_simulation.dart:653:27)
#13     KeyEventSimulator.simulateKeyDownEvent.simulateByRawEvent (package:flutter_test/src/event_simulation.dart:740:14)
#14     KeyEventSimulator.simulateKeyDownEvent (package:flutter_test/src/event_simulation.dart:760:23)
#15     simulateKeyDownEvent (package:flutter_test/src/event_simulation.dart:883:48)
#16     main.<anonymous closure> (file:///Users/mahesh/Development/oss/my_packages/searchfield/test/flutter_test.dart:11:11)
<asynchronous suspension>
#17     testWidgets.<anonymous closure>.<anonymous closure> (package:flutter_test/src/widget_tester.dart:183:15)
<asynchronous suspension>
#18     TestWidgetsFlutterBinding._runTestBody (package:flutter_test/src/binding.dart:1017:5)
<asynchronous suspension>
<asynchronous suspension>
(elided 5 frames from class _AssertionError, dart:async, and package:stack_trace)

The test description was:
  simulate consecutive key down
════════════════════════════════════════════════════════════════════════════════════════════════════
00:03 +0 -1: simulate consecutive key down [E]                                                                                          
  Test failed. See exception logs above.
  The test description was: simulate consecutive key down
  

To run this test again: /Users/mahesh/Development/flutter/bin/cache/dart-sdk/bin/dart test /Users/mahesh/Development/oss/my_packages/searchfield/test/flutter_test.dart -p vm --plain-name 'simulate consecutive key down'
00:03 +0 -1: Some tests failed. 

Flutter Doctor output

Doctor output
mahesh@Maheshs-MacBook-Air-M1-3 searchfield % flutter doctor -v                  
Could not load custom device from config index 0: Expected enabled to be a boolean.
[✓] Flutter (Channel stable, 3.22.0, on macOS 14.3.1 23D60 darwin-arm64, locale en-IN)
    • Flutter version 3.22.0 on channel stable at /Users/mahesh/Development/flutter
    • Upstream repository https://github.com/flutter/flutter.git
    • Framework revision 5dcb86f68f (2 weeks ago), 2024-05-09 07:39:20 -0500
    • Engine revision f6344b75dc
    • Dart version 3.4.0
    • DevTools version 2.34.3

[✓] Android toolchain - develop for Android devices (Android SDK version 33.0.0-rc4)
    • Android SDK at /Users/mahesh/Library/Android/sdk
    • Platform android-34, build-tools 33.0.0-rc4
    • ANDROID_HOME = /Users/mahesh/Library/Android/sdk
    • Java binary at: /Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java
    • Java version OpenJDK Runtime Environment (build 17.0.7+0-17.0.7b1000.6-10550314)
    • All Android licenses accepted.

[!] Xcode - develop for iOS and macOS (Xcode 15.0.1)
    • Xcode at /Applications/Xcode.app/Contents/Developer
    • Build 15A507
    ✗ Unable to get list of installed Simulator runtimes.
    • CocoaPods version 1.14.3

[✓] Chrome - develop for the web
    • Chrome at /Applications/Google Chrome.app/Contents/MacOS/Google Chrome

[✓] Android Studio (version 2023.1)
    • Android Studio at /Applications/Android Studio.app/Contents
    • Flutter plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/9212-flutter
    • Dart plugin can be installed from:
      🔨 https://plugins.jetbrains.com/plugin/6351-dart
    • Java version OpenJDK Runtime Environment (build 17.0.7+0-17.0.7b1000.6-10550314)

[✓] IntelliJ IDEA Community Edition (version 2021.2.1)
    • IntelliJ at /Applications/IntelliJ IDEA CE.app
    • Flutter plugin version 61.2.4
    • Dart plugin version 212.5080.8

[✓] VS Code (version 1.86.1)
    • VS Code at /Applications/Visual Studio Code.app/Contents
    • Flutter extension version 3.88.0

[✓] Connected device (3 available)
    • macOS (desktop)                 • macos                 • darwin-arm64   • macOS 14.3.1 23D60 darwin-arm64
    • Mac Designed for iPad (desktop) • mac-designed-for-ipad • darwin         • macOS 14.3.1 23D60 darwin-arm64
    • Chrome (web)                    • chrome                • web-javascript • Google Chrome 124.0.6367.202

[✓] Network resources
    • All expected network resources are available.

! Doctor found issues in 1 category.
@bleroux
Copy link
Contributor

bleroux commented May 24, 2024

Hey @maheshmnj!

The test above simulates several key down events on the same key, this is why it triggers an error (previously, with version 3.19, the error was not thrown due to a bug).

There are two ways to fix this test:

  • calling simulateKeyUpEvent before simulating another press.
  • relying on tester.sendKeyEvent which simulates a down event followed by an up event.

Thanks for trying these.

@darshankawar darshankawar added in triage Presently being triaged by the triage team waiting for customer response The Flutter team cannot make further progress on this issue until the original reporter responds labels May 24, 2024
@maheshmnj
Copy link
Member Author

Hi @bleroux,

Thanks for the fix, I tried both the ways simulateKeyUpEvent seems to work

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('simulate consecutive key down', (tester) async {
    await tester.pumpWidget(const SizedBox());
    await simulateKeyDownEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyUpEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyDownEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyUpEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyDownEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyUpEvent(LogicalKeyboardKey.arrowDown);
    await simulateKeyDownEvent(LogicalKeyboardKey.enter);
    await simulateKeyUpEvent(LogicalKeyboardKey.enter);
  });
}

but there is still issue with tester.sendKeyEvent Please try the below test

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('simulate consecutive key down', (tester) async {
    await tester.pumpWidget(const SizedBox());
    tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    tester.sendKeyEvent(LogicalKeyboardKey.enter);
  });
}

@github-actions github-actions bot removed the waiting for customer response The Flutter team cannot make further progress on this issue until the original reporter responds label May 24, 2024
@bleroux
Copy link
Contributor

bleroux commented May 24, 2024

but there is still issue with tester.sendKeyEvent Please try the below test

This is because tester.sendKeyEvent should be 'awaited',

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_test/flutter_test.dart';

void main() {
  testWidgets('simulate consecutive key down', (tester) async {
    await tester.pumpWidget(const SizedBox());
    await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    await tester.sendKeyEvent(LogicalKeyboardKey.arrowDown);
    await tester.sendKeyEvent(LogicalKeyboardKey.enter);
  });
}

@maheshmnj
Copy link
Member Author

Oops! looks like I am not fully awake yet 😄
Closing as working as intended.

Thank you.

@darshankawar darshankawar added r: solved Issue is closed as solved and removed in triage Presently being triaged by the triage team labels May 27, 2024
Copy link

This thread has been automatically locked since there has not been any recent activity after it was closed. If you are still experiencing a similar issue, please open a new bug, including the output of flutter doctor -v and a minimal reproduction of the issue.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Jun 10, 2024
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
r: solved Issue is closed as solved
Projects
None yet
Development

No branches or pull requests

3 participants