Debian Codegraph @

test/lib/ansible_test/_internal/commands/sanity/compile.py

raw
1 """Sanity test for proper python syntax."""
2
3 from __future__ import annotations
4
5 import os
6
7 from . import (
8 SanityMultipleVersion,
9 SanityMessage,
10 SanityFailure,
11 SanitySuccess,
12 SanityTargets,
13 SanitySkipped,
14 TARGET_SANITY_ROOT,
15 )
16
17 from ...test import (
18 TestResult,
19 )
20
21 from ...target import (
22 TestTarget,
23 )
24
25 from ...util import (
26 SubprocessError,
27 display,
28 parse_to_list_of_dict,
29 is_subdir,
30 )
31
32 from ...util_common import (
33 run_command,
34 )
35
36 from ...config import (
37 SanityConfig,
38 )
39
40 from ...host_configs import (
41 PythonConfig,
42 )
43
44
45 class CompileTest(SanityMultipleVersion):
46 """Sanity test for proper python syntax."""
47
48 def filter_targets(self, targets: list[TestTarget]) -> list[TestTarget]:
49 """Return the given list of test targets, filtered to include only those relevant for the test."""
50 return [target for target in targets if os.path.splitext(target.path)[1] == '.py' or is_subdir(target.path, 'bin')]
51
52 def test(self, args: SanityConfig, targets: SanityTargets, python: PythonConfig) -> TestResult:
53 if args.prime_venvs:
54 return SanitySkipped(self.name, python_version=python.version)
55
56 settings = self.load_processor(args, python.version)
57
58 paths = [target.path for target in targets.include]
59
60 cmd = [python.path, os.path.join(TARGET_SANITY_ROOT, 'compile', 'compile.py')]
61
62 data = '\n'.join(paths)
63
64 display.info(data, verbosity=4)
65
66 try:
67 stdout, stderr = run_command(args, cmd, data=data, capture=True)
68 status = 0
69 except SubprocessError as ex:
70 stdout = ex.stdout
71 stderr = ex.stderr
72 status = ex.status
73
74 if stderr:
75 raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout)
76
77 if args.explain:
78 return SanitySuccess(self.name, python_version=python.version)
79
80 pattern = r'^(?P<path>[^:]*):(?P<line>[0-9]+):(?P<column>[0-9]+): (?P<message>.*)$'
81
82 results = parse_to_list_of_dict(pattern, stdout)
83
84 results = [SanityMessage(
85 message=r['message'],
86 path=r['path'].replace('./', ''),
87 line=int(r['line']),
88 column=int(r['column']),
89 ) for r in results]
90
91 results = settings.process_errors(results, paths)
92
93 if results:
94 return SanityFailure(self.name, messages=results, python_version=python.version)
95
96 return SanitySuccess(self.name, python_version=python.version)