tools/interactive-evdev: fixup 64bff65
[platform/upstream/libxkbcommon.git] / test / tool-option-parsing.py
1 #!/usr/bin/env python3
2 #
3 # Copyright © 2020 Red Hat, Inc.
4 #
5 # Permission is hereby granted, free of charge, to any person obtaining a
6 # copy of this software and associated documentation files (the "Software"),
7 # to deal in the Software without restriction, including without limitation
8 # the rights to use, copy, modify, merge, publish, distribute, sublicense,
9 # and/or sell copies of the Software, and to permit persons to whom the
10 # Software is furnished to do so, subject to the following conditions:
11 #
12 # The above copyright notice and this permission notice (including the next
13 # paragraph) shall be included in all copies or substantial portions of the
14 # Software.
15 #
16 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL
19 # THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 # FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 # DEALINGS IN THE SOFTWARE.
23
24 import itertools
25 import os
26 import resource
27 import sys
28 import subprocess
29 import logging
30
31 try:
32     import pytest
33 except ImportError:
34     print('Failed to import pytest. Skipping.', file=sys.stderr)
35     sys.exit(77)
36
37
38 top_builddir = os.environ['top_builddir']
39
40 logging.basicConfig(level=logging.DEBUG)
41 logger = logging.getLogger('test')
42 logger.setLevel(logging.DEBUG)
43
44 # Permutation of RMLVO that we use in multiple tests
45 rmlvos = [list(x) for x in itertools.permutations(
46     ['--rules=evdev', '--model=pc104',
47      '--layout=fr', '--options=eurosign:5']
48 )]
49
50
51 def _disable_coredump():
52     resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
53
54
55 def run_command(args):
56     logger.debug('run command: {}'.format(' '.join(args)))
57
58     try:
59         p = subprocess.run(args, preexec_fn=_disable_coredump,
60                            capture_output=True, text=True,
61                            timeout=0.7)
62         return p.returncode, p.stdout, p.stderr
63     except subprocess.TimeoutExpired as e:
64         return 0, e.stdout, e.stderr
65
66
67 class XkbcliTool:
68     xkbcli_tool = 'xkbcli'
69     subtool = None
70
71     def __init__(self, subtool=None):
72         self.tool_path = top_builddir
73         self.subtool = subtool
74
75     def run_command(self, args):
76         if self.subtool is not None:
77             tool = '{}-{}'.format(self.xkbcli_tool, self.subtool)
78         else:
79             tool = self.xkbcli_tool
80         args = [os.path.join(self.tool_path, tool)] + args
81
82         return run_command(args)
83
84     def run_command_success(self, args):
85         rc, stdout, stderr = self.run_command(args)
86         assert rc == 0, (stdout, stderr)
87         return stdout, stderr
88
89     def run_command_invalid(self, args):
90         rc, stdout, stderr = self.run_command(args)
91         assert rc == 2, (rc, stdout, stderr)
92         return rc, stdout, stderr
93
94     def run_command_unrecognized_option(self, args):
95         rc, stdout, stderr = self.run_command(args)
96         assert rc == 2, (rc, stdout, stderr)
97         assert stdout.startswith('Usage') or stdout == ''
98         assert 'unrecognized option' in stderr
99
100     def run_command_missing_arg(self, args):
101         rc, stdout, stderr = self.run_command(args)
102         assert rc == 2, (rc, stdout, stderr)
103         assert stdout.startswith('Usage') or stdout == ''
104         assert 'requires an argument' in stderr
105
106
107 def get_tool(subtool=None):
108     return XkbcliTool(subtool)
109
110
111 def get_all_tools():
112     return [get_tool(x) for x in [None, 'list',
113                                   'compile-keymap',
114                                   'how-to-type',
115                                   'interactive-evdev',
116                                   'interactive-wayland',
117                                   'interactive-x11']]
118
119
120 @pytest.fixture
121 def xkbcli():
122     return get_tool()
123
124
125 @pytest.fixture
126 def xkbcli_list():
127     return get_tool('list')
128
129
130 @pytest.fixture
131 def xkbcli_how_to_type():
132     return get_tool('how-to-type')
133
134
135 @pytest.fixture
136 def xkbcli_compile_keymap():
137     return get_tool('compile-keymap')
138
139
140 @pytest.fixture
141 def xkbcli_interactive_evdev():
142     return get_tool('interactive-evdev')
143
144
145 @pytest.fixture
146 def xkbcli_interactive_x11():
147     return get_tool('interactive-x11')
148
149
150 @pytest.fixture
151 def xkbcli_interactive_wayland():
152     return get_tool('interactive-wayland')
153
154
155 # --help is supported by all tools
156 @pytest.mark.parametrize('tool', get_all_tools())
157 def test_help(tool):
158     stdout, stderr = tool.run_command_success(['--help'])
159     assert stdout.startswith('Usage:')
160     assert stderr == ''
161
162
163 # --foobar generates "Usage:" for all tools
164 @pytest.mark.parametrize('tool', get_all_tools())
165 def test_invalid_option(tool):
166     tool.run_command_unrecognized_option(['--foobar'])
167
168
169 # xkbcli --version
170 def test_xkbcli_version(xkbcli):
171     stdout, stderr = xkbcli.run_command_success(['--version'])
172     assert stdout.startswith('0')
173     assert stderr == ''
174
175
176 def test_xkbcli_too_many_args(xkbcli):
177     xkbcli.run_command_invalid(['a'] * 64)
178
179
180 @pytest.mark.parametrize('args', [['--verbose'],
181                                   ['--rmlvo'],
182                                   # ['--kccgst'],
183                                   ['--verbose', '--rmlvo'],
184                                   # ['--verbose', '--kccgst'],
185                                   ])
186 def test_compile_keymap_args(xkbcli_compile_keymap, args):
187     xkbcli_compile_keymap.run_command_success(args)
188
189
190 @pytest.mark.parametrize('rmlvos', rmlvos)
191 def test_compile_keymap_rmlvo(xkbcli_compile_keymap, rmlvos):
192     xkbcli_compile_keymap.run_command_success(rmlvos)
193
194
195 @pytest.mark.parametrize('args', [['--include', '.', '--include-defaults'],
196                                   ['--include', '/tmp', '--include-defaults'],
197                                   ])
198 def test_compile_keymap_include(xkbcli_compile_keymap, args):
199     # Succeeds thanks to include-defaults
200     xkbcli_compile_keymap.run_command_success(args)
201
202
203 def test_compile_keymap_include_invalid(xkbcli_compile_keymap):
204     # A non-directory is rejected by default
205     args = ['--include', '/proc/version']
206     rc, stdout, stderr = xkbcli_compile_keymap.run_command(args)
207     assert rc == 1, (stdout, stderr)
208     assert "There are no include paths to search" in stderr
209
210     # A non-existing directory is rejected by default
211     args = ['--include', '/tmp/does/not/exist']
212     rc, stdout, stderr = xkbcli_compile_keymap.run_command(args)
213     assert rc == 1, (stdout, stderr)
214     assert "There are no include paths to search" in stderr
215
216     # Valid dir, but missing files
217     args = ['--include', '/tmp']
218     rc, stdout, stderr = xkbcli_compile_keymap.run_command(args)
219     assert rc == 1, (stdout, stderr)
220     assert "Couldn't look up rules" in stderr
221
222
223 # Unicode codepoint conversions, we support whatever strtol does
224 @pytest.mark.parametrize('args', [['123'], ['0x123'], ['0123']])
225 def test_how_to_type(xkbcli_how_to_type, args):
226     xkbcli_how_to_type.run_command_success(args)
227
228
229 @pytest.mark.parametrize('rmlvos', rmlvos)
230 def test_how_to_type_rmlvo(xkbcli_how_to_type, rmlvos):
231     args = rmlvos + ['0x1234']
232     xkbcli_how_to_type.run_command_success(args)
233
234
235 @pytest.mark.parametrize('args', [['--verbose'],
236                                   ['-v'],
237                                   ['--verbose', '--load-exotic'],
238                                   ['--load-exotic'],
239                                   ['--ruleset=evdev'],
240                                   ['--ruleset=base'],
241                                   ])
242 def test_list_rmlvo(xkbcli_list, args):
243     xkbcli_list.run_command_success(args)
244
245
246 def test_list_rmlvo_includes(xkbcli_list):
247     args = ['/tmp/']
248     xkbcli_list.run_command_success(args)
249
250
251 def test_list_rmlvo_includes_invalid(xkbcli_list):
252     args = ['/proc/version']
253     rc, stdout, stderr = xkbcli_list.run_command(args)
254     assert rc == 1
255     assert "Failed to append include path" in stderr
256
257
258 def test_list_rmlvo_includes_no_defaults(xkbcli_list):
259     args = ['--skip-default-paths', '/tmp']
260     rc, stdout, stderr = xkbcli_list.run_command(args)
261     assert rc == 1
262     assert "Failed to parse XKB description" in stderr
263
264
265 @pytest.mark.skipif(not os.path.exists('/dev/input/event0'), reason='event node required')
266 @pytest.mark.skipif(not os.access('/dev/input/event0', os.R_OK), reason='insufficient permissions')
267 @pytest.mark.parametrize('rmlvos', rmlvos)
268 def test_interactive_evdev_rmlvo(xkbcli_interactive_evdev, rmlvos):
269     return
270     xkbcli_interactive_evdev.run_command_success(rmlvos)
271
272
273 @pytest.mark.skipif(not os.path.exists('/dev/input/event0'),
274                     reason='event node required')
275 @pytest.mark.skipif(not os.access('/dev/input/event0', os.R_OK),
276                     reason='insufficient permissions')
277 @pytest.mark.parametrize('args', [['--report-state-changes'],
278                                   ['--enable-compose'],
279                                   ['--consumed-mode=xkb'],
280                                   ['--consumed-mode=gtk'],
281                                   ['--without-x11-offset'],
282                                   ])
283 def test_interactive_evdev(xkbcli_interactive_evdev, args):
284     # Note: --enable-compose fails if $prefix doesn't have the compose tables
285     # installed
286     xkbcli_interactive_evdev.run_command_success(args)
287
288
289 @pytest.mark.skipif(not os.getenv('DISPLAY'), reason='DISPLAY not set')
290 def test_interactive_x11(xkbcli_interactive_x11):
291     # To be filled in if we handle something other than --help
292     pass
293
294
295 @pytest.mark.skipif(not os.getenv('WAYLAND_DISPLAY'),
296                     reason='WAYLAND_DISPLAY not set')
297 def test_interactive_wayland(xkbcli_interactive_wayland):
298     # To be filled in if we handle something other than --help
299     pass
300
301
302 if __name__ == '__main__':
303     sys.exit(pytest.main(args=[__file__]))