| 1 |
"""Context information for the current invocation of ansible-test.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import collections.abc as c |
| 6 |
import dataclasses |
| 7 |
import os |
| 8 |
import typing as t |
| 9 |
|
| 10 |
from .util import ( |
| 11 |
ApplicationError, |
| 12 |
import_plugins, |
| 13 |
is_subdir, |
| 14 |
ANSIBLE_LIB_ROOT, |
| 15 |
ANSIBLE_TEST_ROOT, |
| 16 |
ANSIBLE_SOURCE_ROOT, |
| 17 |
display, |
| 18 |
cache, |
| 19 |
) |
| 20 |
|
| 21 |
from .provider import ( |
| 22 |
find_path_provider, |
| 23 |
get_path_provider_classes, |
| 24 |
ProviderNotFoundForPath, |
| 25 |
) |
| 26 |
|
| 27 |
from .provider.source import ( |
| 28 |
SourceProvider, |
| 29 |
) |
| 30 |
|
| 31 |
from .provider.source.unversioned import ( |
| 32 |
UnversionedSource, |
| 33 |
) |
| 34 |
|
| 35 |
from .provider.source.installed import ( |
| 36 |
InstalledSource, |
| 37 |
) |
| 38 |
|
| 39 |
from .provider.source.unsupported import ( |
| 40 |
UnsupportedSource, |
| 41 |
) |
| 42 |
|
| 43 |
from .provider.layout import ( |
| 44 |
ContentLayout, |
| 45 |
LayoutProvider, |
| 46 |
) |
| 47 |
|
| 48 |
from .provider.layout.unsupported import ( |
| 49 |
UnsupportedLayout, |
| 50 |
) |
| 51 |
|
| 52 |
|
| 53 |
@dataclasses.dataclass(frozen=True) |
| 54 |
class PayloadConfig: |
| 55 |
"""Configuration required to build a source tree payload for delegation.""" |
| 56 |
|
| 57 |
files: list[tuple[str, str]] |
| 58 |
permissions: dict[str, int] |
| 59 |
|
| 60 |
|
| 61 |
class DataContext: |
| 62 |
"""Data context providing details about the current execution environment for ansible-test.""" |
| 63 |
|
| 64 |
def __init__(self) -> None: |
| 65 |
content_path = os.environ.get('ANSIBLE_TEST_CONTENT_ROOT') |
| 66 |
current_path = os.getcwd() |
| 67 |
|
| 68 |
layout_providers = get_path_provider_classes(LayoutProvider) |
| 69 |
source_providers = get_path_provider_classes(SourceProvider) |
| 70 |
|
| 71 |
self.__layout_providers = layout_providers |
| 72 |
self.__source_providers = source_providers |
| 73 |
self.__ansible_source: t.Optional[tuple[tuple[str, str], ...]] = None |
| 74 |
|
| 75 |
self.payload_callbacks: list[c.Callable[[PayloadConfig], None]] = [] |
| 76 |
|
| 77 |
if content_path: |
| 78 |
content, source_provider = self.__create_content_layout(layout_providers, source_providers, content_path, False) |
| 79 |
elif ANSIBLE_SOURCE_ROOT and is_subdir(current_path, ANSIBLE_SOURCE_ROOT): |
| 80 |
content, source_provider = self.__create_content_layout(layout_providers, source_providers, ANSIBLE_SOURCE_ROOT, False) |
| 81 |
else: |
| 82 |
content, source_provider = self.__create_content_layout(layout_providers, source_providers, current_path, True) |
| 83 |
|
| 84 |
self.content: ContentLayout = content |
| 85 |
self.source_provider = source_provider |
| 86 |
|
| 87 |
def create_collection_layouts(self) -> list[ContentLayout]: |
| 88 |
""" |
| 89 |
Return a list of collection layouts, one for each collection in the same collection root as the current collection layout. |
| 90 |
An empty list is returned if the current content layout is not a collection layout. |
| 91 |
""" |
| 92 |
layout = self.content |
| 93 |
collection = layout.collection |
| 94 |
|
| 95 |
if not collection: |
| 96 |
return [] |
| 97 |
|
| 98 |
root_path = os.path.join(collection.root, 'ansible_collections') |
| 99 |
display.info('Scanning collection root: %s' % root_path, verbosity=1) |
| 100 |
namespace_names = sorted(name for name in os.listdir(root_path) if os.path.isdir(os.path.join(root_path, name))) |
| 101 |
collections = [] |
| 102 |
|
| 103 |
for namespace_name in namespace_names: |
| 104 |
namespace_path = os.path.join(root_path, namespace_name) |
| 105 |
collection_names = sorted(name for name in os.listdir(namespace_path) if os.path.isdir(os.path.join(namespace_path, name))) |
| 106 |
|
| 107 |
for collection_name in collection_names: |
| 108 |
collection_path = os.path.join(namespace_path, collection_name) |
| 109 |
|
| 110 |
if collection_path == os.path.join(collection.root, collection.directory): |
| 111 |
collection_layout = layout |
| 112 |
else: |
| 113 |
collection_layout = self.__create_content_layout(self.__layout_providers, self.__source_providers, collection_path, False)[0] |
| 114 |
|
| 115 |
file_count = len(collection_layout.all_files()) |
| 116 |
|
| 117 |
if not file_count: |
| 118 |
continue |
| 119 |
|
| 120 |
display.info('Including collection: %s (%d files)' % (collection_layout.collection.full_name, file_count), verbosity=1) |
| 121 |
collections.append(collection_layout) |
| 122 |
|
| 123 |
return collections |
| 124 |
|
| 125 |
@staticmethod |
| 126 |
def __create_content_layout( |
| 127 |
layout_providers: list[t.Type[LayoutProvider]], |
| 128 |
source_providers: list[t.Type[SourceProvider]], |
| 129 |
root: str, |
| 130 |
walk: bool, |
| 131 |
) -> t.Tuple[ContentLayout, SourceProvider]: |
| 132 |
"""Create a content layout using the given providers and root path.""" |
| 133 |
try: |
| 134 |
layout_provider = find_path_provider(LayoutProvider, layout_providers, root, walk) |
| 135 |
except ProviderNotFoundForPath: |
| 136 |
layout_provider = UnsupportedLayout(root) |
| 137 |
|
| 138 |
try: |
| 139 |
# Begin the search for the source provider at the layout provider root. |
| 140 |
# This intentionally ignores version control within subdirectories of the layout root, a condition which was previously an error. |
| 141 |
# Doing so allows support for older git versions for which it is difficult to distinguish between a super project and a sub project. |
| 142 |
# It also provides a better user experience, since the solution for the user would effectively be the same -- to remove the nested version control. |
| 143 |
if isinstance(layout_provider, UnsupportedLayout): |
| 144 |
source_provider: SourceProvider = UnsupportedSource(layout_provider.root) |
| 145 |
else: |
| 146 |
source_provider = find_path_provider(SourceProvider, source_providers, layout_provider.root, walk) |
| 147 |
except ProviderNotFoundForPath: |
| 148 |
source_provider = UnversionedSource(layout_provider.root) |
| 149 |
|
| 150 |
layout = layout_provider.create(layout_provider.root, source_provider.get_paths(layout_provider.root)) |
| 151 |
|
| 152 |
return layout, source_provider |
| 153 |
|
| 154 |
def __create_ansible_source(self): |
| 155 |
"""Return a tuple of Ansible source files with both absolute and relative paths.""" |
| 156 |
if not ANSIBLE_SOURCE_ROOT: |
| 157 |
sources = [] |
| 158 |
|
| 159 |
source_provider = InstalledSource(ANSIBLE_LIB_ROOT) |
| 160 |
sources.extend((os.path.join(source_provider.root, path), os.path.join('lib', 'ansible', path)) |
| 161 |
for path in source_provider.get_paths(source_provider.root)) |
| 162 |
|
| 163 |
source_provider = InstalledSource(ANSIBLE_TEST_ROOT) |
| 164 |
sources.extend((os.path.join(source_provider.root, path), os.path.join('test', 'lib', 'ansible_test', path)) |
| 165 |
for path in source_provider.get_paths(source_provider.root)) |
| 166 |
|
| 167 |
return tuple(sources) |
| 168 |
|
| 169 |
if self.content.is_ansible: |
| 170 |
return tuple((os.path.join(self.content.root, path), path) for path in self.content.all_files()) |
| 171 |
|
| 172 |
try: |
| 173 |
source_provider = find_path_provider(SourceProvider, self.__source_providers, ANSIBLE_SOURCE_ROOT, False) |
| 174 |
except ProviderNotFoundForPath: |
| 175 |
source_provider = UnversionedSource(ANSIBLE_SOURCE_ROOT) |
| 176 |
|
| 177 |
return tuple((os.path.join(source_provider.root, path), path) for path in source_provider.get_paths(source_provider.root)) |
| 178 |
|
| 179 |
@property |
| 180 |
def ansible_source(self) -> tuple[tuple[str, str], ...]: |
| 181 |
"""Return a tuple of Ansible source files with both absolute and relative paths.""" |
| 182 |
if not self.__ansible_source: |
| 183 |
self.__ansible_source = self.__create_ansible_source() |
| 184 |
|
| 185 |
return self.__ansible_source |
| 186 |
|
| 187 |
def register_payload_callback(self, callback: c.Callable[[PayloadConfig], None]) -> None: |
| 188 |
"""Register the given payload callback.""" |
| 189 |
self.payload_callbacks.append(callback) |
| 190 |
|
| 191 |
def check_layout(self) -> None: |
| 192 |
"""Report an error if the layout is unsupported.""" |
| 193 |
if self.content.unsupported: |
| 194 |
raise ApplicationError(self.explain_working_directory()) |
| 195 |
|
| 196 |
def explain_working_directory(self) -> str: |
| 197 |
"""Return a message explaining the working directory requirements.""" |
| 198 |
blocks = [ |
| 199 |
'The current working directory must be within the source tree being tested.', |
| 200 |
'', |
| 201 |
] |
| 202 |
|
| 203 |
if ANSIBLE_SOURCE_ROOT: |
| 204 |
blocks.append(f'Testing Ansible: {ANSIBLE_SOURCE_ROOT}/') |
| 205 |
blocks.append('') |
| 206 |
|
| 207 |
cwd = os.getcwd() |
| 208 |
|
| 209 |
blocks.append('Testing an Ansible collection: {...}/ansible_collections/{namespace}/{collection}/') |
| 210 |
blocks.append('Example #1: community.general -> ~/code/ansible_collections/community/general/') |
| 211 |
blocks.append('Example #2: ansible.util -> ~/.ansible/collections/ansible_collections/ansible/util/') |
| 212 |
blocks.append('') |
| 213 |
blocks.append(f'Current working directory: {cwd}/') |
| 214 |
|
| 215 |
if os.path.basename(os.path.dirname(cwd)) == 'ansible_collections': |
| 216 |
blocks.append(f'Expected parent directory: {os.path.dirname(cwd)}/{{namespace}}/{{collection}}/') |
| 217 |
elif os.path.basename(cwd) == 'ansible_collections': |
| 218 |
blocks.append(f'Expected parent directory: {cwd}/{{namespace}}/{{collection}}/') |
| 219 |
elif 'ansible_collections' not in cwd.split(os.path.sep): |
| 220 |
blocks.append('No "ansible_collections" parent directory was found.') |
| 221 |
|
| 222 |
if isinstance(self.content.unsupported, list): |
| 223 |
blocks.extend(self.content.unsupported) |
| 224 |
|
| 225 |
message = '\n'.join(blocks) |
| 226 |
|
| 227 |
return message |
| 228 |
|
| 229 |
|
| 230 |
@cache |
| 231 |
def data_context() -> DataContext: |
| 232 |
"""Initialize provider plugins.""" |
| 233 |
provider_types = ( |
| 234 |
'layout', |
| 235 |
'source', |
| 236 |
) |
| 237 |
|
| 238 |
for provider_type in provider_types: |
| 239 |
import_plugins('provider/%s' % provider_type) |
| 240 |
|
| 241 |
context = DataContext() |
| 242 |
|
| 243 |
return context |
| 244 |
|
| 245 |
|
| 246 |
@dataclasses.dataclass(frozen=True) |
| 247 |
class PluginInfo: |
| 248 |
"""Information about an Ansible plugin.""" |
| 249 |
|
| 250 |
plugin_type: str |
| 251 |
name: str |
| 252 |
paths: list[str] |
| 253 |
|
| 254 |
|
| 255 |
@cache |
| 256 |
def content_plugins() -> dict[str, dict[str, PluginInfo]]: |
| 257 |
""" |
| 258 |
Analyze content. |
| 259 |
The primary purpose of this analysis is to facilitate mapping of integration tests to the plugin(s) they are intended to test. |
| 260 |
""" |
| 261 |
plugins: dict[str, dict[str, PluginInfo]] = {} |
| 262 |
|
| 263 |
for plugin_type, plugin_directory in data_context().content.plugin_paths.items(): |
| 264 |
plugin_paths = sorted(data_context().content.walk_files(plugin_directory)) |
| 265 |
plugin_directory_offset = len(plugin_directory.split(os.path.sep)) |
| 266 |
|
| 267 |
plugin_files: dict[str, list[str]] = {} |
| 268 |
|
| 269 |
for plugin_path in plugin_paths: |
| 270 |
plugin_filename = os.path.basename(plugin_path) |
| 271 |
plugin_parts = plugin_path.split(os.path.sep)[plugin_directory_offset:-1] |
| 272 |
|
| 273 |
if plugin_filename == '__init__.py': |
| 274 |
if plugin_type != 'module_utils': |
| 275 |
continue |
| 276 |
else: |
| 277 |
plugin_name = os.path.splitext(plugin_filename)[0] |
| 278 |
|
| 279 |
if data_context().content.is_ansible and plugin_type == 'modules': |
| 280 |
plugin_name = plugin_name.lstrip('_') |
| 281 |
|
| 282 |
plugin_parts.append(plugin_name) |
| 283 |
|
| 284 |
plugin_name = '.'.join(plugin_parts) |
| 285 |
|
| 286 |
plugin_files.setdefault(plugin_name, []).append(plugin_filename) |
| 287 |
|
| 288 |
plugins[plugin_type] = {plugin_name: PluginInfo( |
| 289 |
plugin_type=plugin_type, |
| 290 |
name=plugin_name, |
| 291 |
paths=paths, |
| 292 |
) for plugin_name, paths in plugin_files.items()} |
| 293 |
|
| 294 |
return plugins |