| 1 |
"""Code coverage support for integration tests.""" |
| 2 |
|
| 3 |
from __future__ import annotations |
| 4 |
|
| 5 |
import abc |
| 6 |
import json |
| 7 |
import os |
| 8 |
import shutil |
| 9 |
import tempfile |
| 10 |
import typing as t |
| 11 |
import zipfile |
| 12 |
|
| 13 |
from ...io import ( |
| 14 |
write_text_file, |
| 15 |
) |
| 16 |
|
| 17 |
from ...ansible_util import ( |
| 18 |
run_playbook, |
| 19 |
) |
| 20 |
|
| 21 |
from ...config import ( |
| 22 |
IntegrationConfig, |
| 23 |
) |
| 24 |
|
| 25 |
from ...util import ( |
| 26 |
COVERAGE_CONFIG_NAME, |
| 27 |
MODE_DIRECTORY, |
| 28 |
MODE_DIRECTORY_WRITE, |
| 29 |
MODE_FILE, |
| 30 |
SubprocessError, |
| 31 |
cache, |
| 32 |
display, |
| 33 |
generate_name, |
| 34 |
get_generic_type, |
| 35 |
get_type_map, |
| 36 |
remove_tree, |
| 37 |
sanitize_host_name, |
| 38 |
verified_chmod, |
| 39 |
) |
| 40 |
|
| 41 |
from ...util_common import ( |
| 42 |
ResultType, |
| 43 |
) |
| 44 |
|
| 45 |
from ...coverage_util import ( |
| 46 |
generate_coverage_config, |
| 47 |
get_coverage_platform, |
| 48 |
) |
| 49 |
|
| 50 |
from ...host_configs import ( |
| 51 |
HostConfig, |
| 52 |
PosixConfig, |
| 53 |
WindowsConfig, |
| 54 |
WindowsInventoryConfig, |
| 55 |
WindowsRemoteConfig, |
| 56 |
) |
| 57 |
|
| 58 |
from ...data import ( |
| 59 |
data_context, |
| 60 |
) |
| 61 |
|
| 62 |
from ...host_profiles import ( |
| 63 |
ControllerProfile, |
| 64 |
HostProfile, |
| 65 |
PosixProfile, |
| 66 |
SshTargetHostProfile, |
| 67 |
) |
| 68 |
|
| 69 |
from ...provisioning import ( |
| 70 |
HostState, |
| 71 |
) |
| 72 |
|
| 73 |
from ...connections import ( |
| 74 |
LocalConnection, |
| 75 |
) |
| 76 |
|
| 77 |
from ...inventory import ( |
| 78 |
create_windows_inventory, |
| 79 |
create_posix_inventory, |
| 80 |
) |
| 81 |
|
| 82 |
|
| 83 |
class CoverageHandler[THostConfig: HostConfig](metaclass=abc.ABCMeta): |
| 84 |
"""Base class for configuring hosts for integration test code coverage.""" |
| 85 |
|
| 86 |
def __init__(self, args: IntegrationConfig, host_state: HostState, inventory_path: str) -> None: |
| 87 |
self.args = args |
| 88 |
self.host_state = host_state |
| 89 |
self.inventory_path = inventory_path |
| 90 |
self.profiles = self.get_profiles() |
| 91 |
|
| 92 |
def get_profiles(self) -> list[HostProfile]: |
| 93 |
"""Return a list of profiles relevant for this handler.""" |
| 94 |
profile_type = get_generic_type(type(self), HostConfig) |
| 95 |
profiles = [profile for profile in self.host_state.target_profiles if isinstance(profile.config, profile_type)] |
| 96 |
|
| 97 |
return profiles |
| 98 |
|
| 99 |
@property |
| 100 |
@abc.abstractmethod |
| 101 |
def is_active(self) -> bool: |
| 102 |
"""True if the handler should be used, otherwise False.""" |
| 103 |
|
| 104 |
@abc.abstractmethod |
| 105 |
def setup(self) -> None: |
| 106 |
"""Perform setup for code coverage.""" |
| 107 |
|
| 108 |
@abc.abstractmethod |
| 109 |
def teardown(self) -> None: |
| 110 |
"""Perform teardown for code coverage.""" |
| 111 |
|
| 112 |
@abc.abstractmethod |
| 113 |
def create_inventory(self) -> None: |
| 114 |
"""Create inventory, if needed.""" |
| 115 |
|
| 116 |
@abc.abstractmethod |
| 117 |
def get_environment(self, target_name: str, aliases: tuple[str, ...]) -> dict[str, str]: |
| 118 |
"""Return a dictionary of environment variables for running tests with code coverage.""" |
| 119 |
|
| 120 |
def run_playbook(self, playbook: str, variables: dict[str, str]) -> None: |
| 121 |
"""Run the specified playbook using the current inventory.""" |
| 122 |
self.create_inventory() |
| 123 |
run_playbook(self.args, self.inventory_path, playbook, capture=False, variables=variables) |
| 124 |
|
| 125 |
|
| 126 |
class PosixCoverageHandler(CoverageHandler[PosixConfig]): |
| 127 |
"""Configure integration test code coverage for POSIX hosts.""" |
| 128 |
|
| 129 |
def __init__(self, args: IntegrationConfig, host_state: HostState, inventory_path: str) -> None: |
| 130 |
super().__init__(args, host_state, inventory_path) |
| 131 |
|
| 132 |
# Common temporary directory used on all POSIX hosts that will be created world writeable. |
| 133 |
self.common_temp_path = f'/tmp/ansible-test-{generate_name()}' |
| 134 |
|
| 135 |
def get_profiles(self) -> list[HostProfile]: |
| 136 |
"""Return a list of profiles relevant for this handler.""" |
| 137 |
profiles = super().get_profiles() |
| 138 |
profiles = [profile for profile in profiles if not isinstance(profile, ControllerProfile) or |
| 139 |
profile.python.path != self.host_state.controller_profile.python.path] |
| 140 |
|
| 141 |
return profiles |
| 142 |
|
| 143 |
@property |
| 144 |
def is_active(self) -> bool: |
| 145 |
"""True if the handler should be used, otherwise False.""" |
| 146 |
return True |
| 147 |
|
| 148 |
@property |
| 149 |
def target_profile(self) -> t.Optional[PosixProfile]: |
| 150 |
"""The POSIX target profile, if it uses a different Python interpreter than the controller, otherwise None.""" |
| 151 |
return t.cast(PosixProfile, self.profiles[0]) if self.profiles else None |
| 152 |
|
| 153 |
def setup(self) -> None: |
| 154 |
"""Perform setup for code coverage.""" |
| 155 |
self.setup_controller() |
| 156 |
self.setup_target() |
| 157 |
|
| 158 |
def teardown(self) -> None: |
| 159 |
"""Perform teardown for code coverage.""" |
| 160 |
self.teardown_controller() |
| 161 |
self.teardown_target() |
| 162 |
|
| 163 |
def setup_controller(self) -> None: |
| 164 |
"""Perform setup for code coverage on the controller.""" |
| 165 |
coverage_config_path = os.path.join(self.common_temp_path, COVERAGE_CONFIG_NAME) |
| 166 |
coverage_output_path = os.path.join(self.common_temp_path, ResultType.COVERAGE.name) |
| 167 |
|
| 168 |
coverage_config = generate_coverage_config() |
| 169 |
|
| 170 |
write_text_file(coverage_config_path, coverage_config, create_directories=True) |
| 171 |
|
| 172 |
verified_chmod(coverage_config_path, MODE_FILE) |
| 173 |
os.mkdir(coverage_output_path) |
| 174 |
verified_chmod(coverage_output_path, MODE_DIRECTORY_WRITE) |
| 175 |
|
| 176 |
def setup_target(self) -> None: |
| 177 |
"""Perform setup for code coverage on the target.""" |
| 178 |
if not self.target_profile: |
| 179 |
return |
| 180 |
|
| 181 |
if isinstance(self.target_profile, ControllerProfile): |
| 182 |
return |
| 183 |
|
| 184 |
self.run_playbook('posix_coverage_setup.yml', self.get_playbook_variables()) |
| 185 |
|
| 186 |
def teardown_controller(self) -> None: |
| 187 |
"""Perform teardown for code coverage on the controller.""" |
| 188 |
coverage_temp_path = os.path.join(self.common_temp_path, ResultType.COVERAGE.name) |
| 189 |
platform = get_coverage_platform(self.args.controller) |
| 190 |
|
| 191 |
for filename in os.listdir(coverage_temp_path): |
| 192 |
shutil.copyfile(os.path.join(coverage_temp_path, filename), os.path.join(ResultType.COVERAGE.path, update_coverage_filename(filename, platform))) |
| 193 |
|
| 194 |
remove_tree(self.common_temp_path) |
| 195 |
|
| 196 |
def teardown_target(self) -> None: |
| 197 |
"""Perform teardown for code coverage on the target.""" |
| 198 |
if not self.target_profile: |
| 199 |
return |
| 200 |
|
| 201 |
if isinstance(self.target_profile, ControllerProfile): |
| 202 |
return |
| 203 |
|
| 204 |
profile = t.cast(SshTargetHostProfile, self.target_profile) |
| 205 |
platform = get_coverage_platform(profile.config) |
| 206 |
con = profile.get_controller_target_connections()[0] |
| 207 |
|
| 208 |
with tempfile.NamedTemporaryFile(prefix='ansible-test-coverage-', suffix='.tgz') as coverage_tgz: |
| 209 |
try: |
| 210 |
con.create_archive(chdir=self.common_temp_path, name=ResultType.COVERAGE.name, dst=coverage_tgz) |
| 211 |
except SubprocessError as ex: |
| 212 |
display.warning(f'Failed to download coverage results: {ex}') |
| 213 |
else: |
| 214 |
coverage_tgz.seek(0) |
| 215 |
|
| 216 |
with tempfile.TemporaryDirectory() as temp_dir: |
| 217 |
local_con = LocalConnection(self.args) |
| 218 |
local_con.extract_archive(chdir=temp_dir, src=coverage_tgz) |
| 219 |
|
| 220 |
base_dir = os.path.join(temp_dir, ResultType.COVERAGE.name) |
| 221 |
|
| 222 |
for filename in os.listdir(base_dir): |
| 223 |
shutil.copyfile(os.path.join(base_dir, filename), os.path.join(ResultType.COVERAGE.path, update_coverage_filename(filename, platform))) |
| 224 |
|
| 225 |
self.run_playbook('posix_coverage_teardown.yml', self.get_playbook_variables()) |
| 226 |
|
| 227 |
def get_environment(self, target_name: str, aliases: tuple[str, ...]) -> dict[str, str]: |
| 228 |
"""Return a dictionary of environment variables for running tests with code coverage.""" |
| 229 |
|
| 230 |
# Enable code coverage collection on Ansible modules (both local and remote). |
| 231 |
# Used by the AnsiballZ wrapper generator in lib/ansible/executor/module_common.py to support code coverage. |
| 232 |
config_file = os.path.join(self.common_temp_path, COVERAGE_CONFIG_NAME) |
| 233 |
|
| 234 |
# Include the command, target and platform marker so the remote host can create a filename with that info. |
| 235 |
# The generated AnsiballZ wrapper is responsible for adding '=python-{X.Y}=coverage.{hostname}.{pid}.{id}' |
| 236 |
coverage_file = os.path.join(self.common_temp_path, ResultType.COVERAGE.name, '='.join((self.args.command, target_name, 'platform'))) |
| 237 |
|
| 238 |
if self.args.coverage_check: |
| 239 |
# cause the 'coverage' module to be found, but not imported or enabled |
| 240 |
coverage_file = '' |
| 241 |
|
| 242 |
coverage_options = dict( |
| 243 |
config=config_file, |
| 244 |
output=coverage_file, |
| 245 |
) |
| 246 |
|
| 247 |
variables = dict( |
| 248 |
_ANSIBLE_ANSIBALLZ_COVERAGE_CONFIG=json.dumps(coverage_options), |
| 249 |
) |
| 250 |
|
| 251 |
return variables |
| 252 |
|
| 253 |
def create_inventory(self) -> None: |
| 254 |
"""Create inventory.""" |
| 255 |
create_posix_inventory(self.args, self.inventory_path, self.host_state.target_profiles) |
| 256 |
|
| 257 |
def get_playbook_variables(self) -> dict[str, str]: |
| 258 |
"""Return a dictionary of variables for setup and teardown of POSIX coverage.""" |
| 259 |
return dict( |
| 260 |
common_temp_dir=self.common_temp_path, |
| 261 |
coverage_config=generate_coverage_config(), |
| 262 |
coverage_config_path=os.path.join(self.common_temp_path, COVERAGE_CONFIG_NAME), |
| 263 |
coverage_output_path=os.path.join(self.common_temp_path, ResultType.COVERAGE.name), |
| 264 |
mode_directory=f'{MODE_DIRECTORY:04o}', |
| 265 |
mode_directory_write=f'{MODE_DIRECTORY_WRITE:04o}', |
| 266 |
mode_file=f'{MODE_FILE:04o}', |
| 267 |
) |
| 268 |
|
| 269 |
|
| 270 |
class WindowsCoverageHandler(CoverageHandler[WindowsConfig]): |
| 271 |
"""Configure integration test code coverage for Windows hosts.""" |
| 272 |
|
| 273 |
def __init__(self, args: IntegrationConfig, host_state: HostState, inventory_path: str) -> None: |
| 274 |
super().__init__(args, host_state, inventory_path) |
| 275 |
|
| 276 |
# Common temporary directory used on all Windows hosts that will be created writable by everyone. |
| 277 |
self.remote_temp_path = f'C:\\ansible_test_coverage_{generate_name()}' |
| 278 |
|
| 279 |
@property |
| 280 |
def is_active(self) -> bool: |
| 281 |
"""True if the handler should be used, otherwise False.""" |
| 282 |
return bool(self.profiles) and not self.args.coverage_check |
| 283 |
|
| 284 |
def setup(self) -> None: |
| 285 |
"""Perform setup for code coverage.""" |
| 286 |
self.run_playbook('windows_coverage_setup.yml', self.get_playbook_variables()) |
| 287 |
|
| 288 |
def teardown(self) -> None: |
| 289 |
"""Perform teardown for code coverage.""" |
| 290 |
with tempfile.TemporaryDirectory() as local_temp_path: |
| 291 |
variables = self.get_playbook_variables() |
| 292 |
variables.update( |
| 293 |
local_temp_path=local_temp_path, |
| 294 |
) |
| 295 |
|
| 296 |
self.run_playbook('windows_coverage_teardown.yml', variables) |
| 297 |
|
| 298 |
for filename in os.listdir(local_temp_path): |
| 299 |
if all(isinstance(profile.config, WindowsRemoteConfig) for profile in self.profiles): |
| 300 |
prefix = 'remote' |
| 301 |
elif all(isinstance(profile.config, WindowsInventoryConfig) for profile in self.profiles): |
| 302 |
prefix = 'inventory' |
| 303 |
else: |
| 304 |
raise NotImplementedError() |
| 305 |
|
| 306 |
platform = f'{prefix}-{sanitize_host_name(os.path.splitext(filename)[0])}' |
| 307 |
|
| 308 |
with zipfile.ZipFile(os.path.join(local_temp_path, filename)) as coverage_zip: |
| 309 |
for item in coverage_zip.infolist(): |
| 310 |
if item.is_dir(): |
| 311 |
raise Exception(f'Unexpected directory in zip file: {item.filename}') |
| 312 |
|
| 313 |
item.filename = update_coverage_filename(item.filename, platform) |
| 314 |
|
| 315 |
coverage_zip.extract(item, ResultType.COVERAGE.path) |
| 316 |
|
| 317 |
def get_environment(self, target_name: str, aliases: tuple[str, ...]) -> dict[str, str]: |
| 318 |
"""Return a dictionary of environment variables for running tests with code coverage.""" |
| 319 |
|
| 320 |
# Include the command, target and platform marker so the remote host can create a filename with that info. |
| 321 |
# The remote is responsible for adding '={language-version}=coverage.{hostname}.{pid}.{id}' |
| 322 |
coverage_name = '='.join((self.args.command, target_name, 'platform')) |
| 323 |
|
| 324 |
variables = dict( |
| 325 |
_ANSIBLE_COVERAGE_REMOTE_OUTPUT=os.path.join(self.remote_temp_path, coverage_name), |
| 326 |
_ANSIBLE_COVERAGE_REMOTE_PATH_FILTER=os.path.join(data_context().content.root, '*'), |
| 327 |
) |
| 328 |
|
| 329 |
return variables |
| 330 |
|
| 331 |
def create_inventory(self) -> None: |
| 332 |
"""Create inventory.""" |
| 333 |
create_windows_inventory(self.args, self.inventory_path, self.host_state.target_profiles) |
| 334 |
|
| 335 |
def get_playbook_variables(self) -> dict[str, str]: |
| 336 |
"""Return a dictionary of variables for setup and teardown of Windows coverage.""" |
| 337 |
return dict( |
| 338 |
remote_temp_path=self.remote_temp_path, |
| 339 |
) |
| 340 |
|
| 341 |
|
| 342 |
class CoverageManager: |
| 343 |
"""Manager for code coverage configuration and state.""" |
| 344 |
|
| 345 |
def __init__(self, args: IntegrationConfig, host_state: HostState, inventory_path: str) -> None: |
| 346 |
self.args = args |
| 347 |
self.host_state = host_state |
| 348 |
self.inventory_path = inventory_path |
| 349 |
|
| 350 |
if self.args.coverage: |
| 351 |
handler_types = set(get_handler_type(type(profile.config)) for profile in host_state.profiles) |
| 352 |
handler_types.discard(None) |
| 353 |
else: |
| 354 |
handler_types = set() |
| 355 |
|
| 356 |
handlers = [handler_type(args=args, host_state=host_state, inventory_path=inventory_path) for handler_type in handler_types] |
| 357 |
|
| 358 |
self.handlers = [handler for handler in handlers if handler.is_active] |
| 359 |
|
| 360 |
def setup(self) -> None: |
| 361 |
"""Perform setup for code coverage.""" |
| 362 |
if not self.args.coverage: |
| 363 |
return |
| 364 |
|
| 365 |
for handler in self.handlers: |
| 366 |
handler.setup() |
| 367 |
|
| 368 |
def teardown(self) -> None: |
| 369 |
"""Perform teardown for code coverage.""" |
| 370 |
if not self.args.coverage: |
| 371 |
return |
| 372 |
|
| 373 |
for handler in self.handlers: |
| 374 |
handler.teardown() |
| 375 |
|
| 376 |
def get_environment(self, target_name: str, aliases: tuple[str, ...]) -> dict[str, str]: |
| 377 |
"""Return a dictionary of environment variables for running tests with code coverage.""" |
| 378 |
if not self.args.coverage or 'non_local/' in aliases: |
| 379 |
return {} |
| 380 |
|
| 381 |
env = {} |
| 382 |
|
| 383 |
for handler in self.handlers: |
| 384 |
env.update(handler.get_environment(target_name, aliases)) |
| 385 |
|
| 386 |
return env |
| 387 |
|
| 388 |
|
| 389 |
@cache |
| 390 |
def get_config_handler_type_map() -> dict[t.Type[HostConfig], t.Type[CoverageHandler]]: |
| 391 |
"""Create and return a mapping of HostConfig types to CoverageHandler types.""" |
| 392 |
return get_type_map(CoverageHandler, HostConfig) |
| 393 |
|
| 394 |
|
| 395 |
def get_handler_type(config_type: t.Type[HostConfig]) -> t.Optional[t.Type[CoverageHandler]]: |
| 396 |
"""Return the coverage handler type associated with the given host config type if found, otherwise return None.""" |
| 397 |
queue = [config_type] |
| 398 |
type_map = get_config_handler_type_map() |
| 399 |
|
| 400 |
while queue: |
| 401 |
config_type = queue.pop(0) |
| 402 |
handler_type = type_map.get(config_type) |
| 403 |
|
| 404 |
if handler_type: |
| 405 |
return handler_type |
| 406 |
|
| 407 |
queue.extend(config_type.__bases__) |
| 408 |
|
| 409 |
return None |
| 410 |
|
| 411 |
|
| 412 |
def update_coverage_filename(original_filename: str, platform: str) -> str: |
| 413 |
"""Validate the given filename and insert the specified platform, then return the result.""" |
| 414 |
parts = original_filename.split('=') |
| 415 |
|
| 416 |
if original_filename != os.path.basename(original_filename) or len(parts) != 5 or parts[2] != 'platform': |
| 417 |
raise Exception(f'Unexpected coverage filename: {original_filename}') |
| 418 |
|
| 419 |
parts[2] = platform |
| 420 |
|
| 421 |
updated_filename = '='.join(parts) |
| 422 |
|
| 423 |
display.info(f'Coverage file for platform "{platform}": {original_filename} -> {updated_filename}', verbosity=3) |
| 424 |
|
| 425 |
return updated_filename |