test: add a keysym tester
[platform/upstream/libxkbcommon.git] / test / test-keysym.py
1 #!/usr/bin/env python3
2 #
3 # This script creates a custom layout, overriding the TDLE key with the first
4 # argument given.
5
6 import argparse
7 import tempfile
8 from pathlib import Path
9 import subprocess
10 import os
11 import re
12 import sys
13
14 # Template to force our key to TLDE
15 template = """
16 default
17 xkb_symbols "basic" {{
18     include "us(basic)"
19     replace key <TLDE> {{ [ {} ] }};
20 }};
21 """
22
23 parser = argparse.ArgumentParser(
24     description='Tool to verify whether a keysym is resolved'
25 )
26 parser.add_argument('keysym', type=str, help='XKB keysym')
27 parser.add_argument('--tool', type=str, nargs=1,
28                     default=['xkbcli', 'compile-keymap'],
29                     help='Full path to the xkbcli-compile-keymap tool')
30 args = parser.parse_args()
31
32 with tempfile.TemporaryDirectory() as tmpdir:
33     symfile = Path(tmpdir) / "symbols" / "keytest"
34     symfile.parent.mkdir()
35     with symfile.open(mode='w') as f:
36         f.write(template.format(args.keysym))
37
38     try:
39         cmd = [
40             *args.tool,
41             '--layout', 'keytest',
42         ]
43
44         env = os.environ.copy()
45         env['XKB_CONFIG_EXTRA_PATH'] = tmpdir
46
47         result = subprocess.run(cmd, env=env, capture_output=True,
48                                 universal_newlines=True)
49         if result.returncode != 0:
50             print('ERROR: Failed to compile:')
51             print(result.stderr)
52             sys.exit(1)
53
54         # grep for TLDE actually being remapped
55         for l in result.stdout.split('\n'):
56             match = re.match(r'\s+key \<TLDE\>\s+{\s+\[\s+(?P<keysym>\w+)\s+\]\s+}', l)
57             if match:
58                 if args.keysym == match.group('keysym'):
59                     sys.exit(0)
60                 elif match.group('keysym') == 'NoSymbol':
61                     print('ERROR: key {} not resolved:'.format(args.keysym), l)
62                 else:
63                     print('ERROR: key {} mapped to wrong key:'.format(args.keysym), l)
64                 sys.exit(1)
65
66         print(result.stdout)
67         print('ERROR: above keymap is missing key mapping for {}'.format(args.keysym))
68         sys.exit(1)
69     except FileNotFoundError as err:
70         print('ERROR: invalid or missing tool: {}'.format(err))
71         sys.exit(1)