Debian Codegraph @

tests/tools/test_enum_unknown.py

raw
1 """Tests to ensure inherited enums define `UNKNOWN` members."""
2
3 from collections.abc import Iterator
4 from enum import Enum
5 import importlib
6 import inspect
7 import pkgutil
8
9 import pytest
10
11 from asusrouter.tools import enum as enum_tools
12
13
14 def _iter_enum_classes() -> Iterator[type[Enum]]:
15 """Yield all enum classes in the asusrouter package.
16
17 Check the ones inheriting our mixins.
18 """
19
20 # Clear any previous failed imports
21 if hasattr(_iter_enum_classes, "_failed_imports"):
22 delattr(_iter_enum_classes, "_failed_imports")
23
24 failed_imports: list[tuple[str, str]] = []
25
26 # Import package modules under asusrouter
27 package = importlib.import_module("asusrouter")
28 for finder, name, ispkg in pkgutil.walk_packages(
29 package.__path__, package.__name__ + "."
30 ):
31 # Import module
32 try:
33 mod = importlib.import_module(name)
34 except ImportError as ex:
35 # Record failed imports
36 failed_imports.append((name, repr(ex)))
37 continue
38
39 for _, obj in inspect.getmembers(mod, inspect.isclass):
40 try:
41 if issubclass(obj, Enum) and (
42 issubclass(obj, enum_tools.FromIntMixin)
43 or issubclass(obj, enum_tools.FromStrMixin)
44 ):
45 yield obj
46 except TypeError:
47 # Not compatible with issubclass; skip
48 continue
49
50 # If any imports failed, attach them to the generator function
51 if failed_imports:
52 # attach a list for later inspection
53 setattr(_iter_enum_classes, "_failed_imports", failed_imports)
54
55
56 def test_enums_define_unknown() -> None:
57 """Test to ensure all enums define an UNKNOWN member."""
58
59 enums = list(_iter_enum_classes())
60 total = len(enums)
61
62 # If any imports failed, report them
63 failed = getattr(_iter_enum_classes, "_failed_imports", None)
64 if failed:
65 details = "; ".join(f"{mod} -> {err}" for mod, err in failed)
66 pytest.fail(
67 f"Some modules failed to import during discovery: {details}"
68 )
69
70 # Explicit report if nothing was found (likely a discovery/import issue)
71 assert total > 0, (
72 "No enums inheriting FromIntMixin/FromStrMixin "
73 "were discovered in the package"
74 )
75
76 missing = [
77 f"{enum_cls.__module__}.{enum_cls.__name__}"
78 for enum_cls in enums
79 if not hasattr(enum_cls, "UNKNOWN")
80 ]
81
82 if missing:
83 pytest.fail(
84 f"Found {total} enums inheriting mixins;"
85 f"{len(missing)} missing UNKNOWN: " + ", ".join(missing)
86 )
87
88 # If nothing is missing, the test passes