Debian Codegraph @

test/lib/ansible_test/_internal/target.py

raw
1 """Test target identification, iteration and inclusion/exclusion."""
2
3 from __future__ import annotations
4
5 import collections
6 import collections.abc as c
7 import enum
8 import os
9 import re
10 import itertools
11 import abc
12 import typing as t
13
14 from .encoding import (
15 to_bytes,
16 to_text,
17 )
18
19 from .io import (
20 read_text_file,
21 )
22
23 from .util import (
24 ApplicationError,
25 display,
26 read_lines_without_comments,
27 is_subdir,
28 )
29
30 from .data import (
31 data_context,
32 content_plugins,
33 )
34
35 MODULE_EXTENSIONS = '.py', '.ps1'
36
37
38 def find_target_completion(target_func: c.Callable[[], c.Iterable[CompletionTarget]], prefix: str, short: bool) -> list[str]:
39 """Return a list of targets from the given target function which match the given prefix."""
40 try:
41 targets = target_func()
42 matches = list(walk_completion_targets(targets, prefix, short))
43 return matches
44 except Exception as ex: # pylint: disable=locally-disabled, broad-except
45 return ['%s' % ex]
46
47
48 def walk_completion_targets(targets: c.Iterable[CompletionTarget], prefix: str, short: bool = False) -> tuple[str, ...]:
49 """Return a tuple of targets from the given target iterable which match the given prefix."""
50 aliases = set(alias for target in targets for alias in target.aliases)
51
52 if prefix.endswith('/') and prefix in aliases:
53 aliases.remove(prefix)
54
55 matches = [alias for alias in aliases if alias.startswith(prefix) and '/' not in alias[len(prefix):-1]]
56
57 if short:
58 offset = len(os.path.dirname(prefix))
59 if offset:
60 offset += 1
61 relative_matches = [match[offset:] for match in matches if len(match) > offset]
62 if len(relative_matches) > 1:
63 matches = relative_matches
64
65 return tuple(sorted(matches))
66
67
68 def walk_internal_targets[TCompletionTarget: CompletionTarget](
69 targets: c.Iterable[TCompletionTarget],
70 includes: t.Optional[list[str]] = None,
71 excludes: t.Optional[list[str]] = None,
72 requires: t.Optional[list[str]] = None,
73 ) -> tuple[TCompletionTarget, ...]:
74 """Return a tuple of matching completion targets."""
75 targets = tuple(targets)
76
77 include_targets = sorted(filter_targets(targets, includes), key=lambda include_target: include_target.name)
78
79 if requires:
80 require_targets = set(filter_targets(targets, requires))
81 include_targets = [require_target for require_target in include_targets if require_target in require_targets]
82
83 if excludes:
84 list(filter_targets(targets, excludes, include=False))
85
86 internal_targets = set(filter_targets(include_targets, excludes, errors=False, include=False))
87 return tuple(sorted(internal_targets, key=lambda sort_target: sort_target.name))
88
89
90 def filter_targets[TCompletionTarget: CompletionTarget](
91 targets: c.Iterable[TCompletionTarget],
92 patterns: list[str],
93 include: bool = True,
94 errors: bool = True,
95 ) -> c.Iterable[TCompletionTarget]:
96 """Iterate over the given targets and filter them based on the supplied arguments."""
97 unmatched = set(patterns or ())
98 compiled_patterns = dict((p, re.compile('^%s$' % p)) for p in patterns) if patterns else None
99
100 for target in targets:
101 matched_directories = set()
102 match = False
103
104 if patterns:
105 for alias in target.aliases:
106 for pattern in patterns:
107 if compiled_patterns[pattern].match(alias):
108 match = True
109
110 try:
111 unmatched.remove(pattern)
112 except KeyError:
113 pass
114
115 if alias.endswith('/'):
116 if target.base_path and len(target.base_path) > len(alias):
117 matched_directories.add(target.base_path)
118 else:
119 matched_directories.add(alias)
120 elif include:
121 match = True
122 if not target.base_path:
123 matched_directories.add('.')
124 for alias in target.aliases:
125 if alias.endswith('/'):
126 if target.base_path and len(target.base_path) > len(alias):
127 matched_directories.add(target.base_path)
128 else:
129 matched_directories.add(alias)
130
131 if match != include:
132 continue
133
134 yield target
135
136 if errors:
137 if unmatched:
138 raise TargetPatternsNotMatched(unmatched)
139
140
141 def walk_module_targets() -> c.Iterable[TestTarget]:
142 """Iterate through the module test targets."""
143 for target in walk_test_targets(path=data_context().content.module_path, module_path=data_context().content.module_path, extensions=MODULE_EXTENSIONS):
144 if not target.module:
145 continue
146
147 yield target
148
149
150 def walk_units_targets() -> c.Iterable[TestTarget]:
151 """Return an iterable of units targets."""
152 return walk_test_targets(path=data_context().content.unit_path, module_path=data_context().content.unit_module_path, extensions=('.py',), prefix='test_')
153
154
155 def walk_compile_targets(include_symlinks: bool = True) -> c.Iterable[TestTarget]:
156 """Return an iterable of compile targets."""
157 return walk_test_targets(module_path=data_context().content.module_path, extensions=('.py',), extra_dirs=('bin',), include_symlinks=include_symlinks)
158
159
160 def walk_powershell_targets(include_symlinks: bool = True) -> c.Iterable[TestTarget]:
161 """Return an iterable of PowerShell targets."""
162 return walk_test_targets(module_path=data_context().content.module_path, extensions=('.ps1', '.psm1'), include_symlinks=include_symlinks)
163
164
165 def walk_sanity_targets() -> c.Iterable[TestTarget]:
166 """Return an iterable of sanity targets."""
167 return walk_test_targets(module_path=data_context().content.module_path, include_symlinks=True, include_symlinked_directories=True)
168
169
170 def walk_posix_integration_targets(include_hidden: bool = False) -> c.Iterable[IntegrationTarget]:
171 """Return an iterable of POSIX integration targets."""
172 for target in walk_integration_targets():
173 if 'posix/' in target.aliases or (include_hidden and 'hidden/posix/' in target.aliases):
174 yield target
175
176
177 def walk_network_integration_targets(include_hidden: bool = False) -> c.Iterable[IntegrationTarget]:
178 """Return an iterable of network integration targets."""
179 for target in walk_integration_targets():
180 if 'network/' in target.aliases or (include_hidden and 'hidden/network/' in target.aliases):
181 yield target
182
183
184 def walk_windows_integration_targets(include_hidden: bool = False) -> c.Iterable[IntegrationTarget]:
185 """Return an iterable of windows integration targets."""
186 for target in walk_integration_targets():
187 if 'windows/' in target.aliases or (include_hidden and 'hidden/windows/' in target.aliases):
188 yield target
189
190
191 def walk_integration_targets() -> c.Iterable[IntegrationTarget]:
192 """Return an iterable of integration targets."""
193 path = data_context().content.integration_targets_path
194 modules = frozenset(target.module for target in walk_module_targets())
195 paths = data_context().content.walk_files(path)
196 prefixes = load_integration_prefixes()
197 targets_path_tuple = tuple(path.split(os.path.sep))
198
199 entry_dirs = (
200 'defaults',
201 'files',
202 'handlers',
203 'meta',
204 'tasks',
205 'templates',
206 'vars',
207 )
208
209 entry_files = (
210 'main.yml',
211 'main.yaml',
212 )
213
214 entry_points = []
215
216 for entry_dir in entry_dirs:
217 for entry_file in entry_files:
218 entry_points.append(os.path.join(os.path.sep, entry_dir, entry_file))
219
220 # any directory with at least one file is a target
221 path_tuples = set(tuple(os.path.dirname(p).split(os.path.sep))
222 for p in paths)
223
224 # also detect targets which are ansible roles, looking for standard entry points
225 path_tuples.update(tuple(os.path.dirname(os.path.dirname(p)).split(os.path.sep))
226 for p in paths if any(p.endswith(entry_point) for entry_point in entry_points))
227
228 # remove the top-level directory if it was included
229 if targets_path_tuple in path_tuples:
230 path_tuples.remove(targets_path_tuple)
231
232 previous_path_tuple = None
233 paths = []
234
235 for path_tuple in sorted(path_tuples):
236 if previous_path_tuple and previous_path_tuple == path_tuple[:len(previous_path_tuple)]:
237 # ignore nested directories
238 continue
239
240 previous_path_tuple = path_tuple
241 paths.append(os.path.sep.join(path_tuple))
242
243 for path in paths:
244 yield IntegrationTarget(to_text(path), modules, prefixes)
245
246
247 def load_integration_prefixes() -> dict[str, str]:
248 """Load and return the integration test prefixes."""
249 path = data_context().content.integration_path
250 file_paths = sorted(f for f in data_context().content.get_files(path) if os.path.splitext(os.path.basename(f))[0] == 'target-prefixes')
251 prefixes = {}
252
253 for file_path in file_paths:
254 prefix = os.path.splitext(file_path)[1][1:]
255 prefixes.update(dict((k, prefix) for k in read_text_file(file_path).splitlines()))
256
257 return prefixes
258
259
260 def walk_test_targets(
261 path: t.Optional[str] = None,
262 module_path: t.Optional[str] = None,
263 extensions: t.Optional[tuple[str, ...]] = None,
264 prefix: t.Optional[str] = None,
265 extra_dirs: t.Optional[tuple[str, ...]] = None,
266 include_symlinks: bool = False,
267 include_symlinked_directories: bool = False,
268 ) -> c.Iterable[TestTarget]:
269 """Iterate over available test targets."""
270 if path:
271 file_paths = data_context().content.walk_files(path, include_symlinked_directories=include_symlinked_directories)
272 else:
273 file_paths = data_context().content.all_files(include_symlinked_directories=include_symlinked_directories)
274
275 for file_path in file_paths:
276 name, ext = os.path.splitext(os.path.basename(file_path))
277
278 if extensions and ext not in extensions:
279 continue
280
281 if prefix and not name.startswith(prefix):
282 continue
283
284 symlink = os.path.islink(to_bytes(file_path.rstrip(os.path.sep)))
285
286 if symlink and not include_symlinks:
287 continue
288
289 yield TestTarget(to_text(file_path), module_path, prefix, path, symlink)
290
291 file_paths = []
292
293 if extra_dirs:
294 for extra_dir in extra_dirs:
295 for file_path in data_context().content.get_files(extra_dir):
296 file_paths.append(file_path)
297
298 for file_path in file_paths:
299 symlink = os.path.islink(to_bytes(file_path.rstrip(os.path.sep)))
300
301 if symlink and not include_symlinks:
302 continue
303
304 yield TestTarget(file_path, module_path, prefix, path, symlink)
305
306
307 def analyze_integration_target_dependencies(integration_targets: list[IntegrationTarget]) -> dict[str, set[str]]:
308 """Analyze the given list of integration test targets and return a dictionary expressing target names and the target names which depend on them."""
309 real_target_root = os.path.realpath(data_context().content.integration_targets_path) + '/'
310
311 role_targets = [target for target in integration_targets if target.type == 'role']
312 hidden_role_target_names = set(target.name for target in role_targets if 'hidden/' in target.aliases)
313
314 dependencies: collections.defaultdict[str, set[str]] = collections.defaultdict(set)
315
316 # handle setup dependencies
317 for target in integration_targets:
318 for setup_target_name in target.setup_always + target.setup_once:
319 dependencies[setup_target_name].add(target.name)
320
321 # handle target dependencies
322 for target in integration_targets:
323 for need_target in target.needs_target:
324 dependencies[need_target].add(target.name)
325
326 # handle symlink dependencies between targets
327 # this use case is supported, but discouraged
328 for target in integration_targets:
329 for path in data_context().content.walk_files(target.path):
330 if not os.path.islink(to_bytes(path.rstrip(os.path.sep))):
331 continue
332
333 real_link_path = os.path.realpath(path)
334
335 if not real_link_path.startswith(real_target_root):
336 continue
337
338 link_target = real_link_path[len(real_target_root):].split('/')[0]
339
340 if link_target == target.name:
341 continue
342
343 dependencies[link_target].add(target.name)
344
345 # intentionally primitive analysis of role meta to avoid a dependency on pyyaml
346 # script based targets are scanned as they may execute a playbook with role dependencies
347 for target in integration_targets:
348 meta_dir = os.path.join(target.path, 'meta')
349
350 if not os.path.isdir(meta_dir):
351 continue
352
353 meta_paths = data_context().content.get_files(meta_dir)
354
355 for meta_path in meta_paths:
356 if os.path.exists(meta_path):
357 # try and decode the file as a utf-8 string, skip if it contains invalid chars (binary file)
358 try:
359 meta_lines = read_text_file(meta_path).splitlines()
360 except UnicodeDecodeError:
361 continue
362
363 for meta_line in meta_lines:
364 if re.search(r'^ *#.*$', meta_line):
365 continue
366
367 if not meta_line.strip():
368 continue
369
370 for hidden_target_name in hidden_role_target_names:
371 if hidden_target_name in meta_line:
372 dependencies[hidden_target_name].add(target.name)
373
374 while True:
375 changes = 0
376
377 for dummy, dependent_target_names in dependencies.items():
378 for dependent_target_name in list(dependent_target_names):
379 new_target_names = dependencies.get(dependent_target_name)
380
381 if new_target_names:
382 for new_target_name in new_target_names:
383 if new_target_name not in dependent_target_names:
384 dependent_target_names.add(new_target_name)
385 changes += 1
386
387 if not changes:
388 break
389
390 for target_name in sorted(dependencies):
391 consumers = dependencies[target_name]
392
393 if not consumers:
394 continue
395
396 display.info('%s:' % target_name, verbosity=4)
397
398 for consumer in sorted(consumers):
399 display.info(' %s' % consumer, verbosity=4)
400
401 return dependencies
402
403
404 class CompletionTarget(metaclass=abc.ABCMeta):
405 """Command-line argument completion target base class."""
406
407 def __init__(self) -> None:
408 self.name = ''
409 self.path = ''
410 self.base_path: t.Optional[str] = None
411 self.modules: tuple[str, ...] = tuple()
412 self.aliases: tuple[str, ...] = tuple()
413
414 def __eq__(self, other):
415 if isinstance(other, CompletionTarget):
416 return self.__repr__() == other.__repr__()
417
418 return False
419
420 def __ne__(self, other):
421 return not self.__eq__(other)
422
423 def __lt__(self, other):
424 return self.name.__lt__(other.name)
425
426 def __gt__(self, other):
427 return self.name.__gt__(other.name)
428
429 def __hash__(self):
430 return hash(self.__repr__())
431
432 def __repr__(self):
433 if self.modules:
434 return '%s (%s)' % (self.name, ', '.join(self.modules))
435
436 return self.name
437
438
439 class TestTarget(CompletionTarget):
440 """Generic test target."""
441
442 def __init__(
443 self,
444 path: str,
445 module_path: t.Optional[str],
446 module_prefix: t.Optional[str],
447 base_path: str,
448 symlink: t.Optional[bool] = None,
449 ) -> None:
450 super().__init__()
451
452 if symlink is None:
453 symlink = os.path.islink(to_bytes(path.rstrip(os.path.sep)))
454
455 self.name = path
456 self.path = path
457 self.base_path = base_path + '/' if base_path else None
458 self.symlink = symlink
459
460 name, ext = os.path.splitext(os.path.basename(self.path))
461
462 if module_path and is_subdir(path, module_path) and name != '__init__' and ext in MODULE_EXTENSIONS:
463 self.module = name[len(module_prefix or ''):].lstrip('_')
464 self.modules = (self.module,)
465 else:
466 self.module = None
467 self.modules = tuple()
468
469 aliases = [self.path, self.module]
470 parts = self.path.split('/')
471
472 for i in range(1, len(parts)):
473 alias = '%s/' % '/'.join(parts[:i])
474 aliases.append(alias)
475
476 aliases = [a for a in aliases if a]
477
478 self.aliases = tuple(sorted(aliases))
479
480
481 class IntegrationTargetType(enum.Enum):
482 """Type of integration test target."""
483
484 CONTROLLER = enum.auto()
485 TARGET = enum.auto()
486 UNKNOWN = enum.auto()
487 CONFLICT = enum.auto()
488
489
490 def extract_plugin_references(name: str, aliases: list[str]) -> list[tuple[str, str]]:
491 """Return a list of plugin references found in the given integration test target name and aliases."""
492 plugins = content_plugins()
493 found: list[tuple[str, str]] = []
494
495 for alias in [name] + aliases:
496 plugin_type = 'modules'
497 plugin_name = alias
498
499 if plugin_name in plugins.get(plugin_type, {}):
500 found.append((plugin_type, plugin_name))
501
502 parts = alias.split('_')
503
504 for type_length in (1, 2):
505 if len(parts) > type_length:
506 plugin_type = '_'.join(parts[:type_length])
507 plugin_name = '_'.join(parts[type_length:])
508
509 if plugin_name in plugins.get(plugin_type, {}):
510 found.append((plugin_type, plugin_name))
511
512 return found
513
514
515 def categorize_integration_test(name: str, aliases: list[str], force_target: bool) -> tuple[IntegrationTargetType, IntegrationTargetType]:
516 """Return the integration test target types (used and actual) based on the given target name and aliases."""
517 context_controller = f'context/{IntegrationTargetType.CONTROLLER.name.lower()}' in aliases
518 context_target = f'context/{IntegrationTargetType.TARGET.name.lower()}' in aliases or force_target
519 actual_type = None
520 strict_mode = data_context().content.is_ansible
521
522 if context_controller and context_target:
523 target_type = IntegrationTargetType.CONFLICT
524 elif context_controller and not context_target:
525 target_type = IntegrationTargetType.CONTROLLER
526 elif context_target and not context_controller:
527 target_type = IntegrationTargetType.TARGET
528 else:
529 target_types = {IntegrationTargetType.TARGET if plugin_type in ('modules', 'module_utils') else IntegrationTargetType.CONTROLLER
530 for plugin_type, plugin_name in extract_plugin_references(name, aliases)}
531
532 if len(target_types) == 1:
533 target_type = target_types.pop()
534 elif not target_types:
535 actual_type = IntegrationTargetType.UNKNOWN
536 target_type = actual_type if strict_mode else IntegrationTargetType.TARGET
537 else:
538 target_type = IntegrationTargetType.CONFLICT
539
540 return target_type, actual_type or target_type
541
542
543 class IntegrationTarget(CompletionTarget):
544 """Integration test target."""
545 non_posix = frozenset((
546 'network',
547 'windows',
548 ))
549
550 categories = frozenset(non_posix | frozenset((
551 'posix',
552 'module',
553 'needs',
554 'skip',
555 )))
556
557 def __init__(self, path: str, modules: frozenset[str], prefixes: dict[str, str]) -> None:
558 super().__init__()
559
560 self.relative_path = os.path.relpath(path, data_context().content.integration_targets_path)
561 self.name = self.relative_path.replace(os.path.sep, '.')
562 self.path = path
563
564 # script_path and type
565
566 file_paths = data_context().content.get_files(path)
567 runme_path = os.path.join(path, 'runme.sh')
568
569 if runme_path in file_paths:
570 self.type = 'script'
571 self.script_path = runme_path
572 else:
573 self.type = 'role' # ansible will consider these empty roles, so ansible-test should as well
574 self.script_path = None
575
576 # static_aliases
577
578 aliases_path = os.path.join(path, 'aliases')
579
580 if aliases_path in file_paths:
581 static_aliases = tuple(read_lines_without_comments(aliases_path, remove_blank_lines=True))
582 else:
583 static_aliases = tuple()
584
585 # non-group aliases which need to be extracted before group mangling occurs
586
587 self.env_set: dict[str, str] = {
588 match.group('key'): match.group('value') for match in (
589 re.match(r'env/set/(?P<key>[^/]+)/(?P<value>.*)', alias) for alias in static_aliases
590 ) if match
591 }
592
593 # modules
594
595 if self.name in modules:
596 module_name = self.name
597 elif self.name.startswith('win_') and self.name[4:] in modules:
598 module_name = self.name[4:]
599 else:
600 module_name = None
601
602 self.modules = tuple(sorted(a for a in static_aliases + tuple([module_name]) if a in modules))
603
604 # groups
605
606 groups = [self.type]
607 groups += [a for a in static_aliases if a not in modules]
608 groups += ['module/%s' % m for m in self.modules]
609
610 if data_context().content.is_ansible and (self.name == 'ansible-test' or self.name.startswith('ansible-test-')):
611 groups.append('ansible-test')
612
613 if not self.modules:
614 groups.append('non_module')
615
616 if 'destructive' not in groups:
617 groups.append('non_destructive')
618
619 if 'needs/httptester' in groups:
620 groups.append('cloud/httptester') # backwards compatibility for when it was not a cloud plugin
621
622 for prefix, group in prefixes.items():
623 if not self.name.startswith(f'{prefix}_'):
624 continue
625
626 if group != prefix:
627 group = '%s/%s' % (group, prefix)
628
629 groups.append(group)
630
631 if self.name.startswith('win_'):
632 groups.append('windows')
633
634 if self.name.startswith('connection_'):
635 groups.append('connection')
636
637 if self.name.startswith('setup_') or self.name.startswith('prepare_'):
638 groups.append('hidden')
639
640 if self.type not in ('script', 'role'):
641 groups.append('hidden')
642
643 targets_relative_path = data_context().content.integration_targets_path
644
645 # Collect skip entries before group expansion to avoid registering more specific skip entries as less specific versions.
646 self.skips = tuple(g for g in groups if g.startswith('skip/'))
647
648 # Collect file paths before group expansion to avoid including the directories.
649 # Ignore references to test targets, as those must be defined using `needs/target/*` or other target references.
650 self.needs_file = tuple(sorted(set('/'.join(g.split('/')[2:]) for g in groups if
651 g.startswith('needs/file/') and not g.startswith('needs/file/%s/' % targets_relative_path))))
652
653 # network platform
654 networks = [g.split('/')[1] for g in groups if g.startswith('network/')]
655 self.network_platform = networks[0] if networks else None
656
657 for group in itertools.islice(groups, 0, len(groups)):
658 if '/' in group:
659 parts = group.split('/')
660 for i in range(1, len(parts)):
661 groups.append('/'.join(parts[:i]))
662
663 if not any(g in self.non_posix for g in groups):
664 groups.append('posix')
665
666 # target type
667
668 # targets which are non-posix test against the target, even if they also support posix
669 force_target = any(group in self.non_posix for group in groups)
670
671 target_type, actual_type = categorize_integration_test(self.name, list(static_aliases), force_target)
672
673 groups.extend(['context/', f'context/{target_type.name.lower()}'])
674
675 if target_type != actual_type:
676 # allow users to query for the actual type
677 groups.extend(['context/', f'context/{actual_type.name.lower()}'])
678
679 self.target_type = target_type
680 self.actual_type = actual_type
681
682 # aliases
683
684 aliases = [self.name] + \
685 ['%s/' % g for g in groups] + \
686 ['%s/%s' % (g, self.name) for g in groups if g not in self.categories]
687
688 if 'hidden/' in aliases:
689 aliases = ['hidden/'] + ['hidden/%s' % a for a in aliases if not a.startswith('hidden/')]
690
691 self.aliases = tuple(sorted(set(aliases)))
692
693 # configuration
694
695 self.retry_never = 'retry/never/' in self.aliases
696
697 self.setup_once = tuple(sorted(set(g.split('/')[2] for g in groups if g.startswith('setup/once/'))))
698 self.setup_always = tuple(sorted(set(g.split('/')[2] for g in groups if g.startswith('setup/always/'))))
699 self.needs_target = tuple(sorted(set(g.split('/')[2] for g in groups if g.startswith('needs/target/'))))
700
701
702 class TargetPatternsNotMatched(ApplicationError):
703 """One or more targets were not matched when a match was required."""
704
705 def __init__(self, patterns: set[str]) -> None:
706 self.patterns = sorted(patterns)
707
708 if len(patterns) > 1:
709 message = 'Target patterns not matched:\n%s' % '\n'.join(self.patterns)
710 else:
711 message = 'Target pattern not matched: %s' % self.patterns[0]
712
713 super().__init__(message)