diff --git a/cli/__main__.py b/cli/__main__.py index 5e726d6d03..0c6c443ccd 100755 --- a/cli/__main__.py +++ b/cli/__main__.py @@ -13,7 +13,7 @@ from . import PROJECT_ROOT if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) -from cli.core.app import main # noqa: E402 +from cli.core.app import main if __name__ == "__main__": main() diff --git a/cli/core/app.py b/cli/core/app.py index 7005701eb7..82fcd88a73 100644 --- a/cli/core/app.py +++ b/cli/core/app.py @@ -159,7 +159,7 @@ def main() -> None: log_file, log_path = open_log_file(flags.log_dir) print(color_text(f"Tip: Log file created at {log_path}", Fore.GREEN)) - full_cmd = [sys.executable, "-m", module] + remaining + full_cmd = [sys.executable, "-m", module, *remaining] cfg = RunConfig( log_enabled=flags.log_dir is not None, diff --git a/cli/core/discovery.py b/cli/core/discovery.py index d3a9689da7..406131010f 100644 --- a/cli/core/discovery.py +++ b/cli/core/discovery.py @@ -36,9 +36,7 @@ class Command: def _is_valid_package_dir(path: Path) -> bool: if not path.is_dir(): return False - if path.name == "__pycache__": - return False - return True + return path.name != "__pycache__" def discover_commands(cli_dir: Path) -> list[Command]: diff --git a/cli/core/run.py b/cli/core/run.py index 2a7c890de2..96006ac13d 100644 --- a/cli/core/run.py +++ b/cli/core/run.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib import os import pty import subprocess @@ -26,12 +27,9 @@ def open_log_file(log_dir: Path) -> tuple[TextIO, Path]: log_dir = log_dir.expanduser() log_dir.mkdir(parents=True, exist_ok=True) - # Best-effort permission hardening (ignore failures on non-POSIX / special FS) - try: + # Best-effort permission hardening (ignore failures on non-POSIX / special FS). + with contextlib.suppress(Exception): os.chmod(log_dir, 0o700) - except Exception: - # Intentionally ignore chmod failures: non-critical hardening step - pass timestamp = datetime.now().strftime("%Y%m%dT%H%M%S") log_file_path = log_dir / f"{timestamp}.log" diff --git a/cli/create/credentials/__main__.py b/cli/create/credentials/__main__.py index 025a2ca1ce..20b29e8566 100644 --- a/cli/create/credentials/__main__.py +++ b/cli/create/credentials/__main__.py @@ -72,9 +72,7 @@ def _is_vault_encrypted(val: Any) -> bool: return True if _is_ruamel_vault(val): return True - if isinstance(val, str) and ("$ANSIBLE_VAULT" in val or "!vault" in val): - return True - return False + return bool(isinstance(val, str) and ("$ANSIBLE_VAULT" in val or "!vault" in val)) def _vault_body(text: str) -> str: @@ -330,10 +328,7 @@ def main() -> int: ) value_for_new_key: str | Any - if ov is not None: - value_for_new_key = ov - else: - value_for_new_key = default_val + value_for_new_key = ov if ov is not None else default_val if _is_vault_encrypted(value_for_new_key): creds[key] = to_vault_block( diff --git a/cli/create/inventory/filters.py b/cli/create/inventory/filters.py index 07d84fc7b8..2b5e471537 100644 --- a/cli/create/inventory/filters.py +++ b/cli/create/inventory/filters.py @@ -32,10 +32,11 @@ def _filter_inventory_children( (all_block.get("children", {}) or {}) if isinstance(all_block, dict) else {} ) - filtered: dict[str, Any] = {} - for group_name, group_data in children.items(): - if keep_predicate(group_name, group_data): - filtered[group_name] = group_data + filtered: dict[str, Any] = { + group_name: group_data + for group_name, group_data in children.items() + if keep_predicate(group_name, group_data) + } new_all = dict(all_block) new_all["children"] = filtered diff --git a/cli/deploy/container/__init__.py b/cli/deploy/container/__init__.py index 3aea667c02..31989bab67 100644 --- a/cli/deploy/container/__init__.py +++ b/cli/deploy/container/__init__.py @@ -14,8 +14,8 @@ from .command import ( # noqa: E402 __all__ = [ "main", + "remove_container", "run_in_container", "start_ci_container", "stop_container", - "remove_container", ] diff --git a/cli/deploy/dedicated/__init__.py b/cli/deploy/dedicated/__init__.py index 792cae84a6..7efa36b560 100644 --- a/cli/deploy/dedicated/__init__.py +++ b/cli/deploy/dedicated/__init__.py @@ -1,6 +1,6 @@ from __future__ import annotations from .command import main -from .modes import _parse_bool_literal # noqa: F401 +from .modes import _parse_bool_literal -__all__ = ["main", "_parse_bool_literal"] +__all__ = ["_parse_bool_literal", "main"] diff --git a/cli/deploy/dedicated/modes.py b/cli/deploy/dedicated/modes.py index 049e8827de..d3b5c9819f 100644 --- a/cli/deploy/dedicated/modes.py +++ b/cli/deploy/dedicated/modes.py @@ -117,11 +117,11 @@ def build_modes_from_args( if kind == "bool_true": # if user passed --skip-foo => disable => False, otherwise True - modes[mode_name] = False if value else True + modes[mode_name] = not value elif kind == "bool_false": # if user passed --bar => enable => True, otherwise False - modes[mode_name] = True if value else False + modes[mode_name] = bool(value) else: # explicit if value is not None: diff --git a/cli/deploy/dedicated/paths.py b/cli/deploy/dedicated/paths.py index 09e5f7e7de..2fe37663b8 100644 --- a/cli/deploy/dedicated/paths.py +++ b/cli/deploy/dedicated/paths.py @@ -13,8 +13,7 @@ def _resolve_repo_root() -> str: dedicated_dir = os.path.dirname(here) # .../cli/deploy/dedicated deploy_dir = os.path.dirname(dedicated_dir) # .../cli/deploy cli_root = os.path.dirname(deploy_dir) # .../cli - repo_root = os.path.dirname(cli_root) # .../ - return repo_root + return os.path.dirname(cli_root) # .../ PROJECT_ROOT: str = _resolve_repo_root() diff --git a/cli/deploy/dedicated/runner.py b/cli/deploy/dedicated/runner.py index 78f1506964..a8cdf63e0b 100644 --- a/cli/deploy/dedicated/runner.py +++ b/cli/deploy/dedicated/runner.py @@ -67,7 +67,7 @@ def run_ansible_playbook( # --------------------------------------------------------- # 4) Inventory Validation Phase # --------------------------------------------------------- - if modes.get("MODE_ASSERT", None) is False: + if modes.get("MODE_ASSERT") is False: print("\nšŸ” Inventory assertion explicitly disabled (MODE_ASSERT=false)\n") else: print("\nšŸ” Validating inventory before deployment...\n") diff --git a/cli/deploy/development/inventory.py b/cli/deploy/development/inventory.py index 8c724e2ab4..20e9969d87 100644 --- a/cli/deploy/development/inventory.py +++ b/cli/deploy/development/inventory.py @@ -207,9 +207,7 @@ def _bake_overrides( existing_apps = merged.get("applications") if not isinstance(existing_apps, Mapping): existing_apps = {} - apps: dict[str, Any] = { - app_id: payload for app_id, payload in variant_payloads.items() - } + apps: dict[str, Any] = dict(variant_payloads.items()) # Caller-supplied `applications.*` entries deep-overlay the variant # payload so overrides like `applications.web-app-foo.feature_flag` from # `--vars` still take precedence. diff --git a/cli/deploy/development/up.py b/cli/deploy/development/up.py index 37a6707245..35c35dff99 100644 --- a/cli/deploy/development/up.py +++ b/cli/deploy/development/up.py @@ -53,10 +53,9 @@ def _stack_is_running() -> bool: def handler(args: argparse.Namespace) -> int: # when-down: skip if already running - if args.when_down: - if _stack_is_running(): - print(">>> Stack already running — skipping up") - return 0 + if args.when_down and _stack_is_running(): + print(">>> Stack already running — skipping up") + return 0 rc = _maybe_build_missing() if rc != 0: diff --git a/cli/encrypt/inventory/__main__.py b/cli/encrypt/inventory/__main__.py index fec0a9b2c2..12c6a2ba57 100644 --- a/cli/encrypt/inventory/__main__.py +++ b/cli/encrypt/inventory/__main__.py @@ -33,10 +33,10 @@ def encrypt_recursively( elif isinstance(data, list): for i, item in enumerate(data): data[i] = encrypt_recursively(item, vault_handler, ask_confirmation, prefix) - elif isinstance(data, str): + elif isinstance(data, str): # noqa: SIM102 outer guard, inner ask_confirmation block has independent siblings # Only encrypt if it's not already vaulted if not data.lstrip().startswith("$ANSIBLE_VAULT"): - if ask_confirmation: + if ask_confirmation: # noqa: SIM102 combining changes semantics: encrypted_value below must run regardless of ask_confirmation # Ask for confirmation before encrypting if not `--all` if not ask_for_confirmation(prefix): print(f"Skipping encryption for '{prefix}'.") diff --git a/cli/make/__main__.py b/cli/make/__main__.py index f9090d935d..631bfa83d4 100644 --- a/cli/make/__main__.py +++ b/cli/make/__main__.py @@ -36,7 +36,7 @@ def main(): sys.exit(1) # Invoke make in repo root - cmd = ["make"] + make_args + cmd = ["make", *make_args] try: result = subprocess.run(cmd, cwd=repo_root) sys.exit(result.returncode) diff --git a/cli/meta/applications/invokable/__main__.py b/cli/meta/applications/invokable/__main__.py index 8a036c8831..86c9f6f752 100644 --- a/cli/meta/applications/invokable/__main__.py +++ b/cli/meta/applications/invokable/__main__.py @@ -10,7 +10,7 @@ from . import PROJECT_ROOT sys.path.insert(0, str(PROJECT_ROOT)) -from utils.invokable import list_invokable_app_ids # noqa: E402 +from utils.invokable import list_invokable_app_ids def main() -> None: diff --git a/cli/meta/applications/resolution/dependencies/__main__.py b/cli/meta/applications/resolution/dependencies/__main__.py index 56b37ec970..6959529121 100644 --- a/cli/meta/applications/resolution/dependencies/__main__.py +++ b/cli/meta/applications/resolution/dependencies/__main__.py @@ -152,7 +152,7 @@ def resolve_dependencies_transitively(start_role: str) -> list[str]: def dfs(node: str) -> None: if node in stack: idx = stack.index(node) - cycle = stack[idx:] + [node] + cycle = [*stack[idx:], node] raise DependenciesResolutionError( f"Circular dependencies detected: {' -> '.join(cycle)}" ) diff --git a/cli/meta/applications/resolution/run_after/__main__.py b/cli/meta/applications/resolution/run_after/__main__.py index 91069af18c..088352016a 100644 --- a/cli/meta/applications/resolution/run_after/__main__.py +++ b/cli/meta/applications/resolution/run_after/__main__.py @@ -86,7 +86,7 @@ def resolve_run_after_transitively(start_role: str) -> list[str]: if node in stack: # Cycle: show a readable path: A -> B -> C -> A idx = stack.index(node) - cycle = stack[idx:] + [node] + cycle = [*stack[idx:], node] raise RunAfterResolutionError( f"Circular run_after dependency detected: {' -> '.join(cycle)}" ) diff --git a/cli/meta/applications/resolution/services/resolver.py b/cli/meta/applications/resolution/services/resolver.py index c7a6dfa278..cb4284ec9a 100644 --- a/cli/meta/applications/resolution/services/resolver.py +++ b/cli/meta/applications/resolution/services/resolver.py @@ -139,8 +139,8 @@ class ServicesResolver: resolved.append(role_name) cfg = self._load_role_config(role_name) - for inc in self.direct_includes_from_config(cfg): - if inc not in seen: - queue.append(inc) + queue.extend( + inc for inc in self.direct_includes_from_config(cfg) if inc not in seen + ) return resolved diff --git a/cli/meta/applications/ressources/__main__.py b/cli/meta/applications/ressources/__main__.py index 62522fa694..2df8261408 100644 --- a/cli/meta/applications/ressources/__main__.py +++ b/cli/meta/applications/ressources/__main__.py @@ -11,10 +11,10 @@ from . import PROJECT_ROOT sys.path.insert(0, str(PROJECT_ROOT)) -from humanfriendly import format_size, parse_size # noqa: E402 +from humanfriendly import format_size, parse_size -from utils.entity_name_utils import get_entity_name # noqa: E402 -from utils.service_registry import ( # noqa: E402 +from utils.entity_name_utils import get_entity_name +from utils.service_registry import ( build_service_registry_from_applications, load_applications_from_roles_dir, ) @@ -71,9 +71,7 @@ def _is_enabled(service_conf: dict[str, Any], is_primary: bool) -> bool: if isinstance(raw, bool): return raw text = str(raw).strip().lower() - if text in ("false", "0", "no", "off"): - return False - return True + return text not in ("false", "0", "no", "off") def _is_shared(service_conf: dict[str, Any]) -> bool: @@ -230,17 +228,17 @@ def render_text( headers = ["service", "role", "mem_reservation", "mem_limit", "pids_limit", "cpus"] table_rows: list[tuple[str, ...]] = [] - for row in sorted(rows, key=lambda r: (r["service"], r["role"])): - table_rows.append( - ( - row["service"], - row["role"], - _fmt_mem(row["mem_reservation_bytes"]), - _fmt_mem(row["mem_limit_bytes"]), - _fmt_int(row["pids_limit_int"]), - _fmt_float(row["cpus_float"]), - ) + table_rows.extend( + ( + row["service"], + row["role"], + _fmt_mem(row["mem_reservation_bytes"]), + _fmt_mem(row["mem_limit_bytes"]), + _fmt_int(row["pids_limit_int"]), + _fmt_float(row["cpus_float"]), ) + for row in sorted(rows, key=lambda r: (r["service"], r["role"])) + ) total_label = "TOTAL (mem=SUM, pids=SUM max-provisioned, cpus=MAX)" total_row = ( @@ -253,7 +251,7 @@ def render_text( ) widths = [len(h) for h in headers] - for r in table_rows + [total_row]: + for r in [*table_rows, total_row]: for i, cell in enumerate(r): widths[i] = max(widths[i], len(cell)) @@ -274,8 +272,7 @@ def render_text( if warnings: lines.append("") lines.append("# Warnings") - for w in warnings: - lines.append(f"! {w}") + lines.extend(f"! {w}" for w in warnings) return "\n".join(lines) diff --git a/cli/meta/applications/sufficient_storage/__main__.py b/cli/meta/applications/sufficient_storage/__main__.py index b1fc35811a..d1cfb31b9b 100644 --- a/cli/meta/applications/sufficient_storage/__main__.py +++ b/cli/meta/applications/sufficient_storage/__main__.py @@ -11,7 +11,7 @@ from . import PROJECT_ROOT sys.path.insert(0, str(PROJECT_ROOT)) -from utils.roles.resource_validation import filter_roles_by_min_storage # noqa: E402 +from utils.roles.resource_validation import filter_roles_by_min_storage def parse_args() -> argparse.Namespace: diff --git a/cli/meta/applications/type/__main__.py b/cli/meta/applications/type/__main__.py index 6918863843..aabf11fed0 100644 --- a/cli/meta/applications/type/__main__.py +++ b/cli/meta/applications/type/__main__.py @@ -10,7 +10,7 @@ from . import PROJECT_ROOT sys.path.insert(0, str(PROJECT_ROOT)) -from utils.invokable import list_invokables_by_type # noqa: E402 +from utils.invokable import list_invokables_by_type def main() -> None: diff --git a/cli/meta/callorder/__main__.py b/cli/meta/callorder/__main__.py index 5124413c48..48c18ae9e5 100644 --- a/cli/meta/callorder/__main__.py +++ b/cli/meta/callorder/__main__.py @@ -126,8 +126,7 @@ def flatten_callorder(groups: list[Group]) -> list[tuple[str, str]]: """ out: list[tuple[str, str]] = [] for g in groups: - for r in g.roles: - out.append((g.group_name, r)) + out.extend((g.group_name, r) for r in g.roles) return out diff --git a/cli/meta/domains/__main__.py b/cli/meta/domains/__main__.py index fe0348a6cf..f12209dbb7 100644 --- a/cli/meta/domains/__main__.py +++ b/cli/meta/domains/__main__.py @@ -10,7 +10,7 @@ from . import PROJECT_ROOT if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) -import utils.domains.list as domain_list # noqa: E402 +import utils.domains.list as domain_list def parse_args(argv: list[str] | None = None) -> argparse.Namespace: diff --git a/cli/meta/j2/compiler/__main__.py b/cli/meta/j2/compiler/__main__.py index be89deb81f..fbb8a2c315 100755 --- a/cli/meta/j2/compiler/__main__.py +++ b/cli/meta/j2/compiler/__main__.py @@ -37,8 +37,9 @@ def expand_includes(rel_path, seen=None): else: indent, inc_rel = m.group(1), m.group(2) # rekursiver Aufruf - for inc_line in expand_includes(inc_rel, seen): - output_lines.append(indent + inc_line) + output_lines.extend( + indent + inc_line for inc_line in expand_includes(inc_rel, seen) + ) seen.remove(rp) return output_lines diff --git a/cli/meta/ports/suggest/__main__.py b/cli/meta/ports/suggest/__main__.py index c77e40ad32..625ebcbc66 100644 --- a/cli/meta/ports/suggest/__main__.py +++ b/cli/meta/ports/suggest/__main__.py @@ -115,7 +115,7 @@ def suggest_relay_ranges( gaps_filled = 0 cursor = band_start - sorted_occ = sorted(occupied + [(band_end + 1, band_end + 1)]) + sorted_occ = sorted([*occupied, (band_end + 1, band_end + 1)]) while len(suggestions) < count and cursor + length - 1 <= band_end: candidate = (cursor, cursor + length - 1) diff --git a/cli/mirror/model.py b/cli/mirror/model.py index c914e640c0..96400baade 100644 --- a/cli/mirror/model.py +++ b/cli/mirror/model.py @@ -1,5 +1,5 @@ from __future__ import annotations -from utils.docker.image.discovery import ImageRef # noqa: F401 +from utils.docker.image.discovery import ImageRef __all__ = ["ImageRef"] diff --git a/cli/mirror/sync/__main__.py b/cli/mirror/sync/__main__.py index 3b3db149a0..439dd37b93 100644 --- a/cli/mirror/sync/__main__.py +++ b/cli/mirror/sync/__main__.py @@ -87,13 +87,12 @@ def main() -> int: label = f"{img.role}:{img.service} ({img.name}:{img.version})" try: - if args.only_missing: - if provider.tag_exists(img): - print( - f"[mirror] {label}: destination exists, skipping ({dest})", - flush=True, - ) - continue + if args.only_missing and provider.tag_exists(img): + print( + f"[mirror] {label}: destination exists, skipping ({dest})", + flush=True, + ) + continue print(f"[mirror] {label}: {src} -> {dest}", flush=True) provider.mirror(img) diff --git a/cli/validate/inventory/__main__.py b/cli/validate/inventory/__main__.py index f058aff7cd..1915e22080 100644 --- a/cli/validate/inventory/__main__.py +++ b/cli/validate/inventory/__main__.py @@ -115,9 +115,11 @@ def validate_host_keys(app_ids, inv_dir): children = all_node.get("children") if not isinstance(children, dict): continue - for grp in children.keys(): - if grp not in app_ids: - errs.append(f"{f}: Invalid group '{grp}' (not in application_ids)") + errs.extend( + f"{f}: Invalid group '{grp}' (not in application_ids)" + for grp in children + if grp not in app_ids + ) return errs diff --git a/library/cert_check_exists.py b/library/cert_check_exists.py index 6a78206e9c..f07569a0bd 100644 --- a/library/cert_check_exists.py +++ b/library/cert_check_exists.py @@ -3,13 +3,15 @@ from ansible.module_utils.cert_utils import CertUtils def main(): - module_args = dict( - domain=dict(type="str", required=True), - cert_base_path=dict( - type="str", required=False, default="/etc/letsencrypt/live" - ), - debug=dict(type="bool", required=False, default=False), - ) + module_args = { + "domain": {"type": "str", "required": True}, + "cert_base_path": { + "type": "str", + "required": False, + "default": "/etc/letsencrypt/live", + }, + "debug": {"type": "bool", "required": False, "default": False}, + } module = AnsibleModule(argument_spec=module_args) diff --git a/library/docker_bridge_gateway.py b/library/docker_bridge_gateway.py index 5ae6e48f61..78294c3322 100644 --- a/library/docker_bridge_gateway.py +++ b/library/docker_bridge_gateway.py @@ -15,9 +15,9 @@ def run(cmd: list[str]) -> str: def main(): module = AnsibleModule( - argument_spec=dict( - network=dict(type="str", default="bridge"), - ), + argument_spec={ + "network": {"type": "str", "default": "bridge"}, + }, supports_check_mode=True, ) diff --git a/plugins/filter/active_docker.py b/plugins/filter/active_docker.py index 8bf999d5af..ed4bbe110f 100644 --- a/plugins/filter/active_docker.py +++ b/plugins/filter/active_docker.py @@ -53,7 +53,7 @@ def active_docker_container_count( # sometimes roles define a single service name string; ignore continue - for _svc_name, svc_cfg in services.items(): + for svc_cfg in services.values(): if not _is_mapping(svc_cfg): # allow shorthand like: service: {} or image string -> counts as enabled count += 1 diff --git a/plugins/filter/application_allowed.py b/plugins/filter/application_allowed.py index 13fa23b929..a482d6718a 100644 --- a/plugins/filter/application_allowed.py +++ b/plugins/filter/application_allowed.py @@ -6,7 +6,7 @@ from ansible.errors import AnsibleFilterError def application_allowed( - application_id: str, group_names: list, allowed_applications: list = None + application_id: str, group_names: list, allowed_applications: list | None = None ): """ Return True if: diff --git a/plugins/filter/canonical_domains_map.py b/plugins/filter/canonical_domains_map.py index 562ebb4a49..90079b8a8e 100644 --- a/plugins/filter/canonical_domains_map.py +++ b/plugins/filter/canonical_domains_map.py @@ -117,7 +117,7 @@ class FilterModule: self, app_id, canonical_domains, seen_domains, result ): if isinstance(canonical_domains, dict): - for _, domain in canonical_domains.items(): + for domain in canonical_domains.values(): self._validate_and_check_domain(app_id, domain, seen_domains) result[app_id] = canonical_domains.copy() elif isinstance(canonical_domains, list): diff --git a/plugins/filter/csp_filters.py b/plugins/filter/csp_filters.py index a80c8bbe73..904a995c75 100644 --- a/plugins/filter/csp_filters.py +++ b/plugins/filter/csp_filters.py @@ -268,24 +268,24 @@ class FilterModule: tokens.append(get_url(domains, "web-svc-cdn", web_protocol)) # Matomo (if enabled via services.matomo.enabled) - if directive in ("script-src-elem", "connect-src"): - if self.is_feature_enabled(applications, "matomo", application_id): - tokens.append(get_url(domains, "web-app-matomo", web_protocol)) + if directive in ( + "script-src-elem", + "connect-src", + ) and self.is_feature_enabled(applications, "matomo", application_id): + tokens.append(get_url(domains, "web-app-matomo", web_protocol)) # Simpleicons (if enabled via services.simpleicons.enabled) – typically used via connect-src (fetch) - if directive == "connect-src": - if self.is_feature_enabled( - applications, "simpleicons", application_id - ): - tokens.append( - get_url(domains, "web-svc-simpleicons", web_protocol) - ) + if directive == "connect-src" and self.is_feature_enabled( + applications, "simpleicons", application_id + ): + tokens.append(get_url(domains, "web-svc-simpleicons", web_protocol)) # reCAPTCHA (if enabled via services.recaptcha.enabled) – scripts + frames - if self.is_feature_enabled(applications, "recaptcha", application_id): - if directive in ("script-src-elem", "frame-src"): - tokens.append("https://www.gstatic.com") # nocheck: url - tokens.append("https://www.google.com") + if self.is_feature_enabled( + applications, "recaptcha", application_id + ) and directive in ("script-src-elem", "frame-src"): + tokens.append("https://www.gstatic.com") # nocheck: url + tokens.append("https://www.google.com") # hCaptcha (if enabled via services.hcaptcha.enabled) – scripts + frames if self.is_feature_enabled(applications, "hcaptcha", application_id): @@ -310,9 +310,11 @@ class FilterModule: ) # Logout support requires inline handlers (script-src-attr + script-src-elem) - if directive in ("script-src-attr", "script-src-elem"): - if self.is_feature_enabled(applications, "logout", application_id): - tokens.append("'unsafe-inline'") + if directive in ( + "script-src-attr", + "script-src-elem", + ) and self.is_feature_enabled(applications, "logout", application_id): + tokens.append("'unsafe-inline'") # Custom whitelist tokens += self.get_csp_whitelist( @@ -373,9 +375,11 @@ class FilterModule: tokens_by_dir[directive] = _sort_tokens(toks) parts = [] - for directive in directives: - if directive in tokens_by_dir: - parts.append(f"{directive} {' '.join(tokens_by_dir[directive])};") + parts.extend( + f"{directive} {' '.join(tokens_by_dir[directive])};" + for directive in directives + if directive in tokens_by_dir + ) # Keep permissive img-src for data/blob + any host (as before) parts.append("img-src * data: blob:;") diff --git a/plugins/filter/has_domain.py b/plugins/filter/has_domain.py index 233e45f6cd..12c420800a 100644 --- a/plugins/filter/has_domain.py +++ b/plugins/filter/has_domain.py @@ -29,16 +29,10 @@ def _value_has_domain(v: Any) -> bool: return True if isinstance(v, (list, tuple, set)): - for item in v: - if _value_has_domain(item): - return True - return False + return any(_value_has_domain(item) for item in v) if isinstance(v, dict): - for _, item in v.items(): - if _value_has_domain(item): - return True - return False + return any(_value_has_domain(item) for _, item in v.items()) # Fallback: treat other scalars as "no domain" return False diff --git a/plugins/filter/invokable_paths.py b/plugins/filter/invokable_paths.py index ab11e0b72f..4def1571b1 100644 --- a/plugins/filter/invokable_paths.py +++ b/plugins/filter/invokable_paths.py @@ -71,7 +71,7 @@ def get_invokable_paths( METADATA = {"title", "description", "icon", "invokable"} for key, cfg in subroles.items(): - path = parent + [key] + path = [*parent, key] if cfg.get("invokable", False): p = "-".join(path) if suffix: @@ -122,7 +122,7 @@ def get_non_invokable_paths( METADATA = {"title", "description", "icon", "invokable"} for key, cfg in subroles.items(): - path = parent + [key] + path = [*parent, key] p = "-".join(path) inv = cfg.get("invokable", False) if not inv: diff --git a/plugins/filter/node_autosize.py b/plugins/filter/node_autosize.py index a6a9361913..0638515c62 100644 --- a/plugins/filter/node_autosize.py +++ b/plugins/filter/node_autosize.py @@ -69,7 +69,7 @@ def _to_bytes(val): def _mb(bytes_val: int) -> int: """Return decimal MB (10^6) as integer — Node expects MB units.""" - return int(round(bytes_val / 10**6)) + return round(bytes_val / 10**6) def _compute_old_space_mb( diff --git a/plugins/filter/reserved_users.py b/plugins/filter/reserved_users.py index d60c6cddca..14057a454e 100644 --- a/plugins/filter/reserved_users.py +++ b/plugins/filter/reserved_users.py @@ -13,7 +13,7 @@ def reserved_usernames(users_dict): results = [] - for _key, user in users_dict.items(): + for user in users_dict.values(): if not isinstance(user, dict): continue if not user.get("reserved", False): diff --git a/plugins/filter/resource_filter.py b/plugins/filter/resource_filter.py index 4090464be1..3b1f5290c3 100644 --- a/plugins/filter/resource_filter.py +++ b/plugins/filter/resource_filter.py @@ -6,7 +6,7 @@ from utils.applications.config import ( AppConfigKeyError, ConfigEntryNotSetError, get, -) # noqa: F401 +) from utils.entity_name_utils import get_entity_name diff --git a/plugins/filter/text_filters.py b/plugins/filter/text_filters.py index 948a59694c..8351981b2f 100644 --- a/plugins/filter/text_filters.py +++ b/plugins/filter/text_filters.py @@ -35,9 +35,7 @@ def to_one_liner(s): temp = temp.replace(f"__STR{idx}__", lit) # 5) Collapse all whitespace - one_liner = re.sub(r"\s+", " ", temp).strip() - - return one_liner + return re.sub(r"\s+", " ", temp).strip() class FilterModule: diff --git a/plugins/filter/timeout_start_sec_for_domains.py b/plugins/filter/timeout_start_sec_for_domains.py index c85d63cf5e..80f0f34e9d 100644 --- a/plugins/filter/timeout_start_sec_for_domains.py +++ b/plugins/filter/timeout_start_sec_for_domains.py @@ -63,8 +63,7 @@ class FilterModule: count = len(unique_domains) raw = overhead_seconds + per_domain_seconds * count - clamped = max(min_seconds, min(max_seconds, int(raw))) - return clamped + return max(min_seconds, min(max_seconds, int(raw))) except AnsibleFilterError: raise diff --git a/plugins/filter/url_join.py b/plugins/filter/url_join.py index 7814d9695d..6f6214f8b4 100644 --- a/plugins/filter/url_join.py +++ b/plugins/filter/url_join.py @@ -98,7 +98,7 @@ def url_join(parts): s = after_scheme # check if this is a query element (starts with ? or &) - if s.startswith("?") or s.startswith("&"): + if s.startswith(("?", "&")): in_query = True raw_pair = s[1:] # strip the leading ? or & if raw_pair == "": diff --git a/plugins/lookup/cert.py b/plugins/lookup/cert.py index b1ca84a890..ac780a745f 100644 --- a/plugins/lookup/cert.py +++ b/plugins/lookup/cert.py @@ -158,7 +158,7 @@ class LookupModule(LookupBase): all_domains = collect_domains_for_app(domains, app_id, err_prefix="cert") all_domains = ( - uniq_preserve([primary_domain] + all_domains) + uniq_preserve([primary_domain, *all_domains]) if all_domains else [primary_domain] ) @@ -167,7 +167,7 @@ class LookupModule(LookupBase): if san_override is None: san_domains = all_domains[:] else: - san_domains = uniq_preserve([primary_domain] + san_override) + san_domains = uniq_preserve([primary_domain, *san_override]) elif mode == "self_signed": ss_base_raw = require(variables, "TLS_SELFSIGNED_BASE_PATH", str) @@ -196,7 +196,7 @@ class LookupModule(LookupBase): # Ensure primary domain is always included if primary_domain: - san_domains = uniq_preserve([primary_domain] + san_domains) + san_domains = uniq_preserve([primary_domain, *san_domains]) else: cert_id = app_id @@ -207,7 +207,7 @@ class LookupModule(LookupBase): domains, app_id, err_prefix="cert" ) all_domains = ( - uniq_preserve([primary_domain] + all_domains) + uniq_preserve([primary_domain, *all_domains]) if all_domains else [primary_domain] ) @@ -216,7 +216,7 @@ class LookupModule(LookupBase): if san_override is None: san_domains = all_domains[:] else: - san_domains = uniq_preserve([primary_domain] + san_override) + san_domains = uniq_preserve([primary_domain, *san_override]) else: raise AnsibleError(f"cert: unsupported mode '{mode}'") diff --git a/plugins/lookup/nginx.py b/plugins/lookup/nginx.py index 20d6dc4e9e..50c4521914 100644 --- a/plugins/lookup/nginx.py +++ b/plugins/lookup/nginx.py @@ -182,7 +182,7 @@ class LookupModule(LookupBase): } if domain: - protocol_override = kwargs.get("protocol", None) + protocol_override = kwargs.get("protocol") protocol = ( _resolve_protocol_via_tls( domain=domain, diff --git a/plugins/lookup/rbac_group_path.py b/plugins/lookup/rbac_group_path.py index 6111a12e74..380ff47b68 100644 --- a/plugins/lookup/rbac_group_path.py +++ b/plugins/lookup/rbac_group_path.py @@ -38,7 +38,7 @@ from ansible.errors import AnsibleError from ansible.plugins.lookup import LookupBase try: - from ansible.utils.display import Display # noqa: F401 pragma: no cover + from ansible.utils.display import Display except Exception: # pragma: no cover Display = None # type: ignore @@ -104,7 +104,7 @@ def _resolve_role_scope(app_cfg, application_id, role): raise AnsibleError( f"rbac_group_path: role '{role}' is not declared under " f"applications[{application_id}].rbac.roles. Declared roles: " - f"{declared + [_IMPLICIT_ADMIN_ROLE]}." + f"{[*declared, _IMPLICIT_ADMIN_ROLE]}." ) tenancy = (rbac.get("tenancy") or {}) if isinstance(rbac, dict) else {} diff --git a/plugins/lookup/service.py b/plugins/lookup/service.py index 9d70988625..e780e9a5e6 100644 --- a/plugins/lookup/service.py +++ b/plugins/lookup/service.py @@ -102,11 +102,14 @@ def _is_service_required( dep_app_id = _resolve_service_provider_app_id( applications, service_registry, svc ) - if dep_app_id and dep_app_id in applications: - if _is_service_required( + if ( + dep_app_id + and dep_app_id in applications + and _is_service_required( applications, service_registry, dep_app_id, service_key, visited - ): - return True + ) + ): + return True return False diff --git a/plugins/lookup/tls.py b/plugins/lookup/tls.py index 41b4eeb0ec..4b06d266c7 100644 --- a/plugins/lookup/tls.py +++ b/plugins/lookup/tls.py @@ -74,7 +74,7 @@ class LookupModule(LookupBase): all_domains = collect_domains_for_app(domains, app_id, err_prefix="tls") all_domains = ( - uniq_preserve([primary_domain] + all_domains) + uniq_preserve([primary_domain, *all_domains]) if all_domains else [primary_domain] ) diff --git a/plugins/lookup/unit_name.py b/plugins/lookup/unit_name.py index 5648868596..a58854114d 100644 --- a/plugins/lookup/unit_name.py +++ b/plugins/lookup/unit_name.py @@ -181,10 +181,11 @@ class LookupModule(LookupBase): "unit_name lookup: lookup('version') returned an empty value." ) - suffix = kwargs.get("suffix", None) + suffix = kwargs.get("suffix") results = [] - for term in terms: - results.append(_build_unit_name(term, version, software_domain, suffix)) + results.extend( + _build_unit_name(term, version, software_domain, suffix) for term in terms + ) return results diff --git a/pyproject.toml b/pyproject.toml index 5a8a161fd2..8d843350b7 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -64,13 +64,24 @@ exclude = [ [tool.ruff.lint] # Default ruff is `E4 + E7 + E9 + F`. We add: -# - `I` (isort) — import order, auto-fixable -# - `B` (flake8-bugbear) — likely-bug patterns (mutable defaults, etc.) -# - `UP` (pyupgrade) — modernise syntax to the target_version above -select = ["E", "F", "I", "B", "UP"] +# - `I` (isort) — import order, auto-fixable +# - `B` (flake8-bugbear) — likely-bug patterns (mutable defaults, etc.) +# - `UP` (pyupgrade) — modernise syntax to the target_version above +# - `RUF` (ruff-specific) — unused-noqa, ambiguous unicode, mutable class attrs, … +# - `SIM` (flake8-simplify) — `if x: True else: False` → `bool(x)`, etc. +# - `C4` (flake8-comprehensions) — `list(x for x in y)` → `[x for x in y]`, … +# - `PERF` (perflint) — avoid try/except in hot loops, etc. +# - `RET` (flake8-return) — unneeded `else` after `return`, redundant assigns +# - `PIE` (flake8-pie) — small wins (no-op `pass`, redundant `dict()` calls) +select = ["E", "F", "I", "B", "UP", "RUF", "SIM", "C4", "PERF", "RET", "PIE"] # `ruff format` (run via `make autoformat`) reflows whatever it can. # E501 leftovers are content the formatter can't break (long string # literals, URLs / shell commands inside f-strings, comments). Trust # the formatter; don't fail CI on the unsplittable rest. -ignore = ["E501"] +# +# RUF001/002/003 (ambiguous unicode in strings / docstrings / comments) +# exist to catch homoglyph attacks, not English typography. The project +# uses em/en-dashes deliberately and `ℹ` as a UI-hint glyph in CLI help +# output; flagging those is noise. +ignore = ["E501", "RUF001", "RUF002", "RUF003"] diff --git a/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py b/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py index d2baea5c6a..3947530d7c 100644 --- a/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py +++ b/roles/svc-db-openldap/filter_plugins/build_ldap_role_entries.py @@ -108,7 +108,7 @@ def _role_group_entry( "dn": dn, "cn": cn, "description": display_name, - "objectClass": ["top"] + list(flavors), + "objectClass": ["top", *list(flavors)], } if "posixGroup" in flavors: entry["gidNumber"] = group_id diff --git a/roles/svc-opt-keyboard-color/files/script.py b/roles/svc-opt-keyboard-color/files/script.py index ad8b75c5ee..87fbb98fce 100644 --- a/roles/svc-opt-keyboard-color/files/script.py +++ b/roles/svc-opt-keyboard-color/files/script.py @@ -125,16 +125,16 @@ def main(vendor_and_product_id): start_color, end_color = get_current_period(current_time, color_times) sorted_times = sorted(color_times.keys()) - for time_str in sorted_times + [sorted_times[0]]: + for time_str in [*sorted_times, sorted_times[0]]: next_start_time_obj = datetime.datetime.strptime(time_str, "%H:%M").time() if current_time < next_start_time_obj: break - current_period_start_time_str = [ + current_period_start_time_str = next( time for time, colors in color_times.items() if colors == (start_color, end_color) - ][0] + ) current_period_start_time_obj = datetime.datetime.strptime( current_period_start_time_str, "%H:%M" ).time() diff --git a/roles/svc-opt-ssd-hdd/files/script.py b/roles/svc-opt-ssd-hdd/files/script.py index 38b9972583..3e381c251a 100644 --- a/roles/svc-opt-ssd-hdd/files/script.py +++ b/roles/svc-opt-ssd-hdd/files/script.py @@ -59,10 +59,9 @@ def has_healthcheck(container): def get_health_status(container): """Return the health status.""" - status = run_command( + return run_command( f"container inspect --format='{{{{.State.Health.Status}}}}' {container}" ) - return status def run_rsync(src, dest): diff --git a/roles/sys-ctl-bkp-docker-2-loc/library/file_has_content.py b/roles/sys-ctl-bkp-docker-2-loc/library/file_has_content.py index 1ee2239376..333dfb6194 100644 --- a/roles/sys-ctl-bkp-docker-2-loc/library/file_has_content.py +++ b/roles/sys-ctl-bkp-docker-2-loc/library/file_has_content.py @@ -46,9 +46,9 @@ size: def run_module() -> None: - module_args = dict( - path=dict(type="str", required=True), - ) + module_args = { + "path": {"type": "str", "required": True}, + } module = AnsibleModule( argument_spec=module_args, diff --git a/roles/sys-ctl-cln-bkps/files/script.py b/roles/sys-ctl-cln-bkps/files/script.py index 8cd2621427..2be28cced2 100644 --- a/roles/sys-ctl-cln-bkps/files/script.py +++ b/roles/sys-ctl-cln-bkps/files/script.py @@ -13,7 +13,7 @@ parser.add_argument( type=int, dest="maximum_backup_size_percent", required=True, - choices=range(0, 100), + choices=range(100), help="The directory from which the data should be encrypted.", ) parser.add_argument( @@ -37,9 +37,7 @@ def is_directory_used_by_another_process(directory_path): ) process.communicate() # @See https://stackoverflow.com/questions/29841984/non-zero-exit-code-for-lsof - if process.wait() > bool(0): - return False - return True + return not process.wait() > bool(0) def isSmallerThenMaximumBackupSize(maximum_backup_size_percent, backup_dir): diff --git a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py index 3c67cf0c50..fb70f2c18d 100644 --- a/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py +++ b/roles/sys-ctl-hlth-webserver/filter_plugins/web_health_expectations.py @@ -140,7 +140,7 @@ def web_health_expectations( expectations = {} - for app_id in applications.keys(): + for app_id in applications: if app_id not in selection: continue @@ -186,7 +186,7 @@ def web_health_expectations( if www_enabled: add = {} - for d in expectations.keys(): + for d in expectations: if not d.startswith("www."): add[f"www.{d}"] = [301] expectations.update(add) @@ -194,8 +194,7 @@ def web_health_expectations( if d.startswith("www."): expectations[d] = [301] - ordered = {k: expectations[k] for k in sorted(expectations.keys())} - return ordered + return {k: expectations[k] for k in sorted(expectations.keys())} class FilterModule: diff --git a/roles/sys-dns-wildcards/filter_plugins/wildcard_dns.py b/roles/sys-dns-wildcards/filter_plugins/wildcard_dns.py index b86e670c52..8ca47b53cd 100644 --- a/roles/sys-dns-wildcards/filter_plugins/wildcard_dns.py +++ b/roles/sys-dns-wildcards/filter_plugins/wildcard_dns.py @@ -123,13 +123,10 @@ def _build_wildcard_records( if p == apex: wc = "*" else: - # relative part (drop ".apex") + # relative part (drop ".apex"); empty rel is a safety guard + # — shouldn't happen because p==apex handled above. rel = p[: -len(apex) - 1] - if not rel: - # Safety guard; should not happen because p==apex handled above - wc = "*" - else: - wc = f"*.{rel}" + wc = "*" if not rel else f"*.{rel}" _add(wc, "A", str(ip4)) if ipv6_enabled and ip6 and _is_global(str(ip6)): _add(wc, "AAAA", str(ip6)) diff --git a/roles/sys-lock/files/sys-lock.py b/roles/sys-lock/files/sys-lock.py index 9009410435..cacd7b44a4 100644 --- a/roles/sys-lock/files/sys-lock.py +++ b/roles/sys-lock/files/sys-lock.py @@ -11,8 +11,6 @@ BREAK_TIME_SECONDS = 5 class AttemptException(Exception): """A custom exception for maximum number of attempts.""" - pass - def parse_time_to_seconds(time_str): """ diff --git a/roles/sys-service/filter_plugins/filetype.py b/roles/sys-service/filter_plugins/filetype.py index 20e072f38a..88c7617122 100644 --- a/roles/sys-service/filter_plugins/filetype.py +++ b/roles/sys-service/filter_plugins/filetype.py @@ -21,10 +21,9 @@ def filetype(path, full=False): if len(parts) == 2: return parts[1] return "" - else: - # Last extension only (e.g., "script.sh.j2" -> "j2", "script.py" -> "py") - _, ext = os.path.splitext(basename) - return ext[1:] if ext else "" + # Last extension only (e.g., "script.sh.j2" -> "j2", "script.py" -> "py") + _, ext = os.path.splitext(basename) + return ext[1:] if ext else "" class FilterModule: diff --git a/roles/sys-svc-compose-ca/files/compose_ca.py b/roles/sys-svc-compose-ca/files/compose_ca.py index 4e91cb1ec3..e09b4c281c 100644 --- a/roles/sys-svc-compose-ca/files/compose_ca.py +++ b/roles/sys-svc-compose-ca/files/compose_ca.py @@ -158,6 +158,7 @@ def normalize_cmd(value: Any) -> list[str]: if isinstance(value, str) and value.strip(): return ["/bin/sh", "-lc", value] die(f"Unsupported command type in compose config: {type(value)}") + return None def normalize_entrypoint(value: Any) -> list[str]: @@ -176,6 +177,7 @@ def normalize_entrypoint(value: Any) -> list[str]: if isinstance(value, str) and value.strip(): return ["/bin/sh", "-lc", value] die(f"Unsupported entrypoint type in compose config: {type(value)}") + return None def escape_compose_vars(argv: list[str]) -> list[str]: @@ -310,7 +312,7 @@ def ensure_image_available( if _has_build(svc): run_checked( - compose_base_cmd + ["build", service_name], + [*compose_base_cmd, "build", service_name], cwd=cwd, env=env, label=f"compose build {service_name}", @@ -322,14 +324,14 @@ def ensure_image_available( if not builder_cmd: builder_cmd = compose_base_cmd run_checked( - builder_cmd + ["build", builder], + [*builder_cmd, "build", builder], cwd=cwd, env=env, label=f"compose build {builder} (builder for image {img})", ) else: run_checked( - compose_base_cmd + ["pull", service_name], + [*compose_base_cmd, "pull", service_name], cwd=cwd, env=env, label=f"compose pull {service_name}", @@ -387,7 +389,7 @@ def _discover_profiles_from_files(compose_files: list[Path]) -> list[str]: if not isinstance(services, dict): continue - for _svc_name, svc in services.items(): + for svc in services.values(): if not isinstance(svc, dict): continue p = svc.get("profiles") @@ -402,7 +404,7 @@ def _discover_profiles_from_files(compose_files: list[Path]) -> list[str]: def _compose_base_cmd(*, project: str, parts: list[str], env_file: str) -> list[str]: - cmd: list[str] = ["docker", "compose", "-p", project] + parts + cmd: list[str] = ["docker", "compose", "-p", project, *parts] if env_file.strip(): cmd += ["--env-file", env_file.strip()] return cmd @@ -417,7 +419,7 @@ def _compose_cmd_with_profile(base_cmd: list[str], profile: str) -> list[str]: die(f"Invalid compose base cmd: {base_cmd}") # Insert after the compose wrapper prefix - return base_cmd[:2] + ["--profile", profile] + base_cmd[2:] + return [*base_cmd[:2], "--profile", profile, *base_cmd[2:]] def _load_services_via_config( @@ -427,7 +429,7 @@ def _load_services_via_config( env: dict[str, str], label: str, ) -> dict[str, Any]: - rc, out, err = run(compose_cmd + ["config"], cwd=cwd, env=env) + rc, out, err = run([*compose_cmd, "config"], cwd=cwd, env=env) if rc != 0: die(f"compose config failed for {label} (rc={rc}): {err.strip()}") diff --git a/roles/sys-svc-compose/files/compose.py b/roles/sys-svc-compose/files/compose.py index f58e8c31fa..8b74036caa 100644 --- a/roles/sys-svc-compose/files/compose.py +++ b/roles/sys-svc-compose/files/compose.py @@ -8,7 +8,7 @@ import sys from pathlib import Path # `utils.cache.yaml` is unavailable here: this file is copy-deployed. -import yaml # noqa: E402 +import yaml def detect_env_file(project_dir: Path) -> Path | None: diff --git a/roles/sys-svc-compose/files/pull.py b/roles/sys-svc-compose/files/pull.py index ba3b6978f2..a9565b3419 100644 --- a/roles/sys-svc-compose/files/pull.py +++ b/roles/sys-svc-compose/files/pull.py @@ -41,7 +41,7 @@ def base_compose_cmd(*, project: str, cwd: Path) -> list[str]: def has_buildable_services( *, base_cmd: list[str], cwd: Path, env: dict[str, str] ) -> bool: - rc, out = run_cmd(base_cmd + ["config"], cwd=cwd, env=env) + rc, out = run_cmd([*base_cmd, "config"], cwd=cwd, env=env) if rc != 0: if out.strip(): @@ -104,16 +104,16 @@ def main() -> int: base_cmd=base_cmd, cwd=cwd, env=env ): run_or_fail( - base_cmd + ["build", "--pull"], + [*base_cmd, "build", "--pull"], cwd=cwd, env=env, label="docker compose build --pull", ) - pull_cmd = base_cmd + ["pull"] + pull_cmd = [*base_cmd, "pull"] if args.ignore_buildable: - rc, help_out = run_cmd(base_cmd + ["pull", "--help"], cwd=cwd, env=env) + rc, help_out = run_cmd([*base_cmd, "pull", "--help"], cwd=cwd, env=env) if rc == 0 and "--ignore-buildable" in help_out: pull_cmd.append("--ignore-buildable") diff --git a/roles/sys-svc-container/files/container.py b/roles/sys-svc-container/files/container.py index 5b1f1ee59a..53d7e81866 100644 --- a/roles/sys-svc-container/files/container.py +++ b/roles/sys-svc-container/files/container.py @@ -387,7 +387,7 @@ def container_run(argv: list[str], debug: bool, with_ca: bool) -> int: f"CURL_CA_BUNDLE={ca_container}", ] return exec_docker( - ["docker", "run"] + run_opts + ca_inject_opts + [image] + user_args, + ["docker", "run", *run_opts, *ca_inject_opts, image, *user_args], debug=debug, ) diff --git a/roles/web-app-dashboard/filter_plugins/list_in_filter.py b/roles/web-app-dashboard/filter_plugins/list_in_filter.py index 1250990fcc..b7a433f3dc 100644 --- a/roles/web-app-dashboard/filter_plugins/list_in_filter.py +++ b/roles/web-app-dashboard/filter_plugins/list_in_filter.py @@ -19,8 +19,4 @@ class FilterModule: return False # Iterate over list1 and check if an element exists in list2. - for element in list1: - if element in list2: - return True - - return False + return any(element in list2 for element in list1) diff --git a/roles/web-app-keycloak/library/keycloak_kcadm_update.py b/roles/web-app-keycloak/library/keycloak_kcadm_update.py index 304c8a2567..777632f57e 100644 --- a/roles/web-app-keycloak/library/keycloak_kcadm_update.py +++ b/roles/web-app-keycloak/library/keycloak_kcadm_update.py @@ -242,24 +242,24 @@ def send_create(module, object_kind, api, realm, kcadm_exec, payload): def run_module(): - module_args = dict( - object_kind=dict(type="str", required=True), - lookup_value=dict(type="str", required=True), - desired=dict(type="dict", required=True), - lookup_field=dict(type="str", required=False, default=None), - merge_path=dict(type="str", required=False, default=None), - force_attrs=dict(type="dict", required=False, default=None), - kcadm_exec=dict(type="str", required=True), - realm=dict(type="str", required=False, default=None), - assert_mode=dict(type="bool", required=False, default=True), - ) + module_args = { + "object_kind": {"type": "str", "required": True}, + "lookup_value": {"type": "str", "required": True}, + "desired": {"type": "dict", "required": True}, + "lookup_field": {"type": "str", "required": False, "default": None}, + "merge_path": {"type": "str", "required": False, "default": None}, + "force_attrs": {"type": "dict", "required": False, "default": None}, + "kcadm_exec": {"type": "str", "required": True}, + "realm": {"type": "str", "required": False, "default": None}, + "assert_mode": {"type": "bool", "required": False, "default": True}, + } - result = dict( - changed=False, - object_exists=False, - object_id="", - result={}, - ) + result = { + "changed": False, + "object_exists": False, + "object_id": "", + "result": {}, + } module = AnsibleModule(argument_spec=module_args, supports_check_mode=False) diff --git a/roles/web-app-keycloak/module_utils/kcadm_json.py b/roles/web-app-keycloak/module_utils/kcadm_json.py index 2abc47885e..c6a06d5c9a 100644 --- a/roles/web-app-keycloak/module_utils/kcadm_json.py +++ b/roles/web-app-keycloak/module_utils/kcadm_json.py @@ -42,7 +42,7 @@ def json_from_noisy_stdout(text: Any) -> Any: chunk = s[idx:].strip() try: return json.loads(chunk) - except Exception as e: # noqa: BLE001 + except Exception as e: last_err = e raise ValueError(f"Failed to parse JSON from noisy stdout: {last_err}") diff --git a/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py b/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py index 772fde2d16..aeb80f55ff 100644 --- a/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py +++ b/roles/web-app-odoo/files/addons/auth_oauth_https/controllers/main.py @@ -66,13 +66,13 @@ class OAuthLoginHTTPS(OAuthLogin): for provider in providers: state = self.get_state(provider) - params = dict( - response_type="token", - client_id=provider["client_id"], - redirect_uri=return_url, - scope=provider["scope"], - state=json.dumps(state), - ) + params = { + "response_type": "token", + "client_id": provider["client_id"], + "redirect_uri": return_url, + "scope": provider["scope"], + "state": json.dumps(state), + } provider["auth_link"] = "{}?{}".format( provider["auth_endpoint"], werkzeug.urls.url_encode(params), @@ -96,11 +96,11 @@ class OAuthLoginHTTPS(OAuthLogin): redirect[1:] if redirect.startswith("/") else redirect, ) - state = dict( - d=request.session.db, - p=provider["id"], - r=werkzeug.urls.url_quote_plus(redirect), - ) + state = { + "d": request.session.db, + "p": provider["id"], + "r": werkzeug.urls.url_quote_plus(redirect), + } token = request.params.get("token") if token: state["t"] = token diff --git a/tests/integration/categories/test_invokable_parents.py b/tests/integration/categories/test_invokable_parents.py index 275e69161d..e0a9b0d8b7 100644 --- a/tests/integration/categories/test_invokable_parents.py +++ b/tests/integration/categories/test_invokable_parents.py @@ -27,7 +27,7 @@ class TestCategoriesInvokableExclusion(unittest.TestCase): continue is_invokable = value.get("invokable", False) - current_path = path + [key] + current_path = [*path, key] # Violation: a descendant is invokable despite an invokable ancestor if ancestor_invokable and is_invokable: diff --git a/tests/integration/categories/test_paths.py b/tests/integration/categories/test_paths.py index 5d2194297c..06c8e496b1 100644 --- a/tests/integration/categories/test_paths.py +++ b/tests/integration/categories/test_paths.py @@ -38,9 +38,11 @@ class TestCategoryPaths(unittest.TestCase): expected.add(f"{top_key}-{sub_key}") missing = [] - for name in expected: - if not any(name in dirname for dirname in self.existing_dirs): - missing.append(name) + missing.extend( + name + for name in expected + if not any(name in dirname for dirname in self.existing_dirs) + ) if missing: self.fail(f"Missing role directories for: {', '.join(sorted(missing))}") diff --git a/tests/integration/cli/test_help.py b/tests/integration/cli/test_help.py index 06f7b38e89..2375bb9b04 100644 --- a/tests/integration/cli/test_help.py +++ b/tests/integration/cli/test_help.py @@ -48,7 +48,7 @@ class CLIHelpIntegrationTest(unittest.TestCase): def test_all_cli_commands_help(self): for segments in self._discover_command_dirs(): with self.subTest(command=" ".join(segments)): - cmd = [self.python, self.main_py] + segments + ["--help"] + cmd = [self.python, self.main_py, *segments, "--help"] result = subprocess.run(cmd, capture_output=True, text=True) self.assertEqual( result.returncode, diff --git a/tests/integration/compose/test_build_requires_image.py b/tests/integration/compose/test_build_requires_image.py index 58a97d2358..5005da74ea 100644 --- a/tests/integration/compose/test_build_requires_image.py +++ b/tests/integration/compose/test_build_requires_image.py @@ -70,11 +70,11 @@ class TestComposeBuildTemplateRequiresImageTag(unittest.TestCase): continue ind = TestComposeBuildTemplateRequiresImageTag._indent_len(line) - if ind < props_indent_len: - if line.rstrip().endswith(":") and not line.lstrip().startswith( - ("-", "#") - ): - return i + if ind < props_indent_len and ( + line.rstrip().endswith(":") + and (not line.lstrip().startswith(("-", "#"))) + ): + return i return None def test_build_lookup_requires_image_or_merge_on_same_level(self): diff --git a/tests/integration/compose/test_no_raw_docker.py b/tests/integration/compose/test_no_raw_docker.py index 2e10b57d50..68780b7c4f 100644 --- a/tests/integration/compose/test_no_raw_docker.py +++ b/tests/integration/compose/test_no_raw_docker.py @@ -186,8 +186,7 @@ def git_ls_files(root: Path) -> list[Path]: for d in pruned: dirs.remove(d) - for f in files: - results.append(Path(r) / f) + results.extend(Path(r) / f for f in files) return results @@ -202,10 +201,7 @@ def is_whitelisted(path: Path, root: Path) -> bool: return True rel_wrapped = f"/{rel}/" - if any(fragment in rel_wrapped for fragment in WHITELIST_PATH_FRAGMENTS): - return True - - return False + return bool(any(fragment in rel_wrapped for fragment in WHITELIST_PATH_FRAGMENTS)) def is_probably_text(data: bytes) -> bool: diff --git a/tests/integration/compose/test_templates_require_image.py b/tests/integration/compose/test_templates_require_image.py index e0c1900bce..219f1ab5a1 100644 --- a/tests/integration/compose/test_templates_require_image.py +++ b/tests/integration/compose/test_templates_require_image.py @@ -174,10 +174,10 @@ class TestComposeBuildRequiresImage(unittest.TestCase): "", "Offenders:", ] - for it in all_findings: - msg_lines.append( - f"- {it.file}:{it.build_line} (build indent={it.build_indent}) -> {it.note}" - ) + msg_lines.extend( + f"- {it.file}:{it.build_line} (build indent={it.build_indent}) -> {it.note}" + for it in all_findings + ) msg_lines.append("") msg_lines.append( "Fix: for each service that has `build:`, add a stable `image:` name on the same level, e.g." diff --git a/tests/integration/config/test_csp_consistency.py b/tests/integration/config/test_csp_consistency.py index 0cc36c4467..2b34f18d52 100644 --- a/tests/integration/config/test_csp_consistency.py +++ b/tests/integration/config/test_csp_consistency.py @@ -1,4 +1,5 @@ import unittest +from typing import ClassVar from urllib.parse import urlparse import yaml @@ -19,7 +20,7 @@ class TestCspConfigurationConsistency(unittest.TestCase): On error, include role name and file path for easier debugging. """ - SUPPORTED_DIRECTIVES = { + SUPPORTED_DIRECTIVES: ClassVar[set[str]] = { "default-src", "connect-src", "frame-ancestors", @@ -36,7 +37,7 @@ class TestCspConfigurationConsistency(unittest.TestCase): "script-src-attr", } - SUPPORTED_FLAGS = {"unsafe-eval", "unsafe-inline"} + SUPPORTED_FLAGS: ClassVar[set[str]] = {"unsafe-eval", "unsafe-inline"} def is_valid_whitelist_entry(self, entry: str) -> bool: """ @@ -175,11 +176,11 @@ class TestCspConfigurationConsistency(unittest.TestCase): ) snippets = [] - for snippet in snippets: - if not isinstance(snippet, str) or not snippet.strip(): - errors.append( - f"{role_path.name}: hashes.{directive} contains empty or non-string snippet ({cfg_file})" - ) + errors.extend( + f"{role_path.name}: hashes.{directive} contains empty or non-string snippet ({cfg_file})" + for snippet in snippets + if not isinstance(snippet, str) or not snippet.strip() + ) if errors: self.fail( diff --git a/tests/integration/config/test_non_empty.py b/tests/integration/config/test_non_empty.py index ab11136360..df7ec4dce3 100644 --- a/tests/integration/config/test_non_empty.py +++ b/tests/integration/config/test_non_empty.py @@ -18,14 +18,14 @@ def find_none_values(data, prefix=None): if isinstance(data, dict): for key, value in data.items(): - path = prefix + [str(key)] + path = [*prefix, str(key)] if value is None: errors.append((".".join(path), value)) elif isinstance(value, (dict, list)): errors.extend(find_none_values(value, path)) elif isinstance(data, list): for idx, item in enumerate(data): - path = prefix + [f"[{idx}]"] + path = [*prefix, f"[{idx}]"] if item is None: errors.append((".".join(path), item)) elif isinstance(item, (dict, list)): diff --git a/tests/integration/docker/test_compose_templates.py b/tests/integration/docker/test_compose_templates.py index 8e143112f0..0790a718f0 100644 --- a/tests/integration/docker/test_compose_templates.py +++ b/tests/integration/docker/test_compose_templates.py @@ -1,5 +1,6 @@ import re import unittest +from typing import ClassVar from . import PROJECT_ROOT @@ -9,7 +10,7 @@ class TestDockerComposeTemplates(unittest.TestCase): TEMPLATE_PATTERN = "roles/*/templates/compose.yml.j2" # Allowed lines before BASE_INCLUDE - ALLOWED_BEFORE_BASE = [ + ALLOWED_BEFORE_BASE: ClassVar[list[re.Pattern]] = [ re.compile(r"^\s*$"), # empty line re.compile(r"^\s*version:.*$"), # version: ... re.compile(r"^\s*#.*$"), # YAML comment diff --git a/tests/integration/filters/test_defined.py b/tests/integration/filters/test_defined.py index 9e98ba20e1..2ade0c9b1f 100644 --- a/tests/integration/filters/test_defined.py +++ b/tests/integration/filters/test_defined.py @@ -157,9 +157,11 @@ class _FiltersCollector(ast.NodeVisitor): and isinstance(node.func, ast.Name) and node.func.id == "dict" ): - for kw in node.keywords or []: - if kw.arg: - pairs.append((kw.arg, self._name_of(kw.value))) + pairs.extend( + (kw.arg, self._name_of(kw.value)) + for kw in node.keywords or [] + if kw.arg + ) return pairs if isinstance(node, ast.Name): return [] @@ -328,8 +330,7 @@ class TestAllUsedFiltersAreDefined(unittest.TestCase): "These filters are used in templates/YAML but have no local definition " "(and are not in BUILTIN_FILTERS):" ] - for f in unknown: - lines.append("- " + f) + lines.extend("- " + f for f in unknown) self.fail("\n".join(lines)) diff --git a/tests/integration/filters/test_usage.py b/tests/integration/filters/test_usage.py index bd1e854a2a..55da4d294b 100644 --- a/tests/integration/filters/test_usage.py +++ b/tests/integration/filters/test_usage.py @@ -72,9 +72,11 @@ class _FiltersCollector(ast.NodeVisitor): and node.func.id == "dict" ): # keywords: dict(name=fn) - for kw in node.keywords or []: - if kw.arg: - pairs.append((kw.arg, self._name_of(kw.value))) + pairs.extend( + (kw.arg, self._name_of(kw.value)) + for kw in node.keywords or [] + if kw.arg + ) return pairs # Name (variable) that might be a dict assembled earlier in the function diff --git a/tests/integration/group_vars/test_no_jinja_recursion.py b/tests/integration/group_vars/test_no_jinja_recursion.py index 465c8938c7..f616af74c2 100644 --- a/tests/integration/group_vars/test_no_jinja_recursion.py +++ b/tests/integration/group_vars/test_no_jinja_recursion.py @@ -69,14 +69,13 @@ def build_edges(vars_dict): def walk(node, path): if isinstance(node, dict): for k, v in node.items(): - walk(v, path + [k]) + walk(v, [*path, k]) elif isinstance(node, list): for i, e in enumerate(node): - walk(e, path + [f"[{i}]"]) + walk(e, [*path, f"[{i}]"]) else: full_key = ".".join(path) - for ref in find_jinja_refs(node): - edges.append((full_key, ref)) + edges.extend((full_key, ref) for ref in find_jinja_refs(node)) walk(vars_dict, []) return edges @@ -111,7 +110,7 @@ class TestNoJinjaReferenceCycles(unittest.TestCase): def dfs(node, visited, stack): if node in stack: - return stack[stack.index(node) :] + [node] + return [*stack[stack.index(node) :], node] if node in visited: return None visited.add(node) diff --git a/tests/integration/handlers/test_invoked.py b/tests/integration/handlers/test_invoked.py index 4f9b370ea5..844a1c7d31 100644 --- a/tests/integration/handlers/test_invoked.py +++ b/tests/integration/handlers/test_invoked.py @@ -285,8 +285,7 @@ class TestHandlersInvoked(unittest.TestCase): if missing_groups: representatives: list[str] = [] - for grp in missing_groups: - representatives.append(sorted(grp)[0]) + representatives.extend(sorted(grp)[0] for grp in missing_groups) representatives = sorted(set(representatives)) msg = [ diff --git a/tests/integration/jinja/test_variable_definitions.py b/tests/integration/jinja/test_variable_definitions.py index 02dbf01bce..edb6466b11 100644 --- a/tests/integration/jinja/test_variable_definitions.py +++ b/tests/integration/jinja/test_variable_definitions.py @@ -131,7 +131,7 @@ class TestVariableDefinitions(unittest.TestCase): data = yaml.safe_load(inline_map) if isinstance(data, dict): self.defined.update( - k for k in data.keys() if isinstance(k, str) + k for k in data if isinstance(k, str) ) except yaml.YAMLError as exc: logging.debug( @@ -273,7 +273,7 @@ class TestVariableDefinitions(unittest.TestCase): if m_expr: var = m_expr.group(1) - if var not in ( + if var not in ( # noqa: SIM102 the long literal whitelist is more readable as a separate guard "lookup", "role_name", "domains", diff --git a/tests/integration/lookups/config/_validate.py b/tests/integration/lookups/config/_validate.py index a686605c47..d4147b9da9 100644 --- a/tests/integration/lookups/config/_validate.py +++ b/tests/integration/lookups/config/_validate.py @@ -35,7 +35,7 @@ def match_wildcard_segment(mapping: Any, segment: str) -> bool: return False if "*" not in segment: return segment in mapping - return any(fnmatch.fnmatchcase(k, segment) for k in mapping.keys()) + return any(fnmatch.fnmatchcase(k, segment) for k in mapping) def match_wildcard_path(mapping: Any, dotted: str) -> bool: diff --git a/tests/integration/lookups/config/test_variable_paths.py b/tests/integration/lookups/config/test_variable_paths.py index b7bdcd3450..d1cdf2e068 100644 --- a/tests/integration/lookups/config/test_variable_paths.py +++ b/tests/integration/lookups/config/test_variable_paths.py @@ -84,12 +84,11 @@ class TestVariablePaths(unittest.TestCase): if isinstance(creds, Mapping) and key in creds: return True - if dotted.startswith("images."): - if any( - isinstance(cfg.get("images"), Mapping) - for cfg in ctx.application_defaults.values() - ): - return True + if dotted.startswith("images.") and any( + isinstance(cfg.get("images"), Mapping) + for cfg in ctx.application_defaults.values() + ): + return True if dotted.startswith("users."): subpath = dotted.split(".", 1)[1] diff --git a/tests/integration/lookups/config/test_wildcard_paths.py b/tests/integration/lookups/config/test_wildcard_paths.py index 0521aced5f..78c896ece6 100644 --- a/tests/integration/lookups/config/test_wildcard_paths.py +++ b/tests/integration/lookups/config/test_wildcard_paths.py @@ -92,11 +92,10 @@ class TestWildcardPaths(unittest.TestCase): creds = schema.get("credentials") if isinstance(schema, Mapping) else None if isinstance(creds, Mapping) and match_wildcard_segment(creds, sub): return True - if wildcard_path.startswith("images.") and isinstance( - cfg.get("images"), Mapping - ): - return True - return False + return bool( + wildcard_path.startswith("images.") + and isinstance(cfg.get("images"), Mapping) + ) if __name__ == "__main__": diff --git a/tests/integration/oauth2_oidc/rbac/test_path_join_guard.py b/tests/integration/oauth2_oidc/rbac/test_path_join_guard.py index 62dc5981c0..d4da4a8e74 100644 --- a/tests/integration/oauth2_oidc/rbac/test_path_join_guard.py +++ b/tests/integration/oauth2_oidc/rbac/test_path_join_guard.py @@ -60,12 +60,7 @@ def _iter_text_files(root): for dirpath, dirnames, filenames in os.walk(root): dirnames[:] = [d for d in dirnames if d not in EXCLUDED_DIRS] for filename in filenames: - if not ( - filename.endswith(".yml") - or filename.endswith(".yaml") - or filename.endswith(".j2") - or filename.endswith(".py") - ): + if not (filename.endswith((".yml", ".yaml", ".j2", ".py"))): continue yield os.path.join(dirpath, filename) diff --git a/tests/integration/passwords/test_env_quoted.py b/tests/integration/passwords/test_env_quoted.py index 66b3a80402..951c60b2ed 100644 --- a/tests/integration/passwords/test_env_quoted.py +++ b/tests/integration/passwords/test_env_quoted.py @@ -55,7 +55,7 @@ def _is_full_line_comment(line: str) -> bool: def _is_jinja_control_line(line: str) -> bool: s = line.lstrip() - return s.startswith("{%") or s.startswith("{#") + return s.startswith(("{%", "{#")) class TestEnvPasswordsQuotedAndFiltered(unittest.TestCase): diff --git a/tests/integration/roles/applications/id/test_run_after.py b/tests/integration/roles/applications/id/test_run_after.py index 728e1340ea..2480da2879 100644 --- a/tests/integration/roles/applications/id/test_run_after.py +++ b/tests/integration/roles/applications/id/test_run_after.py @@ -27,9 +27,9 @@ class TestRunAfterRoles(unittest.TestCase): continue run_after = data.get("galaxy_info", {}).get("run_after", []) - for ref in run_after: - if ref not in self.valid_role_names: - invalid_refs.append((role, ref)) + invalid_refs.extend( + (role, ref) for ref in run_after if ref not in self.valid_role_names + ) if invalid_refs: msg = "\n".join( diff --git a/tests/integration/roles/applications/test_web_app_readme.py b/tests/integration/roles/applications/test_web_app_readme.py index 0505574479..8742b68bc0 100644 --- a/tests/integration/roles/applications/test_web_app_readme.py +++ b/tests/integration/roles/applications/test_web_app_readme.py @@ -7,7 +7,7 @@ def find_repo_root(start: Path) -> Path | None: Walk up from `start` until we find a directory containing 'roles'. Returns the repo root (the directory that contains 'roles') or None. """ - for parent in [start] + list(start.parents): + for parent in [start, *list(start.parents)]: if (parent / "roles").is_dir(): return parent return None diff --git a/tests/integration/roles/includes/test_existence.py b/tests/integration/roles/includes/test_existence.py index d9cfd89d83..e03f7b52cf 100644 --- a/tests/integration/roles/includes/test_existence.py +++ b/tests/integration/roles/includes/test_existence.py @@ -49,9 +49,11 @@ class TestIncludeImportExistence(unittest.TestCase): elif isinstance(val, dict) and value_key in val: refs.append(val[value_key]) elif isinstance(val, list): - for item in val: - if isinstance(item, dict) and value_key in item: - refs.append(item[value_key]) + refs.extend( + item[value_key] + for item in val + if isinstance(item, dict) and value_key in item + ) else: refs.extend( TestIncludeImportExistence._collect_refs( @@ -93,7 +95,7 @@ class TestIncludeImportExistence(unittest.TestCase): self.fail( "Invalid include_role/import_role name detected.\n" f" • File: {file_path}\n" - f" • Extracted name value: {repr(role_name)}\n" + f" • Extracted name value: {role_name!r}\n" "The 'name:' field must contain a non-empty string.\n" "Example:\n" " include_role:\n" diff --git a/tests/integration/roles/meta/dependencies/test_circular_meta.py b/tests/integration/roles/meta/dependencies/test_circular_meta.py index 2f2dbb7bf2..20735efbc6 100644 --- a/tests/integration/roles/meta/dependencies/test_circular_meta.py +++ b/tests/integration/roles/meta/dependencies/test_circular_meta.py @@ -15,8 +15,7 @@ def get_meta_info(role_path): if not os.path.isfile(meta_file): return [] meta_data = load_yaml_file(meta_file) - dependencies = meta_data.get("dependencies", []) - return dependencies + return meta_data.get("dependencies", []) def resolve_dependencies(roles_dir): @@ -57,7 +56,7 @@ def resolve_dependencies(roles_dir): visit(role_path, []) # Start recursion from this role except ValueError as e: raise ValueError( - f"Error processing role '{role_name}' at path '{role_path}': {str(e)}" + f"Error processing role '{role_name}' at path '{role_path}': {e!s}" ) from e diff --git a/tests/integration/roles/meta/dependencies/test_unnecessary.py b/tests/integration/roles/meta/dependencies/test_unnecessary.py index 9e523b6abd..ba26776581 100644 --- a/tests/integration/roles/meta/dependencies/test_unnecessary.py +++ b/tests/integration/roles/meta/dependencies/test_unnecessary.py @@ -117,8 +117,7 @@ def find_var_positions(text: str, varname: str) -> list[int]: """Return byte offsets for occurrences of varname (word-ish boundary).""" positions: list[int] = [] pattern = re.compile(rf"(? list[tuple[str, str]]: for key, entry in services.items(): if not isinstance(entry, dict): continue - for flag in ("enabled", "shared"): - if _is_dynamic_flag(entry.get(flag)): - pairs.append((key, flag)) + pairs.extend( + (key, flag) + for flag in ("enabled", "shared") + if _is_dynamic_flag(entry.get(flag)) + ) return pairs diff --git a/tests/integration/roles/meta/variants/test_services_match.py b/tests/integration/roles/meta/variants/test_services_match.py index 172cc37e89..ebc2fb0ee7 100644 --- a/tests/integration/roles/meta/variants/test_services_match.py +++ b/tests/integration/roles/meta/variants/test_services_match.py @@ -52,7 +52,7 @@ class TestVariantsServicesMatch(unittest.TestCase): services = _load_yaml(role_dir / "meta" / "services.yml") if not isinstance(services, dict): continue - declared_keys = {k for k in services.keys() if isinstance(k, str)} + declared_keys = {k for k in services if isinstance(k, str)} variants_raw = _load_yaml(role_dir / "meta" / "variants.yml") if not isinstance(variants_raw, list): @@ -64,7 +64,7 @@ class TestVariantsServicesMatch(unittest.TestCase): variant_services = variant.get("services") if not isinstance(variant_services, dict): continue - for key in variant_services.keys(): + for key in variant_services: if not isinstance(key, str): continue if key in declared_keys: diff --git a/tests/integration/roles/run_once/test_global_usage.py b/tests/integration/roles/run_once/test_global_usage.py index a40f2951ad..12570bed45 100644 --- a/tests/integration/roles/run_once/test_global_usage.py +++ b/tests/integration/roles/run_once/test_global_usage.py @@ -120,7 +120,7 @@ def collect_set_fact_suffixes(obj, out_suffixes: set[str]): elif isinstance(obj, dict): sf = obj.get("set_fact") or obj.get("ansible.builtin.set_fact") if isinstance(sf, dict): - for k in sf.keys(): + for k in sf: if isinstance(k, str): m = RUN_ONCE_USAGE_RE.fullmatch(k.strip()) if m: @@ -169,8 +169,7 @@ def role_defines_suffix_in_doc(doc, role_suffix: str) -> bool: if isinstance(sf, dict) and target_var in sf: return True # Recurse - for v in node.values(): - queue.append(v) + queue.extend(node.values()) elif isinstance(node, list): queue.extend(node) return False @@ -258,26 +257,26 @@ class RunOnceGlobalUsageFastTest(unittest.TestCase): offenders: list[tuple[str, str, str]] = [] # A) Unknown suffixes used (no corresponding role) must be globally defined - for suffix in sorted(used_suffixes): - if suffix not in known_suffixes and suffix not in global_defined_suffixes: - offenders.append( - ( - "", - f"run_once_{suffix}", - "", - ) - ) + offenders.extend( + ( + "", + f"run_once_{suffix}", + "", + ) + for suffix in sorted(used_suffixes) + if suffix not in known_suffixes and suffix not in global_defined_suffixes + ) # B) Known role suffixes used must be defined either globally or in that exact role for role in sorted(roles): suffix = suffix_for_role[role] - if suffix in used_suffixes: - if (suffix not in global_defined_suffixes) and ( - suffix not in role_defined_suffixes[role] - ): - offenders.append( - (role, f"run_once_{suffix}", os.path.join(rroot, role, "tasks")) - ) + if suffix in used_suffixes and ( + suffix not in global_defined_suffixes + and suffix not in role_defined_suffixes[role] + ): + offenders.append( + (role, f"run_once_{suffix}", os.path.join(rroot, role, "tasks")) + ) if offenders: lines = [ diff --git a/tests/integration/roles/when/test_duplication.py b/tests/integration/roles/when/test_duplication.py index 511abda388..71d83e95b5 100644 --- a/tests/integration/roles/when/test_duplication.py +++ b/tests/integration/roles/when/test_duplication.py @@ -77,9 +77,8 @@ def _iter_tasks(node: Any) -> Iterable[dict[str, Any]]: yield from _iter_tasks(item) # Also traverse other nested structures conservatively for k, v in node.items(): - if k not in ("block", "rescue", "always"): - if isinstance(v, (list, dict)): - yield from _iter_tasks(v) + if k not in ("block", "rescue", "always") and isinstance(v, (list, dict)): + yield from _iter_tasks(v) def _load_yaml_documents(path: Path) -> list[Any]: diff --git a/tests/integration/services/test_sys_requires_id.py b/tests/integration/services/test_sys_requires_id.py index 7c10acbc5c..7468ae9b0d 100644 --- a/tests/integration/services/test_sys_requires_id.py +++ b/tests/integration/services/test_sys_requires_id.py @@ -10,9 +10,8 @@ from utils.cache.files import read_text def _safe_yaml_load(path): try: - doc = yaml.safe_load(read_text(path)) + return yaml.safe_load(read_text(path)) # A tasks file can be a list (usual) or a dict (blocks, etc.) - return doc except Exception as e: raise AssertionError(f"Failed to parse YAML: {path}\n{e}") from e @@ -80,7 +79,7 @@ class TestSysServiceRequiresSystemServiceId(unittest.TestCase): for bt in t["block"]: if check_task(bt): return True - elif isinstance(tasks_doc, dict): + elif isinstance(tasks_doc, dict): # noqa: SIM102 pairs with the for-list branch above; flat structure is clearer # top-level block file (rare) if "block" in tasks_doc and isinstance(tasks_doc["block"], list): for bt in tasks_doc["block"]: diff --git a/tests/integration/vars/test_facts_not_overridden.py b/tests/integration/vars/test_facts_not_overridden.py index 9941ff00e9..5eb2f5e0e8 100644 --- a/tests/integration/vars/test_facts_not_overridden.py +++ b/tests/integration/vars/test_facts_not_overridden.py @@ -119,7 +119,7 @@ def _collect_defined_facts(task_files: list[Path]) -> dict[str, set[Path]]: if not _is_set_fact_task(task): continue mapping = _get_set_fact_mapping(task) - for k in mapping.keys(): + for k in mapping: if not isinstance(k, str) or _looks_dynamic(k): continue facts.setdefault(k, set()).add(p) @@ -143,7 +143,7 @@ def _collect_var_overrides(task_files: list[Path]) -> list[tuple[Path, str, str] if not vmap: continue tname = str(task.get("name", "")) - for k in vmap.keys(): + for k in vmap: if not isinstance(k, str) or _looks_dynamic(k): continue overrides.append((p, tname, k)) diff --git a/tests/integration/vars/test_uppercase_constants_unique.py b/tests/integration/vars/test_uppercase_constants_unique.py index e77c9bba6e..f5d377065b 100644 --- a/tests/integration/vars/test_uppercase_constants_unique.py +++ b/tests/integration/vars/test_uppercase_constants_unique.py @@ -57,7 +57,7 @@ def _extract_top_level_uppercase_keys(docs): found = set() for doc in docs: if isinstance(doc, dict): - for k in doc.keys(): + for k in doc: if isinstance(k, str) and UPPER_CONST_RE.match(k): found.add(k) return found @@ -108,8 +108,7 @@ class TestUppercaseConstantVarsUnique(unittest.TestCase): ] for const, files in sorted(duplicates.items()): msg_lines.append(f"* {const} defined in {len(files)} files:") - for f in files: - msg_lines.append(f" - {f}") + msg_lines.extend(f" - {f}" for f in files) msg_lines.append("") # spacer self.fail("\n".join(msg_lines)) diff --git a/tests/integration/workflows/test_dependabot_coverage.py b/tests/integration/workflows/test_dependabot_coverage.py index e94593e03a..fb68e98ebf 100644 --- a/tests/integration/workflows/test_dependabot_coverage.py +++ b/tests/integration/workflows/test_dependabot_coverage.py @@ -177,7 +177,7 @@ def _load_gitignore_patterns() -> list[str]: patterns: list[str] = [] for raw in GITIGNORE_PATH.read_text().splitlines(): line = raw.strip() - if not line or line.startswith("#") or line.startswith("!"): + if not line or line.startswith(("#", "!")): continue patterns.append(line.rstrip("/")) return patterns diff --git a/tests/lint/ansible/roles/test_compose_resource_limits.py b/tests/lint/ansible/roles/test_compose_resource_limits.py index 6d4fabc2eb..b108501412 100644 --- a/tests/lint/ansible/roles/test_compose_resource_limits.py +++ b/tests/lint/ansible/roles/test_compose_resource_limits.py @@ -98,17 +98,17 @@ def _collect_findings(root: Path) -> list[MissingKeyFinding]: continue service_line = _find_service_line(config_path, entity_name) - for key in REQUIRED_KEYS: - if key not in primary_conf: - findings.append( - MissingKeyFinding( - role=role_dir.name, - service=entity_name, - key=key, - config_path=config_path, - line=service_line, - ) - ) + findings.extend( + MissingKeyFinding( + role=role_dir.name, + service=entity_name, + key=key, + config_path=config_path, + line=service_line, + ) + for key in REQUIRED_KEYS + if key not in primary_conf + ) findings.sort(key=lambda f: (f.role, f.service, f.key)) return findings diff --git a/tests/lint/ansible/roles/test_playwright_env_keys_used.py b/tests/lint/ansible/roles/test_playwright_env_keys_used.py index 8d76454e67..d591f87121 100644 --- a/tests/lint/ansible/roles/test_playwright_env_keys_used.py +++ b/tests/lint/ansible/roles/test_playwright_env_keys_used.py @@ -72,7 +72,7 @@ def _extract_env_keys(env_text: str) -> list[str]: stripped = line.lstrip() if not stripped or stripped.startswith("#"): continue - if stripped.startswith("{%") or stripped.startswith("{#"): + if stripped.startswith(("{%", "{#")): continue m = _KEY_LHS_RE.match(stripped) if m: diff --git a/tests/lint/ansible/roles/test_service_core_first_task_run_once.py b/tests/lint/ansible/roles/test_service_core_first_task_run_once.py index 5e196940c8..cf605c4741 100644 --- a/tests/lint/ansible/roles/test_service_core_first_task_run_once.py +++ b/tests/lint/ansible/roles/test_service_core_first_task_run_once.py @@ -67,9 +67,11 @@ class TestServiceCoreFirstTaskRunOnce(unittest.TestCase): def test_01_core_exists(self): missing = [] - for role in unique_roles(self.registry): - if not self._core_path(role).is_file(): - missing.append(role) + missing.extend( + role + for role in unique_roles(self.registry) + if not self._core_path(role).is_file() + ) if missing: self.fail( "roles missing tasks/01_core.yml:\n" diff --git a/tests/lint/ansible/test_no_sh_lc_pipefail.py b/tests/lint/ansible/test_no_sh_lc_pipefail.py index 7494dac80e..af45a6053f 100644 --- a/tests/lint/ansible/test_no_sh_lc_pipefail.py +++ b/tests/lint/ansible/test_no_sh_lc_pipefail.py @@ -72,19 +72,21 @@ def _collect_pipefail_vars(tree: ast.Module) -> set[str]: while changed: changed = False for node in ast.walk(tree): - if isinstance(node, ast.Assign): - if _expr_contains_pipefail(node.value, names): - for t in node.targets: - for name in _iter_assigned_names(t): - if name not in names: - names.add(name) - changed = True - elif isinstance(node, ast.AnnAssign) and node.value is not None: - if _expr_contains_pipefail(node.value, names): - for name in _iter_assigned_names(node.target): + if isinstance(node, ast.Assign) and _expr_contains_pipefail( + node.value, names + ): + for t in node.targets: + for name in _iter_assigned_names(t): if name not in names: names.add(name) changed = True + if ( + isinstance(node, ast.AnnAssign) and node.value is not None + ) and _expr_contains_pipefail(node.value, names): + for name in _iter_assigned_names(node.target): + if name not in names: + names.add(name) + changed = True return names diff --git a/tests/lint/ansible/test_service_shared_consistency.py b/tests/lint/ansible/test_service_shared_consistency.py index 2cf9d75c09..2782b84ac2 100644 --- a/tests/lint/ansible/test_service_shared_consistency.py +++ b/tests/lint/ansible/test_service_shared_consistency.py @@ -88,15 +88,16 @@ class TestServiceSharedConsistency(unittest.TestCase): has_enabled = "enabled" in svc_cfg # Rule 1: enabled=true requires shared=true - if enabled is True and not has_shared: - if svc_name not in exceptions: - errors.append( - f"{role_name}: services.{svc_name} has enabled=true " - f"but is missing shared=true. " - f"Add 'shared: true' or place a '# nocheck: shared' " - f"comment on the line directly above '{svc_name}:' to mark " - f"the intentional exception. ({file_path})" - ) + if ( + enabled is True and (not has_shared) + ) and svc_name not in exceptions: + errors.append( + f"{role_name}: services.{svc_name} has enabled=true " + f"but is missing shared=true. " + f"Add 'shared: true' or place a '# nocheck: shared' " + f"comment on the line directly above '{svc_name}:' to mark " + f"the intentional exception. ({file_path})" + ) # Rule 2: shared key requires enabled key if has_shared and not has_enabled: diff --git a/tests/lint/ansible/variables/test_role_and_group_vars_used.py b/tests/lint/ansible/variables/test_role_and_group_vars_used.py index 442c55b0f3..078c2011f6 100644 --- a/tests/lint/ansible/variables/test_role_and_group_vars_used.py +++ b/tests/lint/ansible/variables/test_role_and_group_vars_used.py @@ -110,9 +110,7 @@ def _collect_top_level_keys(file: Path) -> list[tuple[str, int]]: if not isinstance(data, dict): return [] - declared: set[str] = { - k for k in data.keys() if isinstance(k, str) and k.isidentifier() - } + declared: set[str] = {k for k in data if isinstance(k, str) and k.isidentifier()} if not declared: return [] @@ -195,9 +193,8 @@ def _scan_ansible_expr_idents(node, sink: set[str]) -> None: for k, v in node.items(): if k in _ANSIBLE_EXPR_KEYS: _harvest_idents_from_value(v, sink) - elif isinstance(k, str) and k.startswith("with_"): - if isinstance(v, str): - _harvest_idents_from_value(v, sink) + if (isinstance(k, str) and k.startswith("with_")) and isinstance(v, str): + _harvest_idents_from_value(v, sink) _scan_ansible_expr_idents(v, sink) elif isinstance(node, list): for item in node: diff --git a/tests/lint/ansible/variables/test_vars_usage_in_yaml.py b/tests/lint/ansible/variables/test_vars_usage_in_yaml.py index b2960756eb..1b5e57bec9 100644 --- a/tests/lint/ansible/variables/test_vars_usage_in_yaml.py +++ b/tests/lint/ansible/variables/test_vars_usage_in_yaml.py @@ -1,8 +1,9 @@ +import contextlib import re import unittest from collections.abc import Iterable from pathlib import Path -from typing import Any +from typing import Any, ClassVar from utils.cache.files import iter_project_files, read_text from utils.cache.yaml import load_yaml_all @@ -30,13 +31,13 @@ class TestVarsPassedAreUsed(unittest.TestCase): i.e. treat `var_name(` as a function/macro call, not a variable usage. """ - YAML_EXTENSIONS = {".yml", ".yaml"} - JINJA_EXTENSIONS = {".j2"} + YAML_EXTENSIONS: ClassVar[set[str]] = {".yml", ".yaml"} + JINJA_EXTENSIONS: ClassVar[set[str]] = {".j2"} # Inventories are data-only bundle definitions (not tasks/templates) and can legitimately # contain vars that are not referenced inside Jinja blocks or Ansible expressions. # Therefore they are excluded from this lint. - EXCLUDED_TOP_LEVEL_DIRS = {"inventories"} + EXCLUDED_TOP_LEVEL_DIRS: ClassVar[set[str]] = {"inventories"} # ---------- File iteration & YAML loading ---------- @@ -132,11 +133,9 @@ class TestVarsPassedAreUsed(unittest.TestCase): def _concat_texts(self) -> str: parts: list[str] = [] for f in self._iter_files(self.YAML_EXTENSIONS | self.JINJA_EXTENSIONS): - try: + # Non-UTF8 or unreadable files are silently skipped. + with contextlib.suppress(Exception): parts.append(read_text(str(f))) - except Exception: - # Non-UTF8 or unreadable — ignore - pass return "\n".join(parts) # ---------- Extract Ansible expression strings from YAML ---------- @@ -159,12 +158,11 @@ class TestVarsPassedAreUsed(unittest.TestCase): exprs.append(val) elif isinstance(val, list): exprs.extend([x for x in val if isinstance(x, str)]) - elif key == "loop": - if isinstance(val, str): - exprs.append(val) - elif isinstance(key, str) and key.startswith("with_"): - if isinstance(val, str): - exprs.append(val) + elif ( + key == "loop" + or (isinstance(key, str) and key.startswith("with_")) + ) and isinstance(val, str): + exprs.append(val) return exprs # ---------- Usage checks ---------- @@ -213,9 +211,8 @@ class TestVarsPassedAreUsed(unittest.TestCase): used = self._used_in_jinja_blocks( var_name, all_text ) or self._used_in_ansible_exprs(var_name, ansible_exprs) - if not used: - if var_name not in ["ansible_python_interpreter"]: - unused.append(var_name) + if not used and var_name not in ["ansible_python_interpreter"]: + unused.append(var_name) if unused: lines: list[str] = [] diff --git a/tests/lint/docker/dockerfile/test_arg_scope.py b/tests/lint/docker/dockerfile/test_arg_scope.py index db07e2c3fe..2245a76f40 100644 --- a/tests/lint/docker/dockerfile/test_arg_scope.py +++ b/tests/lint/docker/dockerfile/test_arg_scope.py @@ -54,9 +54,11 @@ def _undeclared_from_args(dockerfile: Path) -> list[tuple[int, str, str]]: # Pass 2 — check every FROM that references an ARG violations: list[tuple[int, str, str]] = [] for lineno, line in enumerate(lines, start=1): - for m in _FROM_ARG_RE.finditer(line): - if m.group(1) not in global_args: - violations.append((lineno, line.strip(), m.group(1))) + violations.extend( + (lineno, line.strip(), m.group(1)) + for m in _FROM_ARG_RE.finditer(line) + if m.group(1) not in global_args + ) return violations diff --git a/tests/lint/filesystem/test_filename_conventions.py b/tests/lint/filesystem/test_filename_conventions.py index e6e65510c1..d2ea3a7f18 100644 --- a/tests/lint/filesystem/test_filename_conventions.py +++ b/tests/lint/filesystem/test_filename_conventions.py @@ -15,9 +15,11 @@ class TestFilenameConventions(unittest.TestCase): for path in iter_project_files(): filename = os.path.basename(path) lower = filename.lower() - if lower in ("readme.md", "todo.md"): - if filename not in ("README.md", "TODO.md"): - bad_files.append(path) + if lower in ("readme.md", "todo.md") and filename not in ( + "README.md", + "TODO.md", + ): + bad_files.append(path) msg = ( ( diff --git a/tests/lint/filesystem/test_python_shebangs.py b/tests/lint/filesystem/test_python_shebangs.py index 2e7f9fb52d..56e1b5f467 100644 --- a/tests/lint/filesystem/test_python_shebangs.py +++ b/tests/lint/filesystem/test_python_shebangs.py @@ -32,8 +32,7 @@ class TestPythonShebangs(unittest.TestCase): files: list[Path] = [] for root, dirs, names in os.walk(self.repo_root): dirs[:] = [d for d in dirs if d != ".git"] - for name in names: - files.append(Path(root) / name) + files.extend(Path(root) / name for name in names) return files @staticmethod diff --git a/tests/lint/repository/test_all_test_files_have_tests.py b/tests/lint/repository/test_all_test_files_have_tests.py index 5001e423e9..b1ecfe3695 100644 --- a/tests/lint/repository/test_all_test_files_have_tests.py +++ b/tests/lint/repository/test_all_test_files_have_tests.py @@ -19,9 +19,11 @@ class TestTestFilesContainUnittestTests(unittest.TestCase): def _iter_test_files(self) -> list[str]: out: list[str] = [] for root, _dirs, files in os.walk(self.tests_dir): - for fn in files: - if fn.startswith("test_") and fn.endswith(".py"): - out.append(os.path.join(root, fn)) + out.extend( + os.path.join(root, fn) + for fn in files + if fn.startswith("test_") and fn.endswith(".py") + ) return sorted(out) def _file_contains_runnable_unittest_test(self, path: str) -> bool: @@ -46,24 +48,22 @@ class TestTestFilesContainUnittestTests(unittest.TestCase): for n in node.names: if n.name == "unittest": unittest_aliases.add(n.asname or "unittest") - elif isinstance(node, ast.ImportFrom): - if node.module == "unittest": - for n in node.names: - if n.name == "TestCase": - testcase_aliases.add(n.asname or "TestCase") + if isinstance(node, ast.ImportFrom) and node.module == "unittest": + for n in node.names: + if n.name == "TestCase": + testcase_aliases.add(n.asname or "TestCase") def is_testcase_base(base: ast.expr) -> bool: # TestCase if isinstance(base, ast.Name) and base.id in testcase_aliases: return True # unittest.TestCase or alias.TestCase - if isinstance(base, ast.Attribute) and base.attr == "TestCase": - if ( - isinstance(base.value, ast.Name) - and base.value.id in unittest_aliases - ): - return True - return False + return bool( + isinstance(base, ast.Attribute) + and base.attr == "TestCase" + and isinstance(base.value, ast.Name) + and base.value.id in unittest_aliases + ) # 1) module-level test_* function (uncommon but valid for discovery in some setups) for node in tree.body: diff --git a/tests/lint/repository/test_domain_primary_spot.py b/tests/lint/repository/test_domain_primary_spot.py index 6f8f14d930..cb1f3a1b03 100644 --- a/tests/lint/repository/test_domain_primary_spot.py +++ b/tests/lint/repository/test_domain_primary_spot.py @@ -227,8 +227,7 @@ class TestDomainPrimarySpot(unittest.TestCase): ] for path, issues in sorted(offenders.items()): lines.append(f" - {rel(path)}:") - for issue in issues: - lines.append(f" * {issue}") + lines.extend(f" * {issue}" for issue in issues) lines.append("") lines.append( "Fix: replace the literal with `\"{{ lookup('domain', " diff --git a/tests/lint/repository/test_literal_protocol_with_lookup.py b/tests/lint/repository/test_literal_protocol_with_lookup.py index c0317af346..c10abf093a 100644 --- a/tests/lint/repository/test_literal_protocol_with_lookup.py +++ b/tests/lint/repository/test_literal_protocol_with_lookup.py @@ -139,8 +139,7 @@ class TestLiteralProtocolWithLookup(unittest.TestCase): ] for path, issues in sorted(offenders.items()): lines.append(f" - {rel(path)}:") - for issue in issues: - lines.append(f" * {issue}") + lines.extend(f" * {issue}" for issue in issues) lines.append("") lines.append( "Fix: replace the literal-protocol concatenation with " diff --git a/tests/lint/repository/test_markdown_links.py b/tests/lint/repository/test_markdown_links.py index 33f19cfa98..18ab6e9f54 100644 --- a/tests/lint/repository/test_markdown_links.py +++ b/tests/lint/repository/test_markdown_links.py @@ -75,9 +75,7 @@ def _is_checkable_link(target: str) -> bool: # Skip placeholder targets used in documentation examples (e.g. [...](...) # where the target consists only of dots and slashes). stripped = target.split("#")[0] - if stripped and all(c in "./" for c in stripped): - return False - return True + return not (stripped and all(c in "./" for c in stripped)) def _strip_anchor(target: str) -> str: diff --git a/tests/lint/repository/test_no_direct_yaml_calls.py b/tests/lint/repository/test_no_direct_yaml_calls.py index 1a624b16cf..5fa67dcd95 100644 --- a/tests/lint/repository/test_no_direct_yaml_calls.py +++ b/tests/lint/repository/test_no_direct_yaml_calls.py @@ -132,11 +132,10 @@ def _file_offenders(path: Path) -> list[str]: for alias in node.names: if alias.name == "yaml": yaml_module_aliases.add(alias.asname or "yaml") - elif isinstance(node, ast.ImportFrom): - if node.module == "yaml": - for alias in node.names: - if alias.name in _FORBIDDEN_FUNCTIONS: - direct_function_aliases[alias.asname or alias.name] = alias.name + elif isinstance(node, ast.ImportFrom) and node.module == "yaml": + for alias in node.names: + if alias.name in _FORBIDDEN_FUNCTIONS: + direct_function_aliases[alias.asname or alias.name] = alias.name # The marker may appear on the call's own line OR, for multi-line # calls, on any line spanned by the call expression. @@ -169,12 +168,11 @@ def _file_offenders(path: Path) -> list[str]: offenders.append( f"line {node.lineno}: {func.value.id}.{func.attr}(...)" ) - elif isinstance(func, ast.Name): - if func.id in direct_function_aliases: - if _is_suppressed(node): - continue - actual = direct_function_aliases[func.id] - offenders.append(f"line {node.lineno}: {func.id}(...) [yaml.{actual}]") + elif isinstance(func, ast.Name) and func.id in direct_function_aliases: + if _is_suppressed(node): + continue + actual = direct_function_aliases[func.id] + offenders.append(f"line {node.lineno}: {func.id}(...) [yaml.{actual}]") return offenders @@ -214,8 +212,7 @@ class TestNoDirectYamlCalls(unittest.TestCase): ] for path, issues in sorted(offenders.items()): lines.append(f" - {rel(path)}:") - for issue in issues: - lines.append(f" * {issue}") + lines.extend(f" * {issue}" for issue in issues) lines.append("") lines.append( "Fix: replace `yaml.safe_load(path.read_text())` with " diff --git a/tests/lint/repository/test_no_hardcoded_dns_resolvers.py b/tests/lint/repository/test_no_hardcoded_dns_resolvers.py index 3def1ac716..e462ed186b 100644 --- a/tests/lint/repository/test_no_hardcoded_dns_resolvers.py +++ b/tests/lint/repository/test_no_hardcoded_dns_resolvers.py @@ -49,9 +49,9 @@ def _load_resolver_ips() -> list[str]: f"NETWORK_PUBLIC_DNS_RESOLVERS missing or non-list in {_NETWORKS_FILE}" ) out: list[str] = [] - for item in resolvers: - if isinstance(item, str) and item.strip(): - out.append(item.strip()) + out.extend( + item.strip() for item in resolvers if isinstance(item, str) and item.strip() + ) if not out: raise AssertionError( f"NETWORK_PUBLIC_DNS_RESOLVERS is empty in {_NETWORKS_FILE}" diff --git a/tests/lint/repository/test_role_meta_info.py b/tests/lint/repository/test_role_meta_info.py index 277d62d696..dc55d296bc 100644 --- a/tests/lint/repository/test_role_meta_info.py +++ b/tests/lint/repository/test_role_meta_info.py @@ -142,8 +142,7 @@ class TestMetaInfoShape(unittest.TestCase): lines = [f"{len(offenders)} meta/info.yml file(s) violate req-011:"] for path, problems in sorted(offenders.items()): lines.append(f" - {rel(path)}:") - for problem in problems: - lines.append(f" * {problem}") + lines.extend(f" * {problem}" for problem in problems) self.fail("\n".join(lines)) @@ -167,8 +166,7 @@ class TestMetaMainHasNoMigratedFields(unittest.TestCase): ] for path, problems in sorted(offenders.items()): lines.append(f" - {rel(path)}:") - for problem in problems: - lines.append(f" * {problem}") + lines.extend(f" * {problem}" for problem in problems) self.fail("\n".join(lines)) diff --git a/tests/lint/repository/test_role_meta_layout.py b/tests/lint/repository/test_role_meta_layout.py index cef0c4b1cd..cc2b8dfbb2 100644 --- a/tests/lint/repository/test_role_meta_layout.py +++ b/tests/lint/repository/test_role_meta_layout.py @@ -20,6 +20,7 @@ from __future__ import annotations import unittest from pathlib import Path +from typing import ClassVar import yaml @@ -107,7 +108,7 @@ class TestNoLegacyPathReferences(unittest.TestCase): "/.cache/", ) - EXEMPT_FILES: set[Path] = { + EXEMPT_FILES: ClassVar[set[Path]] = { PROJECT_ROOT / "tasks" / "utils" / "migrate_meta_layout.py", } @@ -195,10 +196,7 @@ class TestLifecycleAllowedValues(unittest.TestCase): lifecycle = entity.get("lifecycle") if lifecycle is None: continue - if isinstance(lifecycle, str): - value = lifecycle.strip().lower() - else: - value = "" + value = lifecycle.strip().lower() if isinstance(lifecycle, str) else "" if value not in ALLOWED_LIFECYCLES: offenders.append( f"{role_dir.name}/{entity_name}: lifecycle={lifecycle!r}" @@ -246,7 +244,7 @@ class TestHostBoundPortCollisions(unittest.TestCase): # inside the BBB relay range (40000-49999) historically. Same role # owning both ends of the collision is acceptable for this specific # documented exception. - _SAME_ROLE_LEGACY_OVERLAPS = { + _SAME_ROLE_LEGACY_OVERLAPS: ClassVar[set[tuple[str, int]]] = { ("web-app-bigbluebutton", 48087), } diff --git a/tests/lint/repository/test_role_meta_main_galaxy_schema.py b/tests/lint/repository/test_role_meta_main_galaxy_schema.py index 6f079aa38a..da5cb2677a 100644 --- a/tests/lint/repository/test_role_meta_main_galaxy_schema.py +++ b/tests/lint/repository/test_role_meta_main_galaxy_schema.py @@ -203,9 +203,11 @@ def _validate_meta_main(path: Path) -> list[str]: if "galaxy_tags" in galaxy_info: problems.extend(_validate_galaxy_tags(galaxy_info["galaxy_tags"])) - for str_field in ("author", "description", "license", "company"): - if str_field in galaxy_info and not isinstance(galaxy_info[str_field], str): - problems.append(f"galaxy_info.{str_field} must be a string") + problems.extend( + f"galaxy_info.{str_field} must be a string" + for str_field in ("author", "description", "license", "company") + if str_field in galaxy_info and (not isinstance(galaxy_info[str_field], str)) + ) if "min_ansible_version" in galaxy_info: val = galaxy_info["min_ansible_version"] @@ -240,8 +242,7 @@ class TestRoleMetaMainGalaxySchema(unittest.TestCase): ] for path, problems in sorted(offenders.items()): lines.append(f" - {rel(path)}:") - for problem in problems: - lines.append(f" * {problem}") + lines.extend(f" * {problem}" for problem in problems) self.fail("\n".join(lines)) diff --git a/tests/unit/cli/create/test_credentials.py b/tests/unit/cli/create/test_credentials.py index 1afe3bc9ab..b365ceefb8 100644 --- a/tests/unit/cli/create/test_credentials.py +++ b/tests/unit/cli/create/test_credentials.py @@ -38,9 +38,11 @@ class TestCreateCredentials(unittest.TestCase): completed = subprocess.CompletedProcess( args=["ansible-vault"], returncode=1, stdout="", stderr="error" ) - with unittest.mock.patch("subprocess.run", return_value=completed): - with self.assertRaises(RuntimeError): - handler.encrypt_string("plain_val", "name") + with ( + unittest.mock.patch("subprocess.run", return_value=completed), + self.assertRaises(RuntimeError), + ): + handler.encrypt_string("plain_val", "name") def test_main_overrides_and_file_writing(self): # Setup temporary files for role-path vars and inventory diff --git a/tests/unit/cli/deploy/dedicated/test_main.py b/tests/unit/cli/deploy/dedicated/test_main.py index cee52665b0..7da1fc3c67 100644 --- a/tests/unit/cli/deploy/dedicated/test_main.py +++ b/tests/unit/cli/deploy/dedicated/test_main.py @@ -10,7 +10,7 @@ class TestDedicatedMainParser(unittest.TestCase): parser = dedicated_main.build_parser() # Smoke-check: parser exists and has some core options - opts = {a.dest for a in parser._actions} # noqa: SLF001 (test-only introspection) + opts = {a.dest for a in parser._actions} self.assertIn("inventory", opts) self.assertIn("limit", opts) diff --git a/tests/unit/cli/deploy/dedicated/test_runner.py b/tests/unit/cli/deploy/dedicated/test_runner.py index 02c3f4c9d7..ef2fc9762c 100644 --- a/tests/unit/cli/deploy/dedicated/test_runner.py +++ b/tests/unit/cli/deploy/dedicated/test_runner.py @@ -23,10 +23,7 @@ class TestRunAnsiblePlaybook(unittest.TestCase): def _side_effect(cmd, *args, **kwargs): # Normalize command to list[str] for easier assertions - if isinstance(cmd, list): - norm_cmd = cmd - else: - norm_cmd = [cmd] + norm_cmd = cmd if isinstance(cmd, list) else [cmd] calls_store.append((norm_cmd, dict(kwargs))) @@ -231,24 +228,26 @@ class TestRunAnsiblePlaybook(unittest.TestCase): "MODE_DEBUG": False, } - with unittest.mock.patch( - "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env" + with ( + unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env" + ), + self.assertRaises(SystemExit) as ctx, ): - with self.assertRaises(SystemExit) as ctx: - runner.run_ansible_playbook( - repo_root=repo_root, - playbook_path=playbook_path, - inventory_validator_path=inventory_validator_path, - inventory="/etc/inventories/github-ci/devices.yml", - modes=modes, - limit=None, - allowed_applications=None, - password_file=None, - verbose=0, - skip_build=True, - diff=False, - ansible_args=None, - ) + runner.run_ansible_playbook( + repo_root=repo_root, + playbook_path=playbook_path, + inventory_validator_path=inventory_validator_path, + inventory="/etc/inventories/github-ci/devices.yml", + modes=modes, + limit=None, + allowed_applications=None, + password_file=None, + verbose=0, + skip_build=True, + diff=False, + ansible_args=None, + ) self.assertEqual(ctx.exception.code, 4) @@ -279,29 +278,31 @@ class TestRunAnsiblePlaybook(unittest.TestCase): calls: list[tuple[list[str], dict[str, Any]]] = [] mock_run.side_effect = self._fake_run_side_effect(calls, ansible_rc=0) - with unittest.mock.patch( - "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env", - side_effect=ServicesDisabledConflictError("boom"), + with ( + unittest.mock.patch( + "cli.deploy.dedicated.runner.assert_services_disabled_inventory_consistency_from_env", + side_effect=ServicesDisabledConflictError("boom"), + ), + self.assertRaises(SystemExit) as ctx, ): - with self.assertRaises(SystemExit) as ctx: - runner.run_ansible_playbook( - repo_root="/repo", - playbook_path="/repo/playbook.yml", - inventory_validator_path="/repo/cli/validate/inventory/__main__.py", - inventory="/etc/inventories/github-ci/devices.yml", - modes={ - "MODE_CLEANUP": False, - "MODE_ASSERT": True, - "MODE_DEBUG": False, - }, - limit=None, - allowed_applications=None, - password_file=None, - verbose=0, - skip_build=True, - diff=False, - ansible_args=None, - ) + runner.run_ansible_playbook( + repo_root="/repo", + playbook_path="/repo/playbook.yml", + inventory_validator_path="/repo/cli/validate/inventory/__main__.py", + inventory="/etc/inventories/github-ci/devices.yml", + modes={ + "MODE_CLEANUP": False, + "MODE_ASSERT": True, + "MODE_DEBUG": False, + }, + limit=None, + allowed_applications=None, + password_file=None, + verbose=0, + skip_build=True, + diff=False, + ansible_args=None, + ) self.assertEqual(ctx.exception.code, 1) self.assertFalse( diff --git a/tests/unit/cli/deploy/development/test_exec.py b/tests/unit/cli/deploy/development/test_exec.py index ac0d697238..8a610ba042 100644 --- a/tests/unit/cli/deploy/development/test_exec.py +++ b/tests/unit/cli/deploy/development/test_exec.py @@ -26,14 +26,16 @@ class TestDevelopmentExec(unittest.TestCase): compose = unittest.mock.Mock() compose.exec.return_value.returncode = 0 - with unittest.mock.patch( - "cli.deploy.development.exec.make_compose", - return_value=compose, - ): - with unittest.mock.patch.dict( + with ( + unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ), + unittest.mock.patch.dict( os.environ, {"SERVICES_DISABLED": "email"}, clear=False - ): - rc = exec_cmd.handler(_args(cmd=["--", "sh", "-lc", "true"])) + ), + ): + rc = exec_cmd.handler(_args(cmd=["--", "sh", "-lc", "true"])) self.assertEqual(rc, 0) compose.exec.assert_called_once_with( @@ -47,12 +49,14 @@ class TestDevelopmentExec(unittest.TestCase): compose.exec.return_value.returncode = 0 env = {k: v for k, v in os.environ.items() if k != "SERVICES_DISABLED"} - with unittest.mock.patch( - "cli.deploy.development.exec.make_compose", - return_value=compose, + with ( + unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ), + unittest.mock.patch.dict(os.environ, env, clear=True), ): - with unittest.mock.patch.dict(os.environ, env, clear=True): - rc = exec_cmd.handler(_args(cmd=["echo", "hi"])) + rc = exec_cmd.handler(_args(cmd=["echo", "hi"])) self.assertEqual(rc, 0) compose.exec.assert_called_once_with( @@ -68,17 +72,19 @@ class TestDevelopmentExec(unittest.TestCase): compose.exec.return_value.returncode = 0 env = {k: v for k, v in os.environ.items() if k != "SERVICES_DISABLED"} - with unittest.mock.patch( - "cli.deploy.development.exec.make_compose", - return_value=compose, + with ( + unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ), + unittest.mock.patch.dict(os.environ, env, clear=True), ): - with unittest.mock.patch.dict(os.environ, env, clear=True): - rc = exec_cmd.handler( - _args( - cmd=["bash", "/opt/helper.sh"], - env=["INVENTORY_FILE=/srv/inv/devices.yml", "APPS=web-app-foo"], - ) + rc = exec_cmd.handler( + _args( + cmd=["bash", "/opt/helper.sh"], + env=["INVENTORY_FILE=/srv/inv/devices.yml", "APPS=web-app-foo"], ) + ) self.assertEqual(rc, 0) compose.exec.assert_called_once_with( @@ -95,12 +101,14 @@ class TestDevelopmentExec(unittest.TestCase): compose.exec.return_value.returncode = 0 env = {k: v for k, v in os.environ.items() if k != "SERVICES_DISABLED"} - with unittest.mock.patch( - "cli.deploy.development.exec.make_compose", - return_value=compose, + with ( + unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ), + unittest.mock.patch.dict(os.environ, env, clear=True), ): - with unittest.mock.patch.dict(os.environ, env, clear=True): - exec_cmd.handler(_args(cmd=["true"], env=["EXTRA_VARS=a=1 b=2"])) + exec_cmd.handler(_args(cmd=["true"], env=["EXTRA_VARS=a=1 b=2"])) # Only the first '=' splits key from value; everything after stays intact. compose.exec.assert_called_once_with( @@ -113,16 +121,16 @@ class TestDevelopmentExec(unittest.TestCase): compose = unittest.mock.Mock() compose.exec.return_value.returncode = 0 - with unittest.mock.patch( - "cli.deploy.development.exec.make_compose", - return_value=compose, - ): - with unittest.mock.patch.dict( + with ( + unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ), + unittest.mock.patch.dict( os.environ, {"SERVICES_DISABLED": "from-env"}, clear=False - ): - exec_cmd.handler( - _args(cmd=["true"], env=["SERVICES_DISABLED=from-cli"]) - ) + ), + ): + exec_cmd.handler(_args(cmd=["true"], env=["SERVICES_DISABLED=from-cli"])) compose.exec.assert_called_once_with( ["true"], @@ -132,21 +140,25 @@ class TestDevelopmentExec(unittest.TestCase): def test_env_pair_without_equals_is_rejected(self): compose = unittest.mock.Mock() - with unittest.mock.patch( - "cli.deploy.development.exec.make_compose", - return_value=compose, + with ( + unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ), + self.assertRaisesRegex(SystemExit, "expects KEY=VALUE"), ): - with self.assertRaisesRegex(SystemExit, "expects KEY=VALUE"): - exec_cmd.handler(_args(cmd=["true"], env=["BARE"])) + exec_cmd.handler(_args(cmd=["true"], env=["BARE"])) def test_env_pair_with_empty_key_is_rejected(self): compose = unittest.mock.Mock() - with unittest.mock.patch( - "cli.deploy.development.exec.make_compose", - return_value=compose, + with ( + unittest.mock.patch( + "cli.deploy.development.exec.make_compose", + return_value=compose, + ), + self.assertRaisesRegex(SystemExit, "KEY is empty"), ): - with self.assertRaisesRegex(SystemExit, "KEY is empty"): - exec_cmd.handler(_args(cmd=["true"], env=["=value"])) + exec_cmd.handler(_args(cmd=["true"], env=["=value"])) if __name__ == "__main__": diff --git a/tests/unit/cli/deploy/development/test_inventory.py b/tests/unit/cli/deploy/development/test_inventory.py index 7ccd6d7b65..aeb067c463 100644 --- a/tests/unit/cli/deploy/development/test_inventory.py +++ b/tests/unit/cli/deploy/development/test_inventory.py @@ -6,6 +6,7 @@ from __future__ import annotations import json import unittest from pathlib import Path +from typing import ClassVar from unittest.mock import MagicMock, patch from cli.deploy.development.common import DEV_INVENTORY_VARS_FILE @@ -21,12 +22,12 @@ from cli.deploy.development.inventory import ( def _spec(**overrides) -> DevInventorySpec: - base = dict( - inventory_dir="/tmp/inv", - include=("web-app-keycloak", "web-app-nextcloud"), - storage_constrained=False, - runtime="dev", - ) + base = { + "inventory_dir": "/tmp/inv", + "include": ("web-app-keycloak", "web-app-nextcloud"), + "storage_constrained": False, + "runtime": "dev", + } base.update(overrides) return DevInventorySpec(**base) @@ -306,7 +307,7 @@ class TestPlanDevInventoryMatrix(unittest.TestCase): class TestFilterPlanToVariant(unittest.TestCase): - PLAN = [ + PLAN: ClassVar[list[tuple]] = [ ( 0, "/srv/inv-0", diff --git a/tests/unit/cli/deploy/test_container.py b/tests/unit/cli/deploy/test_container.py index c2ef2b2c79..58c7ac53a7 100644 --- a/tests/unit/cli/deploy/test_container.py +++ b/tests/unit/cli/deploy/test_container.py @@ -180,10 +180,12 @@ class TestMain(unittest.TestCase): "foo,bar", ] - with unittest.mock.patch.dict(os.environ, {}, clear=True): - with unittest.mock.patch.object(sys, "argv", argv): - with self.assertRaises(SystemExit): - deploy_container.main() + with ( + unittest.mock.patch.dict(os.environ, {}, clear=True), + unittest.mock.patch.object(sys, "argv", argv), + self.assertRaises(SystemExit), + ): + deploy_container.main() mock_run_in_container.assert_not_called() @@ -204,11 +206,13 @@ class TestMain(unittest.TestCase): "foo,bar", ] - with unittest.mock.patch.dict( - os.environ, {"INVENTORY_DIR": "/env/inventory"}, clear=True + with ( + unittest.mock.patch.dict( + os.environ, {"INVENTORY_DIR": "/env/inventory"}, clear=True + ), + unittest.mock.patch.object(sys, "argv", argv), ): - with unittest.mock.patch.object(sys, "argv", argv): - rc = deploy_container.main() + rc = deploy_container.main() self.assertEqual(rc, 0) mock_run_in_container.assert_called_once() diff --git a/tests/unit/cli/gha/test_annotations.py b/tests/unit/cli/gha/test_annotations.py index 3ae7a28228..b708aea649 100644 --- a/tests/unit/cli/gha/test_annotations.py +++ b/tests/unit/cli/gha/test_annotations.py @@ -15,10 +15,12 @@ class TestAnnotationsInGHA(unittest.TestCase): """Tests for GHA annotation format (GITHUB_ACTIONS=true).""" def _capture(self, fn, *args, **kwargs) -> str: - with patch.dict(os.environ, GHA_ENV): - with patch("sys.stdout", new_callable=StringIO) as mock_out: - fn(*args, **kwargs) - return mock_out.getvalue().strip() + with ( + patch.dict(os.environ, GHA_ENV), + patch("sys.stdout", new_callable=StringIO) as mock_out, + ): + fn(*args, **kwargs) + return mock_out.getvalue().strip() def test_warning_no_props(self) -> None: out = self._capture(warning, "something went wrong") @@ -41,38 +43,46 @@ class TestAnnotationsInGHA(unittest.TestCase): self.assertEqual(out, "::notice::info") def test_warning_each_emits_one_per_item(self) -> None: - with patch.dict(os.environ, GHA_ENV): - with patch("sys.stdout", new_callable=StringIO) as mock_out: - warning_each(["alpha", "beta", "gamma"], title="T") - lines = mock_out.getvalue().splitlines() + with ( + patch.dict(os.environ, GHA_ENV), + patch("sys.stdout", new_callable=StringIO) as mock_out, + ): + warning_each(["alpha", "beta", "gamma"], title="T") + lines = mock_out.getvalue().splitlines() self.assertEqual(len(lines), 3) self.assertIn("alpha", lines[0]) self.assertIn("beta", lines[1]) self.assertIn("gamma", lines[2]) def test_error_each_emits_one_per_item(self) -> None: - with patch.dict(os.environ, GHA_ENV): - with patch("sys.stdout", new_callable=StringIO) as mock_out: - error_each(["x", "y"], title="E") - lines = mock_out.getvalue().splitlines() + with ( + patch.dict(os.environ, GHA_ENV), + patch("sys.stdout", new_callable=StringIO) as mock_out, + ): + error_each(["x", "y"], title="E") + lines = mock_out.getvalue().splitlines() self.assertEqual(len(lines), 2) self.assertTrue(all("::error" in line for line in lines)) def test_warning_each_empty(self) -> None: - with patch.dict(os.environ, GHA_ENV): - with patch("sys.stdout", new_callable=StringIO) as mock_out: - warning_each([]) - self.assertEqual(mock_out.getvalue(), "") + with ( + patch.dict(os.environ, GHA_ENV), + patch("sys.stdout", new_callable=StringIO) as mock_out, + ): + warning_each([]) + self.assertEqual(mock_out.getvalue(), "") class TestAnnotationsPlainText(unittest.TestCase): """Tests for plain text format (no GITHUB_ACTIONS).""" def _capture(self, fn, *args, **kwargs) -> str: - with patch.dict(os.environ, NO_GHA_ENV): - with patch("sys.stdout", new_callable=StringIO) as mock_out: - fn(*args, **kwargs) - return mock_out.getvalue().strip() + with ( + patch.dict(os.environ, NO_GHA_ENV), + patch("sys.stdout", new_callable=StringIO) as mock_out, + ): + fn(*args, **kwargs) + return mock_out.getvalue().strip() def test_warning_no_props(self) -> None: out = self._capture(warning, "something went wrong") @@ -91,10 +101,12 @@ class TestAnnotationsPlainText(unittest.TestCase): self.assertEqual(out, "[NOTICE]: info") def test_warning_each_emits_one_per_item(self) -> None: - with patch.dict(os.environ, NO_GHA_ENV): - with patch("sys.stdout", new_callable=StringIO) as mock_out: - warning_each(["alpha", "beta"], title="T") - lines = mock_out.getvalue().splitlines() + with ( + patch.dict(os.environ, NO_GHA_ENV), + patch("sys.stdout", new_callable=StringIO) as mock_out, + ): + warning_each(["alpha", "beta"], title="T") + lines = mock_out.getvalue().splitlines() self.assertEqual(len(lines), 2) self.assertIn("alpha", lines[0]) self.assertIn("beta", lines[1]) diff --git a/tests/unit/cli/meta/applications/resolution/affected/test_main.py b/tests/unit/cli/meta/applications/resolution/affected/test_main.py index 18b081bf32..12565fb1c3 100644 --- a/tests/unit/cli/meta/applications/resolution/affected/test_main.py +++ b/tests/unit/cli/meta/applications/resolution/affected/test_main.py @@ -111,9 +111,11 @@ class TestAffected(unittest.TestCase): with tempfile.TemporaryDirectory() as td: root = Path(td) _mk_app_role(root, "leaf", "leaf") - with patch.object(repo_paths, "PROJECT_ROOT", root): - with self.assertRaises(SystemExit): - affected_main.affected_roles(["does-not-exist"]) + with ( + patch.object(repo_paths, "PROJECT_ROOT", root), + self.assertRaises(SystemExit), + ): + affected_main.affected_roles(["does-not-exist"]) def test_non_modellable_seed_exits_with_sentinel_code(self) -> None: with tempfile.TemporaryDirectory() as td: @@ -150,12 +152,14 @@ class TestAffected(unittest.TestCase): with patch.object(repo_paths, "PROJECT_ROOT", root): buf = io.StringIO() - with redirect_stdout(buf): - with patch( + with ( + redirect_stdout(buf), + patch( "sys.argv", ["prog", "--changed-roles", "leaf"], - ): - affected_main.main() + ), + ): + affected_main.main() self.assertEqual(buf.getvalue().strip(), "consumer leaf") diff --git a/tests/unit/cli/meta/applications/resolution/combined/test_main.py b/tests/unit/cli/meta/applications/resolution/combined/test_main.py index d24e4638a7..cf770b7223 100644 --- a/tests/unit/cli/meta/applications/resolution/combined/test_main.py +++ b/tests/unit/cli/meta/applications/resolution/combined/test_main.py @@ -51,9 +51,8 @@ class TestCombinedMain(unittest.TestCase): with patch.object(repo_paths, "PROJECT_ROOT", root): buf = io.StringIO() - with redirect_stdout(buf): - with patch("sys.argv", ["prog", "app"]): - combined_main.main() + with redirect_stdout(buf), patch("sys.argv", ["prog", "app"]): + combined_main.main() out = buf.getvalue().strip() self.assertEqual(out, "ra1") @@ -66,9 +65,8 @@ class TestCombinedMain(unittest.TestCase): with patch.object(repo_paths, "PROJECT_ROOT", root): buf = io.StringIO() - with redirect_stdout(buf): - with patch("sys.argv", ["prog", "app", "--tree"]): - combined_main.main() + with redirect_stdout(buf), patch("sys.argv", ["prog", "app", "--tree"]): + combined_main.main() s = buf.getvalue() self.assertIn("app", s) self.assertIn("[run_after]", s) diff --git a/tests/unit/cli/meta/applications/resolution/combined/test_role_introspection.py b/tests/unit/cli/meta/applications/resolution/combined/test_role_introspection.py index 9ffbbec9ad..4657cc7040 100644 --- a/tests/unit/cli/meta/applications/resolution/combined/test_role_introspection.py +++ b/tests/unit/cli/meta/applications/resolution/combined/test_role_introspection.py @@ -91,9 +91,11 @@ a: run_after: dep1 """, ) - with patch.object(repo_paths, "PROJECT_ROOT", root): - with self.assertRaises(CombinedResolutionError): - ri.load_run_after("web-app-a") + with ( + patch.object(repo_paths, "PROJECT_ROOT", root), + self.assertRaises(CombinedResolutionError), + ): + ri.load_run_after("web-app-a") def test_load_dependencies_app_only_filters_non_app_roles(self) -> None: with tempfile.TemporaryDirectory() as td: @@ -151,6 +153,8 @@ dependencies: """, ) - with patch.object(repo_paths, "PROJECT_ROOT", root): - with self.assertRaises(CombinedResolutionError): - ri.load_dependencies_app_only("web-app-a") + with ( + patch.object(repo_paths, "PROJECT_ROOT", root), + self.assertRaises(CombinedResolutionError), + ): + ri.load_dependencies_app_only("web-app-a") diff --git a/tests/unit/cli/meta/applications/resolution/dependencies/test_dependencies_main.py b/tests/unit/cli/meta/applications/resolution/dependencies/test_dependencies_main.py index eaf6564c33..b0649e1032 100644 --- a/tests/unit/cli/meta/applications/resolution/dependencies/test_dependencies_main.py +++ b/tests/unit/cli/meta/applications/resolution/dependencies/test_dependencies_main.py @@ -68,7 +68,6 @@ dependencies: with patch.object(deps_main, "PROJECT_ROOT", root): buf = io.StringIO() - with redirect_stdout(buf): - with patch("sys.argv", ["prog", "app"]): - deps_main.main() + with redirect_stdout(buf), patch("sys.argv", ["prog", "app"]): + deps_main.main() self.assertEqual(buf.getvalue().strip(), "app_dep") diff --git a/tests/unit/cli/meta/categories/invokable/test_command.py b/tests/unit/cli/meta/categories/invokable/test_command.py index d30ba361d9..513d0e88fc 100644 --- a/tests/unit/cli/meta/categories/invokable/test_command.py +++ b/tests/unit/cli/meta/categories/invokable/test_command.py @@ -20,13 +20,16 @@ class TestInvokableCategoriesCommand(unittest.TestCase): out = io.StringIO() err = io.StringIO() - with patch("sys.argv", ["prog", *argv]): - with redirect_stdout(out), redirect_stderr(err): - try: - command.main() - except SystemExit as exc: - code = exc.code if exc.code is not None else 0 - return int(code), out.getvalue(), err.getvalue() + with ( + patch("sys.argv", ["prog", *argv]), + redirect_stdout(out), + redirect_stderr(err), + ): + try: + command.main() + except SystemExit as exc: + code = exc.code if exc.code is not None else 0 + return int(code), out.getvalue(), err.getvalue() # If no SystemExit was raised, it succeeded return 0, out.getvalue(), err.getvalue() diff --git a/tests/unit/cli/meta/ports/suggest/test_main.py b/tests/unit/cli/meta/ports/suggest/test_main.py index 9c79b35833..d54bec8170 100644 --- a/tests/unit/cli/meta/ports/suggest/test_main.py +++ b/tests/unit/cli/meta/ports/suggest/test_main.py @@ -63,9 +63,9 @@ class TestSuggestSinglePorts(unittest.TestCase): patch.object(portsuggest, "lookup_band", return_value=None), patch.object(portsuggest, "available_categories", return_value=["http"]), patch("sys.argv", ["suggest", "--scope", "local", "--category", "metrics"]), + self.assertRaises(SystemExit) as ctx, ): - with self.assertRaises(SystemExit) as ctx: - portsuggest.main() + portsuggest.main() self.assertIn("metrics", str(ctx.exception.code)) def test_explicit_range_overrides_band(self): diff --git a/tests/unit/cli/test_inventory_manager.py b/tests/unit/cli/test_inventory_manager.py index 19f1738f95..e7c87fd9ad 100644 --- a/tests/unit/cli/test_inventory_manager.py +++ b/tests/unit/cli/test_inventory_manager.py @@ -79,11 +79,13 @@ class TestInventoryManager(unittest.TestCase): (role_dir / "vars").mkdir(parents=True) (role_dir / "vars" / "main.yml").write_text("{}", encoding="utf-8") - with patch.object(YamlHandler, "load_yaml", return_value={}): - with self.assertRaises(SystemExit): - InventoryManager( - role_dir, self.tmpdir / "inventory.yml", "pw", {} - ).load_application_id(role_dir) + with ( + patch.object(YamlHandler, "load_yaml", return_value={}), + self.assertRaises(SystemExit), + ): + InventoryManager( + role_dir, self.tmpdir / "inventory.yml", "pw", {} + ).load_application_id(role_dir) def test_generate_value_algorithms(self): """ @@ -155,14 +157,19 @@ class TestInventoryManager(unittest.TestCase): # IMPORTANT: # This unit test is NOT about transitive shared-provider resolution. - with patch.object( - InventoryManager, "resolve_schema_includes_recursive", return_value=[] + with ( + patch.object( + InventoryManager, + "resolve_schema_includes_recursive", + return_value=[], + ), + patch.object( + ValueGenerator, + "generate_value", + side_effect=lambda alg: f"GEN_{alg}", + ), ): - # Patch ValueGenerator for predictable outputs - with patch.object( - ValueGenerator, "generate_value", side_effect=lambda alg: f"GEN_{alg}" - ): - result = mgr.apply_schema() + result = mgr.apply_schema() apps = result["applications"]["testapp"] diff --git a/tests/unit/cli/validate/test_inventory_hosts.py b/tests/unit/cli/validate/test_inventory_hosts.py index 170e7cb356..7eda513361 100644 --- a/tests/unit/cli/validate/test_inventory_hosts.py +++ b/tests/unit/cli/validate/test_inventory_hosts.py @@ -23,7 +23,7 @@ class TestValidateHostKeys(unittest.TestCase): content = {"all": {"children": {}}} for group, hosts in groups.items(): # hosts is a list of hostnames - content["all"]["children"][group] = {"hosts": {h: None for h in hosts}} + content["all"]["children"][group] = {"hosts": dict.fromkeys(hosts)} path = os.path.join(self.test_dir, "devices.yml") with open(path, "w", encoding="utf-8") as f: yaml.safe_dump(content, f) diff --git a/tests/unit/plugins/filter/test_get_all_invokable_apps.py b/tests/unit/plugins/filter/test_get_all_invokable_apps.py index 4fa32cc899..96e51f7175 100644 --- a/tests/unit/plugins/filter/test_get_all_invokable_apps.py +++ b/tests/unit/plugins/filter/test_get_all_invokable_apps.py @@ -78,9 +78,11 @@ class TestGetAllInvokableApps(unittest.TestCase): with self.categories_file.open("w", encoding="utf-8") as f: yaml.safe_dump({"roles": {"foo": {"invokable": False}}}, f) - with patch("utils.invokable.PROJECT_ROOT", self.test_dir): - with self.assertRaises(RuntimeError): - get_all_invokable_apps() + with ( + patch("utils.invokable.PROJECT_ROOT", self.test_dir), + self.assertRaises(RuntimeError), + ): + get_all_invokable_apps() def test_empty_when_no_roles(self): """Should return an empty list if there are no roles, but categories.yml exists.""" @@ -106,13 +108,15 @@ class TestGetAllInvokableApps(unittest.TestCase): """ self.categories_file.unlink() - with patch("utils.invokable.PROJECT_ROOT", self.test_dir): - with patch( + with ( + patch("utils.invokable.PROJECT_ROOT", self.test_dir), + patch( "utils.invokable._get_invokable_paths", side_effect=FileNotFoundError, - ): - with self.assertRaises(FileNotFoundError): - get_all_invokable_apps() + ), + self.assertRaises(FileNotFoundError), + ): + get_all_invokable_apps() if __name__ == "__main__": diff --git a/tests/unit/plugins/filter/test_invokable_paths.py b/tests/unit/plugins/filter/test_invokable_paths.py index 98a5458c08..4601891b90 100644 --- a/tests/unit/plugins/filter/test_invokable_paths.py +++ b/tests/unit/plugins/filter/test_invokable_paths.py @@ -9,9 +9,8 @@ from plugins.filter.invokable_paths import get_invokable_paths class TestInvokablePaths(unittest.TestCase): def write_yaml(self, data): - tmp = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".yml") - yaml.dump(data, tmp) - tmp.close() + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".yml") as tmp: + yaml.dump(data, tmp) return tmp.name def test_empty_roles(self): diff --git a/tests/unit/plugins/filter/test_memory_filters.py b/tests/unit/plugins/filter/test_memory_filters.py index 2bafbeb006..2621e9531a 100644 --- a/tests/unit/plugins/filter/test_memory_filters.py +++ b/tests/unit/plugins/filter/test_memory_filters.py @@ -111,9 +111,9 @@ class TestMemoryFilters(unittest.TestCase): "8Q" if key.endswith(".mem_limit") else "4g" ), ), + self.assertRaises(memory_filters.AnsibleFilterError), ): - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.jvm_max_mb(self.apps, self.app_id) + memory_filters.jvm_max_mb(self.apps, self.app_id) def test_zero_limit_raises(self): with ( @@ -127,9 +127,9 @@ class TestMemoryFilters(unittest.TestCase): "0" if key.endswith(".mem_limit") else "4g" ), ), + self.assertRaises(memory_filters.AnsibleFilterError), ): - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.jvm_max_mb(self.apps, self.app_id) + memory_filters.jvm_max_mb(self.apps, self.app_id) def test_zero_reservation_raises(self): with ( @@ -143,9 +143,9 @@ class TestMemoryFilters(unittest.TestCase): "8g" if key.endswith(".mem_limit") else "0" ), ), + self.assertRaises(memory_filters.AnsibleFilterError), ): - with self.assertRaises(memory_filters.AnsibleFilterError): - memory_filters.jvm_min_mb(self.apps, self.app_id) + memory_filters.jvm_min_mb(self.apps, self.app_id) def test_entity_name_is_derived_not_passed(self): """ diff --git a/tests/unit/plugins/filter/test_native_metrics_target.py b/tests/unit/plugins/filter/test_native_metrics_target.py index 89cc5ad74d..7b7b0374a5 100644 --- a/tests/unit/plugins/filter/test_native_metrics_target.py +++ b/tests/unit/plugins/filter/test_native_metrics_target.py @@ -70,11 +70,14 @@ class TestNativeMetricsTargetErrors(unittest.TestCase): } } } - with patch( - "plugins.filter.native_metrics_target.get_entity_name", return_value="gitea" + with ( + patch( + "plugins.filter.native_metrics_target.get_entity_name", + return_value="gitea", + ), + self.assertRaises(AnsibleFilterError), ): - with self.assertRaises(AnsibleFilterError): - native_metrics_target("web-app-gitea", apps) + native_metrics_target("web-app-gitea", apps) def test_raises_when_port_missing(self): apps = { @@ -85,18 +88,24 @@ class TestNativeMetricsTargetErrors(unittest.TestCase): } } } - with patch( - "plugins.filter.native_metrics_target.get_entity_name", return_value="gitea" + with ( + patch( + "plugins.filter.native_metrics_target.get_entity_name", + return_value="gitea", + ), + self.assertRaises(AnsibleFilterError), ): - with self.assertRaises(AnsibleFilterError): - native_metrics_target("web-app-gitea", apps) + native_metrics_target("web-app-gitea", apps) def test_raises_when_app_not_in_applications(self): - with patch( - "plugins.filter.native_metrics_target.get_entity_name", return_value="gitea" + with ( + patch( + "plugins.filter.native_metrics_target.get_entity_name", + return_value="gitea", + ), + self.assertRaises(AnsibleFilterError), ): - with self.assertRaises(AnsibleFilterError): - native_metrics_target("web-app-gitea", {}) + native_metrics_target("web-app-gitea", {}) if __name__ == "__main__": diff --git a/tests/unit/plugins/filter/test_non_invokable_paths.py b/tests/unit/plugins/filter/test_non_invokable_paths.py index 74e42c88c4..bb18d02306 100644 --- a/tests/unit/plugins/filter/test_non_invokable_paths.py +++ b/tests/unit/plugins/filter/test_non_invokable_paths.py @@ -9,9 +9,8 @@ from plugins.filter.invokable_paths import get_non_invokable_paths class TestNonInvokablePaths(unittest.TestCase): def write_yaml(self, data): - tmp = tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".yml") - yaml.dump(data, tmp) - tmp.close() + with tempfile.NamedTemporaryFile(mode="w", delete=False, suffix=".yml") as tmp: + yaml.dump(data, tmp) return tmp.name def test_empty_roles(self): diff --git a/tests/unit/plugins/filter/test_reserved_users.py b/tests/unit/plugins/filter/test_reserved_users.py index c8007c2a52..3dd732bf28 100644 --- a/tests/unit/plugins/filter/test_reserved_users.py +++ b/tests/unit/plugins/filter/test_reserved_users.py @@ -1,8 +1,8 @@ import unittest -import reserved_users # noqa: E402 -from ansible.errors import AnsibleFilterError # type: ignore # noqa: E402 -from reserved_users import non_reserved_users, reserved_usernames # noqa: E402 +import reserved_users +from ansible.errors import AnsibleFilterError # type: ignore +from reserved_users import non_reserved_users, reserved_usernames class TestReservedUsersFilters(unittest.TestCase): diff --git a/tests/unit/plugins/filter/test_to_primary_domain.py b/tests/unit/plugins/filter/test_to_primary_domain.py index 307a471b9c..b30796a221 100644 --- a/tests/unit/plugins/filter/test_to_primary_domain.py +++ b/tests/unit/plugins/filter/test_to_primary_domain.py @@ -31,9 +31,11 @@ class TestToPrimaryDomain(unittest.TestCase): "", # empty string ] for input_domain in invalid_cases: - with self.subTest(domain=input_domain): - with self.assertRaises(AnsibleFilterError): - self.filtermod.to_primary_domain(input_domain) + with ( + self.subTest(domain=input_domain), + self.assertRaises(AnsibleFilterError), + ): + self.filtermod.to_primary_domain(input_domain) if __name__ == "__main__": diff --git a/tests/unit/plugins/lookup/test_command_path.py b/tests/unit/plugins/lookup/test_command_path.py index 94884b7697..0ef41bc347 100644 --- a/tests/unit/plugins/lookup/test_command_path.py +++ b/tests/unit/plugins/lookup/test_command_path.py @@ -37,9 +37,11 @@ class TestCommandPathLookup(unittest.TestCase): self.plugin.run(["setup-hibernate --help"]) def test_missing_command_raises(self): - with patch("plugins.lookup.command_path.shutil.which", return_value=None): - with self.assertRaises(AnsibleError): - self.plugin.run(["does-not-exist"]) + with ( + patch("plugins.lookup.command_path.shutil.which", return_value=None), + self.assertRaises(AnsibleError), + ): + self.plugin.run(["does-not-exist"]) def test_custom_path_argument_is_passed_to_which(self): with patch( diff --git a/tests/unit/plugins/lookup/test_compose_file_args.py b/tests/unit/plugins/lookup/test_compose_file_args.py index 27e7deb0d9..5e9f824be3 100644 --- a/tests/unit/plugins/lookup/test_compose_file_args.py +++ b/tests/unit/plugins/lookup/test_compose_file_args.py @@ -124,9 +124,9 @@ class TestComposeFArgs(unittest.TestCase): "get", return_value=_TlsResolveStub(True, "self_signed"), ), + self.assertRaises(AnsibleError), ): - with self.assertRaises(AnsibleError): - self.lookup.run(["web-app-a"], variables=self.vars) + self.lookup.run(["web-app-a"], variables=self.vars) def test_includes_only_base_when_role_does_not_provide_override(self): with ( @@ -158,23 +158,23 @@ class TestComposeFArgs(unittest.TestCase): # get_docker_paths returns non-dict -> must fail with ( patch.object(self.m, "get_docker_paths", return_value="nope"), + self.assertRaises(AnsibleError), ): - with self.assertRaises(AnsibleError): - self.lookup.run(["web-app-a"], variables=self.vars) + self.lookup.run(["web-app-a"], variables=self.vars) # get_docker_paths returns dict but missing files -> must fail with ( patch.object(self.m, "get_docker_paths", return_value={}), + self.assertRaises(AnsibleError), ): - with self.assertRaises(AnsibleError): - self.lookup.run(["web-app-a"], variables=self.vars) + self.lookup.run(["web-app-a"], variables=self.vars) # get_docker_paths returns dict with non-dict files -> must fail with ( patch.object(self.m, "get_docker_paths", return_value={"files": "nope"}), + self.assertRaises(AnsibleError), ): - with self.assertRaises(AnsibleError): - self.lookup.run(["web-app-a"], variables=self.vars) + self.lookup.run(["web-app-a"], variables=self.vars) if __name__ == "__main__": diff --git a/tests/unit/plugins/lookup/test_domain_lookup.py b/tests/unit/plugins/lookup/test_domain_lookup.py index 5912d42244..29d22f92d2 100644 --- a/tests/unit/plugins/lookup/test_domain_lookup.py +++ b/tests/unit/plugins/lookup/test_domain_lookup.py @@ -63,12 +63,14 @@ class TestDomainLookup(unittest.TestCase): ) def test_missing_application_id(self): - with self.assertRaises(AnsibleError): - with patch( + with ( + self.assertRaises(AnsibleError), + patch( "plugins.lookup.domain.get_merged_domains", return_value={"app": "example.com"}, - ): - self.lookup.run(terms=[], variables={}) + ), + ): + self.lookup.run(terms=[], variables={}) def test_unknown_application_id(self): with self.assertRaises(AnsibleError): @@ -87,12 +89,14 @@ class TestDomainLookup(unittest.TestCase): self.run_lookup("app", {"app": {}}) def test_invalid_application_id_type(self): - with self.assertRaises(AnsibleError): - with patch( + with ( + self.assertRaises(AnsibleError), + patch( "plugins.lookup.domain.get_merged_domains", return_value={"app": "example.com"}, - ): - self.lookup.run(terms=[123], variables={}) + ), + ): + self.lookup.run(terms=[123], variables={}) if __name__ == "__main__": diff --git a/tests/unit/plugins/lookup/test_nginx.py b/tests/unit/plugins/lookup/test_nginx.py index 520b570288..ecf50fad34 100644 --- a/tests/unit/plugins/lookup/test_nginx.py +++ b/tests/unit/plugins/lookup/test_nginx.py @@ -22,7 +22,7 @@ class _FakeTlsResolveLookup: raise AssertionError(f"Unexpected terms passed to tls: {terms}") # Legacy kwarg want must be ignored; if it appears, fail (we don't expect it anymore) - if "want" in kwargs and kwargs["want"]: + if kwargs.get("want"): raise AssertionError(f"Unexpected want kwarg passed to tls: {kwargs}") return [self._protocol] @@ -145,16 +145,18 @@ class TestNginxPathsLookup(unittest.TestCase): ) def test_invalid_protocol_override_raises(self): - with patch( - "plugins.lookup.nginx.get", - side_effect=self._fake_get, + with ( + patch( + "plugins.lookup.nginx.get", + side_effect=self._fake_get, + ), + self.assertRaises(AnsibleError), ): - with self.assertRaises(AnsibleError): - self.plugin.run( - ["files.domain", "example.com"], - variables=self.variables, - protocol="ftp", - ) + self.plugin.run( + ["files.domain", "example.com"], + variables=self.variables, + protocol="ftp", + ) def test_invalid_usage_raises(self): with patch( diff --git a/tests/unit/plugins/lookup/test_service.py b/tests/unit/plugins/lookup/test_service.py index a1577f4c3d..a800d2b271 100644 --- a/tests/unit/plugins/lookup/test_service.py +++ b/tests/unit/plugins/lookup/test_service.py @@ -257,12 +257,14 @@ class TestServiceCycleGuard(unittest.TestCase): class TestServiceErrors(unittest.TestCase): def test_raises_when_group_names_not_list(self): - with patch("plugins.lookup.service.get_merged_applications", return_value={}): - with self.assertRaises(AnsibleError): - LookupModule().run( - ["matomo"], - variables={"group_names": "not-a-list"}, - ) + with ( + patch("plugins.lookup.service.get_merged_applications", return_value={}), + self.assertRaises(AnsibleError), + ): + LookupModule().run( + ["matomo"], + variables={"group_names": "not-a-list"}, + ) def test_raises_when_term_empty(self): with self.assertRaises(AnsibleError): diff --git a/tests/unit/plugins/lookup/test_unit_name.py b/tests/unit/plugins/lookup/test_unit_name.py index 6565e5e95a..e3a571432f 100644 --- a/tests/unit/plugins/lookup/test_unit_name.py +++ b/tests/unit/plugins/lookup/test_unit_name.py @@ -45,7 +45,7 @@ class UnitNameLookupTests(unittest.TestCase): ) # The plugin calls set_options(); for unit tests we make it a no-op - lm.set_options = lambda *args, **kwargs: None # noqa: E731 + lm.set_options = lambda *args, **kwargs: None return lm @@ -105,7 +105,7 @@ class UnitNameLookupTests(unittest.TestCase): def test_missing_software_name_raises(self): lm = LookupModule() lm._templar = DummyTemplar(available_variables={}, version="1.2.3") - lm.set_options = lambda *args, **kwargs: None # noqa: E731 + lm.set_options = lambda *args, **kwargs: None with self.assertRaises(AnsibleError) as ctx: lm.run(["svc-foo"]) @@ -126,7 +126,7 @@ class UnitNameLookupTests(unittest.TestCase): }, version="2.0.0", ) - lm.set_options = lambda *args, **kwargs: None # noqa: E731 + lm.set_options = lambda *args, **kwargs: None res = lm.run(["svc-foo"]) self.assertEqual(res, ["svc-foo.2.0.0.infinito.nexus.service"]) @@ -137,7 +137,7 @@ class UnitNameLookupTests(unittest.TestCase): available_variables={"SOFTWARE_DOMAIN": "{{ UNKNOWN_VAR | lower }}"}, version="2.0.0", ) - lm.set_options = lambda *args, **kwargs: None # noqa: E731 + lm.set_options = lambda *args, **kwargs: None with self.assertRaises(AnsibleError) as ctx: lm.run(["svc-foo"]) diff --git a/tests/unit/plugins/lookup/test_users.py b/tests/unit/plugins/lookup/test_users.py index 24b4f7d497..e1bda077d4 100644 --- a/tests/unit/plugins/lookup/test_users.py +++ b/tests/unit/plugins/lookup/test_users.py @@ -325,8 +325,7 @@ class _DummyTemplar: rendered = value for key, replacement in self.available_variables.items(): rendered = rendered.replace("{{ " + key + " }}", str(replacement)) - rendered = rendered.replace("{{ 42 | strong_password }}", "strong-password-42") - return rendered + return rendered.replace("{{ 42 | strong_password }}", "strong-password-42") class _NoopTemplar: diff --git a/tests/unit/roles/sys-ctl-bkp-docker-2-loc/library/test_file_has_content.py b/tests/unit/roles/sys-ctl-bkp-docker-2-loc/library/test_file_has_content.py index f669e656b3..00abe83974 100644 --- a/tests/unit/roles/sys-ctl-bkp-docker-2-loc/library/test_file_has_content.py +++ b/tests/unit/roles/sys-ctl-bkp-docker-2-loc/library/test_file_has_content.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import importlib.util import os import tempfile @@ -105,11 +106,9 @@ class TestFileHasContentModule(unittest.TestCase): def test_missing_file_fails(self): missing = "/tmp/this-file-should-not-exist-ansible-test-12345" - try: + # Already-absent is the state this test requires; either way we proceed. + with contextlib.suppress(FileNotFoundError): os.remove(missing) - except FileNotFoundError: - # If the file is already absent, that's the state this test requires. - pass payload = self._run_expect_fail(missing) diff --git a/tests/unit/roles/sys-ctl-hlth-csp/files/test_script.py b/tests/unit/roles/sys-ctl-hlth-csp/files/test_script.py index 198a0b1ccf..7207a47cab 100644 --- a/tests/unit/roles/sys-ctl-hlth-csp/files/test_script.py +++ b/tests/unit/roles/sys-ctl-hlth-csp/files/test_script.py @@ -264,13 +264,15 @@ class TestMain(unittest.TestCase): ) -> None: mock_extract.return_value = None - with patch.object( - script.sys, - "argv", - ["script.py", "--nginx-config-dir", "/missing", "--image", "img:tag"], + with ( + patch.object( + script.sys, + "argv", + ["script.py", "--nginx-config-dir", "/missing", "--image", "img:tag"], + ), + self.assertRaises(SystemExit) as cm, ): - with self.assertRaises(SystemExit) as cm: - script.main() + script.main() self.assertEqual(cm.exception.code, 1) mock_run_checker.assert_not_called() @@ -284,13 +286,15 @@ class TestMain(unittest.TestCase): ) -> None: mock_extract.return_value = [] - with patch.object( - script.sys, - "argv", - ["script.py", "--nginx-config-dir", "/etc/nginx", "--image", "img:tag"], + with ( + patch.object( + script.sys, + "argv", + ["script.py", "--nginx-config-dir", "/etc/nginx", "--image", "img:tag"], + ), + self.assertRaises(SystemExit) as cm, ): - with self.assertRaises(SystemExit) as cm: - script.main() + script.main() self.assertEqual(cm.exception.code, 0) mock_run_checker.assert_not_called() @@ -311,23 +315,25 @@ class TestMain(unittest.TestCase): ] mock_run_checker.return_value = 5 - with patch.object( - script.sys, - "argv", - [ - "script.py", - "--nginx-config-dir", - "/etc/nginx", - "--image", - "img:tag", - "--short", - "--ignore-network-blocks-from", - "pxscdn.com", - "cdn.example.org", - ], + with ( + patch.object( + script.sys, + "argv", + [ + "script.py", + "--nginx-config-dir", + "/etc/nginx", + "--image", + "img:tag", + "--short", + "--ignore-network-blocks-from", + "pxscdn.com", + "cdn.example.org", + ], + ), + self.assertRaises(SystemExit) as cm, ): - with self.assertRaises(SystemExit) as cm: - script.main() + script.main() self.assertEqual(cm.exception.code, 5) @@ -357,20 +363,22 @@ class TestMain(unittest.TestCase): mock_build_urls.return_value = ["http://example.com/"] mock_run_checker.return_value = 0 - with patch.object( - script.sys, - "argv", - [ - "script.py", - "--nginx-config-dir", - "/etc/nginx", - "--image", - "img:tag", - "--no-host-network", - ], + with ( + patch.object( + script.sys, + "argv", + [ + "script.py", + "--nginx-config-dir", + "/etc/nginx", + "--image", + "img:tag", + "--no-host-network", + ], + ), + self.assertRaises(SystemExit) as cm, ): - with self.assertRaises(SystemExit) as cm: - script.main() + script.main() self.assertEqual(cm.exception.code, 0) @@ -389,13 +397,15 @@ class TestMain(unittest.TestCase): mock_extract.return_value = ["example.com"] mock_build_urls.return_value = [] - with patch.object( - script.sys, - "argv", - ["script.py", "--nginx-config-dir", "/etc/nginx", "--image", "img:tag"], + with ( + patch.object( + script.sys, + "argv", + ["script.py", "--nginx-config-dir", "/etc/nginx", "--image", "img:tag"], + ), + self.assertRaises(SystemExit) as cm, ): - with self.assertRaises(SystemExit) as cm: - script.main() + script.main() self.assertEqual(cm.exception.code, 0) mock_run_checker.assert_not_called() diff --git a/tests/unit/roles/sys-ctl-hlth-disc-space/files/test_script.py b/tests/unit/roles/sys-ctl-hlth-disc-space/files/test_script.py index 3797fee5fc..b67124149e 100644 --- a/tests/unit/roles/sys-ctl-hlth-disc-space/files/test_script.py +++ b/tests/unit/roles/sys-ctl-hlth-disc-space/files/test_script.py @@ -53,14 +53,16 @@ class TestDiskSpaceScript(TestCase): return df_print_cp raise AssertionError(f"Unexpected subprocess.run args: {args}") - with mock.patch.object(SCRIPT_MODULE.subprocess, "run", side_effect=fake_run): - with mock.patch.object(sys, "argv", ["script.py", "80"]): - with mock.patch.object( - SCRIPT_MODULE.sys, "exit", side_effect=SystemExit - ) as mock_exit: - with contextlib.redirect_stdout(io.StringIO()): - with self.assertRaises(SystemExit): - SCRIPT_MODULE.main() + with ( + mock.patch.object(SCRIPT_MODULE.subprocess, "run", side_effect=fake_run), + mock.patch.object(sys, "argv", ["script.py", "80"]), + mock.patch.object( + SCRIPT_MODULE.sys, "exit", side_effect=SystemExit + ) as mock_exit, + contextlib.redirect_stdout(io.StringIO()), + self.assertRaises(SystemExit), + ): + SCRIPT_MODULE.main() mock_exit.assert_called_once_with(0) @@ -75,15 +77,16 @@ class TestDiskSpaceScript(TestCase): return df_print_cp raise AssertionError(f"Unexpected subprocess.run args: {args}") - with mock.patch.object(SCRIPT_MODULE.subprocess, "run", side_effect=fake_run): - with mock.patch.object(sys, "argv", ["script.py", "80"]): - with mock.patch.object( - SCRIPT_MODULE.sys, "exit", side_effect=SystemExit - ) as mock_exit: - buffer = io.StringIO() - with contextlib.redirect_stdout(buffer): - with self.assertRaises(SystemExit): - SCRIPT_MODULE.main() + with ( + mock.patch.object(SCRIPT_MODULE.subprocess, "run", side_effect=fake_run), + mock.patch.object(sys, "argv", ["script.py", "80"]), + mock.patch.object( + SCRIPT_MODULE.sys, "exit", side_effect=SystemExit + ) as mock_exit, + ): + buffer = io.StringIO() + with contextlib.redirect_stdout(buffer), self.assertRaises(SystemExit): + SCRIPT_MODULE.main() mock_exit.assert_called_once_with(2) diff --git a/tests/unit/roles/sys-svc-compose-ca/files/test_compose_ca.py b/tests/unit/roles/sys-svc-compose-ca/files/test_compose_ca.py index d6c78e9bd5..913bdaed02 100644 --- a/tests/unit/roles/sys-svc-compose-ca/files/test_compose_ca.py +++ b/tests/unit/roles/sys-svc-compose-ca/files/test_compose_ca.py @@ -339,9 +339,8 @@ class TestComposeCaInject(unittest.TestCase): "/etc/infinito/bin/with-ca-trust.sh", # missing: --trust-name ] - with patch("sys.argv", argv): - with self.assertRaises(SystemExit): - self.m.main() + with patch("sys.argv", argv), self.assertRaises(SystemExit): + self.m.main() def test_docker_image_has_bin_sh_true(self): """ diff --git a/tests/unit/roles/sys-svc-compose/files/test_compose.py b/tests/unit/roles/sys-svc-compose/files/test_compose.py index 626a7adce7..2717f1008d 100644 --- a/tests/unit/roles/sys-svc-compose/files/test_compose.py +++ b/tests/unit/roles/sys-svc-compose/files/test_compose.py @@ -83,9 +83,7 @@ class TestInfinitoComposeWrapper(unittest.TestCase): return True if str(self) == "/proj/compose.override.yml": return True - if str(self) == "/proj/compose.ca.override.yml": - return True - return False + return str(self) == "/proj/compose.ca.override.yml" s.Path.is_file = fake_is_file # type: ignore[assignment] files = s.detect_compose_files(base) @@ -116,9 +114,7 @@ class TestInfinitoComposeWrapper(unittest.TestCase): return False if str(self) == "/proj/.env": return True - if str(self) == "/proj/.env/env": - return True - return False + return str(self) == "/proj/.env/env" s.Path.is_file = fake_is_file # type: ignore[assignment] # Signature changed to accept extra_files=None, but default keeps old call valid. @@ -410,7 +406,7 @@ class TestInfinitoComposeWrapper(unittest.TestCase): list(passthrough), extra_files, ) - return ["docker", "compose", "-p", project] + list(passthrough) + return ["docker", "compose", "-p", project, *list(passthrough)] def fake_execvp(prog, argv): raise RuntimeError("execvp called") diff --git a/tests/unit/roles/sys-svc-compose/files/test_pull.py b/tests/unit/roles/sys-svc-compose/files/test_pull.py index f37663f448..f7d14fbd6a 100644 --- a/tests/unit/roles/sys-svc-compose/files/test_pull.py +++ b/tests/unit/roles/sys-svc-compose/files/test_pull.py @@ -87,11 +87,13 @@ services: ) def test_run_or_fail_failure_raises(self) -> None: - with patch.object(self.m, "run_cmd", return_value=(9, "boom\n")): - with self.assertRaises(RuntimeError) as ctx: - self.m.run_or_fail( - ["docker", "compose", "pull"], cwd=Path("/"), env={}, label="pull" - ) + with ( + patch.object(self.m, "run_cmd", return_value=(9, "boom\n")), + self.assertRaises(RuntimeError) as ctx, + ): + self.m.run_or_fail( + ["docker", "compose", "pull"], cwd=Path("/"), env={}, label="pull" + ) self.assertIn("pull failed", str(ctx.exception)) def test_main_short_circuits_when_lock_exists(self) -> None: @@ -195,8 +197,8 @@ services: ) # Expect two calls: build --pull, then pull --ignore-buildable - self.assertEqual(calls[0], base_cmd + ["build", "--pull"]) - self.assertEqual(calls[1], base_cmd + ["pull", "--ignore-buildable"]) + self.assertEqual(calls[0], [*base_cmd, "build", "--pull"]) + self.assertEqual(calls[1], [*base_cmd, "pull", "--ignore-buildable"]) def test_main_pull_omits_ignore_buildable_when_not_supported(self) -> None: with tempfile.TemporaryDirectory() as td: @@ -248,7 +250,7 @@ services: self.assertEqual(rc, 0) self.assertEqual(len(calls), 1) - self.assertEqual(calls[0], base_cmd + ["pull"]) + self.assertEqual(calls[0], [*base_cmd, "pull"]) if __name__ == "__main__": diff --git a/tests/unit/roles/sys-svc-compose/lookup_plugins/test_compose_ca_inject_cmd.py b/tests/unit/roles/sys-svc-compose/lookup_plugins/test_compose_ca_inject_cmd.py index f6c2785300..9c39e00dbd 100644 --- a/tests/unit/roles/sys-svc-compose/lookup_plugins/test_compose_ca_inject_cmd.py +++ b/tests/unit/roles/sys-svc-compose/lookup_plugins/test_compose_ca_inject_cmd.py @@ -49,7 +49,7 @@ class _FakeComposeFArgsLookup: def run(self, terms, variables=None, **kwargs): self.calls.append({"terms": terms, "kwargs": kwargs}) - if kwargs.get("include_ca", None) is not False: + if kwargs.get("include_ca") is not False: raise AnsibleError( "Fake compose_file_args lookup: expected include_ca=False" ) @@ -226,9 +226,9 @@ class ComposeCaInjectCmdLookupTests(unittest.TestCase): self.mod, "render_ansible_strict", side_effect=lambda **kw: kw["raw"] ), patch.object(self.mod, "get_entity_name", side_effect=lambda _x: "myproj"), + self.assertRaises(AnsibleError) as ctx, ): - with self.assertRaises(AnsibleError) as ctx: - lk.run(["web-app-test"], variables=variables) + lk.run(["web-app-test"], variables=variables) self.assertIn("missing required variable 'CA_TRUST'", str(ctx.exception)) diff --git a/tests/unit/roles/test-e2e-playwright/test_service_gating_helper.py b/tests/unit/roles/test-e2e-playwright/test_service_gating_helper.py index caa56c3fc6..1cecaf40d8 100644 --- a/tests/unit/roles/test-e2e-playwright/test_service_gating_helper.py +++ b/tests/unit/roles/test-e2e-playwright/test_service_gating_helper.py @@ -91,7 +91,7 @@ class TestServiceGatingHelper(unittest.TestCase): script_path = os.path.join(self.tmpdir, "run.js") with open(script_path, "w") as f: f.write(script) - proc = subprocess.run( + return subprocess.run( ["node", "run.js"], capture_output=True, text=True, @@ -99,7 +99,6 @@ class TestServiceGatingHelper(unittest.TestCase): cwd=self.tmpdir, timeout=10, ) - return proc # isServiceEnabled ----------------------------------------------------- diff --git a/tests/unit/roles/web-app-bigbluebutton/filter_plugins/test_compose_mods.py b/tests/unit/roles/web-app-bigbluebutton/filter_plugins/test_compose_mods.py index 0d81774a40..527e9e87c2 100644 --- a/tests/unit/roles/web-app-bigbluebutton/filter_plugins/test_compose_mods.py +++ b/tests/unit/roles/web-app-bigbluebutton/filter_plugins/test_compose_mods.py @@ -20,10 +20,9 @@ from compose_mods import compose_mods def sort_dict(obj): if isinstance(obj, dict): return {k: sort_dict(obj[k]) for k in sorted(obj)} - elif isinstance(obj, list): + if isinstance(obj, list): return [sort_dict(v) for v in obj] - else: - return obj + return obj class TestComposeModsFullFile(unittest.TestCase): diff --git a/tests/unit/roles/web-app-dashboard/filter_plugins/test_simpleicons_source.py b/tests/unit/roles/web-app-dashboard/filter_plugins/test_simpleicons_source.py index 3234c8f840..b2ce4bf64e 100644 --- a/tests/unit/roles/web-app-dashboard/filter_plugins/test_simpleicons_source.py +++ b/tests/unit/roles/web-app-dashboard/filter_plugins/test_simpleicons_source.py @@ -37,11 +37,11 @@ add_simpleicon_source = _simpleicons.add_simpleicon_source class TestGetRequestsVerify(unittest.TestCase): def test_uses_explicit_requests_ca_bundle_when_present(self): - with tempfile.NamedTemporaryFile() as handle: - with patch.dict( - os.environ, {"REQUESTS_CA_BUNDLE": handle.name}, clear=False - ): - self.assertEqual(get_requests_verify(), handle.name) + with ( + tempfile.NamedTemporaryFile() as handle, + patch.dict(os.environ, {"REQUESTS_CA_BUNDLE": handle.name}, clear=False), + ): + self.assertEqual(get_requests_verify(), handle.name) def test_falls_back_to_certifi_bundle_when_no_env_ca_exists(self): with patch.dict( diff --git a/tests/unit/utils/annotations/test_summarize.py b/tests/unit/utils/annotations/test_summarize.py index 1e09f63920..a15bf3b6cc 100644 --- a/tests/unit/utils/annotations/test_summarize.py +++ b/tests/unit/utils/annotations/test_summarize.py @@ -33,9 +33,8 @@ class TestParseProps(unittest.TestCase): class TestParseLog(unittest.TestCase): def _write_log(self, content: str) -> Path: - f = tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) - f.write(content) - f.close() + with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f: + f.write(content) return Path(f.name) def test_parses_warning(self) -> None: diff --git a/tests/unit/utils/cache/test_variants.py b/tests/unit/utils/cache/test_variants.py index bdf9acbf7a..d4afb0bbda 100644 --- a/tests/unit/utils/cache/test_variants.py +++ b/tests/unit/utils/cache/test_variants.py @@ -13,8 +13,8 @@ from . import PROJECT_ROOT if str(PROJECT_ROOT) not in sys.path: sys.path.insert(0, str(PROJECT_ROOT)) -from utils.cache import _reset_cache_for_tests # noqa: E402 -from utils.cache.applications import ( # noqa: E402 +from utils.cache import _reset_cache_for_tests +from utils.cache.applications import ( _build_variants, get_application_defaults, get_merged_applications, @@ -79,10 +79,8 @@ class TestLoadYamlVariantList(unittest.TestCase): def _write_tmp(self, content: str) -> str: import tempfile - f = tempfile.NamedTemporaryFile("w", suffix=".yml", delete=False) - f.write(content) - f.flush() - f.close() + with tempfile.NamedTemporaryFile("w", suffix=".yml", delete=False) as f: + f.write(content) self.addCleanup(os.remove, f.name) return f.name diff --git a/tests/unit/utils/domains/test_list.py b/tests/unit/utils/domains/test_list.py index 8052b33f6a..ef50fad840 100644 --- a/tests/unit/utils/domains/test_list.py +++ b/tests/unit/utils/domains/test_list.py @@ -139,9 +139,11 @@ class TestDomainList(unittest.TestCase): self.write_role(roles_dir, "app-a", "app-a", shared_config) self.write_role(roles_dir, "app-b", "app-b", shared_config) - with patch.object(domain_list, "ROLES_DIR", roles_dir): - with self.assertRaises(AnsibleError): - domain_list.list_application_domains("infinito.example") + with ( + patch.object(domain_list, "ROLES_DIR", roles_dir), + self.assertRaises(AnsibleError), + ): + domain_list.list_application_domains("infinito.example") if __name__ == "__main__": diff --git a/tests/unit/utils/roles/test_resource_validation.py b/tests/unit/utils/roles/test_resource_validation.py index 7b349ed528..a1a1b22cd8 100644 --- a/tests/unit/utils/roles/test_resource_validation.py +++ b/tests/unit/utils/roles/test_resource_validation.py @@ -224,13 +224,15 @@ demo: self.assertIn("Invalid min_storage value", err.getvalue()) def test_invalid_required_storage_raises_value_error(self) -> None: - with patch.object(rrv, "_roles_root", return_value=self.roles_root): - with self.assertRaises(ValueError): - rrv.filter_roles_by_min_storage( - role_names=["web-app-demo"], - required_storage="not-a-size", - emit_warnings=False, - ) + with ( + patch.object(rrv, "_roles_root", return_value=self.roles_root), + self.assertRaises(ValueError), + ): + rrv.filter_roles_by_min_storage( + role_names=["web-app-demo"], + required_storage="not-a-size", + emit_warnings=False, + ) def test_entity_name_missing_emits_warning_and_skips(self) -> None: self._write_role_config( diff --git a/tests/unit/utils/test_invokable.py b/tests/unit/utils/test_invokable.py index d7914d410f..546a8f1cea 100644 --- a/tests/unit/utils/test_invokable.py +++ b/tests/unit/utils/test_invokable.py @@ -51,13 +51,15 @@ class TestInvokable(TestCase): shutil.rmtree(self.tmp) def test_list_invokable_app_ids(self) -> None: - with patch.object(inv, "PROJECT_ROOT", self.tmp): - with patch.object( + with ( + patch.object(inv, "PROJECT_ROOT", self.tmp), + patch.object( inv, "_get_invokable_paths", return_value=["web-app", "update", "util-desk"], - ): - got = inv.list_invokable_app_ids() + ), + ): + got = inv.list_invokable_app_ids() self.assertEqual( got, @@ -65,13 +67,15 @@ class TestInvokable(TestCase): ) def test_list_invokables_by_type(self) -> None: - with patch.object(inv, "PROJECT_ROOT", self.tmp): - with patch.object( + with ( + patch.object(inv, "PROJECT_ROOT", self.tmp), + patch.object( inv, "_get_invokable_paths", return_value=["web-app", "update", "util-desk"], - ): - grouped = inv.list_invokables_by_type() + ), + ): + grouped = inv.list_invokables_by_type() # server: web-app-* minus excluded oauth2 proxy (not present in test) self.assertIn("server", grouped) @@ -91,32 +95,36 @@ class TestInvokable(TestCase): with (rd / "vars" / "main.yml").open("w", encoding="utf-8") as f: yaml.safe_dump({}, f) - with patch.object(inv, "PROJECT_ROOT", self.tmp): - with patch.object( + with ( + patch.object(inv, "PROJECT_ROOT", self.tmp), + patch.object( inv, "_get_invokable_paths", return_value=["web-app", "update", "util-desk"], - ): - grouped = inv.list_invokables_by_type() + ), + ): + grouped = inv.list_invokables_by_type() self.assertNotIn("web-app-oauth2-proxy", grouped["server"]) def test_types_from_group_names(self) -> None: - with patch.object(inv, "PROJECT_ROOT", self.tmp): - with patch.object( + with ( + patch.object(inv, "PROJECT_ROOT", self.tmp), + patch.object( inv, "_get_invokable_paths", return_value=["web-app", "update", "util-desk"], - ): - got = inv.types_from_group_names( - [ - "all", # not invokable -> ignored - "web-app-nextcloud", # invokable + matches server rule - "util-desk-custom", # invokable + matches workstation rule - "update", # invokable leftover -> universal - "foo", # not invokable -> ignored - ] - ) + ), + ): + got = inv.types_from_group_names( + [ + "all", # not invokable -> ignored + "web-app-nextcloud", # invokable + matches server rule + "util-desk-custom", # invokable + matches workstation rule + "update", # invokable leftover -> universal + "foo", # not invokable -> ignored + ] + ) self.assertEqual(got, ["server", "universal", "workstation"]) diff --git a/tests/unit/utils/test_templating.py b/tests/unit/utils/test_templating.py index 4f915c5208..e6f441d699 100644 --- a/tests/unit/utils/test_templating.py +++ b/tests/unit/utils/test_templating.py @@ -2,7 +2,7 @@ import os # Ensure repo root is importable so `utils.*` resolves in all runners -import sys # noqa: E402 +import sys import unittest from unittest.mock import patch @@ -10,9 +10,9 @@ from ansible.errors import AnsibleError from . import PROJECT_ROOT -sys.path.insert(0, str(PROJECT_ROOT)) # noqa: E402 +sys.path.insert(0, str(PROJECT_ROOT)) -from utils.templating import ( # noqa: E402 +from utils.templating import ( render_ansible_strict, ) diff --git a/utils/annotations/suppress.py b/utils/annotations/suppress.py index fa205fa6e7..1f71504d95 100644 --- a/utils/annotations/suppress.py +++ b/utils/annotations/suppress.py @@ -117,10 +117,7 @@ def is_suppressed_in_head( the file so the cost of carrying the exemption stays visible. """ rule = rule.lower() - for line in lines[:scan_lines]: - if line_has_rule(line, rule): - return True - return False + return any(line_has_rule(line, rule) for line in lines[:scan_lines]) def is_suppressed_anywhere(lines: Sequence[str], rule: str) -> bool: diff --git a/utils/applications/config.py b/utils/applications/config.py index 0c9fa99105..3f157bfb18 100644 --- a/utils/applications/config.py +++ b/utils/applications/config.py @@ -20,16 +20,12 @@ class AppConfigKeyError(AnsibleFilterError, ValueError): Compatible with Ansible error handling and Python ValueError. """ - pass - class ConfigEntryNotSetError(AppConfigKeyError): """ Raised when a config entry is defined in schema but not set in application. """ - pass - def get( applications, @@ -98,7 +94,7 @@ def get( raise AppConfigKeyError( f"Key '{k}' not found in dict at '{key}'\n" f"Full path so far: {'.'.join(path_trace)}\n" - f"Current object: {repr(obj)}\n" + f"Current object: {obj!r}\n" f"application_id: {application_id}\n" f"config_path: {config_path}" ) @@ -109,7 +105,7 @@ def get( raise AppConfigKeyError( f"Expected dict for '{k}', got {type(obj).__name__} at '{key}'\n" f"Full path so far: {'.'.join(path_trace)}\n" - f"Current object: {repr(obj)}\n" + f"Current object: {obj!r}\n" f"application_id: {application_id}\n" f"config_path: {config_path}" ) @@ -122,7 +118,7 @@ def get( raise AppConfigKeyError( f"Expected list for '{k}[{idx}]', got {type(obj).__name__}\n" f"Full path so far: {'.'.join(path_trace)}\n" - f"Current object: {repr(obj)}\n" + f"Current object: {obj!r}\n" f"application_id: {application_id}\n" f"config_path: {config_path}" ) @@ -133,7 +129,7 @@ def get( raise AppConfigKeyError( f"Index {i} out of range for list at '{k}'\n" f"Full path so far: {'.'.join(path_trace)}\n" - f"Current object: {repr(obj)}\n" + f"Current object: {obj!r}\n" f"application_id: {application_id}\n" f"config_path: {config_path}" ) @@ -141,7 +137,7 @@ def get( return obj # Begin traversal - path_trace = [f"applications[{repr(application_id)}]"] + path_trace = [f"applications[{application_id!r}]"] try: obj = applications[application_id] except KeyError: diff --git a/utils/cache/applications.py b/utils/cache/applications.py index b4257575a3..052adb2046 100644 --- a/utils/cache/applications.py +++ b/utils/cache/applications.py @@ -99,9 +99,7 @@ def _has_application_metadata(role_dir: Path) -> bool: return True if (meta_dir / "schema.yml").is_file(): return True - if (meta_dir / "users.yml").is_file(): - return True - return False + return bool((meta_dir / "users.yml").is_file()) def _build_role_base_config( diff --git a/utils/cache/files.py b/utils/cache/files.py index 504d94e359..f313f3c2b7 100644 --- a/utils/cache/files.py +++ b/utils/cache/files.py @@ -64,8 +64,7 @@ def _all_project_files() -> tuple[str, ...]: for dirpath, dirnames, filenames in os.walk(root_str, topdown=True): # prune in-place (topdown=True): stops descent into skipped dirs dirnames[:] = [d for d in dirnames if d not in _DEFAULT_SKIP_DIRS] - for fn in filenames: - paths.append(os.path.join(dirpath, fn)) + paths.extend(os.path.join(dirpath, fn) for fn in filenames) return tuple(paths) diff --git a/utils/cache/gitignore.py b/utils/cache/gitignore.py index 93eeb4245c..ae03ff6d69 100644 --- a/utils/cache/gitignore.py +++ b/utils/cache/gitignore.py @@ -50,7 +50,7 @@ def load_gitignore_patterns(root: str | None = None) -> tuple[str, ...]: patterns: list[str] = [] for raw in gitignore.read_text(encoding="utf-8").splitlines(): line = raw.strip() - if not line or line.startswith("#") or line.startswith("!"): + if not line or line.startswith(("#", "!")): continue patterns.append(line) return tuple(patterns) diff --git a/utils/cache/users.py b/utils/cache/users.py index dc95c07ccd..bd49a6cfa0 100644 --- a/utils/cache/users.py +++ b/utils/cache/users.py @@ -279,8 +279,7 @@ def _materialize_builtin_user_aliases( if "://" in text: parsed = urlparse(text) text = parsed.hostname or text - text = text.split("/", 1)[0].split(":", 1)[0].strip() - return text + return text.split("/", 1)[0].split(":", 1)[0].strip() def _to_primary_domain(value: Any) -> str: text = _normalize_domain_candidate(value) diff --git a/utils/cert_utils.py b/utils/cert_utils.py index ce96f49efa..476c4c4082 100644 --- a/utils/cert_utils.py +++ b/utils/cert_utils.py @@ -13,11 +13,10 @@ class CertUtils: @staticmethod def run_openssl(cert_path): try: - output = subprocess.check_output( + return subprocess.check_output( ["openssl", "x509", "-in", cert_path, "-noout", "-text"], universal_newlines=True, ) - return output except subprocess.CalledProcessError: return "" @@ -90,11 +89,10 @@ class CertUtils: # Wildcard matches ONLY one additional label if domain == base: return False - if domain.endswith("." + base) and domain.count(".") == base.count(".") + 1: - return True - return False - else: - return domain == san + return bool( + domain.endswith("." + base) and domain.count(".") == base.count(".") + 1 + ) + return domain == san @classmethod def build_snapshot(cls, cert_base_path): @@ -197,8 +195,7 @@ class CertUtils: if not entries: return None # newest by (not_before, mtime) - best = max(entries, key=cls._score_entry) - return best + return max(entries, key=cls._score_entry) best_exact = _pick_newest(candidates_exact) best_wild = _pick_newest(candidates_wild) diff --git a/utils/docker/image/discovery.py b/utils/docker/image/discovery.py index b34c00f2da..60e25c0190 100644 --- a/utils/docker/image/discovery.py +++ b/utils/docker/image/discovery.py @@ -13,7 +13,8 @@ DOCKER_HUB_PREFIXES = ( ) # All registry hostname prefixes that are stripped when building the canonical name. -_ALL_REGISTRY_PREFIXES = DOCKER_HUB_PREFIXES + ( +_ALL_REGISTRY_PREFIXES = ( + *DOCKER_HUB_PREFIXES, "quay.io/", "ghcr.io/", "mcr.microsoft.com/", diff --git a/utils/handler/vault.py b/utils/handler/vault.py index fcdbd6d598..1670065af9 100644 --- a/utils/handler/vault.py +++ b/utils/handler/vault.py @@ -8,8 +8,6 @@ from yaml.loader import SafeLoader class VaultScalar(str): """A subclass of str to represent vault-encrypted strings.""" - pass - def _vault_constructor(loader, node): """Custom constructor to handle !vault tag as plain text.""" diff --git a/utils/invokable.py b/utils/invokable.py index 68da30699d..1867704cc4 100644 --- a/utils/invokable.py +++ b/utils/invokable.py @@ -79,10 +79,7 @@ def _get_invokable_paths() -> list[str]: def _is_role_invokable(role_name: str, invokable_paths: Iterable[str]) -> bool: # Matches your existing logic: # role == p or role.startswith(p + "-") - for p in invokable_paths: - if role_name == p or role_name.startswith(p + "-"): - return True - return False + return any(role_name == p or role_name.startswith(p + "-") for p in invokable_paths) def _role_to_app_id(role_dir: Path) -> str: @@ -105,11 +102,13 @@ def list_invokable_app_ids() -> list[str]: return [] result: list[str] = [] - for role_dir in sorted( - [p for p in roles_dir.iterdir() if p.is_dir()], key=lambda p: p.name - ): - if _is_role_invokable(role_dir.name, invokable_paths): - result.append(_role_to_app_id(role_dir)) + result.extend( + _role_to_app_id(role_dir) + for role_dir in sorted( + [p for p in roles_dir.iterdir() if p.is_dir()], key=lambda p: p.name + ) + if _is_role_invokable(role_dir.name, invokable_paths) + ) return sorted(set(result)) @@ -117,9 +116,7 @@ def list_invokable_app_ids() -> list[str]: def _rule_matches_role_name(rule: DeploymentTypeRule, role_name: str) -> bool: if not rule.include_re.search(role_name): return False - if rule.exclude_re and rule.exclude_re.search(role_name): - return False - return True + return not (rule.exclude_re and rule.exclude_re.search(role_name)) def list_invokables_by_type( diff --git a/utils/manager/inventory.py b/utils/manager/inventory.py index 68e9c0d3be..8fd2bc531a 100644 --- a/utils/manager/inventory.py +++ b/utils/manager/inventory.py @@ -130,9 +130,11 @@ class InventoryManager: resolved.append(role_name) cfg = self.load_role_config(role_name) - for inc in self._direct_schema_includes_from_config(cfg): - if inc not in seen: - queue.append(inc) + queue.extend( + inc + for inc in self._direct_schema_includes_from_config(cfg) + if inc not in seen + ) return resolved diff --git a/utils/manager/value_generator.py b/utils/manager/value_generator.py index 7e91d0deb8..0e8192b9f6 100644 --- a/utils/manager/value_generator.py +++ b/utils/manager/value_generator.py @@ -70,10 +70,9 @@ class ValueGenerator: pw = secrets.token_urlsafe(16).encode() raw_hash = bcrypt.hashpw(pw, bcrypt.gensalt()).decode() alnum = string.digits + string.ascii_lowercase - escaped = "".join( + return "".join( secrets.choice(alnum) if ch == "$" else ch for ch in raw_hash ) - return escaped if algorithm == "alphanumeric": return self.generate_secure_alphanumeric(64) if algorithm == "base64_prefixed_32": diff --git a/utils/roles/dependency_resolver.py b/utils/roles/dependency_resolver.py index fb2544baaa..f184a3dc83 100644 --- a/utils/roles/dependency_resolver.py +++ b/utils/roles/dependency_resolver.py @@ -97,9 +97,9 @@ class RoleDependencyResolver: candidates = [] for root, _, files in os.walk(tasks_dir): - for f in files: - if f.endswith(".yml") or f.endswith(".yaml"): - candidates.append(os.path.join(root, f)) + candidates.extend( + os.path.join(root, f) for f in files if f.endswith((".yml", ".yaml")) + ) from utils.cache.yaml import load_yaml_any @@ -199,13 +199,16 @@ class RoleDependencyResolver: if isinstance(item, dict): for k in ("role", "name"): v = item.get(k) - if isinstance(v, str) and v.strip(): - if ( + if ( + isinstance(v, str) + and v.strip() + and ( tmpl in (f"{{{{ item.{k} }}}}", f"{{{{item.{k}}}}}") or not tmpl or "item" in tmpl - ): - return v.strip() + ) + ): + return v.strip() return None def _match_glob_into(self, pattern: str, all_roles: Iterable[str], out: set[str]): diff --git a/utils/service_registry.py b/utils/service_registry.py index d81758e953..ad9fde84a2 100644 --- a/utils/service_registry.py +++ b/utils/service_registry.py @@ -40,9 +40,7 @@ def is_explicit_truth(value: Any) -> bool: """ if value is True: return True - if isinstance(value, str) and "in group_names" in value: - return True - return False + return bool(isinstance(value, str) and "in group_names" in value) def detect_service_channel(role_name: str) -> str: @@ -350,7 +348,7 @@ def ordered_primary_service_entries( continue graph: dict[str, list[str]] = {role_name: [] for role_name in roles_in_bucket} - indegree: dict[str, int] = {role_name: 0 for role_name in roles_in_bucket} + indegree: dict[str, int] = dict.fromkeys(roles_in_bucket, 0) for role_name in roles_in_bucket: current = primary_entries[role_name] diff --git a/utils/templating.py b/utils/templating.py index 579cf81a76..a95ae4fa81 100644 --- a/utils/templating.py +++ b/utils/templating.py @@ -1,6 +1,7 @@ # utils/templating.py from __future__ import annotations +import contextlib import os import posixpath import re @@ -320,25 +321,18 @@ def _templar_render_best_effort(templar: Any, s: str, variables: dict) -> str: # If templar is present but fails unexpectedly, fall back to safe subset below. rendered = s finally: + # Best-effort cleanup: failure to restore any of the templar + # attributes is intentionally ignored. if prev_avail is not None and hasattr(templar, "available_variables"): - try: + with contextlib.suppress(Exception): templar.available_variables = prev_avail - except Exception: - # Best-effort cleanup: failure to restore available_variables is ignored. - pass if disable_changed_2: - try: + with contextlib.suppress(Exception): templar._disable_lookups = prev_disable_2 - except Exception: - # Best-effort cleanup: failure to restore _disable_lookups is ignored. - pass if disable_changed_1: - try: + with contextlib.suppress(Exception): templar.disable_lookups = prev_disable_1 - except Exception: - # Best-effort cleanup: failure to restore disable_lookups is ignored. - pass # Normalize to string (templar may return None) out_s = "" if rendered is None else str(rendered) diff --git a/utils/tls_common.py b/utils/tls_common.py index 047d3afb07..6cd7fd5e57 100644 --- a/utils/tls_common.py +++ b/utils/tls_common.py @@ -107,9 +107,9 @@ def resolve_app_id_from_domain(domains: dict, domain: str, *, err_prefix: str) - matches: list[str] = [] for app_id, val in domains.items(): - for d in iter_domains(val): - if norm_domain(d) == needle: - matches.append(str(app_id)) + matches.extend( + str(app_id) for d in iter_domains(val) if norm_domain(d) == needle + ) if not matches: raise AnsibleError( @@ -175,7 +175,7 @@ def collect_domains_for_app( def collect_domains_global(domains: dict) -> list[str]: all_items: list[str] = [] - for _, val in domains.items(): + for val in domains.values(): all_items.extend(list(iter_domains(val))) return uniq_preserve(all_items)