> ## Documentation Index
> Fetch the complete documentation index at: https://calendar-effects.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# tests/test_no_hardcoding.py

> 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:

`tests/test_no_hardcoding.py` · chapter [Tests and team tooling](https://calendar-effects.mintlify.site/tour/10-tests-and-tooling.md), file 6 · 163 lines · [open in the repository](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py)

## What it does

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.

## What is inside

* **`ROOT`** · [line 35](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L35)
* **`CODE_DIRS`** · [line 36](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L36)
* **`DEFINING_MODULES`** · [line 37](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L37)
* **`EXCEPTION_MARKER`** · [line 38](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L38): not-config:\s\*\S")  # a reason must follow
* **`TICKERS`** · [line 40](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L40)
* **`EVENT_IDS`** · [line 41](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L41)
* **`NAMES`** · [line 42](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L42)
* **`YEAR_IN_TEXT`** · [line 44](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L44)
* **`DATA_PATH`** · [line 45](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L45)
* **`DATA_FOLDERS`** · [line 46](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L46)
* **`mentions(text, values)`** · [line 49](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L49): Values that appear in text as whole words, e.g. 'SPY' in "ticker != 'SPY'".
* **`ticker_rule(v)`** · [line 55](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L55)
* **`event_rule(v)`** · [line 60](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L60)
* **`name_rule(v)`** · [line 65](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L65)
* **`year_rule(v)`** · [line 70](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L70)
* **`path_rule(v)`** · [line 77](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L77)
* **`kafka_rule(v)`** · [line 82](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L82)
* **`RULES`** · [line 87](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L87)
* **`code_files()`** · [line 91](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L91)
* **`code_literals(path)`** · [line 96](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L96): (line, value) for every str/int literal in the file's code, minus docstrings, argparse help texts and lines marked `# not-config: &lt;reason>`.
* **`scan(paths, rule_names)`** · [line 119](https://github.sfu.ca/aba395/Calendar-Effects/blob/main/tests/test_no_hardcoding.py#L119)

## What it checks

* the scan sees the pipeline code (line 131)
* no hard coded values (line 137)
* the scanner catches literals and skips docs (line 160)

## Connections

**Uses:** [`src/common/contracts.py`](https://calendar-effects.mintlify.site/reference/src/common/contracts), [`src/common/study.py`](https://calendar-effects.mintlify.site/reference/src/common/study)

## Source

```python title="tests/test_no_hardcoding.py" lines expandable theme={null}
"""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])
```


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.