test/tool-option-parsing: keep isolated by using our own test data
[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 import tempfile
31
32 try:
33     import pytest
34 except ImportError:
35     print('Failed to import pytest. Skipping.', file=sys.stderr)
36     sys.exit(77)
37
38
39 top_builddir = os.environ['top_builddir']
40 top_srcdir = os.environ['top_srcdir']
41
42 logging.basicConfig(level=logging.DEBUG)
43 logger = logging.getLogger('test')
44 logger.setLevel(logging.DEBUG)
45
46 # Permutation of RMLVO that we use in multiple tests
47 rmlvos = [list(x) for x in itertools.permutations(
48     ['--rules=evdev', '--model=pc104',
49      '--layout=ch', '--options=eurosign:5']
50 )]
51
52
53 def _disable_coredump():
54     resource.setrlimit(resource.RLIMIT_CORE, (0, 0))
55
56
57 def run_command(args):
58     logger.debug('run command: {}'.format(' '.join(args)))
59
60     try:
61         p = subprocess.run(args, preexec_fn=_disable_coredump,
62                            capture_output=True, text=True,
63                            timeout=0.7)
64         return p.returncode, p.stdout, p.stderr
65     except subprocess.TimeoutExpired as e:
66         return 0, e.stdout, e.stderr
67
68
69 class XkbcliTool:
70     xkbcli_tool = 'xkbcli'
71     subtool = None
72
73     def __init__(self, subtool=None):
74         self.tool_path = top_builddir
75         self.subtool = subtool
76
77     def run_command(self, args):
78         if self.subtool is not None:
79             tool = '{}-{}'.format(self.xkbcli_tool, self.subtool)
80         else:
81             tool = self.xkbcli_tool
82         args = [os.path.join(self.tool_path, tool)] + args
83
84         return run_command(args)
85
86     def run_command_success(self, args):
87         rc, stdout, stderr = self.run_command(args)
88         assert rc == 0, (stdout, stderr)
89         return stdout, stderr
90
91     def run_command_invalid(self, args):
92         rc, stdout, stderr = self.run_command(args)
93         assert rc == 2, (rc, stdout, stderr)
94         return rc, stdout, stderr
95
96     def run_command_unrecognized_option(self, args):
97         rc, stdout, stderr = self.run_command(args)
98         assert rc == 2, (rc, stdout, stderr)
99         assert stdout.startswith('Usage') or stdout == ''
100         assert 'unrecognized option' in stderr
101
102     def run_command_missing_arg(self, args):
103         rc, stdout, stderr = self.run_command(args)
104         assert rc == 2, (rc, stdout, stderr)
105         assert stdout.startswith('Usage') or stdout == ''
106         assert 'requires an argument' in stderr
107
108
109 def get_tool(subtool=None):
110     return XkbcliTool(subtool)
111
112
113 def get_all_tools():
114     return [get_tool(x) for x in [None, 'list',
115                                   'compile-keymap',
116                                   'how-to-type',
117                                   'interactive-evdev',
118                                   'interactive-wayland',
119                                   'interactive-x11']]
120
121
122 @pytest.fixture
123 def xkbcli():
124     return get_tool()
125
126
127 @pytest.fixture
128 def xkbcli_list():
129     return get_tool('list')
130
131
132 @pytest.fixture
133 def xkbcli_how_to_type():
134     return get_tool('how-to-type')
135
136
137 @pytest.fixture
138 def xkbcli_compile_keymap():
139     return get_tool('compile-keymap')
140
141
142 @pytest.fixture
143 def xkbcli_interactive_evdev():
144     return get_tool('interactive-evdev')
145
146
147 @pytest.fixture
148 def xkbcli_interactive_x11():
149     return get_tool('interactive-x11')
150
151
152 @pytest.fixture
153 def xkbcli_interactive_wayland():
154     return get_tool('interactive-wayland')
155
156
157 # --help is supported by all tools
158 @pytest.mark.parametrize('tool', get_all_tools())
159 def test_help(tool):
160     stdout, stderr = tool.run_command_success(['--help'])
161     assert stdout.startswith('Usage:')
162     assert stderr == ''
163
164
165 # --foobar generates "Usage:" for all tools
166 @pytest.mark.parametrize('tool', get_all_tools())
167 def test_invalid_option(tool):
168     tool.run_command_unrecognized_option(['--foobar'])
169
170
171 # xkbcli --version
172 def test_xkbcli_version(xkbcli):
173     stdout, stderr = xkbcli.run_command_success(['--version'])
174     assert stdout.startswith('1')
175     assert stderr == ''
176
177
178 def test_xkbcli_too_many_args(xkbcli):
179     xkbcli.run_command_invalid(['a'] * 64)
180
181
182 @pytest.mark.parametrize('args', [['--verbose'],
183                                   ['--rmlvo'],
184                                   # ['--kccgst'],
185                                   ['--verbose', '--rmlvo'],
186                                   # ['--verbose', '--kccgst'],
187                                   ])
188 def test_compile_keymap_args(xkbcli_compile_keymap, args):
189     xkbcli_compile_keymap.run_command_success(args)
190
191
192 @pytest.mark.parametrize('rmlvos', rmlvos)
193 def test_compile_keymap_rmlvo(xkbcli_compile_keymap, rmlvos):
194     xkbcli_compile_keymap.run_command_success(rmlvos)
195
196
197 @pytest.mark.parametrize('args', [['--include', '.', '--include-defaults'],
198                                   ['--include', '/tmp', '--include-defaults'],
199                                   ])
200 def test_compile_keymap_include(xkbcli_compile_keymap, args):
201     # Succeeds thanks to include-defaults
202     xkbcli_compile_keymap.run_command_success(args)
203
204
205 def test_compile_keymap_include_invalid(xkbcli_compile_keymap):
206     # A non-directory is rejected by default
207     args = ['--include', '/proc/version']
208     rc, stdout, stderr = xkbcli_compile_keymap.run_command(args)
209     assert rc == 1, (stdout, stderr)
210     assert "There are no include paths to search" in stderr
211
212     # A non-existing directory is rejected by default
213     args = ['--include', '/tmp/does/not/exist']
214     rc, stdout, stderr = xkbcli_compile_keymap.run_command(args)
215     assert rc == 1, (stdout, stderr)
216     assert "There are no include paths to search" in stderr
217
218     # Valid dir, but missing files
219     args = ['--include', '/tmp']
220     rc, stdout, stderr = xkbcli_compile_keymap.run_command(args)
221     assert rc == 1, (stdout, stderr)
222     assert "Couldn't look up rules" in stderr
223
224
225 # Unicode codepoint conversions, we support whatever strtol does
226 @pytest.mark.parametrize('args', [['123'], ['0x123'], ['0123']])
227 def test_how_to_type(xkbcli_how_to_type, args):
228     xkbcli_how_to_type.run_command_success(args)
229
230
231 @pytest.mark.parametrize('rmlvos', rmlvos)
232 def test_how_to_type_rmlvo(xkbcli_how_to_type, rmlvos):
233     args = rmlvos + ['0x1234']
234     xkbcli_how_to_type.run_command_success(args)
235
236
237 @pytest.mark.parametrize('args', [['--verbose'],
238                                   ['-v'],
239                                   ['--verbose', '--load-exotic'],
240                                   ['--load-exotic'],
241                                   ['--ruleset=evdev'],
242                                   ['--ruleset=base'],
243                                   ])
244 def test_list_rmlvo(xkbcli_list, args):
245     xkbcli_list.run_command_success(args)
246
247
248 def test_list_rmlvo_includes(xkbcli_list):
249     args = ['/tmp/']
250     xkbcli_list.run_command_success(args)
251
252
253 def test_list_rmlvo_includes_invalid(xkbcli_list):
254     args = ['/proc/version']
255     rc, stdout, stderr = xkbcli_list.run_command(args)
256     assert rc == 1
257     assert "Failed to append include path" in stderr
258
259
260 def test_list_rmlvo_includes_no_defaults(xkbcli_list):
261     args = ['--skip-default-paths', '/tmp']
262     rc, stdout, stderr = xkbcli_list.run_command(args)
263     assert rc == 1
264     assert "Failed to parse XKB description" in stderr
265
266
267 @pytest.mark.skipif(not os.path.exists('/dev/input/event0'), reason='event node required')
268 @pytest.mark.skipif(not os.access('/dev/input/event0', os.R_OK), reason='insufficient permissions')
269 @pytest.mark.parametrize('rmlvos', rmlvos)
270 def test_interactive_evdev_rmlvo(xkbcli_interactive_evdev, rmlvos):
271     return
272     xkbcli_interactive_evdev.run_command_success(rmlvos)
273
274
275 @pytest.mark.skipif(not os.path.exists('/dev/input/event0'),
276                     reason='event node required')
277 @pytest.mark.skipif(not os.access('/dev/input/event0', os.R_OK),
278                     reason='insufficient permissions')
279 @pytest.mark.parametrize('args', [['--report-state-changes'],
280                                   ['--enable-compose'],
281                                   ['--consumed-mode=xkb'],
282                                   ['--consumed-mode=gtk'],
283                                   ['--without-x11-offset'],
284                                   ])
285 def test_interactive_evdev(xkbcli_interactive_evdev, args):
286     # Note: --enable-compose fails if $prefix doesn't have the compose tables
287     # installed
288     xkbcli_interactive_evdev.run_command_success(args)
289
290
291 @pytest.mark.skipif(not os.getenv('DISPLAY'), reason='DISPLAY not set')
292 def test_interactive_x11(xkbcli_interactive_x11):
293     # To be filled in if we handle something other than --help
294     pass
295
296
297 @pytest.mark.skipif(not os.getenv('WAYLAND_DISPLAY'),
298                     reason='WAYLAND_DISPLAY not set')
299 def test_interactive_wayland(xkbcli_interactive_wayland):
300     # To be filled in if we handle something other than --help
301     pass
302
303
304 if __name__ == '__main__':
305     with tempfile.TemporaryDirectory() as tmpdir:
306         # Use our own test xkeyboard-config copy.
307         os.environ['XKB_CONFIG_ROOT'] = top_srcdir + '/test/data'
308         # libxkbcommon has fallbacks when XDG_CONFIG_HOME isn't set so we need
309         # to override it with a known (empty) directory. Otherwise our test
310         # behavior depends on the system the test is run on.
311         os.environ['XDG_CONFIG_HOME'] = tmpdir
312         # Prevent the legacy $HOME/.xkb from kicking in.
313         del os.environ['HOME']
314         # This needs to be separated if we do specific extra path testing
315         os.environ['XKB_CONFIG_EXTRA_PATH'] = tmpdir
316
317         sys.exit(pytest.main(args=[__file__]))