-
Notifications
You must be signed in to change notification settings - Fork 20
Expand file tree
/
Copy pathtest_metrics_facade.py
More file actions
64 lines (50 loc) · 2.04 KB
/
Copy pathtest_metrics_facade.py
File metadata and controls
64 lines (50 loc) · 2.04 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
"""Enforce that no module outside shared/metrics.py imports exporter packages directly."""
from __future__ import annotations
import ast
from pathlib import Path
import pytest
from tests.arch.conftest import SRC_ROOT, python_files_in
METRICS_MODULE = SRC_ROOT / "shared" / "metrics.py"
FORBIDDEN_IMPORTS = {
"prometheus_client",
"opentelemetry.exporter.prometheus",
"opentelemetry.exporter.otlp.proto.grpc.metric_exporter",
"opentelemetry.exporter.otlp.proto.http.metric_exporter",
}
def _is_exempt(path: Path) -> bool:
return path == METRICS_MODULE
def _violating_imports(path: Path) -> list[str]:
"""Return forbidden import strings found in a source file."""
source = path.read_text()
try:
tree = ast.parse(source)
except SyntaxError:
return []
violations: list[str] = []
for node in ast.walk(tree):
if isinstance(node, ast.Import):
for alias in node.names:
for forbidden in FORBIDDEN_IMPORTS:
if alias.name == forbidden or alias.name.startswith(forbidden + "."):
violations.append(alias.name)
elif isinstance(node, ast.ImportFrom) and node.module:
for forbidden in FORBIDDEN_IMPORTS:
if node.module == forbidden or node.module.startswith(forbidden + "."):
violations.append(node.module)
return violations
@pytest.mark.arch
def test_no_direct_exporter_imports():
"""No source file outside shared/metrics.py may import exporter packages."""
violations: list[tuple[str, list[str]]] = []
for path in python_files_in(SRC_ROOT):
if _is_exempt(path):
continue
found = _violating_imports(path)
if found:
rel = path.relative_to(SRC_ROOT)
violations.append((str(rel), found))
assert not violations, (
"The following files import metrics exporter packages directly "
"(use shared/metrics.py facade instead):\n"
+ "\n".join(f" {f}: {imports}" for f, imports in violations)
)