| 1 |
"""Sanity test using pylint.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import collections.abc as c |
| 6 |
import itertools |
| 7 |
import json |
| 8 |
import os |
| 9 |
import datetime |
| 10 |
import typing as t |
| 11 |
|
| 12 |
from . import ( |
| 13 |
SanitySingleVersion, |
| 14 |
SanityMessage, |
| 15 |
SanityFailure, |
| 16 |
SanitySuccess, |
| 17 |
SanityTargets, |
| 18 |
SANITY_ROOT, |
| 19 |
) |
| 20 |
|
| 21 |
from ...constants import ( |
| 22 |
CONTROLLER_PYTHON_VERSIONS, |
| 23 |
REMOTE_ONLY_PYTHON_VERSIONS, |
| 24 |
) |
| 25 |
|
| 26 |
from ...io import ( |
| 27 |
make_dirs, |
| 28 |
) |
| 29 |
|
| 30 |
from ...test import ( |
| 31 |
TestResult, |
| 32 |
) |
| 33 |
|
| 34 |
from ...target import ( |
| 35 |
TestTarget, |
| 36 |
) |
| 37 |
|
| 38 |
from ...util import ( |
| 39 |
SubprocessError, |
| 40 |
display, |
| 41 |
is_subdir, |
| 42 |
) |
| 43 |
|
| 44 |
from ...util_common import ( |
| 45 |
run_command, |
| 46 |
) |
| 47 |
|
| 48 |
from ...ansible_util import ( |
| 49 |
ansible_environment, |
| 50 |
get_collection_detail, |
| 51 |
CollectionDetail, |
| 52 |
CollectionDetailError, |
| 53 |
ResultType, |
| 54 |
) |
| 55 |
|
| 56 |
from ...config import ( |
| 57 |
SanityConfig, |
| 58 |
) |
| 59 |
|
| 60 |
from ...data import ( |
| 61 |
data_context, |
| 62 |
) |
| 63 |
|
| 64 |
from ...host_configs import ( |
| 65 |
PythonConfig, |
| 66 |
) |
| 67 |
|
| 68 |
|
| 69 |
class PylintTest(SanitySingleVersion): |
| 70 |
"""Sanity test using pylint.""" |
| 71 |
|
| 72 |
def __init__(self) -> None: |
| 73 |
super().__init__() |
| 74 |
self.optional_error_codes.update([ |
| 75 |
'ansible-deprecated-date', |
| 76 |
'too-complex', |
| 77 |
]) |
| 78 |
|
| 79 |
@property |
| 80 |
def error_code(self) -> t.Optional[str]: |
| 81 |
"""Error code for ansible-test matching the format used by the underlying test program, or None if the program does not use error codes.""" |
| 82 |
return 'ansible-test' |
| 83 |
|
| 84 |
def filter_targets(self, targets: list[TestTarget]) -> list[TestTarget]: |
| 85 |
"""Return the given list of test targets, filtered to include only those relevant for the test.""" |
| 86 |
return [target for target in targets if os.path.splitext(target.path)[1] == '.py' or is_subdir(target.path, 'bin')] |
| 87 |
|
| 88 |
def test(self, args: SanityConfig, targets: SanityTargets, python: PythonConfig) -> TestResult: |
| 89 |
target_paths = set(target.path for target in self.filter_remote_targets(list(targets.targets))) |
| 90 |
|
| 91 |
plugin_dir = os.path.join(SANITY_ROOT, 'pylint', 'plugins') |
| 92 |
plugin_names = sorted(p[0] for p in [ |
| 93 |
os.path.splitext(p) for p in os.listdir(plugin_dir)] if p[1] == '.py' and p[0] != '__init__') |
| 94 |
|
| 95 |
settings = self.load_processor(args) |
| 96 |
|
| 97 |
paths = [target.path for target in targets.include] |
| 98 |
|
| 99 |
module_paths = [os.path.relpath(p, data_context().content.module_path).split(os.path.sep) for p in |
| 100 |
paths if is_subdir(p, data_context().content.module_path)] |
| 101 |
module_dirs = sorted({p[0] for p in module_paths if len(p) > 1}) |
| 102 |
|
| 103 |
large_module_group_threshold = 500 |
| 104 |
large_module_groups = [key for key, value in |
| 105 |
itertools.groupby(module_paths, lambda p: p[0] if len(p) > 1 else '') if len(list(value)) > large_module_group_threshold] |
| 106 |
|
| 107 |
large_module_group_paths = [os.path.relpath(p, data_context().content.module_path).split(os.path.sep) for p in paths |
| 108 |
if any(is_subdir(p, os.path.join(data_context().content.module_path, g)) for g in large_module_groups)] |
| 109 |
large_module_group_dirs = sorted({os.path.sep.join(p[:2]) for p in large_module_group_paths if len(p) > 2}) |
| 110 |
|
| 111 |
contexts = [] |
| 112 |
remaining_paths = set(paths) |
| 113 |
|
| 114 |
def add_context(available_paths: set[str], context_name: str, context_filter: c.Callable[[str], bool]) -> None: |
| 115 |
"""Add the specified context to the context list, consuming available paths that match the given context filter.""" |
| 116 |
filtered_paths = set(p for p in available_paths if context_filter(p)) |
| 117 |
|
| 118 |
if selected_paths := sorted(path for path in filtered_paths if path in target_paths): |
| 119 |
contexts.append((context_name, True, selected_paths)) |
| 120 |
|
| 121 |
if selected_paths := sorted(path for path in filtered_paths if path not in target_paths): |
| 122 |
contexts.append((context_name, False, selected_paths)) |
| 123 |
|
| 124 |
available_paths -= filtered_paths |
| 125 |
|
| 126 |
def filter_path(path_filter: str = None) -> c.Callable[[str], bool]: |
| 127 |
"""Return a function that filters out paths which are not a subdirectory of the given path.""" |
| 128 |
|
| 129 |
def context_filter(path_to_filter: str) -> bool: |
| 130 |
"""Return true if the given path matches, otherwise return False.""" |
| 131 |
return is_subdir(path_to_filter, path_filter) |
| 132 |
|
| 133 |
return context_filter |
| 134 |
|
| 135 |
for large_module_dir in large_module_group_dirs: |
| 136 |
add_context(remaining_paths, 'modules/%s' % large_module_dir, filter_path(os.path.join(data_context().content.module_path, large_module_dir))) |
| 137 |
|
| 138 |
for module_dir in module_dirs: |
| 139 |
add_context(remaining_paths, 'modules/%s' % module_dir, filter_path(os.path.join(data_context().content.module_path, module_dir))) |
| 140 |
|
| 141 |
add_context(remaining_paths, 'modules', filter_path(data_context().content.module_path)) |
| 142 |
add_context(remaining_paths, 'module_utils', filter_path(data_context().content.module_utils_path)) |
| 143 |
|
| 144 |
add_context(remaining_paths, 'units', filter_path(data_context().content.unit_path)) |
| 145 |
|
| 146 |
if data_context().content.collection: |
| 147 |
add_context(remaining_paths, 'collection', lambda p: True) |
| 148 |
else: |
| 149 |
add_context(remaining_paths, 'validate-modules', filter_path('test/lib/ansible_test/_util/controller/sanity/validate-modules/')) |
| 150 |
add_context(remaining_paths, 'validate-modules-unit', filter_path('test/lib/ansible_test/tests/validate-modules-unit/')) |
| 151 |
add_context(remaining_paths, 'code-smell', filter_path('test/lib/ansible_test/_util/controller/sanity/code-smell/')) |
| 152 |
add_context(remaining_paths, 'ansible-test-target', filter_path('test/lib/ansible_test/_util/target/')) |
| 153 |
add_context(remaining_paths, 'ansible-test', filter_path('test/lib/')) |
| 154 |
add_context(remaining_paths, 'test', filter_path('test/')) |
| 155 |
add_context(remaining_paths, 'hacking', filter_path('hacking/')) |
| 156 |
add_context(remaining_paths, 'ansible', lambda p: True) |
| 157 |
|
| 158 |
messages = [] |
| 159 |
context_times = [] |
| 160 |
|
| 161 |
collection_detail = None |
| 162 |
|
| 163 |
if data_context().content.collection: |
| 164 |
try: |
| 165 |
collection_detail = get_collection_detail(python) |
| 166 |
|
| 167 |
if not collection_detail.version: |
| 168 |
display.warning('Skipping pylint collection version checks since no collection version was found.') |
| 169 |
except CollectionDetailError as ex: |
| 170 |
display.warning('Skipping pylint collection version checks since collection detail loading failed: %s' % ex.reason) |
| 171 |
|
| 172 |
test_start = datetime.datetime.now(tz=datetime.timezone.utc) |
| 173 |
|
| 174 |
for context, is_target, context_paths in sorted(contexts): |
| 175 |
if not context_paths: |
| 176 |
continue |
| 177 |
|
| 178 |
context_start = datetime.datetime.now(tz=datetime.timezone.utc) |
| 179 |
messages += self.pylint(args, context, is_target, context_paths, plugin_dir, plugin_names, python, collection_detail) |
| 180 |
context_end = datetime.datetime.now(tz=datetime.timezone.utc) |
| 181 |
|
| 182 |
context_times.append('%s: %d (%s)' % (context, len(context_paths), context_end - context_start)) |
| 183 |
|
| 184 |
test_end = datetime.datetime.now(tz=datetime.timezone.utc) |
| 185 |
|
| 186 |
for context_time in context_times: |
| 187 |
display.info(context_time, verbosity=4) |
| 188 |
|
| 189 |
display.info('total: %d (%s)' % (len(paths), test_end - test_start), verbosity=4) |
| 190 |
|
| 191 |
errors = [SanityMessage( |
| 192 |
message=m['message'].replace('\n', ' '), |
| 193 |
path=m['path'], |
| 194 |
line=int(m['line']), |
| 195 |
column=int(m['column']), |
| 196 |
level=m['type'], |
| 197 |
code=m['symbol'], |
| 198 |
) for m in messages] |
| 199 |
|
| 200 |
if args.explain: |
| 201 |
return SanitySuccess(self.name) |
| 202 |
|
| 203 |
errors = settings.process_errors(errors, paths) |
| 204 |
|
| 205 |
if errors: |
| 206 |
return SanityFailure(self.name, messages=errors) |
| 207 |
|
| 208 |
return SanitySuccess(self.name) |
| 209 |
|
| 210 |
@staticmethod |
| 211 |
def pylint( |
| 212 |
args: SanityConfig, |
| 213 |
context: str, |
| 214 |
is_target: bool, |
| 215 |
paths: list[str], |
| 216 |
plugin_dir: str, |
| 217 |
plugin_names: list[str], |
| 218 |
python: PythonConfig, |
| 219 |
collection_detail: CollectionDetail, |
| 220 |
) -> list[dict[str, str]]: |
| 221 |
"""Run pylint using the config specified by the context on the specified paths.""" |
| 222 |
rcfile = os.path.join(SANITY_ROOT, 'pylint', 'config', context.split('/')[0] + '.cfg') |
| 223 |
|
| 224 |
if not os.path.exists(rcfile): |
| 225 |
if data_context().content.collection: |
| 226 |
rcfile = os.path.join(SANITY_ROOT, 'pylint', 'config', 'collection.cfg') |
| 227 |
else: |
| 228 |
rcfile = os.path.join(SANITY_ROOT, 'pylint', 'config', 'default.cfg') |
| 229 |
|
| 230 |
if is_target: |
| 231 |
context_label = 'target' |
| 232 |
min_python_version = REMOTE_ONLY_PYTHON_VERSIONS[0] |
| 233 |
else: |
| 234 |
context_label = 'controller' |
| 235 |
min_python_version = CONTROLLER_PYTHON_VERSIONS[0] |
| 236 |
|
| 237 |
load_plugins = set(plugin_names) |
| 238 |
plugin_options: dict[str, str] = {} |
| 239 |
|
| 240 |
# plugin: deprecated (ansible-test) |
| 241 |
if data_context().content.collection: |
| 242 |
plugin_options.update({'--collection-name': data_context().content.collection.full_name}) |
| 243 |
plugin_options.update({'--collection-path': os.path.join(data_context().content.collection.root, data_context().content.collection.directory)}) |
| 244 |
|
| 245 |
if collection_detail and collection_detail.version: |
| 246 |
plugin_options.update({'--collection-version': collection_detail.version}) |
| 247 |
|
| 248 |
# plugin: pylint.extensions.mccabe |
| 249 |
if args.enable_optional_errors: |
| 250 |
load_plugins.add('pylint.extensions.mccabe') |
| 251 |
plugin_options.update({'--max-complexity': '20'}) |
| 252 |
|
| 253 |
options = { |
| 254 |
'--py-version': min_python_version, |
| 255 |
'--load-plugins': ','.join(sorted(load_plugins)), |
| 256 |
'--rcfile': rcfile, |
| 257 |
'--jobs': '0', |
| 258 |
'--reports': 'n', |
| 259 |
'--output-format': 'json', |
| 260 |
} |
| 261 |
|
| 262 |
cmd = [python.path, '-m', 'pylint'] |
| 263 |
cmd.extend(itertools.chain.from_iterable((options | plugin_options).items())) |
| 264 |
cmd.extend(paths) |
| 265 |
|
| 266 |
append_python_path = [plugin_dir] |
| 267 |
|
| 268 |
if data_context().content.collection: |
| 269 |
append_python_path.append(data_context().content.collection.root) |
| 270 |
|
| 271 |
env = ansible_environment(args) |
| 272 |
env['PYTHONPATH'] += os.path.pathsep + os.path.pathsep.join(append_python_path) |
| 273 |
|
| 274 |
# expose plugin paths for use in custom plugins |
| 275 |
env.update(dict(('ANSIBLE_TEST_%s_PATH' % k.upper(), os.path.abspath(v) + os.path.sep) for k, v in data_context().content.plugin_paths.items())) |
| 276 |
|
| 277 |
# Set PYLINTHOME to prevent pylint from checking for an obsolete directory, which can result in a test failure due to stderr output. |
| 278 |
# See: https://github.com/PyCQA/pylint/blob/e6c6bf5dfd61511d64779f54264b27a368c43100/pylint/constants.py#L148 |
| 279 |
pylint_home = os.path.join(ResultType.TMP.path, 'pylint') |
| 280 |
make_dirs(pylint_home) |
| 281 |
env.update(PYLINTHOME=pylint_home) |
| 282 |
|
| 283 |
if paths: |
| 284 |
display.info(f'Checking {len(paths)} file(s) in context {context!r} ({context_label}) with config: {rcfile}', verbosity=1) |
| 285 |
|
| 286 |
try: |
| 287 |
stdout, stderr = run_command(args, cmd, env=env, capture=True) |
| 288 |
status = 0 |
| 289 |
except SubprocessError as ex: |
| 290 |
stdout = ex.stdout |
| 291 |
stderr = ex.stderr |
| 292 |
status = ex.status |
| 293 |
|
| 294 |
if stderr or status >= 32: |
| 295 |
raise SubprocessError(cmd=cmd, status=status, stderr=stderr, stdout=stdout) |
| 296 |
else: |
| 297 |
stdout = None |
| 298 |
|
| 299 |
if not args.explain and stdout: |
| 300 |
messages = json.loads(stdout) |
| 301 |
else: |
| 302 |
messages = [] |
| 303 |
|
| 304 |
expected_paths = set(paths) |
| 305 |
|
| 306 |
unexpected_messages = [message for message in messages if message["path"] not in expected_paths] |
| 307 |
messages = [message for message in messages if message["path"] in expected_paths] |
| 308 |
|
| 309 |
for unexpected_message in unexpected_messages: |
| 310 |
display.info(f"Unexpected message: {json.dumps(unexpected_message)}", verbosity=4) |
| 311 |
|
| 312 |
if unexpected_messages: |
| 313 |
display.notice(f"Discarded {len(unexpected_messages)} unexpected messages. Use -vvvv to display.") |
| 314 |
|
| 315 |
return messages |