input-remapper/tests/unit/test_groups.py
jonasBoss 3637204bff
Frontend Refactor (#375)
* Tests for the GuiEventHandler

* Implement GuiEventHandler

* tests for data manager

* Implemented data_manager

* Remove Ellipsis from type hint

* workaround for old pydantic version

* workaround for old pydantic version

* some more tests for data_manager

* Updated Data Manager

* move DeviceSelection to its own class

* Data Manager no longer listens for events

* Moved PresetSelection to its own class

* MappingListBox and SelectionLable Listen to the EventHandler

* DataManager no longer creates its own data objects in the init

* removed global reader object

* Changed UI startup

* created backend Interface

* event_handler debug logs show function which emit a event

* some cleanup

* added target selector to components

* created code editor component

* adapted autocompletion & some cleanup

* black

* connected some buttons to the event_handler

* tests for data_manager newest_preset and group

* cleanup presets and test_presets

* migrated confirm delete dialog

* backend tests

* controller tests

* add python3-gi to ci

* more dependencies

* and more ...

* Github-Actions workaround

remove this commit

* not so many permission denyed errors in test.yml

* Fix #404 (hopefully)

* revert Github-Actions workaround

* More tests

* event_handler allows for event supression

* more tests

* WIP Implement Key recording

* Start and Stop Injection

* context no longer stores preset

* restructured the RelToBtnHandler

* Simplified read_loop

* Implement async iterator for ipc.pipe

* multiple event actions

* helper now implements mapping handlers to read inputs all with async

* updated and simplified reader 

the helper uses the mapping handlers, so the reader now can be much simpler

* Fixed race condition in tests

* implemented DataBus

* Fixed a UIMapping bug where the last_error would not be deleted

* added a immutable variant of the UIMapping

* updated data_manager to use data_bus

* Uptdated tests to use the DataBus

* Gui uses DataBus

* removed EventHandler

* Renamed controller methods

* Implemented recording toggle

* implemented StatusBar

* Sending validation errors to status bar

* sending injection status to status bar

* proper preset renaming

* implemented copy preset in the data manager

* implemented copy_preset in controller

* fixed a bug where a wron selection lable would update

* no longer send invalid data over the bus, if the preset or group changes

* Implement create and delete mapping

* Allow for frontend specific mapping defaults

* implemented autoload toggle

* cleanup user_interface

* removed editor

* Docstings renaming and ordering of methods

* more simplifications to user_interface

* integrated backend into data_manager

* removed active preset

* transformation tests

* controller tests

* fix missing uinputs in gui

* moved some tests and implemented basic tests for mapping handlers

* docstring reformatting

Co-authored-by: Tobi <proxima@sezanzeb.de>

* allow for empty groups

* docstring

* fixed TestGroupFromHelper

* some work on integration tests

* test for annoying import error in tests

* testing if test_user_interface works

* I feel lucky

* not so lucky

* some more tests

* fixed but where the group_key was used as folder name

* Fixed a bug where state=NO_GRAB would never be read from the injector

* allow to stop the recorder

* working on integration tests

* integration tests

* fixed more integration tests

* updated coveragerc

* no longer attempt to record keys when injecting

* event_reader cleans up not finished tasks

* More integration tests

* All tests pass

* renamed data_bus

* WIP fixing typing issues

* more typing fixes

* added keyboard+mouse device to tests

* cleanup imports

* new read loop because the evdev async read loop can not be cancelled

* Added field to modify mapping name

* created tests for components

* even more component tests

* do component tests need a screen?

* apparently they do :_(

* created release_input switch

* Don't record relative axis when movement is slow

* show delete dialog above main window

* wip basic dialog to edit combination

* some gui changes to the combination-editor

* Simple implementation of CombinationListbox

* renamed attach_to_events method and mark as private

* shorter str() for UInputsData

* moved logic to generate readable event string from combination to event

* new mapping parameter force release timeout

this helps with the helper when recording multiple relative axis at once

* make it possible to rearange the event_combination

* more work on the combination editor

* tests for DataManager.load_event

* simplyfied test_controller

* more controller tests

* Implement input threshold in gui

* greater range for time dependent unit test

* implemented a output-axis selector

* data_manager now provides injector state

* black

* mypy

* Updated confirm cancel dialog

* created release timeout input

* implemented transformation graph

* Added sliders for gain, expo and deadzone

* fix bug where the system_mapping was overridden in each injector thread

* updated slider settings

* removed debug statement

* explicitly checking output code against None (0 is a valid code)

* usage

* Allow for multiple axis to be activated by same button

* readme

* only warn about not implemented mapping-handler

don't fail to create event-pipelines

* More accurate event names

* Allow removal of single events from the input-combination

* rename callback to notify_callback

* rename event message to selected_event

* made read_continuisly private

* typing for autocompletion

* docstrings for message_broker messages

* make components methods and propreties private

* gui spacings

* removed eval

* make some controller functions private

* move status message generation from data_manager to controller

* parse mapping errors in controller for more helpful messages

* remove system_mapping from code editor

* More component tests

* more tests

* mypy

* make grab_devices less greedy (partial mitigation for #435)

only grab one device if there are multiple which can satisfy the same mapping

* accumulate more values in test

* docstrings

* Updated status messages

* comments, docstrings, imports

Co-authored-by: Tobi <proxima@sezanzeb.de>
2022-07-23 10:53:41 +02:00

324 lines
9.9 KiB
Python

#!/usr/bin/python3
# -*- coding: utf-8 -*-
# input-remapper - GUI for device specific keyboard mappings
# Copyright (C) 2022 sezanzeb <proxima@sezanzeb.de>
#
# This file is part of input-remapper.
#
# input-remapper is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# input-remapper is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with input-remapper. If not, see <https://www.gnu.org/licenses/>.
from tests.test import quick_cleanup, fixtures
import os
import unittest
import json
import evdev
from evdev.ecodes import EV_KEY, KEY_A
from inputremapper.configs.paths import CONFIG_PATH
from inputremapper.groups import (
_FindGroups,
groups,
classify,
DeviceType,
_Group,
)
class FakePipe:
groups = None
def send(self, groups):
self.groups = groups
class TestGroups(unittest.TestCase):
def tearDown(self):
quick_cleanup()
def test_group(self):
group = _Group(
paths=["/dev/a", "/dev/b", "/dev/c"],
names=["name_bar", "name_a", "name_foo"],
types=[DeviceType.MOUSE, DeviceType.KEYBOARD, DeviceType.UNKNOWN],
key="key",
)
self.assertEqual(group.name, "name_a")
self.assertEqual(group.key, "key")
self.assertEqual(
group.get_preset_path("preset1234"),
os.path.join(CONFIG_PATH, "presets", group.name, "preset1234.json"),
)
def test_find_groups(self):
pipe = FakePipe()
_FindGroups(pipe).run()
self.assertIsInstance(pipe.groups, str)
groups.loads(pipe.groups)
self.maxDiff = None
self.assertEqual(
groups.dumps(),
json.dumps(
[
json.dumps(
{
"paths": [
"/dev/input/event1",
],
"names": ["Foo Device"],
"types": [DeviceType.KEYBOARD],
"key": "Foo Device",
}
),
json.dumps(
{
"paths": [
"/dev/input/event11",
"/dev/input/event10",
"/dev/input/event13",
"/dev/input/event15",
],
"names": [
"Foo Device foo",
"Foo Device",
"Foo Device",
"Foo Device bar",
],
"types": [
DeviceType.GAMEPAD,
DeviceType.KEYBOARD,
DeviceType.MOUSE,
],
"key": "Foo Device 2",
}
),
json.dumps(
{
"paths": ["/dev/input/event20"],
"names": ["Bar Device"],
"types": [DeviceType.KEYBOARD],
"key": "Bar Device",
}
),
json.dumps(
{
"paths": ["/dev/input/event30"],
"names": ["gamepad"],
"types": [DeviceType.GAMEPAD],
"key": "gamepad",
}
),
json.dumps(
{
"paths": ["/dev/input/event40"],
"names": ["input-remapper Bar Device"],
"types": [DeviceType.KEYBOARD],
"key": "input-remapper Bar Device",
}
),
]
),
)
groups2 = json.dumps(
[group.dumps() for group in groups.filter(include_inputremapper=True)]
)
self.assertEqual(pipe.groups, groups2)
def test_list_group_names(self):
self.assertListEqual(
groups.list_group_names(),
[
"Foo Device",
"Foo Device",
"Bar Device",
"gamepad",
],
)
def test_filter(self):
# by default no input-remapper devices are present
filtered = groups.filter()
keys = [group.key for group in filtered]
self.assertIn("Foo Device 2", keys)
self.assertNotIn("input-remapper Bar Device", keys)
def test_skip_camera(self):
fixtures["/foo/bar"] = {
"name": "camera",
"phys": "abcd1",
"info": evdev.DeviceInfo(1, 2, 3, 4),
"capabilities": {evdev.ecodes.EV_KEY: [evdev.ecodes.KEY_CAMERA]},
}
groups.refresh()
self.assertIsNone(groups.find(name="camera"))
self.assertIsNotNone(groups.find(name="gamepad"))
def test_device_with_only_ev_abs(self):
# could be anything, a lot of devices have ABS_X capabilities,
# so it is not treated as gamepad joystick and since it also
# doesn't have key capabilities, there is nothing to map.
fixtures["/foo/bar"] = {
"name": "qux",
"phys": "abcd2",
"info": evdev.DeviceInfo(1, 2, 3, 4),
"capabilities": {evdev.ecodes.EV_ABS: [evdev.ecodes.ABS_X]},
}
groups.refresh()
self.assertIsNotNone(groups.find(name="gamepad"))
self.assertIsNone(groups.find(name="qux"))
# verify this test even works at all
fixtures["/foo/bar"]["capabilities"][EV_KEY] = [KEY_A]
groups.refresh()
self.assertIsNotNone(groups.find(name="qux"))
def test_duplicate_device(self):
fixtures["/dev/input/event20"]["name"] = "Foo Device"
groups.refresh()
group1 = groups.find(key="Foo Device")
group2 = groups.find(key="Foo Device 2")
group3 = groups.find(key="Foo Device 3")
self.assertIn("/dev/input/event1", group1.paths)
self.assertIn("/dev/input/event10", group2.paths)
self.assertIn("/dev/input/event20", group3.paths)
self.assertEqual(group1.key, "Foo Device")
self.assertEqual(group2.key, "Foo Device 2")
self.assertEqual(group3.key, "Foo Device 3")
self.assertEqual(group1.name, "Foo Device")
self.assertEqual(group2.name, "Foo Device")
self.assertEqual(group3.name, "Foo Device")
def test_classify(self):
# properly detects if the device is a gamepad
EV_ABS = evdev.ecodes.EV_ABS
EV_KEY = evdev.ecodes.EV_KEY
EV_REL = evdev.ecodes.EV_REL
class FakeDevice:
def __init__(self, capabilities):
self.c = capabilities
def capabilities(self, absinfo):
assert not absinfo
return self.c
"""Gamepads"""
self.assertEqual(
classify(
FakeDevice(
{
EV_ABS: [evdev.ecodes.ABS_X, evdev.ecodes.ABS_Y],
EV_KEY: [evdev.ecodes.BTN_A],
}
)
),
DeviceType.GAMEPAD,
)
"""Mice"""
self.assertEqual(
classify(
FakeDevice(
{
EV_REL: [
evdev.ecodes.REL_X,
evdev.ecodes.REL_Y,
evdev.ecodes.REL_WHEEL,
],
EV_KEY: [evdev.ecodes.BTN_LEFT],
}
)
),
DeviceType.MOUSE,
)
"""Keyboard"""
self.assertEqual(
classify(FakeDevice({EV_KEY: [evdev.ecodes.KEY_A]})), DeviceType.KEYBOARD
)
"""Touchpads"""
self.assertEqual(
classify(
FakeDevice(
{
EV_KEY: [evdev.ecodes.KEY_A],
EV_ABS: [evdev.ecodes.ABS_MT_POSITION_X],
}
)
),
DeviceType.TOUCHPAD,
)
"""Graphics tablets"""
self.assertEqual(
classify(
FakeDevice(
{
EV_ABS: [evdev.ecodes.ABS_X, evdev.ecodes.ABS_Y],
EV_KEY: [evdev.ecodes.BTN_STYLUS],
}
)
),
DeviceType.GRAPHICS_TABLET,
)
"""Weird combos"""
self.assertEqual(
classify(
FakeDevice(
{
EV_ABS: [evdev.ecodes.ABS_X, evdev.ecodes.ABS_Y],
EV_KEY: [evdev.ecodes.KEY_1],
}
)
),
DeviceType.UNKNOWN,
)
self.assertEqual(
classify(
FakeDevice({EV_ABS: [evdev.ecodes.ABS_X], EV_KEY: [evdev.ecodes.BTN_A]})
),
DeviceType.UNKNOWN,
)
self.assertEqual(
classify(FakeDevice({EV_KEY: [evdev.ecodes.BTN_A]})), DeviceType.UNKNOWN
)
self.assertEqual(
classify(FakeDevice({EV_ABS: [evdev.ecodes.ABS_X]})), DeviceType.UNKNOWN
)
if __name__ == "__main__":
unittest.main()