Debian Codegraph @

debian/tests/ansible-test-integration.py

raw
1 #!/usr/bin/python3
2
3 import argparse
4 import os
5 import subprocess
6 import sys
7 import time
8
9 # helper function to print log messages depending on verbosity
10 def log (level, *msg):
11 if args.verbose >= level:
12 print(' '.join([str(x) for x in msg]), flush=True)
13
14 sys.dont_write_bytecode = True
15
16 # helper function to run and log processes
17 def runprog (name, progargs, env=None, exit_on_failure=True):
18 log(1, 'Running', name)
19 proc = subprocess.run(
20 progargs,
21 timeout = 300,
22 capture_output = True,
23 text = True,
24 env = env,
25 )
26 if proc.returncode != 0:
27 log(0,"#"*72)
28 log(0,'Running', name, 'failed!')
29 log(0,"Returncode:", proc.returncode)
30 log(1,"#### STDOUT ####")
31 log(1, proc.stdout)
32 log(1, "#### STDERR ####")
33 log(1, proc.stderr)
34 log(0,"#"*72)
35 if exit_on_failure:
36 sys.exit(proc.returncode)
37 return proc
38
39 def locale_debug(name):
40 if args.verbose >= 2:
41 log(2, name)
42 log(2, 'output of /usr/bin/locale:')
43 subprocess.run(['/usr/bin/locale'])
44 prog = runprog('cat /etc/default/locale', ['cat', '/etc/default/locale'])
45 log(2, prog.stdout, prog.stderr)
46 # grep will exit 1 when it doesn't return anything, so don't fail on it.
47 prog = runprog(
48 'grep -v -P \'^#|^$\' /etc/locale.gen',
49 ['grep', '-v', '-P', '^#|^$', '/etc/locale.gen'],
50 exit_on_failure=False,
51 )
52 log(2, prog.stdout, prog.stderr)
53
54 parser = argparse.ArgumentParser(
55 prog='ansible-test-integration.py',
56 description='python script to run ansible-test integration against the Debian source package',
57 )
58
59 # Whether to run the default tests not in any other list
60 parser.add_argument(
61 '--default-tests',
62 action=argparse.BooleanOptionalAction,
63 default=False,
64 help='Run the default tests not listed anywhere else. (default: no)',
65 )
66
67 parser.add_argument(
68 '--requires-root',
69 action=argparse.BooleanOptionalAction,
70 default=False,
71 help='Run tests that require root. (default: no)',
72 )
73
74 parser.add_argument(
75 '--requires-ssh',
76 action=argparse.BooleanOptionalAction,
77 default=False,
78 help='Run tests that require a specially configured SSH server. (default: no)'
79 )
80
81 parser.add_argument(
82 '--requires-apt-mark-manual',
83 action=argparse.BooleanOptionalAction,
84 default=False,
85 help='Run tests that do "apt-mark manual" on certain packages. (default: no)',
86 )
87
88 parser.add_argument(
89 '--fails-on-pip',
90 action=argparse.BooleanOptionalAction,
91 default=False,
92 help='Run tests that run "pip3 install" on certain modules. (default: no)',
93 )
94
95 parser.add_argument(
96 '--failing',
97 action=argparse.BooleanOptionalAction,
98 default=False,
99 help='Run tests that fail on other reasons. (default: no)',
100 )
101
102 parser.add_argument(
103 '--setup',
104 action=argparse.BooleanOptionalAction,
105 default=True,
106 help='Setup testbed via sudo. (default: yes)',
107 )
108
109 parser.add_argument(
110 '--dry-run',
111 action=argparse.BooleanOptionalAction,
112 default=False,
113 help='Print the list of targets without actually running them',
114 )
115
116 parser.add_argument(
117 '--check-test-lists',
118 action=argparse.BooleanOptionalAction,
119 default=False,
120 help='Check if all the hardcoded integration tests from the other \
121 flags (e.g. --requires-root, --failing, ,etc.) still exist \
122 in the ansible-core test suite. Defaults to no. When set, \
123 skips everything else.',
124 )
125 parser.add_argument(
126 '--verbose', '-v',
127 action='count',
128 default=1,
129 help='verbosity between 0 and 5. 0 will only emit errors. 1=INFO. \
130 More for increasing levels of debug info. Defaults to 1.',
131 )
132
133 args = parser.parse_args()
134
135 # Don't set up test env when checking test lists
136 if args.check_test_lists:
137 args.setup = False
138
139 locale_debug('locale before setting os.environ:')
140 os.environ['LANG'] = 'en_US.UTF-8'
141 locale_debug('locale after setting os.environ:')
142
143 if args.setup is True and args.dry_run == False:
144 proc = runprog('testbed-setup.sh', ['sudo', './debian/tests/testbed-setup.sh'])
145 log(0,"#### STDOUT ####")
146 log(0, proc.stdout)
147 log(0, "#### STDERR ####")
148 log(0, proc.stderr)
149 locale_debug('locale after running testbed-setup.sh:')
150
151 # integration tests requiring a running ssh server
152 integration_requires_ssh = {
153 'become_unprivileged',
154 'cli',
155 'connection_paramiko_ssh',
156 'connection_ssh',
157 'delegate_to',
158 'fetch',
159 'module_tracebacks',
160 'ssh_agent',
161 }
162
163 # integration tests requiring root because the apt module is used to
164 # install missing packages, or to mark packages as manually installed
165 integration_requires_apt_mark_manual = {
166 #'ansible-galaxy-collection-scm', # apt-mark manual git
167 'ansible-pull', # apt-mark manual git
168 #'debconf', # apt-mark manual debconf-utils
169 'iptables', # apt-mark manual iptables
170 'git', # apt-mark manual git
171 }
172
173 integration_fails_on_pip = {
174 'ansible-galaxy-collection-cli', # fails on pip
175 'ansible-inventory', # pip error: externally-managed-environment ## upstream fix
176 'builtin_vars_prompt', # passlib: pip error: externally-managed-environment
177 'debugger', # pip installs pexpect
178 'pause', # pip installs pexpect
179 }
180
181 integration_failing = {
182 'ansible-test-docker': "pwsh doesn't exist in Debian yet",
183 'ansible-test': 'installs and runs python libs from remote',
184 'ansible-test-sanity': 'checks are only valid for the source tree',
185 'ansible-test-units-forked': '?????',
186 'deb822_repository': 'setup_deb_repo seems to generate a repo with hashsum mismatch',
187 'facts_d': 'seems to read an unreadable problem without error', ## needs upstream fix
188 'module_utils_Ansible.Basic': 'requires /usr/bin/pwsh',
189 'module_utils_Ansible.ModuleUtils.AddType': 'requires /usr/bin/pwsh',
190 'mount_facts': 'makes assumptions about static/dynamic mounts without assuring they exist',
191 'powershell_exec_wrapper': 'requires /usr/bin/pwsh',
192 'powershell_module_utils': 'requires /usr/bin/pwsh',
193 }
194
195 if subprocess.check_output(['dpkg', '--print-architecture'], text=True).rstrip('\n') not in {'amd64', 'ppc64el'}:
196 integration_failing['binary_modules_posix'] = 'needs statically-built helloworld_linux_* from ci-files.testing.ansible.com'
197
198 # work around autopkgtest providing the source tree owned by a different user
199 if args.setup:
200 runprog('git config hack for normal user', ['git', 'config', '--global', '--add', 'safe.directory', '*'])
201 runprog('git config hack for root', ['sudo', 'git', 'config', '--global', '--add', 'safe.directory', '*'])
202
203 pyver = str(sys.version_info.major) + '.' + str(sys.version_info.minor)
204
205 overall_test_rc = 0
206 failed_tests = []
207 succeeded_tests = []
208
209 # retrieve a list of all integration tests
210 all_targets_cmd = runprog(
211 'ansible-test to retrieve list of targets',
212 ['ansible-test', 'integration', '--list-targets', '--allow-root', '--allow-destructive'],
213 env={**os.environ, 'PYTHONPATH': os.path.join(os.getcwd(), 'test', 'lib')},
214 )
215
216 # Compile list of all targets
217 all_targets = set(all_targets_cmd.stdout.splitlines())
218
219 default_targets = list(
220 all_targets
221 - integration_requires_ssh
222 - integration_requires_apt_mark_manual
223 - integration_fails_on_pip
224 - set(integration_failing.keys())
225 )
226
227 def check_if_list_in_all_targets( l1, name):
228 l = l1 - all_targets
229 global overall_test_rc # hack to change it out of func
230 if len(l) !=0:
231 log(0, name, 'has elements not in all_targets list!')
232 for i in l:
233 log(0, ' ', i)
234 overall_test_rc = 1
235 log(0, ' ^^^^ consider removing those.')
236 else:
237 log(0, name, 'looks good.')
238
239 if args.check_test_lists:
240 check_if_list_in_all_targets(integration_requires_ssh, 'integration_requires_ssh')
241 check_if_list_in_all_targets(integration_requires_apt_mark_manual, 'integration_requires_apt_mark_manual')
242 check_if_list_in_all_targets(integration_fails_on_pip, 'integration_fails_on_pip')
243 check_if_list_in_all_targets(integration_failing.keys(), 'integration_failing')
244 sys.exit(overall_test_rc)
245
246 # compile a list of targets to run, depending on CLI parameters
247 targets = []
248 skipped = []
249
250 if args.default_tests is True:
251 targets.extend(default_targets)
252 else:
253 skipped.extend(default_targets)
254
255 if args.requires_ssh is True:
256 targets.extend(integration_requires_ssh)
257 else:
258 skipped.extend(integration_requires_ssh)
259
260 if args.requires_apt_mark_manual is True:
261 targets.extend(integration_requires_apt_mark_manual)
262 else:
263 skipped.extend(integration_requires_apt_mark_manual)
264
265 if args.fails_on_pip is True:
266 targets.extend(integration_fails_on_pip)
267 else:
268 skipped.extend(integration_fails_on_pip)
269
270 if args.failing is True:
271 targets.extend(integration_failing)
272 else:
273 skipped.extend(integration_failing)
274
275 # TODO: remove any tests that we're skipping from the list
276 # e.g. "cli" is in requires-root and also requires-ssh
277
278 targets.sort()
279 skipped.sort()
280
281 for i in targets:
282
283 if args.dry_run is True:
284 log(1, 'Would run ansible-test in', i)
285 succeeded_tests.append({
286 'name': i,
287 'time': 0
288 })
289 continue
290
291 log(0, "\n" + "#"*72)
292 log(0, "#### Running integration tests in", i)
293 log(0, "#"*72)
294
295 cmdlist = [
296 'ansible-test',
297 'integration',
298 '--allow-root',
299 '--allow-destructive',
300 '--venv-system-site-packages',
301 '--python-interpreter',
302 '/usr/bin/python3',
303 '--python',
304 pyver,
305 '--local',
306 '--color', 'yes',
307 i,
308 # '-vvvv', # uncomment for more test output
309 ]
310
311 env={
312 **os.environ,
313 'PYTHONPATH': os.path.join(os.getcwd(), 'test', 'lib'),
314 }
315
316 # Check if test requires root privileges via aliases file
317 needs_root = False
318 with open(os.path.join('./test/integration/targets', i, 'aliases')) as f:
319 for line in f.read().splitlines():
320 if line == 'needs/root':
321 needs_root = True
322
323 if needs_root is True:
324 cmdlist = ['sudo', '--preserve-env=PYTHONPATH'] + cmdlist
325
326 # For debugging permission errors on writing results output
327 if args.verbose >= 3:
328 subprocess.run(['ls', '-ld', './test/'])
329 subprocess.run(['ls', '-ld', './test/results/'])
330 subprocess.run(['ls', '-ld', './test/results/.tmp/'])
331 subprocess.run(['ls', '-ld', './test/results/.tmp/output_dir/'])
332
333 # fix any permission errors due to some root tests not cleaning up correctly
334 subprocess.run(['sudo', 'chown', '-R', str(os.getuid()) + ':' + str(os.getgid()), './test'])
335
336 start = time.time()
337 proc = subprocess.run(cmdlist, env=env)
338 end = time.time()
339
340 if proc.returncode != 0:
341 failed_tests.append({
342 'name': i,
343 'time': int( end - start)
344 })
345 overall_test_rc = proc.returncode
346 else:
347 succeeded_tests.append({
348 'name': i,
349 'time': int( end - start)
350 })
351
352 if overall_test_rc != 0:
353 log(0, "#"*72)
354 log(0, "#### failed tests are:")
355 for i in failed_tests:
356 log(0, "####", i['name'])
357 log(0, "#"*72)
358
359 if (args.default_tests is False
360 and (args.failing or args.fails_on_pip or args.requires_ssh)
361 and len(succeeded_tests) > 0):
362 log(0, "#"*72)
363 log(0, "#### succeeded tests are:")
364 for i in succeeded_tests:
365 log(0, "####", i['name'])
366 log(0, "Consider removing these ^^^ tests from the failing list!")
367 log(0, "#"*72)
368
369 log(1, '### TEST SUMMARY ###')
370 log(1, 'succeeded tests:', len(succeeded_tests))
371 log(1, 'failed tests:', len(failed_tests))
372 log(1, 'skipped tests:', len(skipped))
373
374 log(2, '### succeeded test list:')
375 for i in succeeded_tests:
376 log(2, '{:<30} (elapsed time: {:>3}s)'.format( i['name'], i['time'] ) )
377 log(2, '### failed test list:')
378 for i in failed_tests:
379 log(2, '{:<30} (elapsed time: {:>3}s)'.format( i['name'], i['time'] ) )
380 log(2, '### skipped test list:')
381 for i in skipped:
382 log(2, i)
383
384 sys.exit(overall_test_rc)