diff --git a/cli/administration/deploy/ci/gh.py b/cli/administration/deploy/ci/gh.py index 7620d7b682..be140be945 100644 --- a/cli/administration/deploy/ci/gh.py +++ b/cli/administration/deploy/ci/gh.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import json import re import subprocess @@ -32,21 +33,17 @@ def _run(args: list[str]) -> str: def _branch_remote() -> str: """The remote the current branch tracks (e.g. a fork), falling back to ``remote.pushDefault``, then 'origin' or the only configured remote.""" - try: + with contextlib.suppress(subprocess.CalledProcessError): upstream = _run( ["git", "rev-parse", "--abbrev-ref", "--symbolic-full-name", "@{upstream}"] ) if "/" in upstream: return upstream.split("/", 1)[0] - except subprocess.CalledProcessError: - pass remotes = _run(["git", "remote"]).split() - try: + with contextlib.suppress(subprocess.CalledProcessError): push_default = _run(["git", "config", "--get", "remote.pushDefault"]) if push_default in remotes: return push_default - except subprocess.CalledProcessError: - pass if "origin" in remotes: return "origin" if not remotes: diff --git a/cli/administration/deploy/container/__init__.py b/cli/administration/deploy/container/__init__.py index d2b646e40a..9cf3feab47 100644 --- a/cli/administration/deploy/container/__init__.py +++ b/cli/administration/deploy/container/__init__.py @@ -1,10 +1,6 @@ from __future__ import annotations -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] - -from .command import ( # noqa: E402 +from .command import ( main, remove_container, run_in_container, diff --git a/cli/administration/deploy/container/command.py b/cli/administration/deploy/container/command.py index 1bd75bf4a8..9936226a92 100644 --- a/cli/administration/deploy/container/command.py +++ b/cli/administration/deploy/container/command.py @@ -8,7 +8,7 @@ import sys import time import uuid -from . import PROJECT_ROOT +from utils.cache import PROJECT_ROOT INFINITO_SRC_DIR = os.environ["INFINITO_SRC_DIR"] diff --git a/cli/administration/deploy/development/__init__.py b/cli/administration/deploy/development/__init__.py index 3655de3009..a9b50fb880 100644 --- a/cli/administration/deploy/development/__init__.py +++ b/cli/administration/deploy/development/__init__.py @@ -1,9 +1,5 @@ from __future__ import annotations -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] - -from .cli import main # noqa: E402 +from .cli import main __all__ = ["main"] diff --git a/cli/administration/deploy/development/build.py b/cli/administration/deploy/development/build.py index 3ec0913d0c..4fa15489d7 100644 --- a/cli/administration/deploy/development/build.py +++ b/cli/administration/deploy/development/build.py @@ -4,7 +4,8 @@ import os import subprocess from typing import TYPE_CHECKING -from . import PROJECT_ROOT +from utils.cache import PROJECT_ROOT + from .env import resolve_distro if TYPE_CHECKING: diff --git a/cli/administration/deploy/development/common.py b/cli/administration/deploy/development/common.py index 7b6b1a1d95..d9e9267d08 100644 --- a/cli/administration/deploy/development/common.py +++ b/cli/administration/deploy/development/common.py @@ -9,7 +9,8 @@ from __future__ import annotations import os from typing import TYPE_CHECKING -from . import PROJECT_ROOT +from utils.cache import PROJECT_ROOT + from .env import resolve_distro if TYPE_CHECKING: diff --git a/cli/administration/deploy/development/deploy/cli.py b/cli/administration/deploy/development/deploy/cli.py index fab77f9f1f..6beacfe898 100644 --- a/cli/administration/deploy/development/deploy/cli.py +++ b/cli/administration/deploy/development/deploy/cli.py @@ -9,9 +9,6 @@ from cli.administration.deploy.development.common import ( make_compose, resolve_container, ) -from cli.administration.deploy.development.inventory import ( - _build_services_overrides_for_round as build_services_overrides_for_round, -) from cli.administration.deploy.development.inventory import ( plan_dev_inventory_matrix, prune_orphans_after_disable, @@ -25,6 +22,9 @@ from cli.administration.inventory.provision.services.disabler import ( find_provider_roles, parse_services_disabled, ) +from utils.roles.applications.variants import ( + services_overrides_for_round as build_services_overrides_for_round, +) from .drill import _maybe_recover_drill from .purge import _purge_app_entities diff --git a/cli/administration/deploy/development/deploy/purge.py b/cli/administration/deploy/development/deploy/purge.py index 49a12f2624..e8127b89d5 100644 --- a/cli/administration/deploy/development/deploy/purge.py +++ b/cli/administration/deploy/development/deploy/purge.py @@ -5,7 +5,7 @@ from __future__ import annotations import os import subprocess -from cli.administration.deploy.development import PROJECT_ROOT +from utils.cache import PROJECT_ROOT def _purge_app_entities(*, container: str, app_ids: list[str]) -> None: diff --git a/cli/administration/deploy/development/down.py b/cli/administration/deploy/development/down.py index 2bd29871d6..f77f9d6a8b 100644 --- a/cli/administration/deploy/development/down.py +++ b/cli/administration/deploy/development/down.py @@ -5,7 +5,8 @@ import subprocess from pathlib import Path from typing import TYPE_CHECKING -from . import PROJECT_ROOT +from utils.cache import PROJECT_ROOT + from .env import resolve_distro if TYPE_CHECKING: diff --git a/cli/administration/deploy/development/init.py b/cli/administration/deploy/development/init.py index 1dd04803cd..8547f937d4 100644 --- a/cli/administration/deploy/development/init.py +++ b/cli/administration/deploy/development/init.py @@ -10,6 +10,9 @@ from cli.administration.inventory.provision.services.disabler import ( ) from cli.meta.runtime import detect_runtime from plugins.filter.merge.with_defaults import merge_with_defaults +from utils.roles.applications.variants import ( + services_overrides_for_round as build_services_overrides_for_round, +) from utils.security.deploy import deploy_inventory_overrides from .common import make_compose @@ -19,9 +22,6 @@ from .inventory import ( plan_dev_inventory_matrix, prune_orphans_after_disable, ) -from .inventory import ( - _build_services_overrides_for_round as build_services_overrides_for_round, -) from .storage import detect_storage_constrained from .variant_select import ( add_variant_args, diff --git a/cli/administration/deploy/development/inventory/__init__.py b/cli/administration/deploy/development/inventory/__init__.py index 5fab98bf9d..5cb220e93d 100644 --- a/cli/administration/deploy/development/inventory/__init__.py +++ b/cli/administration/deploy/development/inventory/__init__.py @@ -39,7 +39,6 @@ from __future__ import annotations from .builder import build_dev_inventory, build_dev_inventory_matrix from .legacy_resolver import ( - _build_services_overrides_for_round, _resolve_round_include, prune_orphans_after_disable, ) @@ -50,7 +49,6 @@ from .spec import PlanEntry as PlanEntry __all__ = [ "_bake_overrides", - "_build_services_overrides_for_round", "_resolve_round_include", "_resolve_variant_payloads", "build_dev_inventory", diff --git a/cli/administration/deploy/development/inventory/legacy_resolver.py b/cli/administration/deploy/development/inventory/legacy_resolver.py index 77870a4a30..6dedce9b27 100644 --- a/cli/administration/deploy/development/inventory/legacy_resolver.py +++ b/cli/administration/deploy/development/inventory/legacy_resolver.py @@ -16,13 +16,9 @@ from __future__ import annotations from typing import TYPE_CHECKING -from utils.roles.applications.variants import services_overrides_for_round - if TYPE_CHECKING: from collections.abc import Iterable, Sequence -_build_services_overrides_for_round = services_overrides_for_round - def _resolve_round_include( *, diff --git a/cli/build/i18n/__init__.py b/cli/build/i18n/__init__.py index e69de29bb2..d6d5d9657d 100644 --- a/cli/build/i18n/__init__.py +++ b/cli/build/i18n/__init__.py @@ -0,0 +1 @@ +READY_TIMEOUT_SECONDS = 3600 diff --git a/cli/build/i18n/__main__.py b/cli/build/i18n/__main__.py index 8afda2ecbf..f81fecad4a 100644 --- a/cli/build/i18n/__main__.py +++ b/cli/build/i18n/__main__.py @@ -22,6 +22,7 @@ from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor from contextlib import contextmanager from pathlib import Path +from cli.build.i18n import READY_TIMEOUT_SECONDS from utils.cache.files import PROJECT_ROOT from utils.i18n.catalog import ( adopt_template, @@ -31,20 +32,18 @@ from utils.i18n.catalog import ( read_catalog, write_catalog, ) -from utils.i18n.client import BATCH_SIZE +from utils.i18n.client import BATCH_SIZE, LibreTranslate from utils.i18n.extract import core_messages, docs_template +from utils.i18n.gateway import server from utils.i18n.languages import ( DOMAINS, domain_languages, load_languages, ) -from utils.i18n.gateway import ( - READY_TIMEOUT_SECONDS, - LibreTranslate, +from utils.i18n.libretranslate import ( download_status, - server, + served_languages, ) -from utils.i18n.libretranslate import served_languages from utils.i18n.placeholders import Rejected from utils.i18n.translate import ( apply, @@ -214,9 +213,7 @@ def one_catalog(client: LibreTranslate, domain: str, code: str) -> None: criteria.update( value.reason for value in outcome.values if isinstance(value, Rejected) ) - discarded += apply( - chunk, outcome.values, taken, criteria, outcome.engines - ) + discarded += apply(chunk, outcome.values, taken, criteria, outcome.engines) refused += outcome.refused damaged += outcome.damaged refusal = outcome.refusal or refusal @@ -238,7 +235,10 @@ def translate(domains: list[str], requested: list[str], redeploy: bool = False) supported = domain_languages(loaded, domain) unsupported = sorted(set(requested) - set(supported)) if unsupported: - print(f"{', '.join(unsupported)} is not a language this repository names", file=sys.stderr) + print( + f"{', '.join(unsupported)} is not a language this repository names", + file=sys.stderr, + ) return 2 work += [ (domain, code) diff --git a/cli/build/i18n/tune.py b/cli/build/i18n/tune.py index 9ba93a47e5..d279b1f5dc 100644 --- a/cli/build/i18n/tune.py +++ b/cli/build/i18n/tune.py @@ -14,11 +14,11 @@ from concurrent.futures import ThreadPoolExecutor from pathlib import Path from statistics import median +from cli.build.i18n import READY_TIMEOUT_SECONDS from utils.cache.files import PROJECT_ROOT from utils.i18n.catalog import catalog_path, read_catalog +from utils.i18n.client import LibreTranslate from utils.i18n.libretranslate import ( - READY_TIMEOUT_SECONDS, - LibreTranslate, download_status, served_languages, server, diff --git a/cli/console/repl.py b/cli/console/repl.py index 1f3cc39ebb..a29875fd06 100644 --- a/cli/console/repl.py +++ b/cli/console/repl.py @@ -12,6 +12,7 @@ folder, everything else runs with the current path prepended. from __future__ import annotations import contextlib +import importlib import shlex import sys @@ -56,7 +57,7 @@ from .runner import ( ) with contextlib.suppress(ImportError): - import readline # noqa: F401 + importlib.import_module("readline") __all__ = [ "AUTHOR", diff --git a/cli/contributing/network/diagnose/report.py b/cli/contributing/network/diagnose/report.py index ad7ef6bcee..2314b6e9ae 100644 --- a/cli/contributing/network/diagnose/report.py +++ b/cli/contributing/network/diagnose/report.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import os import socket import sys @@ -104,12 +105,10 @@ def has_ipv6_default_route() -> bool: for raw in out.splitlines(): if "default" in raw and " dev lo" not in raw: return True - try: + with contextlib.suppress(OSError): v6_text = Path("/proc/net/ipv6_route").read_text() # nocheck: cache-read for raw in v6_text.splitlines(): parts = raw.split() if len(parts) >= 10 and parts[0] == "0" * 32 and parts[-1] != "lo": return True - except OSError: - pass return False diff --git a/cli/contributing/network/diagnose/tools.py b/cli/contributing/network/diagnose/tools.py index 5637cef544..70d3499f2f 100644 --- a/cli/contributing/network/diagnose/tools.py +++ b/cli/contributing/network/diagnose/tools.py @@ -2,6 +2,7 @@ from __future__ import annotations +import contextlib import os import shutil import sys @@ -13,13 +14,11 @@ from cli.contributing.network.diagnose.format import cmd_capture def detect_distro_id(*, os_release_path: str = "/etc/os-release") -> str: """Return the distro id from /etc/os-release, lowercased; empty string when unreadable.""" - try: + with contextlib.suppress(OSError): text = Path(os_release_path).read_text() # nocheck: cache-read for raw in text.splitlines(): if raw.startswith("ID="): return raw.split("=", 1)[1].strip().strip('"').lower() - except OSError: - pass return "" diff --git a/cli/meta/categories/invokable/__init__.py b/cli/meta/categories/invokable/__init__.py index 1798e533ab..681b460135 100644 --- a/cli/meta/categories/invokable/__init__.py +++ b/cli/meta/categories/invokable/__init__.py @@ -1,9 +1,5 @@ from __future__ import annotations -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] - -from .command import main # noqa: E402 +from .command import main __all__ = ["main"] diff --git a/cli/meta/categories/invokable/command.py b/cli/meta/categories/invokable/command.py index 506ce4c616..518943850e 100755 --- a/cli/meta/categories/invokable/command.py +++ b/cli/meta/categories/invokable/command.py @@ -21,8 +21,7 @@ from plugins.filter.invokable_paths import ( get_invokable_paths, get_non_invokable_paths, ) - -from . import PROJECT_ROOT +from utils.cache import PROJECT_ROOT def main() -> None: diff --git a/cli/meta/roles/applications/complexity/graph.py b/cli/meta/roles/applications/complexity/graph.py index 747586d4ee..b1c1bc3b11 100644 --- a/cli/meta/roles/applications/complexity/graph.py +++ b/cli/meta/roles/applications/complexity/graph.py @@ -10,7 +10,6 @@ from utils.roles.applications.services.registry import ( build_service_registry_from_roles_dir, is_explicit_truth, ) -from utils.roles.deploy import role_has_stack # noqa: F401 - re-exported for callers from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_VARS_MAIN if TYPE_CHECKING: diff --git a/cli/meta/roles/applications/complexity/model.py b/cli/meta/roles/applications/complexity/model.py index f7d05c27f7..86e3752c07 100644 --- a/cli/meta/roles/applications/complexity/model.py +++ b/cli/meta/roles/applications/complexity/model.py @@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any, NamedTuple from utils.cache.applications import get_variants from utils.env.parser import env_setting -from utils.roles.deploy import role_deploy_modes +from utils.roles.deploy import role_deploy_modes, role_has_stack from utils.roles.lifecycle import tested_lifecycles from utils.roles.meta_lookup import ( MetaServicesShapeError, @@ -23,7 +23,6 @@ from .graph import ( direct_dep_roles, is_application_role, resolve_transitively, - role_has_stack, truth_predicate, ) diff --git a/docs/contributing/actions/testing/suppression.md b/docs/contributing/actions/testing/suppression.md index 453303c145..1c86d0d4b2 100644 --- a/docs/contributing/actions/testing/suppression.md +++ b/docs/contributing/actions/testing/suppression.md @@ -58,6 +58,12 @@ The placement rule is per check. The catalog "Position" column uses these labels | `debian-codename` | same or above | [test_no_debian_codename_tags.py](../../../../tests/lint/repository/test_no_debian_codename_tags.py) | Allows an image reference whose tag names a Debian release by codename. Reserved for an upstream that publishes no numeric tag; the marker MUST name which upstream, because a codename pin can never be raised by the updater. | | `direct-yaml` | same line / span | [test_no_direct_calls.py](../../../../tests/lint/repository/yaml/test_no_direct_calls.py) | Allows the marked `yaml.safe_load` / `safe_dump` call to bypass `utils.cache.yaml`. MUST use `nocheck:`, not `noqa:`. | | `curl-timeout` | same or above | [test_curl_via_filter.py](../../../../tests/lint/repository/test_curl_via_filter.py) | Allows a bare curl invocation without the `curl` filter or inline `--max-time`. | +| `import-and-import-from` | same or above | [test_import_and_import_from.py](../../../../tests/lint/repository/python/test_import_and_import_from.py) | Allows an `import m` in a file that also imports `from m`. Default path: keep one form. The marker MUST name why both are needed. | +| `unused-import` | same or above | [test_unused_imports_hidden_from_ruff.py](../../../../tests/lint/repository/python/test_unused_imports_hidden_from_ruff.py) | Allows a module-level import that nothing reads although it carries a redundant `as` alias or `# noqa: F401`. Reserved for an import kept for its side effect; the marker MUST name the effect. | +| `unused-global` | same or above | [test_unused_global_variables.py](../../../../tests/lint/repository/python/test_unused_global_variables.py) | Allows a module-level variable its module never reads and does not export. Reserved for a name other modules import that `__all__` must not publish. | +| `empty-except` | same or above | [test_empty_except.py](../../../../tests/lint/repository/python/test_empty_except.py) | Allows an `except` clause that only passes. Default path: `contextlib.suppress()`. | +| `unused-local` | same or above | [test_unused_local_variables.py](../../../../tests/lint/repository/python/test_unused_local_variables.py) | Allows an underscore-named local that nothing reads, such as a keepalive binding. | +| `mixed-tuple-returns` | same or above the `def` line | [test_mixed_tuple_returns.py](../../../../tests/lint/repository/python/test_mixed_tuple_returns.py) | Allows an unannotated function to return tuple literals of several sizes, such as `return ()` beside a pair. Default path: annotate `-> tuple[T, ...]`. | | `redundant-bool-ternary` | same line | [test_no_redundant_bool_patterns.py](../../../../tests/lint/filesystem/python/test_no_redundant_bool_patterns.py) | Allows the redundant `\| bool \| ternary('true','false')` pattern when a consumer requires the lowercase tokens. | | `redundant-bool-comparison` | same line | [test_no_redundant_bool_patterns.py](../../../../tests/lint/filesystem/python/test_no_redundant_bool_patterns.py) | Allows `... \| bool == True/False/true/false` when a real tri-state guard is intended (distinguishing `None` from `False`). | | `shared` | comment block above | [test_service_shared_consistency.py](../../../../tests/lint/ansible/services/test_service_shared_consistency.py) | Marks a service whose `enabled: true` does not require `shared: true`. | diff --git a/tests/external/i18n/__init__.py b/tests/external/i18n/__init__.py index 01a506de49..80bf186285 100644 --- a/tests/external/i18n/__init__.py +++ b/tests/external/i18n/__init__.py @@ -13,3 +13,5 @@ from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parents[3] SUITE = "external-i18n" + +__all__ = ["PROJECT_ROOT", "SUITE"] diff --git a/tests/external/repository/test_author_profile.py b/tests/external/repository/test_author_profile.py index 0870322761..c4f29b525d 100644 --- a/tests/external/repository/test_author_profile.py +++ b/tests/external/repository/test_author_profile.py @@ -42,7 +42,7 @@ class TestAuthorProfile(unittest.TestCase): name, email = committing_as() if not email: raise unittest.SkipTest("git config user.email is unset here") - _name, self.email = canonical(name, email) + self.email = canonical(name, email)[1] self.url = profile_url(self.email) if not self.url: raise unittest.SkipTest( diff --git a/tests/integration/ansible/lookups/config/test_literal_paths.py b/tests/integration/ansible/lookups/config/test_literal_paths.py index 0f6874e3e5..3aec3e2491 100644 --- a/tests/integration/ansible/lookups/config/test_literal_paths.py +++ b/tests/integration/ansible/lookups/config/test_literal_paths.py @@ -5,6 +5,7 @@ The classifier here owns the rule "literal app id + complete path (does NOT end with `.`)" — partial paths and variable-app calls are handled by the sibling tests.""" +import contextlib import unittest from collections.abc import Iterable @@ -46,17 +47,16 @@ class TestLiteralPaths(unittest.TestCase): missing_apps.append(app_id) continue for dotted, occs in paths.items(): - try: - get( - applications=ctx.application_defaults, - application_id=app_id, - config_path=dotted, - strict=True, - ) - except ConfigEntryNotSetError: - continue - except Exception: - pass + with contextlib.suppress(Exception): + try: + get( + applications=ctx.application_defaults, + application_id=app_id, + config_path=dotted, + strict=True, + ) + except ConfigEntryNotSetError: + continue try: validate_app_path( ctx.application_defaults, diff --git a/tests/integration/i18n/__init__.py b/tests/integration/i18n/__init__.py index 81200c399d..38a95cbc43 100644 --- a/tests/integration/i18n/__init__.py +++ b/tests/integration/i18n/__init__.py @@ -30,6 +30,7 @@ be read is ignored, and a pool that cannot start is replaced by a plain loop. from __future__ import annotations +import contextlib import json import os import time @@ -168,11 +169,9 @@ def _load_cache() -> dict[str, list]: def _save_cache(cache: dict[str, list]) -> None: - try: + with contextlib.suppress(OSError): CACHE_FILE.parent.mkdir(parents=True, exist_ok=True) CACHE_FILE.write_text(json.dumps(cache), encoding="utf-8") - except OSError: - pass def _parse(pending: list[tuple[str, str]], findings: Findings) -> list: diff --git a/tests/integration/infrastructure/docker/test_no_raw_docker.py b/tests/integration/infrastructure/docker/test_no_raw_docker.py index 683940db86..b6da37cfb2 100644 --- a/tests/integration/infrastructure/docker/test_no_raw_docker.py +++ b/tests/integration/infrastructure/docker/test_no_raw_docker.py @@ -71,7 +71,7 @@ from utils.annotations.suppress import ( is_suppressed_at, is_suppressed_in_head, ) -from utils.cache.base import PROJECT_ROOT +from utils.cache import PROJECT_ROOT from utils.cache.files import iter_non_ignored_files, read_text if TYPE_CHECKING: diff --git a/tests/integration/infrastructure/services/test_disabled_provider_dependents.py b/tests/integration/infrastructure/services/test_disabled_provider_dependents.py index 3d07d9770f..77b851e639 100644 --- a/tests/integration/infrastructure/services/test_disabled_provider_dependents.py +++ b/tests/integration/infrastructure/services/test_disabled_provider_dependents.py @@ -28,7 +28,6 @@ from ansible.parsing.dataloader import DataLoader from ansible.template import Templar from cli.administration.deploy.development.inventory import ( - _build_services_overrides_for_round, _resolve_variant_payloads, plan_dev_inventory_matrix, prune_orphans_after_disable, @@ -43,6 +42,7 @@ from utils.cache import _reset_cache_for_tests from utils.cache.applications import get_merged_applications from utils.cache.yaml import dump_yaml, load_yaml_any from utils.github.variant.network import TOR, disabled_services +from utils.roles.applications.variants import services_overrides_for_round from . import PROJECT_ROOT @@ -76,7 +76,7 @@ def _provision_tor_row(workdir: Path) -> tuple[list[str], dict]: include=include, primary_apps=[APP], disabled_app_ids=set(disabled.values()), - services_overrides=_build_services_overrides_for_round( + services_overrides=services_overrides_for_round( roles_dir=str(ROLES_DIR), round_index=round_index, primary_app_variants={APP: round_variants[APP]}, diff --git a/tests/integration/roles/svc-bkp-remote-2-local/__init__.py b/tests/integration/roles/svc-bkp-remote-2-local/__init__.py index 88f288ec1f..eec6d4835a 100644 --- a/tests/integration/roles/svc-bkp-remote-2-local/__init__.py +++ b/tests/integration/roles/svc-bkp-remote-2-local/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[4] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/integration/roles/when/test_guards.py b/tests/integration/roles/when/test_guards.py index 5969c99249..8c94e6642d 100644 --- a/tests/integration/roles/when/test_guards.py +++ b/tests/integration/roles/when/test_guards.py @@ -1,11 +1,11 @@ +import contextlib +import importlib.util import unittest from pathlib import Path from typing import Any -try: - import yaml # noqa: F401 # imported only to assert pyyaml is installed -except ImportError: # pragma: no cover - raise SystemExit("Please `pip install pyyaml` to run this test.") from None +if importlib.util.find_spec("yaml") is None: # pragma: no cover + raise SystemExit("Please `pip install pyyaml` to run this test.") from utils.cache import PROJECT_ROOT from utils.cache.files import iter_project_files @@ -186,13 +186,11 @@ class PureGuardedIncludeTest(unittest.TestCase): continue main_path = str(main_path) role_name = role_dir.name - try: + with contextlib.suppress(Exception): tasks = _load_yaml_file(main_path) guards, pure = _is_pure_guarded_tasks_file(tasks) if pure and guards: cls.pure_guarded_roles[role_name] = (guards, main_path) - except Exception: - pass cls.tasks_file_cache: dict[str, tuple[list[str], bool]] = {} diff --git a/tests/lint/ansible/roles/test_role_host_mode.py b/tests/lint/ansible/roles/test_role_host_mode.py index bf839196c2..b0f59f7352 100644 --- a/tests/lint/ansible/roles/test_role_host_mode.py +++ b/tests/lint/ansible/roles/test_role_host_mode.py @@ -19,8 +19,8 @@ from __future__ import annotations import unittest -from cli.meta.roles.applications.complexity.graph import role_has_stack from utils.cache.yaml import load_yaml_any +from utils.roles.deploy import role_has_stack from utils.roles.entity.name import entity_name from utils.roles.mapping import ROLE_FILE_META_SERVICES from utils.roles.validation.invokable import _get_invokable_paths, _is_role_invokable diff --git a/tests/lint/ansible/shell/container/test_restart_is_compose_only.py b/tests/lint/ansible/shell/container/test_restart_is_compose_only.py index 25880abbdd..2377e2e93e 100644 --- a/tests/lint/ansible/shell/container/test_restart_is_compose_only.py +++ b/tests/lint/ansible/shell/container/test_restart_is_compose_only.py @@ -39,6 +39,7 @@ directly above it. from __future__ import annotations +import contextlib import re import unittest from pathlib import Path @@ -245,11 +246,9 @@ def _offenders(rel_path: str, content: str) -> list[str]: if _MODE.search(line): continue hits.append(index) - try: + with contextlib.suppress(yaml.YAMLError): for document in yaml.compose_all(content, Loader=yaml.SafeLoader): _argv_restart_lines(document, hits) - except yaml.YAMLError: - pass found: list[str] = [] for index in sorted(set(hits)): diff --git a/tests/lint/repository/naming/test_test_files_location.py b/tests/lint/repository/naming/test_test_files_location.py index 9926cca103..56b3450f61 100644 --- a/tests/lint/repository/naming/test_test_files_location.py +++ b/tests/lint/repository/naming/test_test_files_location.py @@ -3,7 +3,7 @@ from __future__ import annotations import unittest from pathlib import Path -from utils.cache.base import PROJECT_ROOT +from utils.cache import PROJECT_ROOT from utils.cache.files import iter_project_files from utils.cache.gitignore import is_path_gitignored, load_gitignore_patterns diff --git a/tests/lint/repository/no_legacy_sso_paths/__init__.py b/tests/lint/repository/no_legacy_sso_paths/__init__.py index 5048a22449..7520777605 100644 --- a/tests/lint/repository/no_legacy_sso_paths/__init__.py +++ b/tests/lint/repository/no_legacy_sso_paths/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parents[4] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/lint/repository/python/__init__.py b/tests/lint/repository/python/__init__.py index 45ed37c7e5..b2f8e6f57e 100644 --- a/tests/lint/repository/python/__init__.py +++ b/tests/lint/repository/python/__init__.py @@ -1,3 +1,119 @@ -from tests.lint.repository import PROJECT_ROOT +from __future__ import annotations -__all__ = ["PROJECT_ROOT"] +import ast +import re +from functools import lru_cache + +from tests.lint.repository import PROJECT_ROOT +from utils.cache.files import iter_project_files, read_text + +__all__ = [ + "ACCEPTABLE_UNUSED", + "PROJECT_ROOT", + "declared_all", + "module_level", + "python_modules", + "read_names", +] + +ACCEPTABLE_UNUSED = re.compile(r"_+|__.*|.*unused.*|.*dummy.*|empty") +_SCOPES = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Lambda) +_IDENTIFIER = re.compile(r"[A-Za-z_]\w*") + + +@lru_cache(maxsize=1) +def python_modules() -> tuple[tuple[str, str, ast.Module], ...]: + """Return every project Python file that parses, read and parsed once. + + Returns: + ``(path relative to the project root, text, tree)`` per file. + """ + found: list[tuple[str, str, ast.Module]] = [] + for path in iter_project_files(extensions=(".py",)): + rel = str(path).replace(f"{PROJECT_ROOT}/", "") + try: + content = read_text(str(path)) + tree = ast.parse(content) + except (OSError, UnicodeDecodeError, SyntaxError, ValueError): + continue + found.append((rel, content, tree)) + return tuple(found) + + +def module_level(body: list[ast.stmt]) -> list[ast.stmt]: + """Return the statements that run in the module's own scope. + + Args: + body: the statements of the module or of a block it descends into. + """ + found: list[ast.stmt] = [] + for node in body: + if isinstance(node, _SCOPES): + continue + found.append(node) + for field in ("body", "orelse", "finalbody"): + found.extend(module_level(getattr(node, field, None) or [])) + for handler in getattr(node, "handlers", None) or []: + found.extend(module_level(handler.body)) + return found + + +def declared_all(tree: ast.Module, statements: list[ast.stmt]) -> set[str] | None: + """Return the literal ``__all__`` of a module, ``None`` when it is computed. + + Args: + tree: the parsed module. + statements: its module-level statements. + """ + for node in ast.walk(tree): + if ( + isinstance(node, ast.Call) + and isinstance(node.func, ast.Attribute) + and isinstance(node.func.value, ast.Name) + and node.func.value.id == "__all__" + ): + return None + names: set[str] = set() + for node in statements: + targets = getattr(node, "targets", None) or [getattr(node, "target", None)] + if not any(isinstance(t, ast.Name) and t.id == "__all__" for t in targets): + continue + if not isinstance(node, ast.Assign) or not isinstance( + node.value, (ast.List, ast.Tuple) + ): + return None + for element in node.value.elts: + if not isinstance(element, ast.Constant): + return None + names.add(element.value) + return names + + +def read_names(tree: ast.Module, content: str) -> set[str]: + """Return every name the module reads, string annotations and type comments included. + + Args: + tree: the parsed module. + content: the module's text. + """ + names = { + node.id + for node in ast.walk(tree) + if isinstance(node, ast.Name) and not isinstance(node.ctx, ast.Store) + } + annotations: list[ast.expr] = [] + for node in ast.walk(tree): + if (isinstance(node, ast.arg) and node.annotation is not None) or isinstance( + node, ast.AnnAssign + ): + annotations.append(node.annotation) + elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and node.returns: + annotations.append(node.returns) + for annotation in annotations: + for leaf in ast.walk(annotation): + if isinstance(leaf, ast.Constant) and isinstance(leaf.value, str): + names.update(_IDENTIFIER.findall(leaf.value)) + for line in content.splitlines(): + if "# type:" in line: + names.update(_IDENTIFIER.findall(line.split("# type:", 1)[1])) + return names diff --git a/tests/lint/repository/python/test_empty_except.py b/tests/lint/repository/python/test_empty_except.py new file mode 100644 index 0000000000..48d86e0758 --- /dev/null +++ b/tests/lint/repository/python/test_empty_except.py @@ -0,0 +1,179 @@ +from __future__ import annotations + +import ast +import unittest + +from utils.annotations.suppress import is_suppressed_at + +from . import python_modules + +_RULE = "empty-except" +_SIMPLE = ( + ast.Expr, + ast.Assign, + ast.AugAssign, + ast.AnnAssign, + ast.Delete, + ast.Assert, + ast.Import, + ast.ImportFrom, + ast.Pass, +) +_EXITS = (ast.Return, ast.Raise, ast.Continue, ast.Break) +_FOCUSSED = { + "subscript": {"LookupError", "KeyError", "IndexError"}, + "attribute": {"AttributeError"}, + "name": {"NameError"}, + "encode": {"UnicodeEncodeError"}, + "decode": {"UnicodeDecodeError"}, +} + + +def _caught(handler: ast.ExceptHandler) -> set[str]: + """Return the exception names a handler catches. + + Args: + handler: the except clause. + """ + kinds = handler.type + elements = kinds.elts if isinstance(kinds, ast.Tuple) else [kinds] + return { + element.id if isinstance(element, ast.Name) else getattr(element, "attr", "") + for element in elements + if element is not None + } + + +def _shape(statement: ast.stmt) -> str: + """Return what a lone statement does, for the handlers that catch only that. + + Args: + statement: the only statement of the try body. + """ + targets = getattr(statement, "targets", None) or [] + value = getattr(statement, "value", None) + probe = targets[0] if isinstance(statement, ast.Delete) and targets else value + if isinstance(probe, ast.Subscript): + return "subscript" + if isinstance(probe, ast.Attribute): + return "attribute" + if isinstance(statement, ast.Expr) and isinstance(value, ast.Name): + return "name" + if isinstance(value, ast.Call): + func = value.func + if isinstance(func, ast.Name) and func.id in ("getattr", "setattr", "delattr"): + return "attribute" + if isinstance(func, ast.Attribute) and func.attr in ("encode", "decode"): + return func.attr + return "" + + +def _left_to_ruff(node: ast.Try) -> bool: + """Whether the try statement has the one shape ruff's SIM105 already reports. + + Args: + node: the try statement. + """ + return ( + len(node.handlers) == 1 + and not node.orelse + and not node.finalbody + and len(node.body) == 1 + and isinstance(node.body[0], _SIMPLE) + ) + + +def _offenders(rel_path: str, tree: ast.Module, content: str) -> list[str]: + """Return the except clauses of one module that do nothing but pass. + + Args: + rel_path: path relative to the project root. + tree: the parsed module. + content: the module's text. + """ + lines = content.splitlines() + found: list[str] = [] + for node in ast.walk(tree): + if not isinstance(node, (ast.Try, ast.TryStar)) or node.orelse: + continue + if isinstance(node.body[-1], _EXITS) or _left_to_ruff(node): + continue + lone = _shape(node.body[0]) if len(node.body) == 1 else "" + for handler in node.handlers: + if not all(isinstance(s, ast.Pass) for s in handler.body): + continue + caught = _caught(handler) + if "StopIteration" in caught: + continue + if lone and caught and caught <= _FOCUSSED[lone]: + continue + if is_suppressed_at(lines, handler.lineno, _RULE, mode="same-or-above"): + continue + found.append(f"{rel_path}:{handler.lineno}") + return found + + +class TestEmptyExcept(unittest.TestCase): + def test_no_except_clause_only_passes(self) -> None: + offenders: list[str] = [] + for rel, content, tree in python_modules(): + offenders.extend(_offenders(rel, tree, content)) + + report = "\n".join(f" - {o}" for o in sorted(offenders)) + self.assertFalse( + offenders, + f"{len(offenders)} except clause(s) do nothing but pass:\n{report}\n\n" + "Wrap the statements in `contextlib.suppress()` so the " + "ignored error is named where the block starts, or handle it. " + f"Where neither fits, say why with `# nocheck: {_RULE} `.", + ) + + +class TestEmptyExceptDetection(unittest.TestCase): + def _run(self, source: str) -> list[str]: + return _offenders("m.py", ast.parse(source), source) + + def test_a_nocheck_suppresses_it(self) -> None: + source = ( + "try:\n a()\n b()\n" + f"except OSError: # nocheck: {_RULE} reason\n pass\n" + ) + + self.assertEqual([], self._run(source)) + + def test_a_two_statement_body_is_reported(self) -> None: + source = "try:\n a()\n b()\nexcept OSError:\n pass\n" + + self.assertEqual(["m.py:4"], self._run(source)) + + def test_a_compound_body_is_reported(self) -> None: + source = "try:\n for x in y:\n a(x)\nexcept ValueError:\n pass\n" + + self.assertEqual(["m.py:4"], self._run(source)) + + def test_the_single_statement_shape_is_left_to_ruff(self) -> None: + self.assertEqual([], self._run("try:\n a()\nexcept OSError:\n pass\n")) + + def test_a_handler_that_acts_is_accepted(self) -> None: + source = "try:\n a()\n b()\nexcept OSError:\n c()\n" + + self.assertEqual([], self._run(source)) + + def test_a_try_with_else_is_accepted(self) -> None: + source = "try:\n a()\n b()\nexcept OSError:\n pass\nelse:\n c()\n" + + self.assertEqual([], self._run(source)) + + def test_a_body_that_always_returns_is_accepted(self) -> None: + source = "def f():\n try:\n a()\n return b()\n except OSError:\n pass\n" + + self.assertEqual([], self._run(source)) + + def test_stop_iteration_is_accepted(self) -> None: + source = "try:\n a()\n b()\nexcept StopIteration:\n pass\n" + + self.assertEqual([], self._run(source)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/python/test_import_and_import_from.py b/tests/lint/repository/python/test_import_and_import_from.py new file mode 100644 index 0000000000..fbd77363d2 --- /dev/null +++ b/tests/lint/repository/python/test_import_and_import_from.py @@ -0,0 +1,107 @@ +from __future__ import annotations + +import ast +import unittest + +from utils.annotations.suppress import is_suppressed_at + +from . import python_modules + +_RULE = "import-and-import-from" + + +def _from_module(node: ast.ImportFrom, rel_path: str) -> str: + """Return the absolute name of the module an ``import from`` reads. + + Args: + node: the statement. + rel_path: path of the importing file relative to the project root. + """ + if not node.level: + return node.module or "" + package = rel_path.removesuffix(".py").split("/")[:-1] + base = package[: len(package) - node.level + 1] + return ".".join([*base, *([node.module] if node.module else [])]) + + +def _offenders(rel_path: str, tree: ast.Module, content: str) -> list[str]: + """Return every ``import`` of a module the same file also imports from. + + Args: + rel_path: path relative to the project root. + tree: the parsed module. + content: the module's text. + """ + read_from = { + _from_module(node, rel_path) + for node in ast.walk(tree) + if isinstance(node, ast.ImportFrom) + } + lines = content.splitlines() + return [ + f"{rel_path}:{node.lineno}: {alias.name}" + for node in ast.walk(tree) + if isinstance(node, ast.Import) + for alias in node.names + if alias.name in read_from + and not is_suppressed_at(lines, node.lineno, _RULE, mode="same-or-above") + ] + + +class TestImportAndImportFrom(unittest.TestCase): + def test_no_module_is_imported_in_both_forms(self) -> None: + offenders: list[str] = [] + for rel, content, tree in python_modules(): + offenders.extend(_offenders(rel, tree, content)) + + report = "\n".join(f" - {o}" for o in sorted(offenders)) + self.assertFalse( + offenders, + f"{len(offenders)} module(s) are imported with both `import m` and " + "`from m import x` in the same file, so one name reaches the module " + f"by two routes:\n{report}\n\n" + "Keep one form: qualify the names through the module, or import " + "the submodule itself (`import unittest.mock`). Where both forms " + f"are needed, say why with `# nocheck: {_RULE} `.", + ) + + +class TestBothFormsDetection(unittest.TestCase): + def _run(self, source: str, rel: str = "m.py") -> list[str]: + return _offenders(rel, ast.parse(source), source) + + def test_import_and_import_from_is_reported(self) -> None: + self.assertEqual( + ["m.py:1: unittest"], + self._run("import unittest\nfrom unittest import mock\n"), + ) + + def test_an_imported_submodule_is_accepted(self) -> None: + self.assertEqual([], self._run("import unittest\nimport unittest.mock\n")) + + def test_importing_from_a_submodule_is_accepted(self) -> None: + self.assertEqual( + [], self._run("import unittest\nfrom unittest.mock import patch\n") + ) + + def test_a_function_level_import_from_still_counts(self) -> None: + source = "import os\n\ndef f():\n from os import path\n" + + self.assertEqual(["m.py:1: os"], self._run(source)) + + def test_a_relative_import_resolves_against_the_package(self) -> None: + source = "import pkg.sub\nfrom . import sub\nfrom .sub import x\n" + + self.assertEqual(["pkg/m.py:1: pkg.sub"], self._run(source, "pkg/m.py")) + + def test_a_nocheck_suppresses_it(self) -> None: + source = ( + f"import typing # nocheck: {_RULE} reason\n" + "from typing import TYPE_CHECKING\n" + ) + + self.assertEqual([], self._run(source)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/python/test_mixed_tuple_returns.py b/tests/lint/repository/python/test_mixed_tuple_returns.py new file mode 100644 index 0000000000..8e65a08a58 --- /dev/null +++ b/tests/lint/repository/python/test_mixed_tuple_returns.py @@ -0,0 +1,129 @@ +from __future__ import annotations + +import ast +import unittest + +from utils.annotations.suppress import is_suppressed_at + +from . import python_modules + +_RULE = "mixed-tuple-returns" +_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef) + + +def _returns(function: ast.FunctionDef | ast.AsyncFunctionDef) -> list[ast.Return]: + """Return the return statements of a function, not of the functions it nests. + + Args: + function: the function. + """ + found: list[ast.Return] = [] + pending: list[ast.AST] = list(function.body) + while pending: + node = pending.pop() + if isinstance(node, (*_FUNCTIONS, ast.ClassDef, ast.Lambda)): + continue + if isinstance(node, ast.Return): + found.append(node) + pending.extend(ast.iter_child_nodes(node)) + return found + + +def _tuple_sizes(value: ast.expr | None) -> set[int]: + """Return the lengths of the tuple literals an expression can evaluate to. + + Args: + value: the returned expression. + """ + if isinstance(value, ast.Tuple): + return {len(value.elts)} + if isinstance(value, ast.IfExp): + return _tuple_sizes(value.body) | _tuple_sizes(value.orelse) + return set() + + +def _offenders(rel_path: str, tree: ast.Module, content: str) -> list[str]: + """Return the unannotated functions of one module that return tuples of several sizes. + + Args: + rel_path: path relative to the project root. + tree: the parsed module. + content: the module's text. + """ + lines = content.splitlines() + found: list[str] = [] + for function in ast.walk(tree): + if not isinstance(function, _FUNCTIONS) or function.returns is not None: + continue + sizes: set[int] = set() + for statement in _returns(function): + sizes |= _tuple_sizes(statement.value) + if len(sizes) < 2: + continue + if is_suppressed_at(lines, function.lineno, _RULE, mode="same-or-above"): + continue + listed = ", ".join(str(size) for size in sorted(sizes)) + found.append(f"{rel_path}:{function.lineno}: {function.name} ({listed})") + return found + + +class TestMixedTupleReturns(unittest.TestCase): + def test_no_function_returns_tuples_of_several_sizes(self) -> None: + offenders: list[str] = [] + for rel, content, tree in python_modules(): + offenders.extend(_offenders(rel, tree, content)) + + report = "\n".join(f" - {o}" for o in sorted(offenders)) + self.assertFalse( + offenders, + f"{len(offenders)} function(s) without a return annotation return " + f"tuple literals of different sizes:\n{report}\n\n" + "Return one shape, or annotate a sequence whose length varies " + "(`-> tuple[str, ...]`). An empty `return ()` beside real tuples " + f"that must stay unannotated says why with `# nocheck: {_RULE} " + "`.", + ) + + +class TestMixedTupleDetection(unittest.TestCase): + def _run(self, source: str) -> list[str]: + return _offenders("m.py", ast.parse(source), source) + + def test_a_nocheck_suppresses_it(self) -> None: + source = ( + f"def f(x): # nocheck: {_RULE} reason\n" + " if x:\n return ()\n return (1, 2)\n" + ) + + self.assertEqual([], self._run(source)) + + def test_two_sizes_are_reported(self) -> None: + source = ( + "def f(x):\n if x:\n return (1, 2)\n return (1, 2, 3, 4)\n" + ) + + self.assertEqual(["m.py:1: f (2, 4)"], self._run(source)) + + def test_a_conditional_expression_is_read_on_both_sides(self) -> None: + source = "def f(c):\n return (a, b, *c) if c else (b,)\n" + + self.assertEqual(["m.py:1: f (1, 3)"], self._run(source)) + + def test_an_annotated_function_is_accepted(self) -> None: + source = "def f(c) -> tuple[str, ...]:\n return (a, b) if c else (b,)\n" + + self.assertEqual([], self._run(source)) + + def test_one_size_is_accepted(self) -> None: + source = "def f(x):\n if x:\n return (1, 2)\n return (3, 4)\n" + + self.assertEqual([], self._run(source)) + + def test_a_nested_function_is_judged_on_its_own(self) -> None: + source = "def f():\n def g():\n return (1,)\n return (1, 2)\n" + + self.assertEqual([], self._run(source)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/python/test_modules_import.py b/tests/lint/repository/python/test_modules_import.py new file mode 100644 index 0000000000..044813cd25 --- /dev/null +++ b/tests/lint/repository/python/test_modules_import.py @@ -0,0 +1,86 @@ +from __future__ import annotations + +import subprocess +import sys +import unittest + +from . import PROJECT_ROOT, python_modules + +_PACKAGES = ("cli", "plugins", "utils") +_MARK = "BROKEN-IMPORT " +_PROBE = f""" +import importlib +import sys + +for name in sys.argv[2].split(","): + try: + importlib.import_module(name) + except ImportError as error: + if (error.name or "").split(".")[0] in sys.argv[1].split(","): + print("{_MARK}" + name + ": " + str(error), flush=True) + except BaseException: + continue +""" + + +def _dotted(rel_path: str) -> str: + """Return the module name a project file is imported under, empty when it has none. + + Args: + rel_path: path relative to the project root. + """ + parts = rel_path.removesuffix(".py").split("/") + if parts[-1] == "__init__": + parts = parts[:-1] + if parts[0] not in _PACKAGES or not all(part.isidentifier() for part in parts): + return "" + return ".".join(parts) + + +class TestModulesImport(unittest.TestCase): + def test_every_project_module_imports(self) -> None: + names = sorted( + {_dotted(rel) for rel, _content, _tree in python_modules()} - {""} + ) + self.assertIn("cli.build.i18n.tune", names) + + result = subprocess.run( + [sys.executable, "-c", _PROBE, ",".join(_PACKAGES), ",".join(names)], + cwd=str(PROJECT_ROOT), + capture_output=True, + text=True, + check=False, + timeout=900, + ) + self.assertEqual(0, result.returncode, result.stderr[-2000:]) + broken = [ + line.removeprefix(_MARK) + for line in result.stdout.splitlines() + if line.startswith(_MARK) + ] + + report = "\n".join(f" - {line}" for line in broken) + self.assertFalse( + broken, + f"{len(broken)} module(s) under {', '.join(_PACKAGES)} import a name " + f"another project module no longer provides:\n{report}\n\n" + "Import the name from the module that defines it.", + ) + + +class TestDottedName(unittest.TestCase): + def test_a_module_maps_to_its_dotted_name(self) -> None: + self.assertEqual("cli.build.i18n.tune", _dotted("cli/build/i18n/tune.py")) + + def test_a_package_init_maps_to_the_package(self) -> None: + self.assertEqual("utils.cache", _dotted("utils/cache/__init__.py")) + + def test_a_path_outside_the_packages_has_none(self) -> None: + self.assertEqual("", _dotted("roles/web-app-x/files/a.py")) + + def test_a_hyphenated_directory_has_none(self) -> None: + self.assertEqual("", _dotted("plugins/x-y/a.py")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/python/test_unused_global_variables.py b/tests/lint/repository/python/test_unused_global_variables.py new file mode 100644 index 0000000000..9810a0b72e --- /dev/null +++ b/tests/lint/repository/python/test_unused_global_variables.py @@ -0,0 +1,161 @@ +from __future__ import annotations + +import ast +import unittest + +from utils.annotations.suppress import is_suppressed_at + +from . import ( + ACCEPTABLE_UNUSED, + declared_all, + module_level, + python_modules, + read_names, +) + +_RULE = "unused-global" + + +def _visible(node: ast.expr) -> bool: + """Whether a value is plain enough that an analyser sees it exported without ``__all__``. + + Args: + node: the assigned value. + """ + if isinstance(node, (ast.Constant, ast.Name, ast.Attribute)): + return True + if isinstance(node, (ast.Tuple, ast.List, ast.Set)): + return all(_visible(element) for element in node.elts) + if isinstance(node, ast.Dict): + return all(_visible(key) for key in node.keys if key is not None) and all( + _visible(value) for value in node.values + ) + if isinstance(node, ast.BinOp): + return _visible(node.left) and _visible(node.right) + if isinstance(node, ast.UnaryOp): + return _visible(node.operand) + return False + + +def _bindings(statements: list[ast.stmt]) -> list[tuple[list[ast.Name], ast.expr]]: + """Return each module-level assignment's target names and its value. + + Args: + statements: the module-level statements. + """ + found: list[tuple[list[ast.Name], ast.expr]] = [] + for node in statements: + if isinstance(node, ast.Assign): + for target in node.targets: + if isinstance(target, ast.Name): + found.append(([target], node.value)) + elif isinstance(target, (ast.Tuple, ast.List)): + names = [e for e in target.elts if isinstance(e, ast.Name)] + found.append((names, node.value)) + elif ( + isinstance(node, ast.AnnAssign) + and node.value is not None + and isinstance(node.target, ast.Name) + ): + found.append(([node.target], node.value)) + return found + + +def _offenders(rel_path: str, tree: ast.Module, content: str) -> list[str]: + """Return the module-level variables of one module that it neither reads nor exports. + + Args: + rel_path: path relative to the project root. + tree: the parsed module. + content: the module's text. + """ + statements = module_level(tree.body) + exported = declared_all(tree, statements) + package = rel_path.endswith("__init__.py") + if exported is None or not (exported or package): + return [] + used = read_names(tree, content) + lines = content.splitlines() + found: list[str] = [] + for names, value in _bindings(statements): + unread = [ + name + for name in names + if name.id not in used + and name.id not in exported + and not ACCEPTABLE_UNUSED.fullmatch(name.id) + and not is_suppressed_at(lines, name.lineno, _RULE, mode="same-or-above") + ] + if not names or len(unread) != len(names): + continue + if not exported and _visible(value): + continue + found.extend(f"{rel_path}:{name.lineno}: {name.id}" for name in unread) + return found + + +class TestUnusedGlobalVariables(unittest.TestCase): + def test_no_module_level_variable_goes_unread(self) -> None: + offenders: list[str] = [] + for rel, content, tree in python_modules(): + offenders.extend(_offenders(rel, tree, content)) + + report = "\n".join(f" - {o}" for o in sorted(offenders)) + self.assertFalse( + offenders, + f"{len(offenders)} module-level variable(s) are never read by their " + f"module and not declared as its exports:\n{report}\n\n" + "Delete a variable nothing reads. A module with `__all__`, and a " + "package `__init__.py` handing a computed value to its modules, " + "list it in `__all__`, or have its readers import it from where " + "it is defined. A name other modules import but `__all__` must not " + f"publish says why with `# nocheck: {_RULE} `.", + ) + + +class TestUnreadGlobalDetection(unittest.TestCase): + def _run(self, source: str, rel: str = "m.py") -> list[str]: + return _offenders(rel, ast.parse(source), source) + + def test_a_name_missing_from_all_is_reported(self) -> None: + source = '__all__ = ["run"]\nTIMEOUT = LIMIT\ndef run():\n pass\n' + + self.assertEqual(["m.py:2: TIMEOUT"], self._run(source)) + + def test_a_nocheck_suppresses_it(self) -> None: + source = f'__all__ = ["run"]\nTIMEOUT = LIMIT # nocheck: {_RULE} reason\n' + + self.assertEqual([], self._run(source)) + + def test_a_computed_value_in_a_package_init_is_reported(self) -> None: + source = "ROOT = Path(__file__).parents[2]\n" + + self.assertEqual(["p/__init__.py:1: ROOT"], self._run(source, "p/__init__.py")) + + def test_a_package_init_declaring_all_is_accepted(self) -> None: + source = 'ROOT = Path(__file__).parents[2]\n__all__ = ["ROOT"]\n' + + self.assertEqual([], self._run(source, "p/__init__.py")) + + def test_a_plain_value_in_a_package_init_is_accepted(self) -> None: + self.assertEqual([], self._run("HANDLERS = [a, b]\n", "p/__init__.py")) + + def test_a_module_without_all_is_skipped(self) -> None: + self.assertEqual([], self._run("GLOB = f'roles/{P}*'\n")) + + def test_a_variable_the_module_reads_is_accepted(self) -> None: + source = "ROOT = Path('.')\ndef f():\n return ROOT\n" + + self.assertEqual([], self._run(source, "p/__init__.py")) + + def test_a_tuple_with_one_read_element_is_accepted(self) -> None: + source = '__all__ = ["f"]\nA, B = g()\ndef f():\n return A\n' + + self.assertEqual([], self._run(source)) + + def test_an_underscore_name_is_accepted(self) -> None: + self.assertEqual([], self._run("_ = setup()\n", "p/__init__.py")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/python/test_unused_imports_hidden_from_ruff.py b/tests/lint/repository/python/test_unused_imports_hidden_from_ruff.py new file mode 100644 index 0000000000..211ae90c2b --- /dev/null +++ b/tests/lint/repository/python/test_unused_imports_hidden_from_ruff.py @@ -0,0 +1,141 @@ +from __future__ import annotations + +import ast +import re +import unittest + +from utils.annotations.suppress import is_suppressed_at + +from . import ( + ACCEPTABLE_UNUSED, + declared_all, + module_level, + python_modules, + read_names, +) + +_RULE = "unused-import" +_NOQA_F401 = re.compile(r"#\s*noqa:[^#]*\bF401\b", re.IGNORECASE) + + +def _bound(alias: ast.alias) -> str: + """Return the name an import alias binds in the importing module. + + Args: + alias: one entry of an import statement. + """ + if alias.asname: + return alias.asname + return alias.name.split(".")[0] + + +def _hidden_from_ruff(alias: ast.alias, lines: list[str]) -> bool: + """Whether ruff's F401 lets the import pass although nothing reads it. + + Args: + alias: one entry of an import statement. + lines: the module's lines. + """ + redundant = alias.asname is not None and alias.asname == alias.name + return redundant or bool(_NOQA_F401.search(lines[alias.lineno - 1])) + + +def _offenders(rel_path: str, tree: ast.Module, content: str) -> list[str]: + """Return the unused imports of one module that ruff is told to accept. + + Args: + rel_path: path relative to the project root. + tree: the parsed module. + content: the module's text. + """ + if rel_path.endswith("__init__.py"): + return [] + statements = module_level(tree.body) + exported = declared_all(tree, statements) + if exported is None: + return [] + used = read_names(tree, content) + lines = content.splitlines() + found: list[str] = [] + for node in statements: + if not isinstance(node, (ast.Import, ast.ImportFrom)): + continue + if isinstance(node, ast.ImportFrom) and node.module == "__future__": + continue + for alias in node.names: + name = _bound(alias) + if alias.name == "*" or name in used or name in exported: + continue + if ACCEPTABLE_UNUSED.fullmatch(name): + continue + if is_suppressed_at(lines, alias.lineno, _RULE, mode="same-or-above"): + continue + if _hidden_from_ruff(alias, lines): + found.append(f"{rel_path}:{node.lineno}: {name}") + return found + + +class TestUnusedImportsHiddenFromRuff(unittest.TestCase): + def test_no_module_keeps_an_import_nothing_reads(self) -> None: + offenders: list[str] = [] + for rel, content, tree in python_modules(): + offenders.extend(_offenders(rel, tree, content)) + + report = "\n".join(f" - {o}" for o in sorted(offenders)) + self.assertFalse( + offenders, + f"{len(offenders)} import(s) bind a name the module never reads; " + "a redundant `as` alias or `# noqa: F401` keeps ruff quiet, but the " + f"import is still unused:\n{report}\n\n" + "Import the name where it is used, from the module that defines " + "it, and drop it here. For an import kept for its side effect, " + f"say so with `# nocheck: {_RULE} `.", + ) + + +class TestHiddenImportDetection(unittest.TestCase): + def _run(self, source: str, rel: str = "m.py") -> list[str]: + return _offenders(rel, ast.parse(source), source) + + def test_a_redundant_alias_nothing_reads_is_reported(self) -> None: + self.assertEqual(["m.py:1: mask"], self._run("from s import mask as mask\n")) + + def test_a_noqa_import_nothing_reads_is_reported(self) -> None: + self.assertEqual( + ["m.py:1: utils"], self._run("import utils.handler.vault # noqa: F401\n") + ) + + def test_a_plain_unused_import_is_left_to_ruff(self) -> None: + self.assertEqual([], self._run("from s import mask\n")) + + def test_a_redundant_alias_the_module_reads_is_accepted(self) -> None: + self.assertEqual([], self._run("from s import mask as mask\nmask('x')\n")) + + def test_a_name_in_all_is_accepted(self) -> None: + source = 'from s import mask as mask\n\n__all__ = ["mask"]\n' + + self.assertEqual([], self._run(source)) + + def test_a_package_init_is_skipped(self) -> None: + self.assertEqual([], self._run("from s import mask as mask\n", "p/__init__.py")) + + def test_a_function_level_import_is_skipped(self) -> None: + self.assertEqual([], self._run("def f():\n import x # noqa: F401\n")) + + def test_an_import_under_a_guard_still_counts(self) -> None: + source = ( + "import contextlib\n" + "with contextlib.suppress(ImportError):\n" + " import readline # noqa: F401\n" + ) + + self.assertEqual(["m.py:3: readline"], self._run(source)) + + def test_a_nocheck_suppresses_it(self) -> None: + source = f"# nocheck: {_RULE} registers a loader\nimport x.y # noqa: F401\n" + + self.assertEqual([], self._run(source)) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/python/test_unused_local_variables.py b/tests/lint/repository/python/test_unused_local_variables.py new file mode 100644 index 0000000000..47c278ceca --- /dev/null +++ b/tests/lint/repository/python/test_unused_local_variables.py @@ -0,0 +1,153 @@ +from __future__ import annotations + +import ast +import re +import unittest + +from utils.annotations.suppress import is_suppressed_at + +from . import ACCEPTABLE_UNUSED, python_modules + +_RULE = "unused-local" +_RUFF_DUMMY = re.compile(r"_+|_+[a-zA-Z0-9_]*[a-zA-Z0-9]+?") +_FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef) + + +def _own_statements(function: ast.FunctionDef | ast.AsyncFunctionDef) -> list[ast.AST]: + """Return the nodes of a function body outside its nested functions and classes. + + Args: + function: the function. + """ + found: list[ast.AST] = [] + pending: list[ast.AST] = list(function.body) + while pending: + node = pending.pop() + found.append(node) + if isinstance(node, (*_FUNCTIONS, ast.ClassDef, ast.Lambda)): + continue + pending.extend(ast.iter_child_nodes(node)) + return found + + +def _targets(node: ast.AST) -> list[list[ast.Name]]: + """Return the name groups one statement binds, a tuple target as one group. + + Args: + node: a node of the function body. + """ + if isinstance(node, ast.Assign): + raw = node.targets + elif (isinstance(node, ast.AnnAssign) and node.value is not None) or isinstance( + node, ast.NamedExpr + ): + raw = [node.target] + elif isinstance(node, ast.withitem) and node.optional_vars is not None: + raw = [node.optional_vars] + else: + return [] + groups: list[list[ast.Name]] = [] + for target in raw: + if isinstance(target, ast.Name): + groups.append([target]) + elif isinstance(target, (ast.Tuple, ast.List)): + groups.append([e for e in target.elts if isinstance(e, ast.Name)]) + return groups + + +def _offenders(rel_path: str, tree: ast.Module, content: str) -> list[str]: + """Return the dummy-named locals of one module that nothing reads. + + Args: + rel_path: path relative to the project root. + tree: the parsed module. + content: the module's text. + """ + lines = content.splitlines() + found: list[str] = [] + for function in ast.walk(tree): + if not isinstance(function, _FUNCTIONS): + continue + read = { + node.id + for node in ast.walk(function) + if isinstance(node, ast.Name) and not isinstance(node.ctx, ast.Store) + } + shared = { + name + for node in ast.walk(function) + if isinstance(node, (ast.Global, ast.Nonlocal)) + for name in node.names + } + for node in _own_statements(function): + for group in _targets(node): + unread = [n for n in group if n.id not in read and n.id not in shared] + if not group or len(unread) != len(group): + continue + found.extend( + f"{rel_path}:{name.lineno}: {name.id}" + for name in unread + if _RUFF_DUMMY.fullmatch(name.id) + and not ACCEPTABLE_UNUSED.fullmatch(name.id) + and not is_suppressed_at( + lines, name.lineno, _RULE, mode="same-or-above" + ) + ) + return found + + +class TestUnusedLocalVariables(unittest.TestCase): + def test_no_underscore_local_goes_unread(self) -> None: + offenders: list[str] = [] + for rel, content, tree in python_modules(): + offenders.extend(_offenders(rel, tree, content)) + + report = "\n".join(f" - {o}" for o in sorted(offenders)) + self.assertFalse( + offenders, + f"{len(offenders)} local variable(s) carry a leading underscore, " + "which keeps ruff quiet, but nothing reads them:\n" + f"{report}\n\n" + "Bind only what is used: index or slice the value, or use a bare " + "`_` for a position the code has to skip. A binding that has to " + f"live, such as a keepalive, says why with `# nocheck: {_RULE} " + "`.", + ) + + +class TestUnusedLocalDetection(unittest.TestCase): + def _run(self, source: str) -> list[str]: + return _offenders("m.py", ast.parse(source), source) + + def test_a_nocheck_suppresses_it(self) -> None: + source = f"def f():\n _keep = g() # nocheck: {_RULE} reason\n" + + self.assertEqual([], self._run(source)) + + def test_an_unread_underscore_name_is_reported(self) -> None: + source = "def f():\n _name, self.email = g()\n" + + self.assertEqual(["m.py:2: _name"], self._run(source)) + + def test_a_bare_underscore_is_accepted(self) -> None: + self.assertEqual([], self._run("def f():\n _, b = g()\n return b\n")) + + def test_a_tuple_with_a_read_element_is_accepted(self) -> None: + source = "def f():\n _name, email = g()\n return email\n" + + self.assertEqual([], self._run(source)) + + def test_a_plain_unread_name_is_left_to_ruff(self) -> None: + self.assertEqual([], self._run("def f():\n name = g()\n")) + + def test_a_name_read_in_a_closure_is_accepted(self) -> None: + source = "def f():\n _cache = {}\n def g():\n return _cache\n return g\n" + + self.assertEqual([], self._run(source)) + + def test_a_double_underscore_name_is_accepted(self) -> None: + self.assertEqual([], self._run("def f():\n __x = g()\n")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/lint/repository/structure/test_python_file_size.py b/tests/lint/repository/structure/test_python_file_size.py index 6d43a6530d..c57a4050b7 100644 --- a/tests/lint/repository/structure/test_python_file_size.py +++ b/tests/lint/repository/structure/test_python_file_size.py @@ -33,7 +33,7 @@ import unittest from pathlib import Path from utils.annotations.suppress import is_suppressed_in_head -from utils.cache.base import PROJECT_ROOT +from utils.cache import PROJECT_ROOT from utils.cache.files import iter_non_ignored_files MAX_PY_LINES: int = 500 diff --git a/tests/lint/repository/test_i18n_catalogs.py b/tests/lint/repository/test_i18n_catalogs.py index 1b7c026737..6911153518 100644 --- a/tests/lint/repository/test_i18n_catalogs.py +++ b/tests/lint/repository/test_i18n_catalogs.py @@ -19,17 +19,11 @@ from babel.messages.checkers import python_format from utils.cache.files import PROJECT_ROOT from utils.i18n.catalog import LOCALE_DIR, catalog_path, read_catalog +from utils.i18n.damage import MARKUP, added_spans, protected_spans from utils.i18n.extract import core_messages from utils.i18n.languages import domain_languages, load_languages -from utils.i18n.placeholders import ( - MARKUP, - TOKEN, - added_spans, - mask, - protected_spans, - resegment, - tighten, -) +from utils.i18n.placeholders import TOKEN, resegment, tighten +from utils.i18n.spans import mask SAMPLE = 20 QUOTED = re.compile(r"['\"][\w.-]+['\"]") diff --git a/tests/oracle/__init__.py b/tests/oracle/__init__.py index 42a5c69f62..8d77130e66 100644 --- a/tests/oracle/__init__.py +++ b/tests/oracle/__init__.py @@ -23,3 +23,5 @@ from pathlib import Path PROJECT_ROOT = Path(__file__).resolve().parents[2] SUITE = "oracle" + +__all__ = ["PROJECT_ROOT", "SUITE"] diff --git a/tests/unit/python/cli/administration/deploy/dedicated/test_command.py b/tests/unit/python/cli/administration/deploy/dedicated/test_command.py index 9476110fbd..6e8ff23fcb 100644 --- a/tests/unit/python/cli/administration/deploy/dedicated/test_command.py +++ b/tests/unit/python/cli/administration/deploy/dedicated/test_command.py @@ -1,8 +1,8 @@ from __future__ import annotations import unittest +import unittest.mock from types import SimpleNamespace -from unittest import mock from cli.administration.deploy.dedicated import command from cli.administration.deploy.dedicated.command import ( @@ -12,12 +12,12 @@ from cli.administration.deploy.dedicated.command import ( class TestPullCustomRoles(unittest.TestCase): - @mock.patch("cli.administration.deploy.dedicated.command.pull_or_exit") + @unittest.mock.patch("cli.administration.deploy.dedicated.command.pull_or_exit") def test_pulls_the_inventory_by_default(self, pull_or_exit): pull_custom_roles(SimpleNamespace(inventory="inv/devices.yml", skip_pull=False)) pull_or_exit.assert_called_once_with("inv/devices.yml") - @mock.patch("cli.administration.deploy.dedicated.command.pull_or_exit") + @unittest.mock.patch("cli.administration.deploy.dedicated.command.pull_or_exit") def test_skip_pull_keeps_the_placed_roles(self, pull_or_exit): pull_custom_roles(SimpleNamespace(inventory="inv/devices.yml", skip_pull=True)) pull_or_exit.assert_not_called() @@ -26,11 +26,13 @@ class TestPullCustomRoles(unittest.TestCase): calls: list[str] = [] args = SimpleNamespace(inventory="inv/devices.yml", skip_pull=False) with ( - mock.patch.object(command, "parse_args", return_value=(args, [], {})), - mock.patch.object( + unittest.mock.patch.object( + command, "parse_args", return_value=(args, [], {}) + ), + unittest.mock.patch.object( command, "pull_or_exit", side_effect=lambda _inv: calls.append("pull") ), - mock.patch.object( + unittest.mock.patch.object( command, "run_from_args", side_effect=lambda *_a: calls.append("deploy") or 0, diff --git a/tests/unit/python/cli/administration/deploy/development/deploy/test_run.py b/tests/unit/python/cli/administration/deploy/development/deploy/test_run.py index 07864c1178..6994687160 100644 --- a/tests/unit/python/cli/administration/deploy/development/deploy/test_run.py +++ b/tests/unit/python/cli/administration/deploy/development/deploy/test_run.py @@ -2,8 +2,8 @@ from __future__ import annotations import json import unittest +import unittest.mock from types import SimpleNamespace -from unittest import mock from ansible.parsing.splitter import parse_kv @@ -12,7 +12,7 @@ from cli.administration.deploy.development.deploy.run import _run_deploy class TestRunDeploy(unittest.TestCase): def deploy_cmd(self, extra_ansible_vars=None) -> list[str]: - compose = mock.Mock() + compose = unittest.mock.Mock() compose.exec.return_value = SimpleNamespace(returncode=0) _run_deploy( compose, diff --git a/tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py b/tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py index 105ec385f9..49a087f377 100644 --- a/tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py +++ b/tests/unit/python/cli/administration/deploy/development/inventory/test_builder.py @@ -258,11 +258,6 @@ class TestBuildDevInventoryMatrix(unittest.TestCase): "cli.administration.deploy.development.inventory.legacy_resolver._resolve_round_include", autospec=True, ) - @patch( - "cli.administration.deploy.development.inventory.legacy_resolver._build_services_overrides_for_round", - autospec=True, - return_value={}, - ) @patch( "cli.administration.deploy.development.inventory.builder.build_dev_inventory", autospec=True, @@ -279,7 +274,6 @@ class TestBuildDevInventoryMatrix(unittest.TestCase): self, _variants_mock: MagicMock, build_inventory_mock: MagicMock, - _overrides_mock: MagicMock, resolve_include_mock: MagicMock, ) -> None: resolve_include_mock.side_effect = [ diff --git a/tests/unit/python/cli/administration/deploy/swarm/test_command.py b/tests/unit/python/cli/administration/deploy/swarm/test_command.py index ed6c33c2c5..0f11ec01f1 100644 --- a/tests/unit/python/cli/administration/deploy/swarm/test_command.py +++ b/tests/unit/python/cli/administration/deploy/swarm/test_command.py @@ -1,8 +1,8 @@ from __future__ import annotations import unittest +import unittest.mock from types import SimpleNamespace -from unittest import mock from cli.administration.deploy.swarm import command @@ -17,14 +17,18 @@ class TestSwarmMain(unittest.TestCase): return ids with ( - mock.patch.object(command, "parse_args", return_value=(args, [], {})), - mock.patch.object( + unittest.mock.patch.object( + command, "parse_args", return_value=(args, [], {}) + ), + unittest.mock.patch.object( command, "pull_custom_roles", side_effect=lambda _args: calls.append("pull"), ), - mock.patch.object(command, "swarm_deploy_targets", side_effect=closure), - mock.patch.object(command, "run_from_args", return_value=0) as run, + unittest.mock.patch.object( + command, "swarm_deploy_targets", side_effect=closure + ), + unittest.mock.patch.object(command, "run_from_args", return_value=0) as run, ): self.assertEqual(0, command.main([])) diff --git a/tests/unit/python/cli/administration/inventory/provision/test_network_mode.py b/tests/unit/python/cli/administration/inventory/provision/test_network_mode.py index df67e3cd20..681f47ed0a 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_network_mode.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_network_mode.py @@ -1,10 +1,9 @@ import shutil import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock -import utils.handler.vault # noqa: F401 registers the !vault YAML constructor from cli.administration.inventory.provision.network_mode import ( apply_network_mode_from_env, ) @@ -29,7 +28,7 @@ class TestApplyNetworkModeFromEnv(unittest.TestCase): if existing: hv.write_text(existing, encoding="utf-8") env = {} if network is None else {"network": network} - with mock.patch.dict("os.environ", env, clear=True): + with unittest.mock.patch.dict("os.environ", env, clear=True): apply_network_mode_from_env(hv) return hv diff --git a/tests/unit/python/cli/administration/inventory/provision/test_tor_node.py b/tests/unit/python/cli/administration/inventory/provision/test_tor_node.py index 021bbab775..23fcd943f8 100644 --- a/tests/unit/python/cli/administration/inventory/provision/test_tor_node.py +++ b/tests/unit/python/cli/administration/inventory/provision/test_tor_node.py @@ -2,7 +2,6 @@ import tempfile import unittest from pathlib import Path -import utils.handler.vault # noqa: F401 registers the !vault YAML constructor from cli.administration.inventory.provision.tor_node import apply_tor_node_onion from cli.administration.inventory.provision.yaml_io import load_yaml diff --git a/tests/unit/python/cli/administration/roles/clean/test_main.py b/tests/unit/python/cli/administration/roles/clean/test_main.py index c3b921fc3c..b88115e357 100644 --- a/tests/unit/python/cli/administration/roles/clean/test_main.py +++ b/tests/unit/python/cli/administration/roles/clean/test_main.py @@ -3,7 +3,7 @@ from __future__ import annotations import contextlib import io import unittest -from unittest import mock +import unittest.mock import cli.administration.roles.clean.__main__ as clean_main @@ -15,7 +15,9 @@ class TestCleanMain(unittest.TestCase): "web-app-cst-hand: left in place, the pull did not place it", ] with ( - mock.patch.object(clean_main, "clean", return_value=lines) as clean, + unittest.mock.patch.object( + clean_main, "clean", return_value=lines + ) as clean, contextlib.redirect_stdout(io.StringIO()) as out, ): self.assertEqual(0, clean_main.main([])) @@ -28,7 +30,9 @@ class TestCleanMain(unittest.TestCase): def test_a_filesystem_error_exits_with_it(self): with ( - mock.patch.object(clean_main, "clean", side_effect=OSError("busy")), + unittest.mock.patch.object( + clean_main, "clean", side_effect=OSError("busy") + ), self.assertRaises(SystemExit) as exit_, ): clean_main.main([]) diff --git a/tests/unit/python/cli/administration/roles/list/test_main.py b/tests/unit/python/cli/administration/roles/list/test_main.py index 7e89a24a5e..e8ee313b37 100644 --- a/tests/unit/python/cli/administration/roles/list/test_main.py +++ b/tests/unit/python/cli/administration/roles/list/test_main.py @@ -4,8 +4,8 @@ import contextlib import io import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock import cli.administration.roles.list.__main__ as list_main from cli.administration.roles.marker import MARKER_FILE, marker_text @@ -25,7 +25,7 @@ class TestListMain(unittest.TestCase): (roles / "web-app-cst-hand").mkdir() (roles / "web-app-nextcloud").mkdir() with ( - mock.patch.object(list_main, "ROLES_DIR", roles), + unittest.mock.patch.object(list_main, "ROLES_DIR", roles), contextlib.redirect_stdout(io.StringIO()) as out, ): self.assertEqual(0, list_main.main([])) diff --git a/tests/unit/python/cli/administration/roles/pull/test_command.py b/tests/unit/python/cli/administration/roles/pull/test_command.py index 6412c37d9e..4d8ce1eab0 100644 --- a/tests/unit/python/cli/administration/roles/pull/test_command.py +++ b/tests/unit/python/cli/administration/roles/pull/test_command.py @@ -4,8 +4,8 @@ import contextlib import io import tarfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from yaml.constructor import ConstructorError @@ -16,7 +16,7 @@ from utils.roles.custom import CustomRoleError class TestPullCommand(unittest.TestCase): - @mock.patch.object( + @unittest.mock.patch.object( command, "pull", return_value=["web-app-cst-demo: repo path @ v1 (commit abc)"] ) def test_pulls_the_inventory_into_the_core_roles(self, pull): @@ -25,7 +25,7 @@ class TestPullCommand(unittest.TestCase): pull.assert_called_once_with(Path("inv/devices.yml"), ROLES_DIR, WORK_DIR) self.assertIn("web-app-cst-demo: repo path @ v1 (commit abc)", out.getvalue()) - @mock.patch.object(command, "pull", return_value=[]) + @unittest.mock.patch.object(command, "pull", return_value=[]) def test_nothing_declared_or_placed_prints_nothing(self, _pull): with contextlib.redirect_stdout(io.StringIO()) as out: command.main(["inv/devices.yml"]) @@ -39,7 +39,7 @@ class TestPullCommand(unittest.TestCase): ): with self.subTest(error=type(error).__name__): with ( - mock.patch.object(command, "pull", side_effect=error), + unittest.mock.patch.object(command, "pull", side_effect=error), contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as exit_, ): @@ -47,7 +47,7 @@ class TestPullCommand(unittest.TestCase): self.assertEqual(1, exit_.exception.code) self.assertIn(str(error), err.getvalue()) - @mock.patch.object( + @unittest.mock.patch.object( command, "pull", side_effect=CustomRoleError( @@ -64,7 +64,7 @@ class TestPullCommand(unittest.TestCase): self.assertNotIn("s3cr3t", err.getvalue()) self.assertIn("web-app-cst-demo: git fetch of v1 failed", err.getvalue()) - @mock.patch.object( + @unittest.mock.patch.object( command, "pull", side_effect=CustomRoleError("web-app-cst-demo: refused") ) def test_refused_pull_exits_1_with_the_reason(self, _pull): diff --git a/tests/unit/python/cli/administration/roles/test_placement.py b/tests/unit/python/cli/administration/roles/test_placement.py index 74a2f32b9f..c7b6fb5573 100644 --- a/tests/unit/python/cli/administration/roles/test_placement.py +++ b/tests/unit/python/cli/administration/roles/test_placement.py @@ -7,8 +7,8 @@ import stat import tempfile import threading import unittest +import unittest.mock from pathlib import Path -from unittest import mock from cli.administration.roles import placement from cli.administration.roles.marker import MARKER_FILE, is_placed @@ -403,7 +403,7 @@ class TestPullCommit(_PullFixture, unittest.TestCase): return rmtree(path, *args, **kwargs) with ( - mock.patch.object(placement.shutil, "rmtree", interrupted), + unittest.mock.patch.object(placement.shutil, "rmtree", interrupted), self.assertRaises(KeyboardInterrupt), ): self.pull({ROLE: declaration(str(self.repo))}) @@ -420,7 +420,9 @@ class TestPullCommit(_PullFixture, unittest.TestCase): return stage(group, source, target) with ( - mock.patch.object(placement, "stage", stage_beside_a_hand_placed_copy), + unittest.mock.patch.object( + placement, "stage", stage_beside_a_hand_placed_copy + ), self.assertRaisesRegex( CustomRoleError, f"{ROLE}: .* was not placed by a pull" ), @@ -443,7 +445,7 @@ class TestPullCommit(_PullFixture, unittest.TestCase): events.append(("clean still waiting", cleaner.is_alive())) return stage(group, source, target) - with mock.patch.object(placement, "stage", stage_while_a_clean_starts): + with unittest.mock.patch.object(placement, "stage", stage_while_a_clean_starts): self.pull({ROLE: declaration(str(self.repo))}) cleaner.join(timeout=30) self.assertEqual(("clean still waiting", True), events[0]) diff --git a/tests/unit/python/cli/administration/roles/test_source.py b/tests/unit/python/cli/administration/roles/test_source.py index f8d529643a..e7013e4284 100644 --- a/tests/unit/python/cli/administration/roles/test_source.py +++ b/tests/unit/python/cli/administration/roles/test_source.py @@ -4,8 +4,8 @@ import re import subprocess import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from cli.administration.roles import source as source_module from cli.administration.roles.declaration import Source @@ -167,7 +167,7 @@ class TestGitNeverPrompts(unittest.TestCase): source = Source("git@example.invalid:acme/widgets.git", "v1.0.0", ROLE_PATH) with ( tempfile.TemporaryDirectory() as tmp, - mock.patch.dict( + unittest.mock.patch.dict( "os.environ", { "GIT_ASKPASS": "/bin/askpass", @@ -175,7 +175,7 @@ class TestGitNeverPrompts(unittest.TestCase): "SSH_AUTH_SOCK": "/run/agent.sock", }, ), - mock.patch.object( + unittest.mock.patch.object( source_module.subprocess, "run", return_value=failed ) as run, self.assertRaisesRegex(CustomRoleError, "could not read Username"), diff --git a/tests/unit/python/cli/build/i18n/test_main.py b/tests/unit/python/cli/build/i18n/test_main.py index 53b263bf04..0e48f0e5d2 100644 --- a/tests/unit/python/cli/build/i18n/test_main.py +++ b/tests/unit/python/cli/build/i18n/test_main.py @@ -10,8 +10,9 @@ from pathlib import Path from tempfile import TemporaryDirectory from utils.i18n.catalog import catalog_path, new_catalog, write_catalog +from utils.i18n.client import Outcome from utils.i18n.languages import LANGUAGES_FILE -from utils.i18n.libretranslate import SERVICE_KEY, SERVICES_FILE, Outcome +from utils.i18n.libretranslate import SERVICE_KEY, SERVICES_FILE cli = importlib.import_module("cli.build.i18n.__main__") @@ -74,7 +75,9 @@ class TestTranslate(unittest.TestCase): self.root = _checkout(self) _catalog(self.root, "de", "Hallo") - def _run(self, requested: list[str] | None = None) -> tuple[int, mock.Mock, mock.Mock]: + def _run( + self, requested: list[str] | None = None + ) -> tuple[int, mock.Mock, mock.Mock]: started = mock.Mock(return_value=contextlib.nullcontext("http://lt")) client = mock.Mock() client.return_value.translate.side_effect = lambda texts, code: Outcome( diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_main.py b/tests/unit/python/cli/meta/ci/variant_split/test_main.py index 9739ea1398..4ff34e9f53 100644 --- a/tests/unit/python/cli/meta/ci/variant_split/test_main.py +++ b/tests/unit/python/cli/meta/ci/variant_split/test_main.py @@ -4,9 +4,9 @@ import io import json import tempfile import unittest +import unittest.mock from contextlib import redirect_stderr, redirect_stdout from pathlib import Path -from unittest import mock from cli.meta.ci.variant_split import __main__ as cli from cli.meta.ci.variant_split import snapshot as snapshot_module @@ -95,7 +95,7 @@ class TestMain(unittest.TestCase): def test_snapshot_passes_the_seed_and_records_it(self) -> None: out_path = self.tmp / "snap.json" - with mock.patch.object( + with unittest.mock.patch.object( snapshot_module, "take", return_value=_snap(seed="42") ) as take: rc, _, _ = self._run( diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py b/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py index 51502f89e6..db5eb45c58 100644 --- a/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py +++ b/tests/unit/python/cli/meta/ci/variant_split/test_rounds.py @@ -2,8 +2,8 @@ from __future__ import annotations import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from cli.meta.ci.variant_split import rounds from utils.roles.mapping import ROLE_FILE_META_SERVICES, ROLE_FILE_META_VARIANTS @@ -92,7 +92,9 @@ class TestDictated(unittest.TestCase): def _dictated(self, include: list[str], active: dict[str, int]) -> dict: found = {("web-app-a", 1): {"web-app-b", "web-app-gone"}} - with mock.patch.object(rounds, "overridden_providers", return_value=found): + with unittest.mock.patch.object( + rounds, "overridden_providers", return_value=found + ): return rounds.dictated(include, active, roles_dir="/roles") def test_a_member_whose_config_a_variant_dictates_names_that_variant( diff --git a/tests/unit/python/cli/meta/ci/variant_split/test_snapshot.py b/tests/unit/python/cli/meta/ci/variant_split/test_snapshot.py index ea9b6f1399..684ab24fc3 100644 --- a/tests/unit/python/cli/meta/ci/variant_split/test_snapshot.py +++ b/tests/unit/python/cli/meta/ci/variant_split/test_snapshot.py @@ -3,8 +3,8 @@ from __future__ import annotations import os import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from cli.meta.ci.variant_split import snapshot from utils.roles.mapping import ROLE_FILE_META_VARIANTS @@ -83,7 +83,7 @@ class TestSeeds(unittest.TestCase): def test_an_empty_seed_never_takes_a_snapshot(self) -> None: with ( - mock.patch.object(snapshot, "pipeline") as pipeline, + unittest.mock.patch.object(snapshot, "pipeline") as pipeline, self.assertRaises(ValueError), ): snapshot.take([0], seed=" ") @@ -97,8 +97,8 @@ class TestSeeds(unittest.TestCase): raise RuntimeError with ( - mock.patch.dict(os.environ, {}), - mock.patch.object(snapshot, "pipeline", pipeline), + unittest.mock.patch.dict(os.environ, {}), + unittest.mock.patch.object(snapshot, "pipeline", pipeline), self.assertRaises(RuntimeError), ): snapshot.take([0], seed="42305502796") diff --git a/tests/unit/python/cli/meta/ci/variant_tree/test_main.py b/tests/unit/python/cli/meta/ci/variant_tree/test_main.py index da625b5722..594e0e7a66 100644 --- a/tests/unit/python/cli/meta/ci/variant_tree/test_main.py +++ b/tests/unit/python/cli/meta/ci/variant_tree/test_main.py @@ -3,8 +3,8 @@ from __future__ import annotations import io import json import unittest +import unittest.mock from contextlib import redirect_stderr, redirect_stdout -from unittest import mock from cli.meta.ci.variant_tree import __main__ as cli from cli.meta.ci.variant_tree import tree @@ -32,12 +32,14 @@ AXES = {"0": {"entries": [], "job_position": 3, "in_budget_head": True, "covered class TestMain(unittest.TestCase): def _run( self, *argv: str, built: dict | None = None - ) -> tuple[int, str, str, mock.Mock]: + ) -> tuple[int, str, str, unittest.mock.Mock]: out, err = io.StringIO(), io.StringIO() with ( - mock.patch("utils.cache.applications.get_variants", return_value=FOUR), - mock.patch.object(tree, "build", wraps=tree.build) as build, - mock.patch( + unittest.mock.patch( + "utils.cache.applications.get_variants", return_value=FOUR + ), + unittest.mock.patch.object(tree, "build", wraps=tree.build) as build, + unittest.mock.patch( "cli.meta.ci.variant_split.snapshot.row_axes", return_value=AXES ) as axes, redirect_stdout(out), diff --git a/tests/unit/python/library/test_ldap_entries.py b/tests/unit/python/library/test_ldap_entries.py index 14dd9bf225..5781b23a69 100644 --- a/tests/unit/python/library/test_ldap_entries.py +++ b/tests/unit/python/library/test_ldap_entries.py @@ -4,13 +4,9 @@ import importlib.util import sys import types import unittest -from typing import TYPE_CHECKING from . import PROJECT_ROOT -if TYPE_CHECKING: - from types import ModuleType - sys.path.insert(0, str(PROJECT_ROOT)) MODULE_PATH = PROJECT_ROOT / "library" / "ldap_entries.py" @@ -36,7 +32,7 @@ def _fake_ldap() -> types.ModuleType: return fake -def _load_ldap_entries() -> ModuleType: +def _load_ldap_entries() -> types.ModuleType: fake = _fake_ldap() sys.modules["ldap"] = fake sys.modules["ldap.modlist"] = fake.modlist diff --git a/tests/unit/python/library/test_ldap_passwords.py b/tests/unit/python/library/test_ldap_passwords.py index cfe305431b..d91dc51819 100644 --- a/tests/unit/python/library/test_ldap_passwords.py +++ b/tests/unit/python/library/test_ldap_passwords.py @@ -4,13 +4,9 @@ import importlib.util import sys import types import unittest -from typing import TYPE_CHECKING from . import PROJECT_ROOT -if TYPE_CHECKING: - from types import ModuleType - sys.path.insert(0, str(PROJECT_ROOT)) MODULE_PATH = PROJECT_ROOT / "library" / "ldap_passwords.py" @@ -61,7 +57,7 @@ class _Connection: self.server.passwords[dn] = newpw -def _load(server) -> ModuleType: +def _load(server) -> types.ModuleType: fake = types.ModuleType("ldap") fake.LDAPError = _LDAPError fake.INVALID_CREDENTIALS = _InvalidCredentialsError diff --git a/tests/unit/python/plugins/filter/test_reserved_users.py b/tests/unit/python/plugins/filter/test_reserved_users.py index 42431a4e0d..4a624ef09d 100644 --- a/tests/unit/python/plugins/filter/test_reserved_users.py +++ b/tests/unit/python/plugins/filter/test_reserved_users.py @@ -2,7 +2,6 @@ import unittest import reserved_users from ansible.errors import AnsibleFilterError -from reserved_users import non_reserved_users, reserved_usernames class TestReservedUsersFilters(unittest.TestCase): @@ -41,10 +40,10 @@ class TestReservedUsersFilters(unittest.TestCase): def test_reserved_usernames_requires_dict(self): with self.assertRaises(AnsibleFilterError): - reserved_usernames(["not", "a", "dict"]) + reserved_users.reserved_usernames(["not", "a", "dict"]) def test_reserved_usernames_returns_only_non_identity(self): - result = reserved_usernames(self.users) + result = reserved_users.reserved_usernames(self.users) self.assertIn("admin", result) self.assertIn("backup", result) self.assertIn("service\\.user", result) @@ -52,29 +51,31 @@ class TestReservedUsersFilters(unittest.TestCase): self.assertNotIn("kevin", result) def test_missing_accounts_field_counts_as_reserved(self): - self.assertIn("noaccounts", reserved_usernames(self.users)) - self.assertNotIn("no_accounts_field", non_reserved_users(self.users)) + self.assertIn("noaccounts", reserved_users.reserved_usernames(self.users)) + self.assertNotIn( + "no_accounts_field", reserved_users.non_reserved_users(self.users) + ) def test_reserved_usernames_ignores_entries_without_username(self): - result = reserved_usernames(self.users) + result = reserved_users.reserved_usernames(self.users) for item in result: self.assertNotIn("no_username_field", item) def test_reserved_usernames_escapes_special_chars(self): - result = reserved_usernames(self.users) + result = reserved_users.reserved_usernames(self.users) self.assertIn("service\\.user", result) self.assertNotIn("service.user", result) def test_reserved_usernames_empty_dict(self): - result = reserved_usernames({}) + result = reserved_users.reserved_usernames({}) self.assertEqual(result, []) def test_non_reserved_users_requires_dict(self): with self.assertRaises(AnsibleFilterError): - non_reserved_users("not-a-dict") + reserved_users.non_reserved_users("not-a-dict") def test_non_reserved_users_returns_only_identity_provisioned(self): - result = non_reserved_users(self.users) + result = reserved_users.non_reserved_users(self.users) self.assertIsInstance(result, dict) self.assertIn("kevin", result) @@ -83,11 +84,11 @@ class TestReservedUsersFilters(unittest.TestCase): self.assertNotIn("service.user", result) def test_non_reserved_users_ignores_non_dict_entries(self): - result = non_reserved_users(self.users) + result = reserved_users.non_reserved_users(self.users) self.assertNotIn("not_a_dict", result) def test_non_reserved_users_empty_dict(self): - result = non_reserved_users({}) + result = reserved_users.non_reserved_users({}) self.assertEqual(result, {}) def test_filtermodule_registers_filters(self): diff --git a/tests/unit/python/plugins/lookup/test_addon_env_flags.py b/tests/unit/python/plugins/lookup/test_addon_env_flags.py index 273d88ae24..65598562f2 100644 --- a/tests/unit/python/plugins/lookup/test_addon_env_flags.py +++ b/tests/unit/python/plugins/lookup/test_addon_env_flags.py @@ -1,6 +1,5 @@ import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -51,12 +50,12 @@ class TestAddonEnvFlagsLookup(unittest.TestCase): "no_required": {"enabled": True}, } self._patchers = [ - patch( + mock.patch( "plugins.lookup.addon_env_flags.lookup_loader", _applications_loader({}), ), - patch("plugins.lookup.addon_env_flags.get", return_value=self.addons), - patch( + mock.patch("plugins.lookup.addon_env_flags.get", return_value=self.addons), + mock.patch( "plugins.lookup.addon_env_flags._render_with_templar", side_effect=lambda v, **k: v, ), @@ -108,12 +107,12 @@ class TestNoAddons(unittest.TestCase): lookup = LookupModule() lookup._loader = mock.MagicMock() with ( - patch( + mock.patch( "plugins.lookup.addon_env_flags.lookup_loader", _applications_loader({}), ), - patch("plugins.lookup.addon_env_flags.get", return_value={}), - patch( + mock.patch("plugins.lookup.addon_env_flags.get", return_value={}), + mock.patch( "plugins.lookup.addon_env_flags._render_with_templar", side_effect=lambda v, **k: v, ), @@ -154,12 +153,12 @@ class TestBridgeDeploymentGating(unittest.TestCase): }, } self._patchers = [ - patch( + mock.patch( "plugins.lookup.addon_env_flags.lookup_loader", _applications_loader({}), ), - patch("plugins.lookup.addon_env_flags.get", return_value=self.addons), - patch( + mock.patch("plugins.lookup.addon_env_flags.get", return_value=self.addons), + mock.patch( "plugins.lookup.addon_env_flags._render_with_templar", side_effect=lambda v, **k: v, ), @@ -231,12 +230,12 @@ class TestBridgeResolvesProviderKey(unittest.TestCase): "ca_trust": {"enabled": True, "required": True, "bridges": ["sso"]}, } self._patchers = [ - patch( + mock.patch( "plugins.lookup.addon_env_flags.lookup_loader", _applications_loader(self.applications), ), - patch("plugins.lookup.addon_env_flags.get", return_value=self.addons), - patch( + mock.patch("plugins.lookup.addon_env_flags.get", return_value=self.addons), + mock.patch( "plugins.lookup.addon_env_flags._render_with_templar", side_effect=lambda v, **k: v, ), diff --git a/tests/unit/python/plugins/lookup/test_address_pool_overlaps.py b/tests/unit/python/plugins/lookup/test_address_pool_overlaps.py index ae9cb6ab03..6dc5bde6e3 100644 --- a/tests/unit/python/plugins/lookup/test_address_pool_overlaps.py +++ b/tests/unit/python/plugins/lookup/test_address_pool_overlaps.py @@ -1,6 +1,6 @@ import json import unittest -from unittest import mock +import unittest.mock from ansible.errors import AnsibleError @@ -17,19 +17,19 @@ def _context(): roles=["sys-ctl-hlth-csp", "web-app-matomo"], applications={}, config=lambda role, path, default: SUBNETS.get(role, default), - lookup=mock.Mock(), + lookup=unittest.mock.Mock(), ) class TestAddressPoolOverlapsLookup(unittest.TestCase): def _run(self, terms, side_effect=None): with ( - mock.patch( + unittest.mock.patch( f"{MODULE}.deploy_closure_context", return_value=_context(), side_effect=side_effect, ), - mock.patch( + unittest.mock.patch( f"{MODULE}.entity_name", side_effect=lambda role: role.split("-", 2)[-1] ), ): diff --git a/tests/unit/python/plugins/lookup/test_asset.py b/tests/unit/python/plugins/lookup/test_asset.py index 0ee22862a4..22b5291718 100644 --- a/tests/unit/python/plugins/lookup/test_asset.py +++ b/tests/unit/python/plugins/lookup/test_asset.py @@ -5,7 +5,6 @@ import tempfile import unittest import unittest.mock as mock from pathlib import Path -from unittest.mock import patch from ansible.errors import AnsibleError @@ -44,7 +43,7 @@ def _patched_loader(flavor="internal", base="https://cdn.example.org/"): loader_mock = mock.MagicMock() loader_mock.get.side_effect = _get - return patch.object(asset_mod, "lookup_loader", loader_mock) + return mock.patch.object(asset_mod, "lookup_loader", loader_mock) def _write_lock(tmpdir: str, packages: dict) -> None: @@ -98,7 +97,7 @@ class TestLockedVersion(unittest.TestCase): self.tmpdir = tempfile.mkdtemp() def _patched_role_path(self): - return patch.object( + return mock.patch.object( asset_mod, "abs_role_path_by_application_id", return_value=self.tmpdir ) @@ -139,7 +138,7 @@ class TestAssetRun(unittest.TestCase): def _run(self, terms, variables): with ( - patch.object( + mock.patch.object( asset_mod, "abs_role_path_by_application_id", return_value=self.tmpdir ), _patched_loader(flavor="internal"), diff --git a/tests/unit/python/plugins/lookup/test_cert.py b/tests/unit/python/plugins/lookup/test_cert.py index 1e9dd89bd4..72698c812e 100644 --- a/tests/unit/python/plugins/lookup/test_cert.py +++ b/tests/unit/python/plugins/lookup/test_cert.py @@ -1,7 +1,6 @@ import sys import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -66,7 +65,7 @@ class TestCertPlanLookup(unittest.TestCase): return mock.MagicMock(run=_applications_from_vars) return mock.MagicMock(run=lambda *_ra, **_rk: [{}]) - loader_patcher = patch("plugins.lookup.cert.lookup_loader") + loader_patcher = mock.patch("plugins.lookup.cert.lookup_loader") loader_mock = loader_patcher.start() loader_mock.get.side_effect = _get self.addCleanup(loader_patcher.stop) diff --git a/tests/unit/python/plugins/lookup/test_container_address.py b/tests/unit/python/plugins/lookup/test_container_address.py index ae6d8734ed..5e1051f5f0 100644 --- a/tests/unit/python/plugins/lookup/test_container_address.py +++ b/tests/unit/python/plugins/lookup/test_container_address.py @@ -12,7 +12,6 @@ from __future__ import annotations import unittest import unittest.mock as mock from typing import Any -from unittest.mock import patch from ansible.errors import AnsibleError @@ -37,7 +36,7 @@ def _run( applications: dict[str, Any] | None = None, ) -> list[str]: apps = applications if applications is not None else _apps() - with patch("plugins.lookup.container_address.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_address.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) lm = LookupModule() lm._loader = mock.MagicMock() diff --git a/tests/unit/python/plugins/lookup/test_container_depends_on.py b/tests/unit/python/plugins/lookup/test_container_depends_on.py index 80ea1eae4d..bf47896904 100644 --- a/tests/unit/python/plugins/lookup/test_container_depends_on.py +++ b/tests/unit/python/plugins/lookup/test_container_depends_on.py @@ -3,7 +3,6 @@ from __future__ import annotations import unittest import unittest.mock as mock from typing import Any, ClassVar -from unittest.mock import patch from ansible.errors import AnsibleError @@ -36,7 +35,7 @@ def _apps(*, db_enabled=False, db_shared=False, redis=False, oauth2=False): def _run(app_id, applications, *, variables=None, **kwargs): lookup = LookupModule() lookup._loader = mock.MagicMock() - with patch("plugins.lookup.container_depends_on.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_depends_on.lookup_loader") as loader_mock: loader_mock.get.side_effect = _applications_loader(applications) return lookup.run([app_id], variables=variables or {}, **kwargs) @@ -164,7 +163,9 @@ class TestContainerDependsOnLookup(unittest.TestCase): lookup = LookupModule() lookup._templar = _StubTemplar() lookup._loader = mock.MagicMock() - with patch("plugins.lookup.container_depends_on.lookup_loader") as loader_mock: + with mock.patch( + "plugins.lookup.container_depends_on.lookup_loader" + ) as loader_mock: loader_mock.get.side_effect = _applications_loader( _apps(db_enabled=True, redis=True) ) diff --git a/tests/unit/python/plugins/lookup/test_container_image.py b/tests/unit/python/plugins/lookup/test_container_image.py index 9e01d4e7b7..f5375c3247 100644 --- a/tests/unit/python/plugins/lookup/test_container_image.py +++ b/tests/unit/python/plugins/lookup/test_container_image.py @@ -9,7 +9,6 @@ from __future__ import annotations import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -18,7 +17,7 @@ from plugins.lookup.container_image import LookupModule def _run_with_ref(ref: str, terms, **kwargs) -> tuple[list[str], mock.MagicMock]: image_plugin = mock.MagicMock(run=mock.MagicMock(return_value=[ref])) - with patch("plugins.lookup.container_image.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_image.lookup_loader") as loader_mock: loader_mock.get.return_value = image_plugin lm = LookupModule() lm._loader = mock.MagicMock() @@ -60,7 +59,7 @@ class TestContainerImageLookup(unittest.TestCase): image_plugin = mock.MagicMock( run=mock.MagicMock(side_effect=AnsibleError("boom")) ) - with patch("plugins.lookup.container_image.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_image.lookup_loader") as loader_mock: loader_mock.get.return_value = image_plugin lm = LookupModule() lm._loader = mock.MagicMock() diff --git a/tests/unit/python/plugins/lookup/test_container_ports.py b/tests/unit/python/plugins/lookup/test_container_ports.py index 385946855a..72d0c20026 100644 --- a/tests/unit/python/plugins/lookup/test_container_ports.py +++ b/tests/unit/python/plugins/lookup/test_container_ports.py @@ -1,7 +1,6 @@ import unittest import unittest.mock as mock from typing import ClassVar -from unittest.mock import patch from ansible.errors import AnsibleError @@ -28,7 +27,7 @@ def _run(terms, *, app_id="web-app-gitea", **kwargs): lm = LookupModule() lm._loader = mock.MagicMock() apps = _apps() - with patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) return lm.run(terms, variables={"application_id": app_id}, **kwargs) @@ -90,7 +89,7 @@ class TestContainerPortsLookup(unittest.TestCase): lm = LookupModule() lm._loader = mock.MagicMock() with ( - patch("plugins.lookup.container_ports.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.container_ports.lookup_loader") as loader_mock, self.assertRaises(AnsibleError), ): loader_mock.get.return_value = mock.MagicMock( @@ -108,7 +107,7 @@ class TestContainerPortsLookup(unittest.TestCase): lookup = LookupModule() lookup._templar = _Templar() lookup._loader = mock.MagicMock() - with patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock( run=lambda *_a, **_k: [_apps()] ) @@ -147,7 +146,7 @@ def _run_edge(terms): lookup = LookupModule() lookup._loader = mock.MagicMock() apps = _edge_apps() - with patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) return lookup.run(terms, variables={"application_id": "web-svc-coturn"})[0] @@ -213,7 +212,7 @@ class TestContainerPortsDictTerms(unittest.TestCase): def test_key_names_the_block(self): lookup = LookupModule() lookup._loader = mock.MagicMock() - with patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_ports.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock( run=lambda *_a, **_k: [_edge_apps()] ) @@ -228,7 +227,7 @@ class TestContainerPortsDictTerms(unittest.TestCase): lookup = LookupModule() lookup._loader = mock.MagicMock() with ( - patch("plugins.lookup.container_ports.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.container_ports.lookup_loader") as loader_mock, self.assertRaises(AnsibleError), ): loader_mock.get.return_value = mock.MagicMock( diff --git a/tests/unit/python/plugins/lookup/test_container_service.py b/tests/unit/python/plugins/lookup/test_container_service.py index 6868290494..6b5b3d7887 100644 --- a/tests/unit/python/plugins/lookup/test_container_service.py +++ b/tests/unit/python/plugins/lookup/test_container_service.py @@ -9,7 +9,6 @@ from __future__ import annotations import unittest import unittest.mock as mock from typing import Any -from unittest.mock import patch from ansible.errors import AnsibleError @@ -36,7 +35,7 @@ def _run( apps = applications if applications is not None else _apps() lm = LookupModule() lm._loader = mock.MagicMock() - with patch("plugins.lookup.container_service.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.container_service.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) return lm.run([application_id, service_key], variables=variables or {}) diff --git a/tests/unit/python/plugins/lookup/test_database.py b/tests/unit/python/plugins/lookup/test_database.py index 95aee7ccc6..42bfaf834d 100644 --- a/tests/unit/python/plugins/lookup/test_database.py +++ b/tests/unit/python/plugins/lookup/test_database.py @@ -1,7 +1,6 @@ import importlib.util import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -88,7 +87,7 @@ class DatabaseLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -115,7 +114,7 @@ class DatabaseLookupTests(unittest.TestCase): self.assertEqual(out["version"], "") self.assertEqual(out["reach_host"], "127.0.0.1") - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -150,7 +149,7 @@ class DatabaseLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -183,7 +182,7 @@ class DatabaseLookupTests(unittest.TestCase): self.assertEqual(out["reach_host"], "127.0.0.1") self.assertEqual(out["instance"], "foo") - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -229,7 +228,7 @@ class DatabaseLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -266,7 +265,7 @@ class DatabaseLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -316,7 +315,7 @@ class DatabaseLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -361,7 +360,7 @@ class DatabaseLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -407,7 +406,7 @@ class DatabaseLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -433,7 +432,7 @@ class DatabaseLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -445,7 +444,7 @@ class DatabaseLookupTests(unittest.TestCase): self.assertFalse(out["local"]) self.assertEqual(out["host"], "") - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, @@ -525,7 +524,7 @@ class DatabaseLookupTests(unittest.TestCase): def _resolve(self, vars_): lookup = self._make_lookup(vars_) - with patch.object( + with mock.patch.object( self.db_lookup_mod, "entity_name", side_effect=self._fake_entity_name, diff --git a/tests/unit/python/plugins/lookup/test_deploy_domains.py b/tests/unit/python/plugins/lookup/test_deploy_domains.py index 84333a6fbc..7db1372255 100644 --- a/tests/unit/python/plugins/lookup/test_deploy_domains.py +++ b/tests/unit/python/plugins/lookup/test_deploy_domains.py @@ -1,5 +1,5 @@ import unittest -from unittest import mock +import unittest.mock from ansible.errors import AnsibleError @@ -17,14 +17,14 @@ def _context(): return DeployClosureContext( roles=["svc-db-mariadb", "web-app-matomo", "web-app-nextcloud"], applications={}, - config=mock.Mock(), + config=unittest.mock.Mock(), lookup=lambda name, role, default: DOMAINS.get(role, default), ) class TestDeployDomainsLookup(unittest.TestCase): def _run(self, terms, side_effect=None): - with mock.patch( + with unittest.mock.patch( f"{MODULE}.deploy_closure_context", return_value=_context(), side_effect=side_effect, diff --git a/tests/unit/python/plugins/lookup/test_docker_cards.py b/tests/unit/python/plugins/lookup/test_docker_cards.py index f6620d8695..09009b630e 100644 --- a/tests/unit/python/plugins/lookup/test_docker_cards.py +++ b/tests/unit/python/plugins/lookup/test_docker_cards.py @@ -17,7 +17,6 @@ sys.path.insert( ) import docker_cards as docker_cards_module -from docker_cards import LookupModule from utils.roles.mapping import ( ROLE_FILE_META_INFO, @@ -224,7 +223,7 @@ logo: return lookup_module.run([self.test_roles_dir], variables=fake_variables) def test_lookup_when_group_includes_application_id(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() fake_variables["TLS_ENABLED"] = True @@ -246,7 +245,7 @@ logo: self.assertTrue(card["iframe"]) def test_iframe_flag_defaults_to_enabled(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() result = self._run_lookup(lookup_module, fake_variables) @@ -254,7 +253,7 @@ logo: self.assertTrue(result[0][0]["iframe"]) def test_iframe_flag_false_decouples_from_enabled(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() fake_variables["applications"]["portfolio"]["services"]["dashboard"][ "iframe" @@ -267,7 +266,7 @@ logo: self.assertFalse(cards[0]["iframe"]) def test_lookup_url_uses_https_when_tls_enabled_true(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() fake_variables["TLS_ENABLED"] = True @@ -276,7 +275,7 @@ logo: self.assertEqual(result[0][0]["url"], "https://myportfolio.com") def test_lookup_url_uses_http_when_tls_enabled_false(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() fake_variables["TLS_ENABLED"] = False @@ -285,7 +284,7 @@ logo: self.assertEqual(result[0][0]["url"], "http://myportfolio.com") def test_lookup_when_group_excludes_application_id(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() fake_variables["group_names"] = [] @@ -295,7 +294,7 @@ logo: self.assertEqual(len(result[0]), 0) def test_lookup_url_renders_domain_url_jinja(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() fake_variables["domains"] = {"portfolio": "{{ DOMAIN_PRIMARY }}"} @@ -307,7 +306,7 @@ logo: self.assertEqual(result[0][0]["url"], "https://myportfolio.com") def test_lookup_url_https_when_tls_enabled_is_string(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() fake_variables["TLS_ENABLED"] = "true" @@ -317,7 +316,7 @@ logo: self.assertEqual(result[0][0]["url"], "https://myportfolio.com") def test_lookup_url_http_when_tls_enabled_is_string(self): - lookup_module = LookupModule() + lookup_module = docker_cards_module.LookupModule() fake_variables = self._base_fake_variables() fake_variables["TLS_ENABLED"] = "false" @@ -342,14 +341,14 @@ logo: {"enabled": True, "card": "client"} ) - result = self._run_lookup(LookupModule(), fake_variables) + result = self._run_lookup(docker_cards_module.LookupModule(), fake_variables) self.assertEqual(result[0][0]["url"], "https://client.myportfolio.com") def test_card_url_without_card_key_targets_the_primary_domain(self): fake_variables = self._card_target_variables({"enabled": True}) - result = self._run_lookup(LookupModule(), fake_variables) + result = self._run_lookup(docker_cards_module.LookupModule(), fake_variables) self.assertEqual(result[0][0]["url"], "https://myportfolio.com") @@ -357,7 +356,7 @@ logo: fake_variables = self._card_target_variables({"enabled": True, "card": "nope"}) with self.assertRaisesRegex(AnsibleError, "nope"): - self._run_lookup(LookupModule(), fake_variables) + self._run_lookup(docker_cards_module.LookupModule(), fake_variables) def _add_role(self, role_name, application_id, info_yaml): role_dir = Path(self.test_roles_dir) / role_name @@ -388,7 +387,7 @@ logo: "enabled" ] = False - result = self._run_lookup(LookupModule(), fake_variables) + result = self._run_lookup(docker_cards_module.LookupModule(), fake_variables) self.assertEqual(result, [[]]) @@ -396,14 +395,14 @@ logo: fake_variables = self._base_fake_variables() fake_variables["applications"]["portfolio"]["services"] = {} - result = self._run_lookup(LookupModule(), fake_variables) + result = self._run_lookup(docker_cards_module.LookupModule(), fake_variables) self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) def test_enabled_true_shows_the_card(self): fake_variables = self._base_fake_variables() - result = self._run_lookup(LookupModule(), fake_variables) + result = self._run_lookup(docker_cards_module.LookupModule(), fake_variables) self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) @@ -413,14 +412,14 @@ logo: False ) - result = self._run_lookup(LookupModule(), fake_variables) + result = self._run_lookup(docker_cards_module.LookupModule(), fake_variables) self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) def test_both_cards_render_when_both_are_enabled(self): fake_variables = self._two_role_variables() - result = self._run_lookup(LookupModule(), fake_variables) + result = self._run_lookup(docker_cards_module.LookupModule(), fake_variables) self.assertEqual( [c["title"] for c in result[0]], @@ -434,7 +433,9 @@ logo: encoding="utf-8", ) - result = self._run_lookup(LookupModule(), self._base_fake_variables()) + result = self._run_lookup( + docker_cards_module.LookupModule(), self._base_fake_variables() + ) self.assertEqual([c["title"] for c in result[0]], ["Portfolio Application"]) @@ -445,7 +446,7 @@ logo: ] = "maybe" with self.assertRaisesRegex(AnsibleError, "portfolio"): - self._run_lookup(LookupModule(), fake_variables) + self._run_lookup(docker_cards_module.LookupModule(), fake_variables) if __name__ == "__main__": diff --git a/tests/unit/python/plugins/lookup/test_docker_ownership.py b/tests/unit/python/plugins/lookup/test_docker_ownership.py index db92138362..ae5cf98b72 100644 --- a/tests/unit/python/plugins/lookup/test_docker_ownership.py +++ b/tests/unit/python/plugins/lookup/test_docker_ownership.py @@ -1,5 +1,5 @@ import unittest -from unittest import mock +import unittest.mock from ansible.errors import AnsibleError @@ -45,12 +45,12 @@ def _context(roles=("svc-db-mariadb", "web-app-matomo", "web-app-discourse")): class TestDockerOwnershipLookup(unittest.TestCase): def _run(self, terms, side_effect=None): with ( - mock.patch( + unittest.mock.patch( f"{MODULE}.deploy_closure_context", return_value=_context(), side_effect=side_effect, ) as context, - mock.patch( + unittest.mock.patch( f"{MODULE}.entity_name", side_effect=lambda role: role.split("-", 2)[-1] ), ): diff --git a/tests/unit/python/plugins/lookup/test_domain_lookup.py b/tests/unit/python/plugins/lookup/test_domain_lookup.py index b62a95c5e8..c506da6d9e 100644 --- a/tests/unit/python/plugins/lookup/test_domain_lookup.py +++ b/tests/unit/python/plugins/lookup/test_domain_lookup.py @@ -1,7 +1,6 @@ import sys import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -32,7 +31,7 @@ class TestDomainLookup(unittest.TestCase): self.lookup._loader = mock.MagicMock() def run_lookup(self, application_id, domains_map): - with patch("plugins.lookup.domain.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.domain.lookup_loader") as loader_mock: def _get(name, *a, **k): if name == "domains": @@ -90,7 +89,7 @@ class TestDomainLookup(unittest.TestCase): self.run_lookup_raw([123]) def run_lookup_raw(self, terms): - with patch("plugins.lookup.domain.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.domain.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock( run=lambda *_a, **_k: [{"app": "example.com"}] ) diff --git a/tests/unit/python/plugins/lookup/test_group_roles.py b/tests/unit/python/plugins/lookup/test_group_roles.py index 67c7b406d0..6c42c8df09 100644 --- a/tests/unit/python/plugins/lookup/test_group_roles.py +++ b/tests/unit/python/plugins/lookup/test_group_roles.py @@ -15,8 +15,8 @@ for every host, and per-host narrowing stays in the body's ``when``. from __future__ import annotations import unittest +import unittest.mock from typing import ClassVar -from unittest import mock from plugins.lookup.group_roles import LookupModule @@ -28,7 +28,7 @@ ENTRIES = [ def run(**kwargs): - with mock.patch( + with unittest.mock.patch( "plugins.lookup.group_roles.ordered_roles", return_value=list(ENTRIES) ): return LookupModule().run(["web-app"], **kwargs)[0] diff --git a/tests/unit/python/plugins/lookup/test_image.py b/tests/unit/python/plugins/lookup/test_image.py index db32ce61de..468c7be996 100644 --- a/tests/unit/python/plugins/lookup/test_image.py +++ b/tests/unit/python/plugins/lookup/test_image.py @@ -13,7 +13,6 @@ from __future__ import annotations import unittest import unittest.mock as mock from typing import Any -from unittest.mock import patch from ansible.errors import AnsibleError @@ -47,7 +46,7 @@ def _run( **kwargs: Any, ) -> list[str]: apps = applications if applications is not None else _apps() - with patch("plugins.lookup.image.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.image.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) lm = LookupModule() lm._loader = mock.MagicMock() @@ -205,7 +204,7 @@ class TestImageLookup(unittest.TestCase): def test_missing_version_returns_bare_image_with_warning(self): apps = _apps(version=None) - with patch("plugins.lookup.image._warn") as warn: + with mock.patch("plugins.lookup.image._warn") as warn: out = _run( "web-app-mattermost", "mattermost", @@ -217,7 +216,7 @@ class TestImageLookup(unittest.TestCase): def test_image_override_with_missing_services_version_warns(self): apps = _apps(version=None) - with patch("plugins.lookup.image._warn") as warn: + with mock.patch("plugins.lookup.image._warn") as warn: out = _run( "web-app-mattermost", "mattermost", @@ -245,7 +244,7 @@ class TestImageLookup(unittest.TestCase): self.assertEqual(out, ["mattermost/mattermost-team-edition:11.8.0"]) def test_custom_true_uses_entity_name_custom(self): - with patch( + with mock.patch( "plugins.lookup.image.entity_name", return_value="mattermost", ): @@ -258,7 +257,7 @@ class TestImageLookup(unittest.TestCase): self.assertEqual(out, ["mattermost_custom:11.8.0"]) def test_custom_true_with_version_override(self): - with patch( + with mock.patch( "plugins.lookup.image.entity_name", return_value="mattermost", ): @@ -272,7 +271,7 @@ class TestImageLookup(unittest.TestCase): self.assertEqual(out, ["mattermost_custom:local"]) def test_custom_true_with_image_override_image_wins(self): - with patch( + with mock.patch( "plugins.lookup.image.entity_name", return_value="mattermost", ) as get_name: @@ -287,7 +286,7 @@ class TestImageLookup(unittest.TestCase): get_name.assert_not_called() def test_custom_true_swarm_prefix_applied(self): - with patch( + with mock.patch( "plugins.lookup.image.entity_name", return_value="mattermost", ): @@ -314,7 +313,7 @@ class TestImageLookup(unittest.TestCase): def test_custom_true_ignores_services_image(self): apps = _apps(image="mattermost/mattermost-team-edition", version="11.8.0") - with patch( + with mock.patch( "plugins.lookup.image.entity_name", return_value="mattermost", ): @@ -328,7 +327,7 @@ class TestImageLookup(unittest.TestCase): self.assertEqual(out, ["mattermost_custom:11.8.0"]) def test_custom_true_tag_only_returns_bare(self): - with patch( + with mock.patch( "plugins.lookup.image.entity_name", return_value="mattermost", ): @@ -354,7 +353,7 @@ class TestImageLookup(unittest.TestCase): def test_entry_custom_true_used_without_kwarg(self): apps = _apps() apps["web-app-mattermost"]["services"]["mattermost"]["custom"] = True - with patch( + with mock.patch( "plugins.lookup.image.entity_name", return_value="mattermost", ): @@ -394,7 +393,7 @@ class TestImageLookup(unittest.TestCase): apps["web-app-mattermost"]["services"]["wb"] = apps["web-app-mattermost"][ "services" ].pop("mattermost") - with patch( + with mock.patch( "plugins.lookup.image.entity_name", return_value="mattermost", ) as get_name: @@ -429,7 +428,7 @@ class TestImageLookup(unittest.TestCase): def test_custom_true_empty_entity_name_raises(self): with ( - patch( + mock.patch( "plugins.lookup.image.entity_name", return_value="", ), diff --git a/tests/unit/python/plugins/lookup/test_native_metrics_apps.py b/tests/unit/python/plugins/lookup/test_native_metrics_apps.py index 9f08e43c77..a2424584b4 100644 --- a/tests/unit/python/plugins/lookup/test_native_metrics_apps.py +++ b/tests/unit/python/plugins/lookup/test_native_metrics_apps.py @@ -4,7 +4,6 @@ import tempfile import unittest import unittest.mock as mock from pathlib import Path -from unittest.mock import patch from plugins.lookup.native_metrics_apps import LookupModule @@ -26,8 +25,8 @@ def _run( lm._loader = mock.MagicMock() lm._templar = mock.MagicMock(template=lambda v: v) with ( - patch("plugins.lookup.native_metrics_apps.ROLES_DIR", roles_dir), - patch("plugins.lookup.native_metrics_apps.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.native_metrics_apps.ROLES_DIR", roles_dir), + mock.patch("plugins.lookup.native_metrics_apps.lookup_loader") as loader_mock, ): def _get(name, *a, **k): diff --git a/tests/unit/python/plugins/lookup/test_network_ownership.py b/tests/unit/python/plugins/lookup/test_network_ownership.py index 9d82374188..8d69366158 100644 --- a/tests/unit/python/plugins/lookup/test_network_ownership.py +++ b/tests/unit/python/plugins/lookup/test_network_ownership.py @@ -1,6 +1,6 @@ import json import unittest -from unittest import mock +import unittest.mock from ansible.errors import AnsibleError @@ -17,25 +17,27 @@ def _config_run(terms, variables=None): class TestNetworkOwnershipLookup(unittest.TestCase): def _run(self, terms, closure=None, side_effect=None): - applications = mock.Mock() + applications = unittest.mock.Mock() applications.run.return_value = [{"web-app-matomo": {}}] - config = mock.Mock() + config = unittest.mock.Mock() config.run.side_effect = _config_run with ( - mock.patch( + unittest.mock.patch( f"{MODULE}.lookup_loader.get", side_effect=lambda name, **kwargs: { "applications": applications, "config": config, }[name], ), - mock.patch(f"{MODULE}.types_from_group_names", return_value=["server"]), - mock.patch( + unittest.mock.patch( + f"{MODULE}.types_from_group_names", return_value=["server"] + ), + unittest.mock.patch( f"{MODULE}.deploy_closure", return_value=closure or {"web-app-matomo", "sys-ctl-hlth-csp"}, side_effect=side_effect, ) as closure_mock, - mock.patch( + unittest.mock.patch( f"{MODULE}.entity_name", side_effect=lambda role: role.split("-", 2)[-1] ), ): diff --git a/tests/unit/python/plugins/lookup/test_nginx.py b/tests/unit/python/plugins/lookup/test_nginx.py index ad1aaf5c58..674f2df476 100644 --- a/tests/unit/python/plugins/lookup/test_nginx.py +++ b/tests/unit/python/plugins/lookup/test_nginx.py @@ -1,6 +1,5 @@ import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -58,15 +57,15 @@ class TestNginxPathsLookup(unittest.TestCase): def _run(self, terms, **kwargs): with ( - patch( + mock.patch( "plugins.lookup.nginx.get", side_effect=self._fake_get, ), - patch( + mock.patch( "plugins.lookup.nginx.get_canonical_volumes", return_value={}, ), - patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.nginx.lookup_loader") as loader_mock, ): loader_mock.get.side_effect = self._loader_get() return self.plugin.run(terms, variables=self.variables, **kwargs)[0] @@ -124,17 +123,17 @@ class TestNginxPathsLookup(unittest.TestCase): "nginx": {"type": "volume", "path": "/opt/canonical/nginx"}, } with ( - patch( + mock.patch( "plugins.lookup.nginx.get", side_effect=AssertionError( "get() must not be called when canonical paths are present" ), ), - patch( + mock.patch( "plugins.lookup.nginx.get_canonical_volumes", return_value=canonical, ), - patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.nginx.lookup_loader") as loader_mock, ): loader_mock.get.side_effect = self._loader_get() out = self.plugin.run(["files.configuration"], variables=self.variables)[0] @@ -144,15 +143,15 @@ class TestNginxPathsLookup(unittest.TestCase): fake_tls = _FakeTlsResolveLookup("https") with ( - patch( + mock.patch( "plugins.lookup.nginx.get", side_effect=self._fake_get, ), - patch( + mock.patch( "plugins.lookup.nginx.get_canonical_volumes", return_value={}, ), - patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.nginx.lookup_loader") as loader_mock, ): loader_mock.get.side_effect = self._loader_get(tls=fake_tls) out = self.plugin.run( @@ -166,15 +165,15 @@ class TestNginxPathsLookup(unittest.TestCase): def test_domain_protocol_override_http(self): with ( - patch( + mock.patch( "plugins.lookup.nginx.get", side_effect=self._fake_get, ), - patch( + mock.patch( "plugins.lookup.nginx.get_canonical_volumes", return_value={}, ), - patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.nginx.lookup_loader") as loader_mock, ): loader_mock.get.side_effect = self._loader_get() out = self.plugin.run( @@ -190,15 +189,15 @@ class TestNginxPathsLookup(unittest.TestCase): def test_invalid_protocol_override_raises(self): with ( - patch( + mock.patch( "plugins.lookup.nginx.get", side_effect=self._fake_get, ), - patch( + mock.patch( "plugins.lookup.nginx.get_canonical_volumes", return_value={}, ), - patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.nginx.lookup_loader") as loader_mock, self.assertRaises(AnsibleError), ): loader_mock.get.side_effect = self._loader_get() @@ -210,15 +209,15 @@ class TestNginxPathsLookup(unittest.TestCase): def test_files_lua_is_one_file_per_domain(self): with ( - patch( + mock.patch( "plugins.lookup.nginx.get", side_effect=self._fake_get, ), - patch( + mock.patch( "plugins.lookup.nginx.get_canonical_volumes", return_value={}, ), - patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.nginx.lookup_loader") as loader_mock, ): loader_mock.get.side_effect = self._loader_get() out = self.plugin.run( @@ -231,15 +230,15 @@ class TestNginxPathsLookup(unittest.TestCase): def test_files_lua_without_domain_raises(self): with ( - patch( + mock.patch( "plugins.lookup.nginx.get", side_effect=self._fake_get, ), - patch( + mock.patch( "plugins.lookup.nginx.get_canonical_volumes", return_value={}, ), - patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.nginx.lookup_loader") as loader_mock, self.assertRaises(AnsibleError), ): loader_mock.get.side_effect = self._loader_get() @@ -247,15 +246,15 @@ class TestNginxPathsLookup(unittest.TestCase): def test_invalid_usage_raises(self): with ( - patch( + mock.patch( "plugins.lookup.nginx.get", side_effect=self._fake_get, ), - patch( + mock.patch( "plugins.lookup.nginx.get_canonical_volumes", return_value={}, ), - patch("plugins.lookup.nginx.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.nginx.lookup_loader") as loader_mock, ): loader_mock.get.side_effect = self._loader_get() diff --git a/tests/unit/python/plugins/lookup/test_objstore.py b/tests/unit/python/plugins/lookup/test_objstore.py index 7c682d99de..3cc9ae3426 100644 --- a/tests/unit/python/plugins/lookup/test_objstore.py +++ b/tests/unit/python/plugins/lookup/test_objstore.py @@ -9,7 +9,6 @@ import importlib.util import unittest import unittest.mock as mock from typing import ClassVar -from unittest.mock import patch from ansible.errors import AnsibleError @@ -59,7 +58,9 @@ class ObjstoreLookupTests(unittest.TestCase): lookup = self._make_lookup(vars_) with ( mock.patch.object(self.mod, "lookup_loader") as loader_mock, - patch.object(self.mod, "entity_name", side_effect=self._fake_entity_name), + mock.patch.object( + self.mod, "entity_name", side_effect=self._fake_entity_name + ), ): loader_mock.get.return_value = mock.MagicMock( run=lambda *_a, **_k: [applications] @@ -358,7 +359,7 @@ class ObjstoreSameOriginProxyTests(unittest.TestCase): with ( mock.patch.object(self.mod, "lookup_loader") as loader_mock, - patch.object( + mock.patch.object( self.mod, "entity_name", side_effect=lambda r: r.split("-", 2)[-1], diff --git a/tests/unit/python/plugins/lookup/test_package_batch.py b/tests/unit/python/plugins/lookup/test_package_batch.py index 207854df7d..322b37381e 100644 --- a/tests/unit/python/plugins/lookup/test_package_batch.py +++ b/tests/unit/python/plugins/lookup/test_package_batch.py @@ -1,5 +1,5 @@ import unittest -from unittest import mock +import unittest.mock from ansible.errors import AnsibleError @@ -11,17 +11,23 @@ MODULE = "plugins.lookup.package_batch" class TestPackageBatchLookup(unittest.TestCase): def _run(self, terms, group_names, closure=None, side_effect=None): - applications = mock.Mock() + applications = unittest.mock.Mock() applications.run.return_value = [{"web-app-x": {}}] with ( - mock.patch(f"{MODULE}.lookup_loader.get", return_value=applications), - mock.patch(f"{MODULE}.types_from_group_names", return_value=["server"]), - mock.patch( + unittest.mock.patch( + f"{MODULE}.lookup_loader.get", return_value=applications + ), + unittest.mock.patch( + f"{MODULE}.types_from_group_names", return_value=["server"] + ), + unittest.mock.patch( f"{MODULE}.deploy_closure", return_value=closure or {"web-app-x"}, side_effect=side_effect, ) as closure_mock, - mock.patch(f"{MODULE}.batch_ids", return_value=["git"]) as ids_mock, + unittest.mock.patch( + f"{MODULE}.batch_ids", return_value=["git"] + ) as ids_mock, ): lookup = LookupModule() result = lookup.run(terms, variables={"group_names": group_names}) diff --git a/tests/unit/python/plugins/lookup/test_proxy_pass.py b/tests/unit/python/plugins/lookup/test_proxy_pass.py index c9a19880d1..4899577366 100644 --- a/tests/unit/python/plugins/lookup/test_proxy_pass.py +++ b/tests/unit/python/plugins/lookup/test_proxy_pass.py @@ -5,7 +5,6 @@ from __future__ import annotations import unittest import unittest.mock as mock from typing import Any -from unittest.mock import patch from ansible.errors import AnsibleError @@ -43,7 +42,7 @@ def _run(terms, *, variables, **kwargs): lm = LookupModule() lm._templar = _Templar(variables) lm._loader = mock.MagicMock() - with patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [_apps()]) return lm.run(terms, variables=variables, **kwargs) @@ -98,7 +97,7 @@ class TestProxyPassLookup(unittest.TestCase): lm = LookupModule() lm._templar = _Templar({"DEPLOYMENT_MODE": "swarm"}) lm._loader = mock.MagicMock() - with patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) out = lm.run( ["web-app-matrix", "matrix", "http"], @@ -121,7 +120,7 @@ class TestProxyPassLookup(unittest.TestCase): lm = LookupModule() lm._templar = _ResolvingTemplar({"DEPLOYMENT_MODE": "swarm"}) lm._loader = mock.MagicMock() - with patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) out = lm.run( ["web-app-matrix", "matrix", "http"], @@ -140,7 +139,7 @@ class TestProxyPassLookup(unittest.TestCase): lm._templar = _Templar({"DEPLOYMENT_MODE": "swarm"}) lm._loader = mock.MagicMock() with ( - patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock, self.assertRaises(AnsibleError), ): loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) @@ -161,7 +160,7 @@ class TestProxyPassLookup(unittest.TestCase): {"DEPLOYMENT_MODE": "swarm", "compose_mode_force": "compose"} ) lm._loader = mock.MagicMock() - with patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) out = lm.run( ["web-app-matrix", "matrix", "http"], @@ -186,7 +185,7 @@ class TestProxyPassLookup(unittest.TestCase): {"DEPLOYMENT_MODE": "compose", "compose_mode_force": "compose"} ) lm._loader = mock.MagicMock() - with patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [apps]) out = lm.run( ["web-app-matrix", "matrix", "http"], @@ -232,7 +231,7 @@ class TestProxyPassLookup(unittest.TestCase): lm._templar = _Templar({"DEPLOYMENT_MODE": "swarm"}) lm._loader = mock.MagicMock() with ( - patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.proxy_pass.lookup_loader") as loader_mock, self.assertRaises(AnsibleError), ): loader_mock.get.return_value = mock.MagicMock( diff --git a/tests/unit/python/plugins/lookup/test_public_ports.py b/tests/unit/python/plugins/lookup/test_public_ports.py index d58be295c0..d7b5bf42fb 100644 --- a/tests/unit/python/plugins/lookup/test_public_ports.py +++ b/tests/unit/python/plugins/lookup/test_public_ports.py @@ -1,5 +1,5 @@ import unittest -from unittest import mock +import unittest.mock from ansible.errors import AnsibleError @@ -44,13 +44,13 @@ def _context(): roles=sorted(APPLICATIONS), applications=APPLICATIONS, config=_config, - lookup=mock.Mock(), + lookup=unittest.mock.Mock(), ) class TestPublicPortsLookup(unittest.TestCase): def _run(self, terms, side_effect=None): - with mock.patch( + with unittest.mock.patch( f"{MODULE}.deploy_closure_context", return_value=_context(), side_effect=side_effect, diff --git a/tests/unit/python/plugins/lookup/test_rbac_group_path.py b/tests/unit/python/plugins/lookup/test_rbac_group_path.py index 84b94eff82..f77a844e14 100644 --- a/tests/unit/python/plugins/lookup/test_rbac_group_path.py +++ b/tests/unit/python/plugins/lookup/test_rbac_group_path.py @@ -1,6 +1,5 @@ import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -22,7 +21,7 @@ class TestRbacGroupPathLookup(unittest.TestCase): def _applications_from_vars(_terms, variables=None, **_kwargs): return [(variables or {}).get("applications", {})] - patcher = patch("plugins.lookup.rbac_group_path.lookup_loader") + patcher = mock.patch("plugins.lookup.rbac_group_path.lookup_loader") loader_mock = patcher.start() loader_mock.get.return_value = mock.MagicMock(run=_applications_from_vars) self.addCleanup(patcher.stop) diff --git a/tests/unit/python/plugins/lookup/test_roles_with_service.py b/tests/unit/python/plugins/lookup/test_roles_with_service.py index d5a3ca45f6..7d6eb0ab74 100644 --- a/tests/unit/python/plugins/lookup/test_roles_with_service.py +++ b/tests/unit/python/plugins/lookup/test_roles_with_service.py @@ -8,7 +8,6 @@ tests stay hermetic — no filesystem access into ``roles/``. import importlib.util import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -128,7 +127,7 @@ class RolesWithServiceLookupTests(unittest.TestCase): def _dispatch(name, **_kwargs): return stubs[name] - with patch.object(self.mod.lookup_loader, "get", side_effect=_dispatch): + with mock.patch.object(self.mod.lookup_loader, "get", side_effect=_dispatch): return lookup.run(terms, variables=vars_ or {}, **kwargs) def test_zero_terms_raises(self): diff --git a/tests/unit/python/plugins/lookup/test_service.py b/tests/unit/python/plugins/lookup/test_service.py index 24768b6df4..3abbf5d21c 100644 --- a/tests/unit/python/plugins/lookup/test_service.py +++ b/tests/unit/python/plugins/lookup/test_service.py @@ -2,7 +2,6 @@ from __future__ import annotations import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -25,17 +24,17 @@ def _run( static_registry=None, **kwargs, ): - loader_patch = patch("plugins.lookup.service.lookup_loader") + loader_patch = mock.patch("plugins.lookup.service.lookup_loader") patches = [ loader_patch, - patch( + mock.patch( "plugins.lookup.service.build_service_registry_from_roles_dir", return_value=static_registry or {}, ), ] if service_registry is not None: patches.append( - patch( + mock.patch( "plugins.lookup.service.build_service_registry_from_applications", return_value=service_registry, ) @@ -308,7 +307,7 @@ class TestServiceCycleGuard(unittest.TestCase): class TestServiceErrors(unittest.TestCase): def test_raises_when_group_names_not_list(self): with ( - patch("plugins.lookup.service.lookup_loader") as loader_mock, + mock.patch("plugins.lookup.service.lookup_loader") as loader_mock, self.assertRaises(AnsibleError), ): loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [{}]) diff --git a/tests/unit/python/plugins/lookup/test_service_extensions.py b/tests/unit/python/plugins/lookup/test_service_extensions.py index 636ef6b08f..565277a6c2 100644 --- a/tests/unit/python/plugins/lookup/test_service_extensions.py +++ b/tests/unit/python/plugins/lookup/test_service_extensions.py @@ -9,7 +9,6 @@ The lookup walks ``group_names`` and returns a import importlib.util import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -51,7 +50,7 @@ class ServiceExtensionsLookupTests(unittest.TestCase): group_names: list[str], ): lookup = self._make_lookup({"group_names": group_names}) - with patch.object(self.mod, "lookup_loader") as loader_mock: + with mock.patch.object(self.mod, "lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock( run=lambda *_a, **_k: [applications] ) @@ -72,7 +71,7 @@ class ServiceExtensionsLookupTests(unittest.TestCase): def test_non_list_group_names_raises(self): lookup = self._make_lookup({"group_names": "not-a-list"}) with ( - patch.object(self.mod, "lookup_loader") as loader_mock, + mock.patch.object(self.mod, "lookup_loader") as loader_mock, self.assertRaises(AnsibleError), ): loader_mock.get.return_value = mock.MagicMock(run=lambda *_a, **_k: [{}]) diff --git a/tests/unit/python/plugins/lookup/test_service_registry.py b/tests/unit/python/plugins/lookup/test_service_registry.py index 3f6d943358..e14bad3492 100644 --- a/tests/unit/python/plugins/lookup/test_service_registry.py +++ b/tests/unit/python/plugins/lookup/test_service_registry.py @@ -4,7 +4,6 @@ import tempfile import unittest import unittest.mock as mock from pathlib import Path -from unittest.mock import patch from plugins.lookup.service_registry import LookupModule from utils.cache.yaml import dump_yaml_str @@ -82,7 +81,9 @@ class TestServiceRegistryOrdered(unittest.TestCase): result-arrival order (consumers deploy before their engines).""" with tempfile.TemporaryDirectory() as td: roles_dir = self._roles_dir(td) - with patch("plugins.lookup.service_registry.lookup_loader") as loader_mock: + with mock.patch( + "plugins.lookup.service_registry.lookup_loader" + ) as loader_mock: lm = LookupModule() lm._loader = mock.MagicMock() result = lm.run( @@ -121,7 +122,7 @@ class TestServiceRegistryOrdered(unittest.TestCase): } } } - with patch("plugins.lookup.service_registry.lookup_loader") as loader_mock: + with mock.patch("plugins.lookup.service_registry.lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock( run=lambda *_a, **_k: [applications] ) diff --git a/tests/unit/python/plugins/lookup/test_sso_whitelist_domains.py b/tests/unit/python/plugins/lookup/test_sso_whitelist_domains.py index 0a187dfdf7..45f6598a03 100644 --- a/tests/unit/python/plugins/lookup/test_sso_whitelist_domains.py +++ b/tests/unit/python/plugins/lookup/test_sso_whitelist_domains.py @@ -2,8 +2,8 @@ from __future__ import annotations import os import unittest +import unittest.mock from typing import ClassVar -from unittest import mock from ansible.errors import AnsibleError @@ -45,7 +45,7 @@ class TestSsoWhitelistDomains(unittest.TestCase): def _run(self, variables, domains=None, node_onion=""): domains = {self.APP: f"pihole.{PRIMARY}"} if domains is None else domains - with mock.patch( + with unittest.mock.patch( "plugins.lookup.sso_whitelist_domains.lookup_loader.get", side_effect=_loader_for(domains, node_onion), ): diff --git a/tests/unit/python/plugins/lookup/test_tls.py b/tests/unit/python/plugins/lookup/test_tls.py index 2d9c24fe5d..fa47419bff 100644 --- a/tests/unit/python/plugins/lookup/test_tls.py +++ b/tests/unit/python/plugins/lookup/test_tls.py @@ -1,7 +1,6 @@ import sys import unittest import unittest.mock as mock -from unittest.mock import patch from ansible.errors import AnsibleError @@ -43,7 +42,7 @@ class TestTlsResolveLookup(unittest.TestCase): return mock.MagicMock(run=_run) - loader_patcher = patch("plugins.lookup.tls.lookup_loader") + loader_patcher = mock.patch("plugins.lookup.tls.lookup_loader") loader_mock = loader_patcher.start() loader_mock.get.side_effect = _get self.addCleanup(loader_patcher.stop) diff --git a/tests/unit/python/roles/svc-ai-agent-broker/__init__.py b/tests/unit/python/roles/svc-ai-agent-broker/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/svc-ai-agent-broker/__init__.py +++ b/tests/unit/python/roles/svc-ai-agent-broker/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/svc-ai-agent-broker/files/__init__.py b/tests/unit/python/roles/svc-ai-agent-broker/files/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/svc-ai-agent-broker/files/__init__.py +++ b/tests/unit/python/roles/svc-ai-agent-broker/files/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/svc-ai-agent-broker/files/test_agents.py b/tests/unit/python/roles/svc-ai-agent-broker/files/test_agents.py index 90f5bdce88..e0f35ef854 100644 --- a/tests/unit/python/roles/svc-ai-agent-broker/files/test_agents.py +++ b/tests/unit/python/roles/svc-ai-agent-broker/files/test_agents.py @@ -3,8 +3,8 @@ from __future__ import annotations import json import sys import unittest +import unittest.mock import urllib.error -from unittest import mock import yaml @@ -123,9 +123,13 @@ class TestAgentCalls(unittest.TestCase): broker = make_agents() refused = urllib.error.URLError("connection refused") with ( - mock.patch.object(agents.urllib.request, "urlopen", side_effect=refused), - mock.patch.object(agents.time, "monotonic", side_effect=[0, 0, 100]), - mock.patch.object(agents.time, "sleep"), + unittest.mock.patch.object( + agents.urllib.request, "urlopen", side_effect=refused + ), + unittest.mock.patch.object( + agents.time, "monotonic", side_effect=[0, 0, 100] + ), + unittest.mock.patch.object(agents.time, "sleep"), self.assertRaises(TimeoutError) as caught, ): broker._wait_healthy("hermes", "agent-hermes-1", "k") @@ -135,7 +139,9 @@ class TestAgentCalls(unittest.TestCase): events = [] broker = make_agents(log=lambda event, **fields: events.append((event, fields))) refused = urllib.error.URLError("connection refused") - with mock.patch.object(agents.urllib.request, "urlopen", side_effect=refused): + with unittest.mock.patch.object( + agents.urllib.request, "urlopen", side_effect=refused + ): model = broker.agent_model("hermes", "http://agent-hermes-1:8642", "k") self.assertEqual(model, "hermes-agent") self.assertEqual(len(events), 1) diff --git a/tests/unit/python/roles/svc-ai-libretranslate-engine/files/__init__.py b/tests/unit/python/roles/svc-ai-libretranslate-engine/files/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/svc-ai-libretranslate-engine/files/__init__.py +++ b/tests/unit/python/roles/svc-ai-libretranslate-engine/files/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/svc-ai-libretranslate-engine/files/test_prefetch_models.py b/tests/unit/python/roles/svc-ai-libretranslate-engine/files/test_prefetch_models.py index 05b22c87e8..ebed05ec42 100644 --- a/tests/unit/python/roles/svc-ai-libretranslate-engine/files/test_prefetch_models.py +++ b/tests/unit/python/roles/svc-ai-libretranslate-engine/files/test_prefetch_models.py @@ -9,11 +9,10 @@ import importlib.util import sys import types import unittest +import unittest.mock import zipfile from pathlib import Path from tempfile import TemporaryDirectory -from types import ModuleType -from unittest import mock from . import PROJECT_ROOT @@ -37,7 +36,7 @@ class FakePackage: return self._path -def _load() -> ModuleType: +def _load() -> types.ModuleType: package = types.ModuleType("argostranslate.package") package.update_package_index = lambda: None package.get_available_packages = list @@ -59,7 +58,7 @@ def _load() -> ModuleType: "libretranslate.language": language, "minisbd": minisbd, } - with mock.patch.dict(sys.modules, modules): + with unittest.mock.patch.dict(sys.modules, modules): spec = importlib.util.spec_from_file_location("prefetch_models", SCRIPT) module = importlib.util.module_from_spec(spec) assert spec and spec.loader @@ -134,7 +133,7 @@ class TestMain(unittest.TestCase): self.module.download_models = lambda codes, _: self.minisbd_got.append(codes) def test_minisbd_gets_the_model_codes_not_the_iso_codes(self) -> None: - with mock.patch.object( + with unittest.mock.patch.object( sys, "argv", ["prefetch_models.py", "--load_only_lang_codes", "en,zh"] ): self.assertEqual(self.module.main(), 0) @@ -142,7 +141,7 @@ class TestMain(unittest.TestCase): self.assertEqual(self.minisbd_got, [["en", "zh-Hans"]]) def test_minisbd_gets_none_when_no_codes_were_requested(self) -> None: - with mock.patch.object(sys, "argv", ["prefetch_models.py"]): + with unittest.mock.patch.object(sys, "argv", ["prefetch_models.py"]): self.assertEqual(self.module.main(), 0) self.assertEqual(self.minisbd_got, [None]) diff --git a/tests/unit/python/roles/svc-ai-litellm/__init__.py b/tests/unit/python/roles/svc-ai-litellm/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/svc-ai-litellm/__init__.py +++ b/tests/unit/python/roles/svc-ai-litellm/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/svc-ai-litellm/vars/__init__.py b/tests/unit/python/roles/svc-ai-litellm/vars/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/svc-ai-litellm/vars/__init__.py +++ b/tests/unit/python/roles/svc-ai-litellm/vars/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/svc-ai-mcp-adapter/__init__.py b/tests/unit/python/roles/svc-ai-mcp-adapter/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/svc-ai-mcp-adapter/__init__.py +++ b/tests/unit/python/roles/svc-ai-mcp-adapter/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/svc-ai-s1/files/__init__.py b/tests/unit/python/roles/svc-ai-s1/files/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/svc-ai-s1/files/__init__.py +++ b/tests/unit/python/roles/svc-ai-s1/files/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/svc-ai-s1/files/infinito_decider/__init__.py b/tests/unit/python/roles/svc-ai-s1/files/infinito_decider/__init__.py index 171dff4517..b8a5a8e9bc 100644 --- a/tests/unit/python/roles/svc-ai-s1/files/infinito_decider/__init__.py +++ b/tests/unit/python/roles/svc-ai-s1/files/infinito_decider/__init__.py @@ -29,3 +29,5 @@ def _load(name: str): HISTORY = _load("history") JUDGE = _load("judge") SAMPLING = _load("sampling") + +__all__ = ["HISTORY", "JUDGE", "SAMPLING"] diff --git a/tests/unit/python/roles/svc-net-firewall/__init__.py b/tests/unit/python/roles/svc-net-firewall/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/svc-net-firewall/__init__.py +++ b/tests/unit/python/roles/svc-net-firewall/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/svc-net-tor-smtp/__init__.py b/tests/unit/python/roles/svc-net-tor-smtp/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/svc-net-tor-smtp/__init__.py +++ b/tests/unit/python/roles/svc-net-tor-smtp/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/svc-net-tor/__init__.py b/tests/unit/python/roles/svc-net-tor/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/svc-net-tor/__init__.py +++ b/tests/unit/python/roles/svc-net-tor/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/svc-opt-ssd-hdd/__init__.py b/tests/unit/python/roles/svc-opt-ssd-hdd/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/svc-opt-ssd-hdd/__init__.py +++ b/tests/unit/python/roles/svc-opt-ssd-hdd/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/svc-storage-nfs-server/__init__.py b/tests/unit/python/roles/svc-storage-nfs-server/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/svc-storage-nfs-server/__init__.py +++ b/tests/unit/python/roles/svc-storage-nfs-server/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/__init__.py b/tests/unit/python/roles/sys-ctl-hlth-csp/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/__init__.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py b/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py index 0e443f9e70..820c5d9d1e 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/files/test_script.py @@ -486,7 +486,7 @@ class TestBuildUrlsFromNginxConfs(unittest.TestCase): ) -> None: mock_detect.return_value = None - with patch("sys.stderr") as _stderr: + with patch("sys.stderr"): urls = script.build_urls_from_nginx_confs( _vhosts("example.com"), ["example.com"] ) diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_accept_status.py b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_accept_status.py index 3378cc06e2..1a58dc5302 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_accept_status.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_accept_status.py @@ -4,7 +4,6 @@ import importlib.util import sys import unittest import unittest.mock as mock -from unittest.mock import patch from . import PROJECT_ROOT @@ -36,7 +35,7 @@ class CspAcceptStatusLookupTests(unittest.TestCase): lm = self.module.LookupModule() lm._templar = _DummyTemplar() lm._loader = mock.MagicMock() - with patch.object(self.module, "lookup_loader") as loader_mock: + with mock.patch.object(self.module, "lookup_loader") as loader_mock: loader_mock.get.return_value = mock.MagicMock( run=lambda *_a, **_k: [applications] ) diff --git a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py index 04b536f738..22bf0db30b 100644 --- a/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py +++ b/tests/unit/python/roles/sys-ctl-hlth-csp/lookup_plugins/test_csp_skip_domains.py @@ -4,7 +4,6 @@ import importlib.util import sys import unittest import unittest.mock as mock -from unittest.mock import patch from . import PROJECT_ROOT @@ -44,7 +43,7 @@ class CspSkipDomainsLookupTests(unittest.TestCase): lm._templar = _DummyTemplar() lm._loader = mock.MagicMock() results = {"applications": applications, "domains": domains or {}} - with patch.object(self.module, "lookup_loader") as loader_mock: + with mock.patch.object(self.module, "lookup_loader") as loader_mock: loader_mock.get.side_effect = lambda name, **_k: mock.MagicMock( run=lambda *_a, **_kw: [results[name]] ) diff --git a/tests/unit/python/roles/sys-front-inj-all/test_injector_code_shallow.py b/tests/unit/python/roles/sys-front-inj-all/test_injector_code_shallow.py index 7ffe5939d3..0a4f288ce6 100644 --- a/tests/unit/python/roles/sys-front-inj-all/test_injector_code_shallow.py +++ b/tests/unit/python/roles/sys-front-inj-all/test_injector_code_shallow.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock from ansible.parsing.dataloader import DataLoader from ansible.plugins.loader import filter_loader, lookup_loader @@ -116,7 +116,7 @@ def render(injector: str, expression: str, variables: dict): "ansible_search_path": [str(PROJECT_ROOT / "roles" / role)], } try: - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): code = Templar(loader=DataLoader(), variables=scope).template( trust_as_template(expression) ) diff --git a/tests/unit/python/roles/sys-front-inj-design/test_css_per_network.py b/tests/unit/python/roles/sys-front-inj-design/test_css_per_network.py index e215f15a5a..17e0f0f3e5 100644 --- a/tests/unit/python/roles/sys-front-inj-design/test_css_per_network.py +++ b/tests/unit/python/roles/sys-front-inj-design/test_css_per_network.py @@ -14,7 +14,7 @@ from __future__ import annotations import hashlib import re import unittest -from unittest import mock +import unittest.mock from urllib.parse import parse_qs, urlsplit from ansible.parsing.dataloader import DataLoader @@ -105,9 +105,9 @@ def _templar(siblings, extra): "TLS_MODE": "letsencrypt", **extra, } - return Templar(loader=DataLoader(), variables=variables), mock.patch.object( - lookup_loader, "get", side_effect=get - ) + return Templar( + loader=DataLoader(), variables=variables + ), unittest.mock.patch.object(lookup_loader, "get", side_effect=get) def resolve(siblings, domain, expression): diff --git a/tests/unit/python/roles/sys-front-inj-design/test_resolve_render_once.py b/tests/unit/python/roles/sys-front-inj-design/test_resolve_render_once.py index a0dd7fd31b..d9fe00a666 100644 --- a/tests/unit/python/roles/sys-front-inj-design/test_resolve_render_once.py +++ b/tests/unit/python/roles/sys-front-inj-design/test_resolve_render_once.py @@ -2,9 +2,9 @@ from __future__ import annotations import tempfile import unittest +import unittest.mock from collections import Counter from pathlib import Path -from unittest import mock from ansible.errors import AnsibleUndefinedVariable from ansible.parsing.dataloader import DataLoader @@ -191,7 +191,7 @@ def run_tasks(tasks, app, vhost, logo, root=PROJECT_ROOT): design_css_states={}, ) facts: dict = {} - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): for task in tasks: renders.append(Counter()) scope = {**variables, **facts, **_trusted(task["vars"])} diff --git a/tests/unit/python/roles/sys-front-inj-design/test_resolve_shallow_equivalence.py b/tests/unit/python/roles/sys-front-inj-design/test_resolve_shallow_equivalence.py index 3c7b047507..c4107718ca 100644 --- a/tests/unit/python/roles/sys-front-inj-design/test_resolve_shallow_equivalence.py +++ b/tests/unit/python/roles/sys-front-inj-design/test_resolve_shallow_equivalence.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock from ansible.plugins.loader import lookup_loader @@ -50,7 +50,7 @@ def base_tasks(): return [_builtin(task) for task in resolve_tasks()] -def _outcome(tasks, app, vhost, logo): +def _outcome(tasks, app, vhost, logo) -> tuple[object, ...]: try: facts, renders = run_tasks(tasks, app, vhost, logo) except Exception as error: @@ -110,7 +110,7 @@ class TestShallowMatchesBuiltinForEveryRole(unittest.TestCase): plugin.run = watched return plugin - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): run_tasks(resolve_tasks(), "web-svc-logout", f"x.app.{DOMAIN}", True) self.assertTrue(copies) self.assertEqual(set(copies), {"_SharedVariables"}) diff --git a/tests/unit/python/roles/sys-svc-mail-msmtp/__init__.py b/tests/unit/python/roles/sys-svc-mail-msmtp/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/sys-svc-mail-msmtp/__init__.py +++ b/tests/unit/python/roles/sys-svc-mail-msmtp/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/sys-svc-proxy/__init__.py b/tests/unit/python/roles/sys-svc-proxy/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/sys-svc-proxy/__init__.py +++ b/tests/unit/python/roles/sys-svc-proxy/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/sys-svc-rdbms/__init__.py b/tests/unit/python/roles/sys-svc-rdbms/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/sys-svc-rdbms/__init__.py +++ b/tests/unit/python/roles/sys-svc-rdbms/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/test-e2e-cli/__init__.py b/tests/unit/python/roles/test-e2e-cli/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/test-e2e-cli/__init__.py +++ b/tests/unit/python/roles/test-e2e-cli/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-bookwyrm/files/__init__.py b/tests/unit/python/roles/web-app-bookwyrm/files/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/web-app-bookwyrm/files/__init__.py +++ b/tests/unit/python/roles/web-app-bookwyrm/files/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-dashboard/templates/test_compose_build_once.py b/tests/unit/python/roles/web-app-dashboard/templates/test_compose_build_once.py index 139d765f85..4fb0752eef 100644 --- a/tests/unit/python/roles/web-app-dashboard/templates/test_compose_build_once.py +++ b/tests/unit/python/roles/web-app-dashboard/templates/test_compose_build_once.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock from ansible.plugins.loader import lookup_loader from ansible.plugins.lookup import LookupBase @@ -83,7 +83,7 @@ def render(domains: list[str], mode: str) -> dict: return "" env.globals["lookup"] = lookup - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): rendered = env.from_string(read_text(str(TEMPLATE))).render( application_id=APP, DASHBOARD_INSTANCES=network_instances(domains), diff --git a/tests/unit/python/roles/web-app-decidim/__init__.py b/tests/unit/python/roles/web-app-decidim/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-app-decidim/__init__.py +++ b/tests/unit/python/roles/web-app-decidim/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/__init__.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/__init__.py index 86efabd459..6290ad0f99 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/__init__.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/__init__.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/__init__.py index 1f90564319..0bd565f9d2 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/__init__.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[8] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/local/__init__.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/local/__init__.py index 29c0dccaa7..4c5478c018 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/local/__init__.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/local/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[9] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/test_mermaid.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/test_mermaid.py index ee6cd32ec2..ff047fee93 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/test_mermaid.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/test_mermaid.py @@ -3,7 +3,7 @@ from __future__ import annotations import importlib import sys import unittest -from unittest import mock +import unittest.mock from docutils import nodes from docutils.frontend import get_default_settings @@ -60,7 +60,7 @@ class TestMermaidFences(unittest.TestCase): self.assertEqual(len(list(document.findall(nodes.literal_block))), 1) def test_setup_registers_the_transform_and_both_scripts(self) -> None: - app = mock.Mock() + app = unittest.mock.Mock() meta = mermaid.setup(app) diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/test_remote_images.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/test_remote_images.py index ba1de138ff..a747e5c58c 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/test_remote_images.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/test_remote_images.py @@ -4,9 +4,9 @@ import importlib import sys import tempfile import unittest +import unittest.mock from pathlib import Path from types import SimpleNamespace -from unittest import mock from docutils import nodes from docutils.utils import new_document @@ -23,8 +23,10 @@ BADGE = "https://img.shields.io/badge/Infinito.Nexus-%2ECloud-000000?labelColor= SVG = b'' -def _response(content_type: str, content: bytes = SVG) -> mock.Mock: - response = mock.Mock(headers={"Content-Type": content_type}, content=content) +def _response(content_type: str, content: bytes = SVG) -> unittest.mock.Mock: + response = unittest.mock.Mock( + headers={"Content-Type": content_type}, content=content + ) response.raise_for_status.return_value = None return response @@ -33,7 +35,7 @@ def _app(doctreedir: str, builder_format: str = "html") -> SimpleNamespace: return SimpleNamespace( builder=SimpleNamespace(format=builder_format), doctreedir=doctreedir, - env=SimpleNamespace(images=mock.Mock()), + env=SimpleNamespace(images=unittest.mock.Mock()), ) @@ -52,7 +54,7 @@ class TestFetchImage(unittest.TestCase): def test_an_svg_lands_under_a_suffix_that_names_its_type(self) -> None: with ( tempfile.TemporaryDirectory() as tmp, - mock.patch.object( + unittest.mock.patch.object( remote_images.requests, "get", return_value=_response("image/svg+xml; charset=utf-8"), @@ -66,7 +68,7 @@ class TestFetchImage(unittest.TestCase): def test_a_second_page_reuses_the_download(self) -> None: with ( tempfile.TemporaryDirectory() as tmp, - mock.patch.object( + unittest.mock.patch.object( remote_images.requests, "get", return_value=_response("image/png") ) as get, ): @@ -79,7 +81,7 @@ class TestFetchImage(unittest.TestCase): def test_an_answer_that_is_no_image_is_dropped(self) -> None: with ( tempfile.TemporaryDirectory() as tmp, - mock.patch.object( + unittest.mock.patch.object( remote_images.requests, "get", return_value=_response("text/html") ), ): @@ -89,7 +91,7 @@ class TestFetchImage(unittest.TestCase): def test_an_unreachable_host_is_dropped(self) -> None: with ( tempfile.TemporaryDirectory() as tmp, - mock.patch.object( + unittest.mock.patch.object( remote_images.requests, "get", side_effect=remote_images.requests.ConnectionError("down"), @@ -104,7 +106,7 @@ class TestLocalizeRemoteImages(unittest.TestCase): doctree = _page(image) with ( tempfile.TemporaryDirectory() as tmp, - mock.patch.object( + unittest.mock.patch.object( remote_images.requests, "get", return_value=_response("image/svg+xml") ), ): @@ -121,7 +123,7 @@ class TestLocalizeRemoteImages(unittest.TestCase): doctree = _page(nodes.image(uri=BADGE, alt="Infinito.Nexus")) with ( tempfile.TemporaryDirectory() as tmp, - mock.patch.object( + unittest.mock.patch.object( remote_images.requests, "get", side_effect=remote_images.requests.Timeout("slow"), @@ -139,7 +141,7 @@ class TestLocalizeRemoteImages(unittest.TestCase): remote = nodes.image(uri=BADGE) with ( tempfile.TemporaryDirectory() as tmp, - mock.patch.object(remote_images.requests, "get") as get, + unittest.mock.patch.object(remote_images.requests, "get") as get, ): remote_images.localize_remote_images(_app(tmp), _page(local), "index") remote_images.localize_remote_images( @@ -151,7 +153,7 @@ class TestLocalizeRemoteImages(unittest.TestCase): self.assertEqual(remote["uri"], BADGE) def test_setup_hooks_the_resolved_doctree(self) -> None: - app = mock.Mock() + app = unittest.mock.Mock() meta = remote_images.setup(app) diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/untranslated/__init__.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/untranslated/__init__.py index 29c0dccaa7..4c5478c018 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/untranslated/__init__.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/extensions/untranslated/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[9] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-docs/files/infinito_docs/generators/__init__.py b/tests/unit/python/roles/web-app-docs/files/infinito_docs/generators/__init__.py index 1f90564319..0bd565f9d2 100644 --- a/tests/unit/python/roles/web-app-docs/files/infinito_docs/generators/__init__.py +++ b/tests/unit/python/roles/web-app-docs/files/infinito_docs/generators/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[8] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-docs/files/test/__init__.py b/tests/unit/python/roles/web-app-docs/files/test/__init__.py index 86efabd459..6290ad0f99 100644 --- a/tests/unit/python/roles/web-app-docs/files/test/__init__.py +++ b/tests/unit/python/roles/web-app-docs/files/test/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-docs/files/test/test_extract.py b/tests/unit/python/roles/web-app-docs/files/test/test_extract.py index 13d8bdbe63..6bf83267b3 100644 --- a/tests/unit/python/roles/web-app-docs/files/test/test_extract.py +++ b/tests/unit/python/roles/web-app-docs/files/test/test_extract.py @@ -2,8 +2,8 @@ from __future__ import annotations import importlib.util import unittest +import unittest.mock import urllib.error -from unittest import mock from . import PROJECT_ROOT @@ -68,14 +68,14 @@ class TestPageUrl(unittest.TestCase): class TestFetch(unittest.TestCase): def _response(self, status: int, body: bytes = b""): - response = mock.MagicMock() + response = unittest.mock.MagicMock() response.status = status response.read.return_value = body response.__enter__.return_value = response return response def test_a_ready_page_is_returned_at_once(self) -> None: - with mock.patch.object(extract.urllib.request, "urlopen") as opener: + with unittest.mock.patch.object(extract.urllib.request, "urlopen") as opener: opener.return_value = self._response(200, b"

ok

") self.assertEqual(extract.fetch("http://x/", timeout=1), "

ok

") @@ -83,8 +83,10 @@ class TestFetch(unittest.TestCase): def test_it_waits_while_the_version_is_building(self) -> None: answers = [self._response(202), self._response(200, b"

ok

")] with ( - mock.patch.object(extract.urllib.request, "urlopen", side_effect=answers), - mock.patch.object(extract.time, "sleep"), + unittest.mock.patch.object( + extract.urllib.request, "urlopen", side_effect=answers + ), + unittest.mock.patch.object(extract.time, "sleep"), ): self.assertEqual( extract.fetch("http://x/", timeout=60, poll=0), "

ok

" @@ -92,8 +94,8 @@ class TestFetch(unittest.TestCase): def test_a_build_that_never_finishes_times_out(self) -> None: with ( - mock.patch.object(extract.urllib.request, "urlopen") as opener, - mock.patch.object(extract.time, "sleep"), + unittest.mock.patch.object(extract.urllib.request, "urlopen") as opener, + unittest.mock.patch.object(extract.time, "sleep"), ): opener.return_value = self._response(202) with self.assertRaises(TimeoutError): @@ -102,7 +104,9 @@ class TestFetch(unittest.TestCase): def test_an_error_other_than_building_is_raised(self) -> None: failure = urllib.error.HTTPError("http://x/", 404, "gone", {}, None) with ( - mock.patch.object(extract.urllib.request, "urlopen", side_effect=failure), + unittest.mock.patch.object( + extract.urllib.request, "urlopen", side_effect=failure + ), self.assertRaises(urllib.error.HTTPError), ): extract.fetch("http://x/", timeout=1) @@ -111,7 +115,7 @@ class TestFetch(unittest.TestCase): class TestBlockEntry(unittest.TestCase): def test_a_page_without_instructions_is_an_error(self) -> None: with ( - mock.patch.object(extract, "fetch", return_value=WITHOUT), + unittest.mock.patch.object(extract, "fetch", return_value=WITHOUT), self.assertRaises(ValueError), ): extract.block("http://x/", "web-app-x", timeout=1) diff --git a/tests/unit/python/roles/web-app-flowise/__init__.py b/tests/unit/python/roles/web-app-flowise/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/web-app-flowise/__init__.py +++ b/tests/unit/python/roles/web-app-flowise/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-app-funkwhale/__init__.py b/tests/unit/python/roles/web-app-funkwhale/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-app-funkwhale/__init__.py +++ b/tests/unit/python/roles/web-app-funkwhale/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-funkwhale/files/__init__.py b/tests/unit/python/roles/web-app-funkwhale/files/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/web-app-funkwhale/files/__init__.py +++ b/tests/unit/python/roles/web-app-funkwhale/files/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/__init__.py b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/__init__.py index 86efabd459..6290ad0f99 100644 --- a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/__init__.py +++ b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_settings.py b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_settings.py index 6e1bd92754..2550e08ffb 100644 --- a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_settings.py +++ b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_settings.py @@ -3,8 +3,8 @@ from __future__ import annotations import runpy import sys import unittest +import unittest.mock from types import ModuleType -from unittest import mock from . import PROJECT_ROOT @@ -34,7 +34,7 @@ def _run() -> tuple[dict, dict]: "config.settings": ModuleType("config.settings"), "config.settings.production": production, } - with mock.patch.dict(sys.modules, modules): + with unittest.mock.patch.dict(sys.modules, modules): return runpy.run_path(str(MODULE_PATH)), original diff --git a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_storage.py b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_storage.py index e3afb6cefd..fce5dc6966 100644 --- a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_storage.py +++ b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_storage.py @@ -4,8 +4,8 @@ import importlib.util import posixpath import sys import unittest +import unittest.mock from types import ModuleType, SimpleNamespace -from unittest import mock from urllib.parse import parse_qs, quote, urlsplit from . import PROJECT_ROOT @@ -117,7 +117,7 @@ def load() -> ModuleType: Returns: same_origin_storage imported over the stand-ins. """ - with mock.patch.dict(sys.modules, stand_ins()): + with unittest.mock.patch.dict(sys.modules, stand_ins()): spec = importlib.util.spec_from_file_location( "same_origin_storage", MODULE_PATH ) diff --git a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_urls.py b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_urls.py index 7a5bfd4648..150dfad5a3 100644 --- a/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_urls.py +++ b/tests/unit/python/roles/web-app-funkwhale/files/same_origin/test_urls.py @@ -4,9 +4,9 @@ import importlib.util import re import sys import unittest +import unittest.mock import urllib.parse from types import ModuleType, SimpleNamespace -from unittest import mock from utils.cache.files import read_text @@ -98,13 +98,13 @@ def nginx_rewrite(body: str, uri: str) -> str: return re.sub(pattern, re.sub(r"\$(\d)", r"\\\1", replacement), uri) -def load() -> tuple[ModuleType, mock.MagicMock, ModuleType]: +def load() -> tuple[ModuleType, unittest.mock.MagicMock, ModuleType]: """ Returns: same_origin_urls imported over stand-ins for django and funkwhale, the default storage it signs with and the same_origin_storage it checks names with. """ storage_module = load_storage() - storage = mock.MagicMock() + storage = unittest.mock.MagicMock() storage.signed_url.return_value = SIGNED files_storage = ModuleType("django.core.files.storage") files_storage.default_storage = storage @@ -138,7 +138,7 @@ def load() -> tuple[ModuleType, mock.MagicMock, ModuleType]: "funkwhale_api.music.views": music_views, "same_origin_storage": storage_module, } - with mock.patch.dict(sys.modules, modules): + with unittest.mock.patch.dict(sys.modules, modules): spec = importlib.util.spec_from_file_location("same_origin_urls", MODULE_PATH) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) diff --git a/tests/unit/python/roles/web-app-gitlab/__init__.py b/tests/unit/python/roles/web-app-gitlab/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-app-gitlab/__init__.py +++ b/tests/unit/python/roles/web-app-gitlab/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-listmonk/templates/__init__.py b/tests/unit/python/roles/web-app-listmonk/templates/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/web-app-listmonk/templates/__init__.py +++ b/tests/unit/python/roles/web-app-listmonk/templates/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-matomo/__init__.py b/tests/unit/python/roles/web-app-matomo/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-app-matomo/__init__.py +++ b/tests/unit/python/roles/web-app-matomo/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-matrix/__init__.py b/tests/unit/python/roles/web-app-matrix/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-app-matrix/__init__.py +++ b/tests/unit/python/roles/web-app-matrix/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-n8n/__init__.py b/tests/unit/python/roles/web-app-n8n/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/web-app-n8n/__init__.py +++ b/tests/unit/python/roles/web-app-n8n/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-app-openbao/__init__.py b/tests/unit/python/roles/web-app-openbao/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-app-openbao/__init__.py +++ b/tests/unit/python/roles/web-app-openbao/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-pgadmin/files/__init__.py b/tests/unit/python/roles/web-app-pgadmin/files/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/web-app-pgadmin/files/__init__.py +++ b/tests/unit/python/roles/web-app-pgadmin/files/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-semaphore/test_onion_login.py b/tests/unit/python/roles/web-app-semaphore/test_onion_login.py index 432d41cebb..311f31f7eb 100644 --- a/tests/unit/python/roles/web-app-semaphore/test_onion_login.py +++ b/tests/unit/python/roles/web-app-semaphore/test_onion_login.py @@ -18,7 +18,7 @@ from __future__ import annotations import json import unittest -from unittest import mock +import unittest.mock from ansible.parsing.dataloader import DataLoader from ansible.plugins.loader import filter_loader, lookup_loader @@ -138,7 +138,7 @@ def resolve(names, *, siblings, domain, canonical=CLEAR, sso=True) -> dict: declared = DataLoader().load_from_file(str(VARS), trusted_as_template=True) templar = Templar(loader=DataLoader(), variables={**declared, **variables}) - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): return {name: templar.template(declared[name]) for name in names} diff --git a/tests/unit/python/roles/web-app-socialhome/files/__init__.py b/tests/unit/python/roles/web-app-socialhome/files/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/web-app-socialhome/files/__init__.py +++ b/tests/unit/python/roles/web-app-socialhome/files/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-stalwart/__init__.py b/tests/unit/python/roles/web-app-stalwart/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-app-stalwart/__init__.py +++ b/tests/unit/python/roles/web-app-stalwart/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-taiga/test_onion_sibling.py b/tests/unit/python/roles/web-app-taiga/test_onion_sibling.py index 299d142f31..6e5f647a51 100644 --- a/tests/unit/python/roles/web-app-taiga/test_onion_sibling.py +++ b/tests/unit/python/roles/web-app-taiga/test_onion_sibling.py @@ -2,7 +2,7 @@ from __future__ import annotations import re import unittest -from unittest import mock +import unittest.mock from ansible.parsing.dataloader import DataLoader from ansible.plugins.loader import filter_loader, lookup_loader @@ -77,7 +77,7 @@ def resolve(*, siblings, domain, canonical=CLEAR, tls=True) -> dict: declared = DataLoader().load_from_file(str(VARS), trusted_as_template=True) variables = {"domain": domain, "TLS_ENABLED": tls, "TLS_MODE": "letsencrypt"} templar = Templar(loader=DataLoader(), variables={**declared, **variables}) - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): return {name: templar.template(declared[name]) for name in NAMES} diff --git a/tests/unit/python/roles/web-app-taiga/test_static_url.py b/tests/unit/python/roles/web-app-taiga/test_static_url.py index 10f039d8f6..6e6b633f05 100644 --- a/tests/unit/python/roles/web-app-taiga/test_static_url.py +++ b/tests/unit/python/roles/web-app-taiga/test_static_url.py @@ -3,7 +3,7 @@ from __future__ import annotations import sys import types import unittest -from unittest import mock +import unittest.mock from jinja2 import Environment, StrictUndefined, select_autoescape @@ -66,7 +66,7 @@ def mail_static(namespace: dict, path: str) -> str: "django.templatetags": types.ModuleType("django.templatetags"), "django.templatetags.static": static, } - with mock.patch.dict(sys.modules, modules): + with unittest.mock.patch.dict(sys.modules, modules): return namespace["TEMPLATES"][0]["OPTIONS"]["globals"]["static"](path) diff --git a/tests/unit/python/roles/web-app-wordpress/__init__.py b/tests/unit/python/roles/web-app-wordpress/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-app-wordpress/__init__.py +++ b/tests/unit/python/roles/web-app-wordpress/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-app-wordpress/test_design_tokens.py b/tests/unit/python/roles/web-app-wordpress/test_design_tokens.py index 9257e5aee0..1866c2e34d 100644 --- a/tests/unit/python/roles/web-app-wordpress/test_design_tokens.py +++ b/tests/unit/python/roles/web-app-wordpress/test_design_tokens.py @@ -1,7 +1,7 @@ from __future__ import annotations import unittest -from unittest import mock +import unittest.mock from ansible.parsing.dataloader import DataLoader from ansible.plugins.loader import lookup_loader @@ -49,7 +49,7 @@ def render_tokens() -> list[str]: declared = DataLoader().load_from_file(str(VARS), trusted_as_template=True) templar = Templar(loader=DataLoader(), variables={}) - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): return [ templar.template(token) for token in declared["WORDPRESS_DESIGN_CONFIG"]["tokens"] diff --git a/tests/unit/python/roles/web-app-wordpress/test_options.py b/tests/unit/python/roles/web-app-wordpress/test_options.py index fa2c6cbf09..59c4b179d7 100644 --- a/tests/unit/python/roles/web-app-wordpress/test_options.py +++ b/tests/unit/python/roles/web-app-wordpress/test_options.py @@ -17,8 +17,8 @@ import re import shlex import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from ansible.errors import AnsibleError from ansible.parsing.dataloader import DataLoader @@ -137,7 +137,7 @@ def _resolve(name: str, scenario: dict): templar = Templar( loader=DataLoader(), variables={**declared, "entity_name": "wordpress"} ) - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): return templar.template(declared[name]) diff --git a/tests/unit/python/roles/web-opt-rdr-www/__init__.py b/tests/unit/python/roles/web-opt-rdr-www/__init__.py index 8ee16d7567..e69de29bb2 100644 --- a/tests/unit/python/roles/web-opt-rdr-www/__init__.py +++ b/tests/unit/python/roles/web-opt-rdr-www/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] diff --git a/tests/unit/python/roles/web-svc-api/files/infinito_api/__init__.py b/tests/unit/python/roles/web-svc-api/files/infinito_api/__init__.py index 86efabd459..6290ad0f99 100644 --- a/tests/unit/python/roles/web-svc-api/files/infinito_api/__init__.py +++ b/tests/unit/python/roles/web-svc-api/files/infinito_api/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[7] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-svc-collabora/test_frame_ancestors.py b/tests/unit/python/roles/web-svc-collabora/test_frame_ancestors.py index 337f36ecc0..ca500cc2c0 100644 --- a/tests/unit/python/roles/web-svc-collabora/test_frame_ancestors.py +++ b/tests/unit/python/roles/web-svc-collabora/test_frame_ancestors.py @@ -3,7 +3,6 @@ from __future__ import annotations import sys import unittest import unittest.mock as mock -from unittest.mock import patch from jinja2 import StrictUndefined from jinja2.nativetypes import NativeEnvironment @@ -76,8 +75,8 @@ def frame_ancestors(domains, siblings): expression = load_yaml_str(read_text(str(VARS)))["COLLABORA_FRAME_ANCESTORS"] with ( - patch("plugins.lookup.tls.lookup_loader") as tls_loader, - patch("plugins.lookup.network_urls.lookup_loader") as urls_loader, + mock.patch("plugins.lookup.tls.lookup_loader") as tls_loader, + mock.patch("plugins.lookup.network_urls.lookup_loader") as urls_loader, ): tls_loader.get.side_effect = _tls_loader urls_loader.get.side_effect = _network_urls_loader diff --git a/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py b/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py index d730492cf0..4ba8c90972 100644 --- a/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py +++ b/tests/unit/python/roles/web-svc-collabora/test_wopi_host.py @@ -3,7 +3,6 @@ from __future__ import annotations import sys import unittest import unittest.mock as mock -from unittest.mock import patch from jinja2 import Environment, StrictUndefined, select_autoescape @@ -62,7 +61,7 @@ def wopi_host( undefined=StrictUndefined, autoescape=select_autoescape(default_for_string=False), ) - with patch("plugins.lookup.tls.lookup_loader") as loader: + with mock.patch("plugins.lookup.tls.lookup_loader") as loader: loader.get.side_effect = _get return env.from_string(expression).render(lookup=lookup) diff --git a/tests/unit/python/roles/web-svc-libretranslate/files/__init__.py b/tests/unit/python/roles/web-svc-libretranslate/files/__init__.py index 9f69c70b47..087c384b57 100644 --- a/tests/unit/python/roles/web-svc-libretranslate/files/__init__.py +++ b/tests/unit/python/roles/web-svc-libretranslate/files/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-svc-libretranslate/files/test_prefetch_models.py b/tests/unit/python/roles/web-svc-libretranslate/files/test_prefetch_models.py index fa25d10be9..27a52f2f5f 100644 --- a/tests/unit/python/roles/web-svc-libretranslate/files/test_prefetch_models.py +++ b/tests/unit/python/roles/web-svc-libretranslate/files/test_prefetch_models.py @@ -9,11 +9,10 @@ import importlib.util import sys import types import unittest +import unittest.mock import zipfile from pathlib import Path from tempfile import TemporaryDirectory -from types import ModuleType -from unittest import mock from . import PROJECT_ROOT @@ -37,7 +36,7 @@ class FakePackage: return self._path -def _load() -> ModuleType: +def _load() -> types.ModuleType: package = types.ModuleType("argostranslate.package") package.update_package_index = lambda: None package.get_available_packages = list @@ -59,7 +58,7 @@ def _load() -> ModuleType: "libretranslate.language": language, "minisbd": minisbd, } - with mock.patch.dict(sys.modules, modules): + with unittest.mock.patch.dict(sys.modules, modules): spec = importlib.util.spec_from_file_location("prefetch_models", SCRIPT) module = importlib.util.module_from_spec(spec) assert spec and spec.loader @@ -134,7 +133,7 @@ class TestMain(unittest.TestCase): self.module.download_models = lambda codes, _: self.minisbd_got.append(codes) def test_minisbd_gets_the_model_codes_not_the_iso_codes(self) -> None: - with mock.patch.object( + with unittest.mock.patch.object( sys, "argv", ["prefetch_models.py", "--load_only_lang_codes", "en,zh"] ): self.assertEqual(self.module.main(), 0) @@ -142,7 +141,7 @@ class TestMain(unittest.TestCase): self.assertEqual(self.minisbd_got, [["en", "zh-Hans"]]) def test_minisbd_gets_none_when_no_codes_were_requested(self) -> None: - with mock.patch.object(sys, "argv", ["prefetch_models.py"]): + with unittest.mock.patch.object(sys, "argv", ["prefetch_models.py"]): self.assertEqual(self.module.main(), 0) self.assertEqual(self.minisbd_got, [None]) diff --git a/tests/unit/python/roles/web-svc-logout/templates/test_compose_siblings.py b/tests/unit/python/roles/web-svc-logout/templates/test_compose_siblings.py index ce1d32fb9f..c9e52f20db 100644 --- a/tests/unit/python/roles/web-svc-logout/templates/test_compose_siblings.py +++ b/tests/unit/python/roles/web-svc-logout/templates/test_compose_siblings.py @@ -2,7 +2,7 @@ from __future__ import annotations import importlib.util import unittest -from unittest import mock +import unittest.mock from ansible.parsing.dataloader import DataLoader from ansible.plugins.loader import filter_loader, lookup_loader @@ -108,7 +108,7 @@ def render(conductor: list[str], shop: list[str]) -> dict: logout_domains=logout_domains, ) env.globals["lookup"] = lookup - with mock.patch.object(lookup_loader, "get", side_effect=get): + with unittest.mock.patch.object(lookup_loader, "get", side_effect=get): instances = templar.template(declared["LOGOUT_INSTANCES"]) rendered = env.from_string(read_text(str(TEMPLATE))).render( application_id=APP, diff --git a/tests/unit/python/roles/web-svc-seaweedfs/__init__.py b/tests/unit/python/roles/web-svc-seaweedfs/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/roles/web-svc-seaweedfs/__init__.py +++ b/tests/unit/python/roles/web-svc-seaweedfs/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/roles/web-svc-translate/files/__init__.py b/tests/unit/python/roles/web-svc-translate/files/__init__.py index 9f69c70b47..e69de29bb2 100644 --- a/tests/unit/python/roles/web-svc-translate/files/__init__.py +++ b/tests/unit/python/roles/web-svc-translate/files/__init__.py @@ -1,3 +0,0 @@ -from pathlib import Path - -PROJECT_ROOT: Path = Path(__file__).resolve().parents[6] diff --git a/tests/unit/python/roles/web-svc-translate/files/translate_gateway/__init__.py b/tests/unit/python/roles/web-svc-translate/files/translate_gateway/__init__.py index f4dc78c170..5430683f18 100644 --- a/tests/unit/python/roles/web-svc-translate/files/translate_gateway/__init__.py +++ b/tests/unit/python/roles/web-svc-translate/files/translate_gateway/__init__.py @@ -37,3 +37,16 @@ FAILURES = _load("failures") MEMORY = _load("memory") ROUTER = _load("router") GATEWAY = _load("gateway") + +__all__ = [ + "CACHE", + "ENGINES", + "ERRORS", + "FAILURES", + "FLORES", + "GATEWAY", + "MEMORY", + "PROJECT_ROOT", + "ROUTER", + "SIGNATURE", +] diff --git a/tests/unit/python/tests/test_untracked_files_in_scope.py b/tests/unit/python/tests/test_untracked_files_in_scope.py index 661e576ebb..d9f3510f06 100644 --- a/tests/unit/python/tests/test_untracked_files_in_scope.py +++ b/tests/unit/python/tests/test_untracked_files_in_scope.py @@ -4,10 +4,10 @@ from __future__ import annotations import subprocess import unittest +import unittest.mock from pathlib import Path from tempfile import TemporaryDirectory from types import SimpleNamespace -from unittest import mock from tests.integration.infrastructure.compose import test_no_raw_docker as raw_docker from tests.lint.filesystem.python import test_python_shebangs as shebangs @@ -37,7 +37,7 @@ class _ListingFixture: for name in (TRACKED, UNTRACKED): (self.root / name).write_text("", encoding="utf-8") for module in (files_module, comments): - patcher = mock.patch.object(module, "PROJECT_ROOT", self.root) + patcher = unittest.mock.patch.object(module, "PROJECT_ROOT", self.root) patcher.start() self.addCleanup(patcher.stop) @@ -50,7 +50,9 @@ class _ListingFixture: raise listing return SimpleNamespace(stdout=listing) - return mock.patch.object(files_module.subprocess, "run", side_effect=run) + return unittest.mock.patch.object( + files_module.subprocess, "run", side_effect=run + ) class TestScansListUntrackedFiles(_ListingFixture, unittest.TestCase): diff --git a/tests/unit/python/utils/cache/test_base.py b/tests/unit/python/utils/cache/test_base.py index 1d06d73671..55e8ea7db7 100644 --- a/tests/unit/python/utils/cache/test_base.py +++ b/tests/unit/python/utils/cache/test_base.py @@ -17,7 +17,7 @@ import unittest import unittest.mock as mock from pathlib import Path -from utils.cache import _reset_cache_for_tests, base +from utils.cache import PROJECT_ROOT, _reset_cache_for_tests, base from utils.domains.default_primary import default_domain_primary from utils.paths import FILE_TOKENS @@ -30,15 +30,15 @@ def _write(path: Path, content: str) -> None: class TestProjectRootInvariants(unittest.TestCase): - """`base.PROJECT_ROOT` must point at the actual repo root, not at + """`PROJECT_ROOT` must point at the actual repo root, not at `/utils/`. CI run 24934007615 was caused by exactly this drift after `utils/cache/data.py` was moved one level deeper. """ def test_project_root_resolves_to_repo_root(self): - self.assertTrue((base.PROJECT_ROOT / "roles").is_dir()) - self.assertTrue((base.PROJECT_ROOT / "cli").is_dir()) - self.assertEqual(base.ROLES_DIR, base.PROJECT_ROOT / "roles") + self.assertTrue((PROJECT_ROOT / "roles").is_dir()) + self.assertTrue((PROJECT_ROOT / "cli").is_dir()) + self.assertEqual(base.ROLES_DIR, PROJECT_ROOT / "roles") def test_default_tokens_file_is_secrets_yaml(self): self.assertEqual(base.DEFAULT_TOKENS_FILE, FILE_TOKENS) diff --git a/tests/unit/python/utils/cache/test_data.py b/tests/unit/python/utils/cache/test_data.py index 463b4aa8ac..11adc50705 100644 --- a/tests/unit/python/utils/cache/test_data.py +++ b/tests/unit/python/utils/cache/test_data.py @@ -5,10 +5,9 @@ import textwrap import unittest from pathlib import Path -from utils.cache import _reset_cache_for_tests +from utils.cache import PROJECT_ROOT, _reset_cache_for_tests from utils.cache.applications import get_application_defaults from utils.cache.base import ( - PROJECT_ROOT, ROLES_DIR, _deep_merge, _fingerprint_mapping, diff --git a/tests/unit/python/utils/design/__init__.py b/tests/unit/python/utils/design/__init__.py index 8ee16d7567..aa7a30d2e5 100644 --- a/tests/unit/python/utils/design/__init__.py +++ b/tests/unit/python/utils/design/__init__.py @@ -1,3 +1,5 @@ from pathlib import Path PROJECT_ROOT: Path = Path(__file__).resolve().parents[5] + +__all__ = ["PROJECT_ROOT"] diff --git a/tests/unit/python/utils/i18n/test_catalog.py b/tests/unit/python/utils/i18n/test_catalog.py index a154f92bb6..924a6e38c9 100644 --- a/tests/unit/python/utils/i18n/test_catalog.py +++ b/tests/unit/python/utils/i18n/test_catalog.py @@ -1,8 +1,8 @@ import errno import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from utils.i18n.catalog import ( build_template, @@ -106,7 +106,7 @@ class TestWrite(unittest.TestCase): raise OSError(errno.ENOSPC, "No space left on device") with ( - mock.patch.object( + unittest.mock.patch.object( Path, "write_bytes", autospec=True, side_effect=full_disk ), self.assertRaises(OSError), diff --git a/tests/unit/python/utils/i18n/test_libretranslate.py b/tests/unit/python/utils/i18n/test_libretranslate.py index 32345827dc..ea04f5eb55 100644 --- a/tests/unit/python/utils/i18n/test_libretranslate.py +++ b/tests/unit/python/utils/i18n/test_libretranslate.py @@ -6,8 +6,8 @@ import urllib.error from pathlib import Path from tempfile import TemporaryDirectory +from utils.i18n.client import LibreTranslate from utils.i18n.libretranslate import ( - LibreTranslate, accelerated, deploying, server, diff --git a/tests/unit/python/utils/i18n/test_names.py b/tests/unit/python/utils/i18n/test_names.py index 9bb0f3240c..eed39d0ebd 100644 --- a/tests/unit/python/utils/i18n/test_names.py +++ b/tests/unit/python/utils/i18n/test_names.py @@ -9,13 +9,9 @@ from __future__ import annotations import unittest from itertools import pairwise +from utils.i18n.damage import missing_names, protected_spans from utils.i18n.names import spans -from utils.i18n.placeholders import ( - has_words, - matches, - missing_names, - protected_spans, -) +from utils.i18n.spans import has_words, matches def _protected(text: str) -> set[str]: diff --git a/tests/unit/python/utils/i18n/test_no_python_format.py b/tests/unit/python/utils/i18n/test_no_python_format.py index c8ba1ada49..1824f8ab04 100644 --- a/tests/unit/python/utils/i18n/test_no_python_format.py +++ b/tests/unit/python/utils/i18n/test_no_python_format.py @@ -14,7 +14,7 @@ import unittest from babel.messages.catalog import Catalog from utils.i18n.catalog import render -from utils.i18n.placeholders import carries_placeholder +from utils.i18n.spans import carries_placeholder class TestCarriesPlaceholder(unittest.TestCase): diff --git a/tests/unit/python/utils/i18n/test_placeholders.py b/tests/unit/python/utils/i18n/test_placeholders.py index 426aaef02a..0e29f0b011 100644 --- a/tests/unit/python/utils/i18n/test_placeholders.py +++ b/tests/unit/python/utils/i18n/test_placeholders.py @@ -1,15 +1,14 @@ import unittest +from utils.i18n.damage import MARKUP from utils.i18n.placeholders import ( - MARKUP, TOKEN, Rejected, - mask, - mask_tokens, resegment, tighten, unmask, ) +from utils.i18n.spans import mask, mask_tokens class TestMaskTokens(unittest.TestCase): diff --git a/tests/unit/python/utils/i18n/test_repairs.py b/tests/unit/python/utils/i18n/test_repairs.py index fa819f13ac..b3a34d0649 100644 --- a/tests/unit/python/utils/i18n/test_repairs.py +++ b/tests/unit/python/utils/i18n/test_repairs.py @@ -10,18 +10,16 @@ from __future__ import annotations import unittest from typing import ClassVar +from utils.i18n.damage import collapsed, harms, truncated from utils.i18n.placeholders import ( collapse, - collapsed, - harms, - mask, recapitalise, resegment, terminate, tighten, - truncated, unmask, ) +from utils.i18n.spans import mask def _round_trip(source: str, translated: str) -> str | None: diff --git a/tests/unit/python/utils/i18n/test_translate.py b/tests/unit/python/utils/i18n/test_translate.py index 378fafb9f1..b8c49fce1e 100644 --- a/tests/unit/python/utils/i18n/test_translate.py +++ b/tests/unit/python/utils/i18n/test_translate.py @@ -18,7 +18,7 @@ from utils.i18n.catalog import ( merge, render, ) -from utils.i18n.libretranslate import LibreTranslate +from utils.i18n.client import LibreTranslate from utils.i18n.placeholders import Rejected from utils.i18n.translate import ( URL_SUPPRESSION, diff --git a/tests/unit/python/utils/meta/test_identity.py b/tests/unit/python/utils/meta/test_identity.py index 4fbdc85e05..78217bacd8 100644 --- a/tests/unit/python/utils/meta/test_identity.py +++ b/tests/unit/python/utils/meta/test_identity.py @@ -2,8 +2,8 @@ from __future__ import annotations import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from utils.meta.identity import ( DOMAIN, @@ -102,15 +102,15 @@ class TestCommittingAs(unittest.TestCase): "INFINITO_GIT_AUTHOR_NAME": "Carried Name", "INFINITO_GIT_AUTHOR_EMAIL": "carried@example.com", } - with mock.patch.dict("os.environ", carried): + with unittest.mock.patch.dict("os.environ", carried): self.assertEqual(committing_as(), ("Carried Name", "carried@example.com")) def test_an_empty_carried_address_falls_through_to_git(self) -> None: with ( - mock.patch.dict("os.environ", {"INFINITO_GIT_AUTHOR_EMAIL": " "}), - mock.patch("subprocess.run") as run, + unittest.mock.patch.dict("os.environ", {"INFINITO_GIT_AUTHOR_EMAIL": " "}), + unittest.mock.patch("subprocess.run") as run, ): - run.return_value = mock.Mock(stdout="from-git\n") + run.return_value = unittest.mock.Mock(stdout="from-git\n") self.assertEqual(committing_as(), ("from-git", "from-git")) diff --git a/tests/unit/python/utils/preflight/test_context.py b/tests/unit/python/utils/preflight/test_context.py index 138bc3f166..dfcd19286a 100644 --- a/tests/unit/python/utils/preflight/test_context.py +++ b/tests/unit/python/utils/preflight/test_context.py @@ -1,5 +1,5 @@ import unittest -from unittest import mock +import unittest.mock from utils.preflight.context import deploy_closure_context @@ -9,23 +9,25 @@ MODULE = "utils.preflight.context" class TestDeployClosureContext(unittest.TestCase): def _build(self, closure=None, side_effect=None): plugins = { - "applications": mock.Mock(), - "config": mock.Mock(), - "domains": mock.Mock(), + "applications": unittest.mock.Mock(), + "config": unittest.mock.Mock(), + "domains": unittest.mock.Mock(), } plugins["applications"].run.return_value = [{"web-app-matomo": {}}] plugins["config"].run.side_effect = lambda terms, variables=None: [ f"{terms[0]}:{terms[1]}" ] plugins["domains"].run.return_value = [["matomo.example.org"]] - lookup = mock.Mock(_loader="loader", _templar=None) + lookup = unittest.mock.Mock(_loader="loader", _templar=None) with ( - mock.patch( + unittest.mock.patch( f"{MODULE}.lookup_loader.get", side_effect=lambda name, **kwargs: plugins[name], ), - mock.patch(f"{MODULE}.types_from_group_names", return_value=["server"]), - mock.patch( + unittest.mock.patch( + f"{MODULE}.types_from_group_names", return_value=["server"] + ), + unittest.mock.patch( f"{MODULE}.deploy_closure", return_value=closure or {"web-app-matomo", "svc-db-mariadb"}, side_effect=side_effect, diff --git a/tests/unit/python/utils/roles/applications/test_variants_pin_scope.py b/tests/unit/python/utils/roles/applications/test_variants_pin_scope.py index 429ef79d2a..3ff0615e40 100644 --- a/tests/unit/python/utils/roles/applications/test_variants_pin_scope.py +++ b/tests/unit/python/utils/roles/applications/test_variants_pin_scope.py @@ -91,7 +91,7 @@ class TestPinScope(unittest.TestCase): {"services": {"carrier": {"enabled": False}}}, ] - def include(*, primary_apps, services_overrides): + def include(*, primary_apps, services_overrides) -> tuple[str, ...]: carried = services_overrides[PARTNER]["carrier"]["enabled"] is True return (CARRIER, PARTNER, *primary_apps) if carried else (PARTNER,) diff --git a/tests/unit/python/utils/tests/swarm/test_extra_vars.py b/tests/unit/python/utils/tests/swarm/test_extra_vars.py index aac0159a2b..62b24e51d0 100644 --- a/tests/unit/python/utils/tests/swarm/test_extra_vars.py +++ b/tests/unit/python/utils/tests/swarm/test_extra_vars.py @@ -2,7 +2,7 @@ from __future__ import annotations import json import unittest -from unittest import mock +import unittest.mock from utils.tests.swarm import extra_vars @@ -18,7 +18,7 @@ ROUND_OVERRIDES = { class TestInventoryExtraVars(unittest.TestCase): def test_unset_or_empty_variable_keeps_the_round_overrides(self): for env in ({}, {"INFINITO_INVENTORY_EXTRA_VARS": ""}): - with mock.patch.dict(extra_vars.os.environ, env, clear=True): + with unittest.mock.patch.dict(extra_vars.os.environ, env, clear=True): self.assertEqual( extra_vars.with_extra_vars(ROUND_OVERRIDES), ROUND_OVERRIDES ) @@ -30,7 +30,7 @@ class TestInventoryExtraVars(unittest.TestCase): }, "STORAGE_CONSTRAINED": True, } - with mock.patch.dict( + with unittest.mock.patch.dict( extra_vars.os.environ, {"INFINITO_INVENTORY_EXTRA_VARS": json.dumps(extra)}, clear=True, @@ -45,7 +45,7 @@ class TestInventoryExtraVars(unittest.TestCase): def test_a_non_object_variable_fails_loud(self): with ( - mock.patch.dict( + unittest.mock.patch.dict( extra_vars.os.environ, {"INFINITO_INVENTORY_EXTRA_VARS": "[]"}, clear=True, diff --git a/tests/unit/python/utils/tests/swarm/test_matrix.py b/tests/unit/python/utils/tests/swarm/test_matrix.py index 211bc8e050..199475b9d2 100644 --- a/tests/unit/python/utils/tests/swarm/test_matrix.py +++ b/tests/unit/python/utils/tests/swarm/test_matrix.py @@ -2,13 +2,13 @@ from __future__ import annotations import tempfile import unittest -from unittest import mock +import unittest.mock from utils.tests.swarm import matrix class TestSwarmDeployCommands(unittest.TestCase): - @mock.patch.object(matrix, "_run", return_value=0) + @unittest.mock.patch.object(matrix, "_run", return_value=0) def test_round_deploy_keeps_the_placed_custom_roles(self, run): matrix._deploy( app_id="web-app-cst-demo", @@ -21,7 +21,7 @@ class TestSwarmDeployCommands(unittest.TestCase): self.assertIn("cli.administration.deploy.swarm", cmd) self.assertIn("--skip-pull", cmd) - @mock.patch.object(matrix, "_run", return_value=0) + @unittest.mock.patch.object(matrix, "_run", return_value=0) def test_backup_host_deploy_keeps_the_placed_custom_roles(self, run): with tempfile.TemporaryDirectory() as inv_dir: matrix._deploy_backup_host( diff --git a/tests/unit/python/utils/update/test_follow.py b/tests/unit/python/utils/update/test_follow.py index 6045d6c3e5..18b7b1830a 100644 --- a/tests/unit/python/utils/update/test_follow.py +++ b/tests/unit/python/utils/update/test_follow.py @@ -5,8 +5,8 @@ import http.client import io import json import unittest +import unittest.mock import urllib.error -from unittest import mock from utils.update.follow import followed_tags, tag_digest @@ -31,12 +31,12 @@ def _digests(table: dict[str, str]): class TestFollowedTags(unittest.TestCase): def test_ubuntu_on_the_lts_gets_no_interim_release(self) -> None: - with mock.patch("utils.update.follow.tag_digest", _digests(UBUNTU)): + with unittest.mock.patch("utils.update.follow.tag_digest", _digests(UBUNTU)): found = followed_tags("ubuntu", list(UBUNTU), {"follow": "latest"}, "26.04") self.assertEqual(found, []) def test_fedora_moves_to_the_stable_release_not_rawhide(self) -> None: - with mock.patch("utils.update.follow.tag_digest", _digests(FEDORA)): + with unittest.mock.patch("utils.update.follow.tag_digest", _digests(FEDORA)): found = followed_tags("fedora", list(FEDORA), {"follow": "latest"}, "44") self.assertEqual(found, ["45"]) @@ -48,7 +48,9 @@ class TestFollowedTags(unittest.TestCase): def test_an_unreadable_registry_proposes_nothing_and_says_so(self) -> None: stderr = io.StringIO() with ( - mock.patch("utils.update.follow.tag_digest", side_effect=OSError("429")), + unittest.mock.patch( + "utils.update.follow.tag_digest", side_effect=OSError("429") + ), contextlib.redirect_stderr(stderr), ): found = followed_tags("fedora", list(FEDORA), {"follow": "latest"}, "44") @@ -58,7 +60,7 @@ class TestFollowedTags(unittest.TestCase): def test_an_incomplete_response_proposes_nothing_and_says_so(self) -> None: stderr = io.StringIO() with ( - mock.patch( + unittest.mock.patch( "utils.update.follow.get", side_effect=http.client.IncompleteRead(b"{", 120), ), @@ -79,10 +81,10 @@ class TestFollowedTags(unittest.TestCase): "3.14.2-slim", ] with ( - mock.patch( + unittest.mock.patch( "utils.update.follow.requires_python", return_value=">=3.11,<3.16" ), - mock.patch("utils.update.follow.tag_digest") as digest, + unittest.mock.patch("utils.update.follow.tag_digest") as digest, contextlib.redirect_stderr(io.StringIO()), ): found = followed_tags( @@ -93,10 +95,10 @@ class TestFollowedTags(unittest.TestCase): def test_requires_python_at_the_cap_proposes_nothing(self) -> None: with ( - mock.patch( + unittest.mock.patch( "utils.update.follow.requires_python", return_value=">=3.11,<3.15" ), - mock.patch( + unittest.mock.patch( "utils.update.follow.tag_digest", return_value="sha256:one" ) as digest, contextlib.redirect_stderr(io.StringIO()), @@ -114,16 +116,16 @@ class TestFollowedTags(unittest.TestCase): limited = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None) body = json.dumps({"digest": "sha256:45"}).encode() with ( - mock.patch("utils.update.follow.get", side_effect=[limited, body]), - mock.patch("utils.update.follow.time.sleep"), + unittest.mock.patch("utils.update.follow.get", side_effect=[limited, body]), + unittest.mock.patch("utils.update.follow.time.sleep"), ): self.assertEqual(tag_digest("fedora", "latest"), "sha256:45") def test_a_persistent_rate_limit_still_raises(self) -> None: limited = urllib.error.HTTPError("url", 429, "Too Many Requests", {}, None) with ( - mock.patch("utils.update.follow.get", side_effect=[limited] * 3), - mock.patch("utils.update.follow.time.sleep"), + unittest.mock.patch("utils.update.follow.get", side_effect=[limited] * 3), + unittest.mock.patch("utils.update.follow.time.sleep"), self.assertRaises(urllib.error.HTTPError), ): tag_digest("fedora", "latest") diff --git a/tests/unit/python/utils/update/test_repository.py b/tests/unit/python/utils/update/test_repository.py index 0a23beb2ed..fc433c782b 100644 --- a/tests/unit/python/utils/update/test_repository.py +++ b/tests/unit/python/utils/update/test_repository.py @@ -3,8 +3,8 @@ from __future__ import annotations import subprocess import tempfile import unittest +import unittest.mock from pathlib import Path -from unittest import mock from utils.cache.files import read_text from utils.roles.mapping import ROLE_DIR_META_ADDONS, ROLE_FILE_META_SERVICES @@ -374,8 +374,8 @@ def _write_role( def _find(root: Path, ls_remote: _LsRemote) -> list[RepositoryRefUpdate]: with ( - mock.patch.object(module, "resolve_max_fetch_workers", return_value=2), - mock.patch.object(module.subprocess, "run", side_effect=ls_remote), + unittest.mock.patch.object(module, "resolve_max_fetch_workers", return_value=2), + unittest.mock.patch.object(module.subprocess, "run", side_effect=ls_remote), ): return find_outdated_updates(root) @@ -414,7 +414,9 @@ class TestIsCommitSha(unittest.TestCase): class TestGitLsRemoteHead(unittest.TestCase): def test_returns_the_head_commit(self) -> None: ls_remote = _LsRemote(heads={SHA_REPO: TIP_SHA}) - with mock.patch.object(module.subprocess, "run", side_effect=ls_remote): + with unittest.mock.patch.object( + module.subprocess, "run", side_effect=ls_remote + ): self.assertEqual(git_ls_remote_head(SHA_REPO), TIP_SHA) self.assertEqual(ls_remote.calls, [(SHA_REPO, "HEAD")]) @@ -426,12 +428,16 @@ class TestGitLsRemoteHead(unittest.TestCase): ): with ( self.subTest(failure=type(failure).__name__), - mock.patch.object(module.subprocess, "run", side_effect=failure), + unittest.mock.patch.object( + module.subprocess, "run", side_effect=failure + ), ): self.assertIsNone(git_ls_remote_head(SHA_REPO)) def test_an_empty_answer_returns_none(self) -> None: - with mock.patch.object(module.subprocess, "run", side_effect=_LsRemote()): + with unittest.mock.patch.object( + module.subprocess, "run", side_effect=_LsRemote() + ): self.assertIsNone(git_ls_remote_head(SHA_REPO)) diff --git a/tests/utils/services.py b/tests/utils/services.py index ebecc5d61f..5a9e2496c0 100644 --- a/tests/utils/services.py +++ b/tests/utils/services.py @@ -11,6 +11,7 @@ which has a ``/tmp`` of its own. from __future__ import annotations +import contextlib import time import urllib.error import urllib.request @@ -45,12 +46,10 @@ def progress(suite: str, message: str) -> None: """ stamp = time.strftime("%H:%M:%S") path = progress_log(suite) - try: + with contextlib.suppress(OSError): path.parent.mkdir(parents=True, exist_ok=True) with path.open("a", encoding="utf-8") as handle: handle.write(f"{stamp} {message}\n") - except OSError: - pass def answers(url: str) -> bool: diff --git a/utils/cache/base.py b/utils/cache/base.py index 0face6c0a8..e49d920292 100644 --- a/utils/cache/base.py +++ b/utils/cache/base.py @@ -23,13 +23,10 @@ from collections.abc import Mapping from pathlib import Path from typing import Any -from plugins.filter.merge.with_defaults import ( - merge_with_defaults, # noqa: F401 re-exported -) from utils.cache.errors import is_unresolvable from utils.paths import FILE_TOKENS -from . import PROJECT_ROOT, ROLES_DIR # noqa: F401 +from . import ROLES_DIR _TOKENS_DIGESTS: dict[tuple, str] = {} diff --git a/utils/i18n/catalog.py b/utils/i18n/catalog.py index 15f1e95380..523227ec40 100644 --- a/utils/i18n/catalog.py +++ b/utils/i18n/catalog.py @@ -10,7 +10,7 @@ from typing import TYPE_CHECKING from babel.messages.catalog import Catalog from babel.messages.pofile import read_po, write_po -from utils.i18n.placeholders import carries_placeholder +from utils.i18n.spans import carries_placeholder from utils.i18n.untranslatable import untranslatable from utils.software import ( SOFTWARE_AUTHOR, diff --git a/utils/i18n/client.py b/utils/i18n/client.py index b23b2e9055..e8f137b804 100644 --- a/utils/i18n/client.py +++ b/utils/i18n/client.py @@ -17,7 +17,8 @@ from typing import TYPE_CHECKING from utils.i18n.languages import SOURCE_LANGUAGE from utils.i18n.limits import BATCH_SIZE -from utils.i18n.placeholders import Rejected, mask, mask_tokens, unmask +from utils.i18n.placeholders import Rejected, unmask +from utils.i18n.spans import mask, mask_tokens from utils.i18n.untranslatable import untranslatable if TYPE_CHECKING: diff --git a/utils/i18n/gateway.py b/utils/i18n/gateway.py index 0625879f67..a43c327ed9 100644 --- a/utils/i18n/gateway.py +++ b/utils/i18n/gateway.py @@ -23,9 +23,6 @@ from utils.i18n.libretranslate import ( probe, unaccelerated, ) -from utils.i18n.libretranslate import READY_TIMEOUT_SECONDS as READY_TIMEOUT_SECONDS -from utils.i18n.libretranslate import LibreTranslate as LibreTranslate -from utils.i18n.libretranslate import download_status as download_status from utils.roles.mapping import ROLE_FILE_META_SERVICES if TYPE_CHECKING: diff --git a/utils/i18n/libretranslate.py b/utils/i18n/libretranslate.py index 009d754f2f..d6e7e32c9f 100644 --- a/utils/i18n/libretranslate.py +++ b/utils/i18n/libretranslate.py @@ -11,8 +11,6 @@ from pathlib import Path from typing import TYPE_CHECKING from utils.cache.yaml import load_yaml -from utils.i18n.client import LibreTranslate as LibreTranslate -from utils.i18n.client import Outcome as Outcome from utils.i18n.client import merge from utils.inventory.tools import LANE_SERVICE from utils.roles.mapping import ROLE_FILE_META_SERVICES @@ -29,11 +27,9 @@ GATEWAY_ROLE = "web-svc-translate" GATEWAY_SERVICE_KEY = "translate" GATEWAY_SERVICES_FILE = Path("roles") / GATEWAY_ROLE / ROLE_FILE_META_SERVICES POLL_SECONDS = 5 -READY_TIMEOUT_SECONDS = 3600 DEPLOYED_TIMEOUT_SECONDS = 5 DEPLOY_TIMEOUT_SECONDS = 4 * 3600 RUNNER_TIMEOUT_SECONDS = 300 -SERVICE_TIMEOUT_SECONDS = READY_TIMEOUT_SECONDS INVENTORY_DIR = Path.home() / "inventories" / "infinito-tools" DEPLOY_PID_FILE = Path("build") / "deploy.pid" DEPLOY_ROUTER = "deploy/main.sh" diff --git a/utils/i18n/placeholders.py b/utils/i18n/placeholders.py index 9fadc81199..6baf8cea0f 100644 --- a/utils/i18n/placeholders.py +++ b/utils/i18n/placeholders.py @@ -11,49 +11,15 @@ from __future__ import annotations import html -from utils.i18n.damage import COLLAPSE_FLOOR as COLLAPSE_FLOOR -from utils.i18n.damage import COLLAPSE_RATIO as COLLAPSE_RATIO -from utils.i18n.damage import ECHO_FLOOR as ECHO_FLOOR -from utils.i18n.damage import LATIN_SHARE as LATIN_SHARE -from utils.i18n.damage import MARKUP as MARKUP -from utils.i18n.damage import MAX_SHARING_SOURCES as MAX_SHARING_SOURCES -from utils.i18n.damage import NON_LATIN_SCRIPTS as NON_LATIN_SCRIPTS -from utils.i18n.damage import STRUCTURE as STRUCTURE -from utils.i18n.damage import STUTTER as STUTTER -from utils.i18n.damage import TRUNCATION_FLOOR as TRUNCATION_FLOOR -from utils.i18n.damage import TRUNCATION_RATIO as TRUNCATION_RATIO -from utils.i18n.damage import WORDS as WORDS from utils.i18n.damage import Rejected as Rejected -from utils.i18n.damage import added_spans as added_spans -from utils.i18n.damage import collapsed as collapsed -from utils.i18n.damage import harms as harms -from utils.i18n.damage import missing_names as missing_names -from utils.i18n.damage import protected_spans as protected_spans from utils.i18n.damage import reason as reason -from utils.i18n.damage import structure as structure -from utils.i18n.damage import stutters as stutters -from utils.i18n.damage import truncated as truncated -from utils.i18n.damage import untranslated as untranslated -from utils.i18n.repairs import EMPHASIS as EMPHASIS -from utils.i18n.repairs import RUN_OF_SPACES as RUN_OF_SPACES -from utils.i18n.repairs import TERMINATORS as TERMINATORS from utils.i18n.repairs import collapse as collapse from utils.i18n.repairs import recapitalise as recapitalise from utils.i18n.repairs import resegment as resegment from utils.i18n.repairs import terminate as terminate from utils.i18n.repairs import tighten as tighten -from utils.i18n.spans import EXTRA as EXTRA -from utils.i18n.spans import PLACEHOLDER as PLACEHOLDER -from utils.i18n.spans import PRINTF as PRINTF -from utils.i18n.spans import PROTECTED as PROTECTED from utils.i18n.spans import TOKEN as TOKEN from utils.i18n.spans import Masked as Masked -from utils.i18n.spans import carries_placeholder as carries_placeholder -from utils.i18n.spans import has_words as has_words -from utils.i18n.spans import mask as mask -from utils.i18n.spans import mask_tokens as mask_tokens -from utils.i18n.spans import matches as matches -from utils.i18n.spans import prose as prose def unmask( diff --git a/utils/i18n/translate.py b/utils/i18n/translate.py index 1e46690939..fda7d9554a 100644 --- a/utils/i18n/translate.py +++ b/utils/i18n/translate.py @@ -12,13 +12,13 @@ from utils.i18n.catalog import ( is_machine_translation, machine_translation, ) -from utils.i18n.placeholders import ( +from utils.i18n.damage import ( COLLAPSE_FLOOR, MAX_SHARING_SOURCES, - Rejected, harms, protected_spans, ) +from utils.i18n.placeholders import Rejected from utils.i18n.spans import prose if TYPE_CHECKING: diff --git a/utils/i18n/untranslatable.py b/utils/i18n/untranslatable.py index 1a284424cd..c60b254b5b 100644 --- a/utils/i18n/untranslatable.py +++ b/utils/i18n/untranslatable.py @@ -28,7 +28,7 @@ from __future__ import annotations import re import unicodedata -from utils.i18n.placeholders import has_words +from utils.i18n.spans import has_words from utils.meta.authors import author_names from utils.meta.role.brands import brand_titles from utils.software import SOFTWARE_NAME diff --git a/utils/roles/validation/resources.py b/utils/roles/validation/resources.py index 56969cda4a..4e24ececf8 100644 --- a/utils/roles/validation/resources.py +++ b/utils/roles/validation/resources.py @@ -1,5 +1,6 @@ from __future__ import annotations +import contextlib from typing import TYPE_CHECKING, Any from humanfriendly import parse_size @@ -71,12 +72,10 @@ def filter_roles_by_min_storage( if not entity: cfg_path_early = role_dir / ROLE_FILE_META_SERVICES if cfg_path_early.is_file(): - try: + with contextlib.suppress(Exception): early_cfg = _load_yaml_file(cfg_path_early) if isinstance(early_cfg, dict) and role_name in early_cfg: entity = role_name - except Exception: # noqa: S110 - non-fatal: malformed services.yml just skips the role - pass if not entity: if emit_warnings: warning(