Source code for s365b.modules.testing

"""Contract checks that every module must pass.

Module authors call these from their own tests::

    from s365b.modules.testing import assert_module_contract

    def test_contract():
        assert_module_contract(ExchangeModule)

The project's own test suite also runs them against every installed module.
"""

from __future__ import annotations

import re

from s365b.modules.registry import validate_module_class
from s365b.modules.sdk import BackupModule

_PERMISSION_RE = re.compile(r"^[A-Z][A-Za-z]+(\.[A-Za-z]+)+$")
_ID_RE = re.compile(r"^[a-z][a-z0-9_]*$")


[docs] def assert_module_contract(cls: type[BackupModule]) -> None: """Assert that a module class follows the static parts of the contract. Checks: valid metadata and config model, well-formed permission names, backup permissions are a subset of what restore needs or read-only, unique item type and event IDs. Args: cls: Module class to check. Raises: AssertionError: Describing the first violation. """ try: validate_module_class(cls) except Exception as exc: raise AssertionError(str(exc)) from exc module = cls() config = cls.config_model() for restore in (False, True): perms = module.required_permissions(config, restore=restore) bad = sorted(p for p in perms if not _PERMISSION_RE.match(p)) if bad: raise AssertionError(f"{cls.id}: malformed permission names {bad}") backup_perms = module.required_permissions(config, restore=False) writes = sorted(p for p in backup_perms if "Write" in p or p.endswith(".Send")) if writes: raise AssertionError(f"{cls.id}: backup must be read-only, but requests {writes}") types = module.item_types() if not types: raise AssertionError(f"{cls.id}: item_types() must not be empty") _assert_unique_ids(cls.id, "item type", [t.id for t in types]) _assert_unique_ids(cls.id, "event type", [e.id for e in module.event_types()]) _assert_unique_ids(cls.id, "export format", module.export_formats())
def _assert_unique_ids(module_id: str, what: str, ids: list[str]) -> None: bad = [i for i in ids if not _ID_RE.match(i)] if bad: raise AssertionError(f"{module_id}: invalid {what} IDs {bad}") if len(set(ids)) != len(ids): raise AssertionError(f"{module_id}: duplicate {what} IDs")