test: ignore the real XDG_CONFIG_HOME during tests
[platform/upstream/libxkbcommon.git] / test / xkeyboard-config-test.py.in
1 #!/usr/bin/env python3
2 import argparse
3 import sys
4 import subprocess
5 import os
6 import io
7 import xml.etree.ElementTree as ET
8 from multiprocessing import Pool
9
10
11 verbose = True
12
13 DEFAULT_RULES_XML = '@XKB_CONFIG_ROOT@/rules/evdev.xml'
14
15 # Meson needs to fill this in so we can call the tool in the buildir.
16 EXTRA_PATH = '@MESON_BUILD_ROOT@'
17 os.environ['PATH'] = ':'.join([EXTRA_PATH, os.getenv('PATH')])
18
19
20 def noop_progress_bar(x, total):
21     return x
22
23
24 # The function generating the progress bar (if any).
25 progress_bar = noop_progress_bar
26 if os.isatty(sys.stdout.fileno()):
27     try:
28         from tqdm import tqdm
29         progress_bar = tqdm
30
31         verbose = False
32     except ImportError:
33         pass
34
35
36 def xkbcommontool(rmlvo):
37     try:
38         r = rmlvo.get('r', 'evdev')
39         m = rmlvo.get('m', 'pc105')
40         l = rmlvo.get('l', 'us')
41         v = rmlvo.get('v', None)
42         o = rmlvo.get('o', None)
43         args = [
44             'xkbcli',
45             'compile-keymap',
46             '--rules', r,
47             '--model', m,
48             '--layout', l,
49         ]
50         if v is not None:
51             args += ['--variant', v]
52         if o is not None:
53             args += ['--options', o]
54
55         success = True
56         out = io.StringIO()
57         if verbose:
58             print(':: {}'.format(' '.join(args)), file=out)
59
60         try:
61             output = subprocess.check_output(args, stderr=subprocess.STDOUT,
62                                              universal_newlines=True)
63             if verbose:
64                 print(output, file=out)
65         except subprocess.CalledProcessError as err:
66             print('ERROR: Failed to compile: {}'.format(' '.join(args)), file=out)
67             print(err.output, file=out)
68             success = False
69
70         return success, out.getvalue()
71     except KeyboardInterrupt:
72         pass
73
74
75 def xkbcomp(rmlvo):
76     try:
77         r = rmlvo.get('r', 'evdev')
78         m = rmlvo.get('m', 'pc105')
79         l = rmlvo.get('l', 'us')
80         v = rmlvo.get('v', None)
81         o = rmlvo.get('o', None)
82         args = ['setxkbmap', '-print']
83         if r is not None:
84             args.append('-rules')
85             args.append('{}'.format(r))
86         if m is not None:
87             args.append('-model')
88             args.append('{}'.format(m))
89         if l is not None:
90             args.append('-layout')
91             args.append('{}'.format(l))
92         if v is not None:
93             args.append('-variant')
94             args.append('{}'.format(v))
95         if o is not None:
96             args.append('-option')
97             args.append('{}'.format(o))
98
99         success = True
100         out = io.StringIO()
101         if verbose:
102             print(':: {}'.format(' '.join(args)), file=out)
103
104         try:
105             xkbcomp_args = ['xkbcomp', '-xkb', '-', '-']
106
107             setxkbmap = subprocess.Popen(args, stdout=subprocess.PIPE)
108             xkbcomp = subprocess.Popen(xkbcomp_args, stdin=setxkbmap.stdout,
109                                        stdout=subprocess.PIPE, stderr=subprocess.PIPE,
110                                        universal_newlines=True)
111             setxkbmap.stdout.close()
112             stdout, stderr = xkbcomp.communicate()
113             if xkbcomp.returncode != 0:
114                 print('ERROR: Failed to compile: {}'.format(' '.join(args)), file=out)
115                 success = False
116             if xkbcomp.returncode != 0 or verbose:
117                 print(stdout, file=out)
118                 print(stderr, file=out)
119
120         # This catches setxkbmap errors.
121         except subprocess.CalledProcessError as err:
122             print('ERROR: Failed to compile: {}'.format(' '.join(args)), file=out)
123             print(err.output, file=out)
124             success = False
125
126         return success, out.getvalue()
127     except KeyboardInterrupt:
128         pass
129
130
131 def parse(path):
132     root = ET.fromstring(open(path).read())
133     layouts = root.findall('layoutList/layout')
134
135     options = [
136         e.text
137         for e in root.findall('optionList/group/option/configItem/name')
138     ]
139
140     combos = []
141     for l in layouts:
142         layout = l.find('configItem/name').text
143         combos.append({'l': layout})
144
145         variants = l.findall('variantList/variant')
146         for v in variants:
147             variant = v.find('configItem/name').text
148
149             combos.append({'l': layout, 'v': variant})
150             for option in options:
151                 combos.append({'l': layout, 'v': variant, 'o': option})
152
153     return combos
154
155
156 def run(combos, tool, njobs):
157     failed = False
158     with Pool(njobs) as p:
159         results = p.imap_unordered(tool, combos)
160         for success, output in progress_bar(results, total=len(combos)):
161             if not success:
162                 failed = True
163             if output:
164                 print(output, file=sys.stdout if success else sys.stderr)
165     return failed
166
167
168 def main(args):
169     tools = {
170         'libxkbcommon': xkbcommontool,
171         'xkbcomp': xkbcomp,
172     }
173
174     parser = argparse.ArgumentParser(
175         description='Tool to test all layout/variant/option combinations.'
176     )
177     parser.add_argument('path', metavar='/path/to/evdev.xml',
178                         nargs='?', type=str,
179                         default=DEFAULT_RULES_XML,
180                         help='Path to xkeyboard-config\'s evdev.xml')
181     parser.add_argument('--tool', choices=tools.keys(),
182                         type=str, default='libxkbcommon',
183                         help='parsing tool to use')
184     parser.add_argument('--jobs', '-j', type=int,
185                         default=os.cpu_count() * 4,
186                         help='number of processes to use')
187     args = parser.parse_args()
188
189     tool = tools[args.tool]
190
191     combos = parse(args.path)
192     failed = run(combos, tool, args.jobs)
193     sys.exit(failed)
194
195
196 if __name__ == '__main__':
197     try:
198         main(sys.argv)
199     except KeyboardInterrupt:
200         print('Exiting after Ctrl+C')