STAR
Cal STAR — firmware, DAQ server, and engine design
Loading...
Searching...
No Matches
test_code_constants.py
Go to the documentation of this file.
1"""CODE_CONSTANTS is the register behind the Parameters workspace's "In code" section
2(``GET /api/config/parameters`` -> ``backend/routers/config.py`` -> ``ConstantsTable`` in
3``frontend/src/components/ParametersWorkspace.tsx``). Every entry claims a specific file and a
4specific symbol in it; this test is the only thing that checks the claim is still true, since
5nothing else re-reads this module against the source it describes.
6"""
7
8from __future__ import annotations
9
10import re
11from pathlib import Path
12
13import pytest
14
15from engine.pipeline.code_constants import CODE_CONSTANTS
16
17REPO_ROOT = Path(__file__).resolve().parents[1]
18
19_CATEGORIES = {
20 "Propellants",
21 "Injector",
22 "Discharge & Cd",
23 "Combustion efficiency",
24 "Chamber & nozzle",
25 "Thermal protection",
26 "Stability",
27 "Feed & tanks",
28 "Vehicle & flight",
29 "Optimizer",
30}
31
32_REQUIRED_KEYS = {"name", "value", "where", "meaning", "category", "affects_results"}
33
34# Cache file contents across the whole parametrized run instead of re-reading per entry.
35_FILE_CACHE: dict[str, str] = {}
36
37
38def _read(rel_path: str) -> str:
39 if rel_path not in _FILE_CACHE:
40 _FILE_CACHE[rel_path] = (REPO_ROOT / rel_path).read_text(encoding="utf-8", errors="replace")
41 return _FILE_CACHE[rel_path]
42
43
45 assert isinstance(CODE_CONSTANTS, list)
46 # 60-150 per the constants_registry task; this is a sanity band, not a magic number to game.
47 assert 60 <= len(CODE_CONSTANTS) <= 150, (
48 f"CODE_CONSTANTS has {len(CODE_CONSTANTS)} entries; expected 60-150"
49 )
50
51
53 seen = set()
54 dupes = []
55 for c in CODE_CONSTANTS:
56 key = (c.get("name"), c.get("where"))
57 if key in seen:
58 dupes.append(key)
59 seen.add(key)
60 assert not dupes, f"Duplicate (name, where) pairs: {dupes}"
61
62
63@pytest.mark.parametrize("i,entry", list(enumerate(CODE_CONSTANTS)))
64def test_entry_schema(i, entry):
65 """Every entry has exactly the required keys, with the right types and constraints."""
66 missing = _REQUIRED_KEYS - entry.keys()
67 extra = entry.keys() - _REQUIRED_KEYS
68 assert not missing, f"entry {i} ({entry.get('name')!r}) missing keys: {missing}"
69 assert not extra, f"entry {i} ({entry.get('name')!r}) has unexpected keys: {extra}"
70
71 assert isinstance(entry["name"], str) and entry["name"].strip(), f"entry {i}: empty name"
72 assert isinstance(entry["value"], str) and entry["value"].strip(), f"entry {i}: value must be a non-empty string"
73 assert isinstance(entry["meaning"], str) and entry["meaning"].strip(), f"entry {i}: empty meaning"
74 assert len(entry["meaning"]) <= 110, (
75 f"entry {i} ({entry['name']!r}): meaning is {len(entry['meaning'])} chars, must be <= 110"
76 )
77 assert isinstance(entry["affects_results"], bool), (
78 f"entry {i} ({entry['name']!r}): affects_results must be a bool, got {type(entry['affects_results'])}"
79 )
80 assert entry["category"] in _CATEGORIES, (
81 f"entry {i} ({entry['name']!r}): category {entry['category']!r} not in {sorted(_CATEGORIES)}"
82 )
83
84 where = entry["where"]
85 assert isinstance(where, str) and ":" in where, (
86 f"entry {i} ({entry['name']!r}): where must be 'path/file.py:symbol', got {where!r}"
87 )
88 path_part, _, symbol_part = where.partition(":")
89 assert path_part.endswith(".py"), f"entry {i} ({entry['name']!r}): where's path is not a .py file: {path_part!r}"
90 assert not re.fullmatch(r"\d+", symbol_part), (
91 f"entry {i} ({entry['name']!r}): where's symbol looks like a bare line number: {symbol_part!r}"
92 )
93 assert symbol_part.strip(), f"entry {i} ({entry['name']!r}): where has no symbol after ':'"
94
95
96@pytest.mark.parametrize("i,entry", list(enumerate(CODE_CONSTANTS)))
98 path_part = entry["where"].split(":", 1)[0]
99 full = REPO_ROOT / path_part
100 assert full.is_file(), f"entry {i} ({entry['name']!r}): file does not exist: {path_part}"
101
102
103@pytest.mark.parametrize("i,entry", list(enumerate(CODE_CONSTANTS)))
105 """The claimed symbol must actually appear in the claimed file, as a whole identifier.
106
107 ``where`` may name a dotted path like ``ClassName.method_name`` or a bracketed dict access
108 like ``TABLE['key']``; we check the last bare identifier component, since that is the part a
109 reader would actually search for, and it is robust to the class/function/constant living on
110 different lines than any wrapping name.
111 """
112 path_part, symbol_part = entry["where"].split(":", 1)
113 text = _read(path_part)
114
115 # Take the last identifier-like token: strip a trailing [...] subscript, then split on '.'.
116 core = re.sub(r"\‍[.*\‍]$", "", symbol_part.strip())
117 ident = core.split(".")[-1].strip()
118 assert ident, f"entry {i} ({entry['name']!r}): could not extract a symbol from {symbol_part!r}"
119
120 pattern = re.compile(r"\b" + re.escape(ident) + r"\b")
121 assert pattern.search(text), (
122 f"entry {i} ({entry['name']!r}): symbol {ident!r} not found in {path_part}"
123 )
124
125
127 """Every category the frontend can filter by should have at least one entry, or the filter
128 silently shows nothing -- a smell that a whole area of code was never surveyed."""
129 used = {c["category"] for c in CODE_CONSTANTS}
130 missing = _CATEGORIES - used
131 assert not missing, f"No CODE_CONSTANTS entries for categories: {sorted(missing)}"
132
133
135 """A test that cannot fail is not a test (CLAUDE.md). Prove the file/symbol checks above are
136 live by running them against entries engineered to be wrong, using the exact same logic."""
137 bad_file = {
138 "name": "bogus", "value": "1", "where": "engine/pipeline/does_not_exist_at_all.py:X",
139 "meaning": "m", "category": "Optimizer", "affects_results": False,
140 }
141 assert not (REPO_ROOT / bad_file["where"].split(":", 1)[0]).is_file()
142
143 bad_symbol = {
144 "name": "bogus2", "value": "1", "where": "engine/pipeline/code_constants.py:ThisSymbolDoesNotExistXYZ",
145 "meaning": "m", "category": "Optimizer", "affects_results": False,
146 }
147 path_part, symbol_part = bad_symbol["where"].split(":", 1)
148 text = _read(path_part)
149 ident = re.sub(r"\‍[.*\‍]$", "", symbol_part.strip()).split(".")[-1]
150 assert not re.search(r"\b" + re.escape(ident) + r"\b", text)
151
152 bad_meaning = dict(CODE_CONSTANTS[0])
153 bad_meaning["meaning"] = "x" * 111
154 assert len(bad_meaning["meaning"]) > 110
155
156 bad_category = dict(CODE_CONSTANTS[0])
157 bad_category["category"] = "NotARealCategory"
158 assert bad_category["category"] not in _CATEGORIES
static std::vector< string_t > split(const string_t &reference_string)
split the string input to reference tokens
Definition json.hpp:14471
test_module_is_a_nonempty_list_within_the_stated_range()
test_entry_symbol_appears_in_file(i, entry)
str _read(str rel_path)