"""Pipeline code must not type in a value that config/ or common/ already defines
(decision 0005). Otherwise adding a retailer, an event or a year means hunting through
scripts, and the copies drift apart. If a test here fails, import the value instead:
tickers common.contracts.price_tickers(), load_retailers(); common.study.MARKET_TICKER
event ids and dates common.contracts.expand_events(), load_event_types()
Wikipedia titles common.contracts.load_wiki_articles()
FRED series common.contracts.load_retail_series()
years and dates common.study.STUDY_START, STUDY_END, STUDY_START_YEAR, STUDY_END_YEAR
file locations common.settings.clean_path(), RAW_DIR, DATA_DIR, REPLAY_DIR, STREAM_DIR, CHECKPOINT_DIR
Kafka topic and servers common.contracts.KAFKA_TOPICS, common.settings.KAFKA_BOOTSTRAP
Only code is checked: comments, docstrings and argparse help texts may show examples.
A value that only looks like config (pandas' month code 'M', a bootstrap count of 2000)
can be kept by ending its line with `# not-config: <reason>`, which reviewers can see.
The modules that define the values (DEFINING_MODULES) and the tests are not scanned.
"""
from __future__ import annotations
import ast
import re
from pathlib import Path
import pytest
from common.contracts import (
KAFKA_TOPICS,
load_event_types,
load_retail_series,
load_retailers,
load_wiki_articles,
)
from common.study import MARKET_TICKER
ROOT = Path(__file__).resolve().parents[1]
CODE_DIRS = ("etl", "src", "scripts")
DEFINING_MODULES = {"src/common/contracts.py", "src/common/settings.py", "src/common/study.py"}
EXCEPTION_MARKER = re.compile(r"# not-config:\s*\S") # a reason must follow
TICKERS = {r["ticker"] for r in load_retailers()} | {MARKET_TICKER}
EVENT_IDS = {e["event_type"] for e in load_event_types()}
NAMES = {a["article"] for a in load_wiki_articles()} | {s["series_id"] for s in load_retail_series()}
YEAR_IN_TEXT = re.compile(r"\b(19|20)\d{2}(-?\d{2}-?\d{2})?\b")
DATA_PATH = re.compile(r"(^|[/.])(raw|clean|data|config|lookup|checkpoints)/")
DATA_FOLDERS = {"raw", "clean", "lookup", "checkpoints", "config"}
def mentions(text: str, values) -> list[str]:
"""Values that appear in text as whole words, e.g. 'SPY' in "ticker != 'SPY'"."""
return [v for v in values
if re.search(r"(?<![\w.\-])" + re.escape(v) + r"(?![\w\-])", text)]
def ticker_rule(v):
if v in TICKERS or (isinstance(v, str) and mentions(v, {t for t in TICKERS if len(t) > 1})):
return "is a ticker from config/retailers.csv or the market index"
def event_rule(v):
if isinstance(v, str) and mentions(v, EVENT_IDS):
return "names an event from config/event_types.csv"
def name_rule(v):
if isinstance(v, str) and mentions(v, NAMES):
return "names a title or series from config/wiki_articles.csv or config/retail_series.csv"
def year_rule(v):
if isinstance(v, int) and 1990 <= v <= 2099:
return "looks like a year: use common.study"
if isinstance(v, str) and YEAR_IN_TEXT.search(v):
return "contains a year or date: use common.study"
def path_rule(v):
if isinstance(v, str) and (DATA_PATH.search(v) or v in DATA_FOLDERS):
return "is a data path or folder: use common.settings"
def kafka_rule(v):
if isinstance(v, str) and (v in KAFKA_TOPICS.values() or ":9092" in v):
return "is Kafka config: use KAFKA_TOPICS or common.settings.KAFKA_BOOTSTRAP"
RULES = {"tickers": ticker_rule, "events": event_rule, "names": name_rule,
"years": year_rule, "paths": path_rule, "kafka": kafka_rule}
def code_files() -> list[Path]:
files = [p for d in CODE_DIRS for p in (ROOT / d).rglob("*.py")]
return sorted(p for p in files if p.relative_to(ROOT).as_posix() not in DEFINING_MODULES)
def code_literals(path: Path):
"""(line, value) for every str/int literal in the file's code, minus docstrings,
argparse help texts and lines marked `# not-config: <reason>`."""
source = path.read_text(encoding="utf-8")
lines = source.splitlines()
tree = ast.parse(source)
skip = set()
for node in ast.walk(tree):
if isinstance(node, (ast.Module, ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
first = node.body[0] if node.body else None
if isinstance(first, ast.Expr) and isinstance(first.value, ast.Constant):
skip.add(id(first.value))
if isinstance(node, ast.keyword) and node.arg == "help":
skip.update(id(sub) for sub in ast.walk(node.value))
for node in ast.walk(tree):
if not (isinstance(node, ast.Constant) and id(node) not in skip
and isinstance(node.value, (str, int)) and not isinstance(node.value, bool)):
continue
if any(EXCEPTION_MARKER.search(lines[n - 1]) for n in {node.lineno, node.end_lineno or node.lineno}):
continue
yield node.lineno, node.value
def scan(paths, rule_names=RULES) -> list[str]:
problems = []
for path in paths:
for line, value in code_literals(path):
for name in rule_names:
why = RULES[name](value)
if why:
shown = path.relative_to(ROOT) if path.is_relative_to(ROOT) else path.name
problems.append(f"{shown}:{line}: {value!r} {why}")
return problems
def test_the_scan_sees_the_pipeline_code():
names = {p.name for p in code_files()}
assert {"prices_download.py", "join_master.py", "job.py", "replay_master.py"} <= names
@pytest.mark.parametrize("rule", list(RULES))
def test_no_hard_coded_values(rule):
problems = scan(code_files(), [rule])
assert not problems, "\n".join(problems)
@pytest.mark.parametrize("source, expected", [
("TICKERS = ['AMZN', 'WMT']", 2),
("df.filter(\"ticker != 'SPY'\")", 1),
("tickers = 'AMZN WMT'.split()", 1),
("is_black_friday = df['event_type'] == 'black_friday'", 1),
("start = '2016-01-01'", 1),
("url = base + '/daily/20160101/'", 1),
("rows = expand_events(2016, 2025)", 2),
("path = 'clean/prices.parquet'", 1),
("path = REPO_ROOT / 'clean' / 'prices.parquet'", 1),
("bootstrap = 'node1.local:9092'", 1),
('"""Docstring with AMZN, 2016 and clean/prices.parquet is fine."""', 0),
("parser.add_argument('--start', help='e.g. 2024-01-01')", 0),
("x = 1 # a comment about 2016 and AMZN is fine", 0),
("stamp = now.strftime('%H:%M')", 0),
("monthly = s.resample('M').sum() # not-config: pandas month code, not Macy's", 0),
("monthly = s.resample('M').sum() # not-config:", 1),
])
def test_the_scanner_catches_literals_and_skips_docs(tmp_path, source, expected):
sample = tmp_path / "sample.py"
sample.write_text(source + "\n")
assert len(scan([sample])) == expected, scan([sample])