Coverage for tests/misplaced_marks.py: 0%
48 statements
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
« prev ^ index » next coverage.py v7.17.3, created at 2026-11-17 21:20 +0000
1import ast
2from functools import cache
3from pathlib import Path
5import pytest
7# Run as `pytest --collect-only -q -m "" -p tests.misplaced_marks`: marks decide which
8# CI job runs a test, so a wrong one drops it from a job without failing anything.
9TESTS_ROOT = Path(__file__).parent
11BROKERS = ("kafka", "confluent", "rabbit", "nats", "redis", "mqtt")
14@pytest.hookimpl(trylast=True)
15def pytest_collection_finish(session: pytest.Session) -> None:
16 problems = sorted({
17 problem
18 for item in session.items
19 if isinstance(item, pytest.Function)
20 for problem in (
21 _connected_in_memory(item),
22 _missing_broker_mark(item),
23 _unmarked_broker_import(item),
24 )
25 if problem
26 })
28 if problems:
29 pytest.exit("Misplaced marks:\n" + "\n".join(problems), returncode=1)
32def _connected_in_memory(item: pytest.Function) -> str | None:
33 if item.cls is None or not any(
34 base.__name__.endswith("MemoryTestcaseConfig") for base in item.cls.__mro__
35 ):
36 return None
38 # a single test of an in-memory class may still open a real connection
39 # (`with_real=True`), so only a mark covering the whole class is wrong
40 for node, _ in item.iter_markers_with_node("connected"):
41 if node is not item:
42 return (
43 f"{_location(item)}::{item.cls.__name__} -- in-memory class under "
44 "`connected`, mark the tests that reach a broker instead"
45 )
47 return None
50def _missing_broker_mark(item: pytest.Function) -> str | None:
51 directories = item.path.relative_to(TESTS_ROOT).parts[:-1]
53 for broker in BROKERS:
54 if broker not in directories:
55 continue
57 position = directories.index(broker)
58 in_cluster = directories[position : position + 2] == ("redis", "cluster")
59 mark = "redis_cluster" if in_cluster else broker
61 if item.get_closest_marker(mark) is None:
62 return f"{_location(item)} -- under `{broker}/`, not marked `{mark}`"
64 return None
67def _unmarked_broker_import(item: pytest.Function) -> str | None:
68 # an unmarked test still runs in `test-basic`; a `connected` one only runs
69 # in its broker's job, so a missing mark there means it never runs at all
70 if item.get_closest_marker("connected") is None:
71 return None
73 # a module that imports several brokers uses one of them as an example;
74 # only a module built on a single broker names the job that must run it
75 brokers = _imported_brokers(item.path)
76 if len(brokers) != 1:
77 return None
79 for broker in brokers:
80 if broker == "redis" and item.get_closest_marker("redis_cluster") is not None:
81 continue
83 if item.get_closest_marker(broker) is None:
84 return (
85 f"{_location(item)} -- imports `faststream.{broker}`, "
86 f"not marked `{broker}`"
87 )
89 return None
92@cache
93def _imported_brokers(path: Path) -> frozenset[str]:
94 modules: list[str] = []
95 for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
96 if isinstance(node, ast.Import):
97 modules.extend(alias.name for alias in node.names)
98 elif isinstance(node, ast.ImportFrom) and node.module and not node.level:
99 modules.append(node.module)
101 return frozenset(
102 parts[1]
103 for module in modules
104 if (parts := module.split("."))[0] == "faststream"
105 and len(parts) > 1
106 and parts[1] in BROKERS
107 )
110def _location(item: pytest.Function) -> str:
111 return str(item.path.relative_to(TESTS_ROOT.parent))