feat: tiered test infrastructure with Makefile + smart selector + OpenCode commands

Root Makefile with timeout-protected test targets:
  - Tier 1 (<30s):   make test, make test-unit, make test-frontend
  - Tier 2 (smart):  make test-related F=file.py (via @RELATION BINDS_TO)
  - Tier 3 (<5min):  make test-integration (Docker, --run-integration)
  - Coverage:        make coverage (backend + frontend)
  - Lint:            make lint (ruff + eslint)

Smart test selector (scripts/find-related-tests.py):
  - Extracts module names from #region anchors, class/function defs
  - Searches 400 BINDS_TO entries across all test files
  - Confidence scoring: exact > case-insensitive > substring > heuristic
  - Fallback: filename-based fuzzy matching

OpenCode commands:
  - /test.all      — full suite + coverage
  - /test.unit     — fast unit tests (<30s)
  - /test.related  — smart selection by file
  - /test.coverage — coverage reports with thresholds

Speckit workflow updated:
  - speckit.test.md:   raw pytest → make targets with timeout safety
  - speckit.plan.md:   quickstart uses make targets
  - speckit.tasks.md:  verification uses make targets
  - speckit.implement.md: default stack uses make targets

Frontend: added 'coverage' script to package.json
This commit is contained in:
2026-07-21 18:24:53 +03:00
parent 8bc805d27b
commit d1d2a0f92e
11 changed files with 765 additions and 30 deletions

View File

@@ -40,12 +40,13 @@ You **MUST** consider the user input before proceeding (if not empty).
- Source paths: `backend/src/**/*.py` and `frontend/src/**/*.svelte`.
- Active feature docs always live under `specs/<feature>/...` and are discovered via the `.specify/scripts/bash/*` helpers.
- Default verification stack:
- Backend: `cd backend && source .venv/bin/activate && python -m pytest -v`
- Backend lint: `cd backend && python -m ruff check .`
- Frontend lint: `cd frontend && npm run lint`
- Frontend: `cd frontend && npm run test`
- Frontend build: `cd frontend && npm run build`
- Default verification stack (all timeout-protected via root Makefile):
- `make test-unit` — backend unit tests (SQLite, <120s)
- `make test-frontend` — frontend vitest tests
- `make lint` — ruff + eslint
- `cd frontend && npm run build` — production build check
- `make coverage` — coverage reports (optional, run after tests pass)
- `make test-related F=path/to/changed_file.py` — smart selection for narrow scopes
- Do not fall back to Rust `cargo`/`src/server/` conventions — this is a Python/Svelte project.
## Semantic Execution Rules

View File

@@ -329,12 +329,29 @@ Extend `traceability.md` with a Fixture column:
### Quickstart Output
Generate `quickstart.md` using real repository verification paths:
- Backend: `cd backend && source .venv/bin/activate && python -m pytest -v`
- Frontend: `cd frontend && npm run test`
- Lint: `cd backend && python -m ruff check .`
- Frontend lint: `cd frontend && npm run lint`
- Docker: `docker compose up --build`
Generate `quickstart.md` using real repository verification paths via the root Makefile (timeout-protected, tiered):
```bash
# Tier 1: Fast unit tests (<120s, no Docker)
make test # backend + frontend unit tests
make test-unit # backend SQLite tests only
make test-frontend # frontend vitest tests only
# Tier 2: Smart selection
make test-related F=backend/src/path/to/file.py # only tests linked via @RELATION BINDS_TO
# Tier 3: Integration tests (Docker required, <600s)
make test-integration
# Coverage
make coverage # backend pytest-cov + frontend vitest v8
# Linting
make lint # ruff + eslint
# Docker
docker compose up --build
```
### Traceability Matrix Output

View File

@@ -98,12 +98,13 @@ Each story phase must end with:
- a verification task against `ux_reference.md` interpreted as the operator/caller interaction contract
- a semantic audit / verification task tied to repository validators and touched contracts
Typical verification tasks may include:
- `cd backend && source .venv/bin/activate && python -m pytest backend/tests/test_*.py -v`
- `cd backend && python -m ruff check .`
- `cd frontend && npm run lint`
- `cd frontend && npm run test`
- `cd frontend && npm run build`
Typical verification tasks may include (all timeout-protected via root Makefile):
- `make test-unit` — backend unit tests (SQLite, no Docker, <120s)
- `make test-frontend` — frontend vitest tests
- `make test-related F=path/to/changed_file.py` — smart selection via @RELATION BINDS_TO
- `make lint` — ruff + eslint
- `make coverage` — backend + frontend coverage reports
- `cd frontend && npm run build` — production build check
Only include the commands that are truly required by the feature scope.

View File

@@ -21,9 +21,15 @@ Run the full verification loop for the touched superset-tools scope:
1. **Mocking discipline audit** — scan every test file in scope, classify every mock/spy/stub/patch, flag violations
2. **Auto-fix violations** — correct SUT mocks and Logic Mirrors (no flag needed; fix by default)
3. **Semantic audit** — contract density, belief runtime, rejected-path regression
4. **Executable tests** — run pytest + vitest + lint
4. **Executable tests** — run pytest + vitest + lint via `make test` (tiered, timeout-protected)
5. **Documentation** — mock audit report + coverage summary + ADR guardrail status
**When to use `/speckit.test` vs `/test.*`:** Use this command for COMPREHENSIVE audit (mocking + semantic + execution) on a feature batch. For quick verify loops during development (just run tests, no audit), use the lightweight alternatives:
- `/test.unit` — fast unit tests (backend + frontend, <30s)
- `/test.related` — only tests linked to a changed file via `@RELATION BINDS_TO`
- `/test.coverage` — coverage reports only
- `/test.all` — full suite + coverage
## Operating Constraints
### Golden Rules (from `semantics-testing` skill)
@@ -221,20 +227,35 @@ For UI features, use browser validation via `chrome-devtools` MCP.
### 8. Execute Verifiers
Run the full verification stack for the touched scope:
Run the full verification stack for the touched scope. The project Makefile provides tiered targets with built-in timeout protection:
```bash
# Backend
cd backend && source .venv/bin/activate && python -m pytest -v
python -m ruff check backend/src/ backend/tests/
# Tier 1: Fast unit tests (no Docker, <120s timeout)
make test-unit # backend SQLite tests
make test-frontend # frontend vitest tests
# Frontend
cd frontend && npm run test
npm run lint
npm run build
# Tier 1 alt: Smart test selection (only tests related to changed files)
make test-related F=backend/src/path/to/changed_file.py
# Linting (ruff + eslint)
make lint
# Coverage (optional — run after tests pass)
make coverage
# Tier 2: Integration tests (requires Docker, <600s timeout)
# Only when the scope includes integration boundaries
make test-integration
# Full suite (unit + integration + coverage)
make test-all
```
Use narrower test runs when sufficient, then widen verification when finalizing.
**Timeout safety**: All `make test-*` targets are wrapped with `timeout N` shell guards. Unit tests have 120s; integration tests have 600s. The agent NEVER hangs on a hung test.
**Narrow-first principle**: Start with `make test-unit` for backend changes, `make test-frontend` for frontend changes. Use `make test-related F=<file>` to run only semantically-linked tests. Widen to `make test` (both layers) when finalizing.
**When to run integration tests**: Only when the scope includes files under `backend/tests/integration/` or when the change touches Docker/testcontainers fixtures. Otherwise, skip.
### 9. Test Documentation
@@ -326,9 +347,9 @@ Produce a single Markdown test report containing all of the following sections:
```
### 2. Coverage Summary
- Commands executed
- Commands executed: `make coverage` (backend pytest-cov + frontend vitest v8)
- Pass/fail counts per layer
- Coverage percentage (if available)
- Coverage percentage: backend statement/line %, frontend statement/line/function/branch % with threshold comparison
### 3. Semantic Audit Verdict
- Contract density check results

View File

@@ -0,0 +1,107 @@
---
description: "Run full test suite: backend unit tests, frontend vitest, coverage reports. Use as final verification gate."
handoffs:
- label: "Fix Test Failures"
agent: "fullstack-coder"
prompt: "Fix the following test failures from the full test suite run. Review the error output and implement fixes."
condition: "Tests failed"
- label: "Coverage Deep Dive"
agent: "qa-tester"
prompt: "Review the coverage report. Identify uncovered critical paths and propose additional tests."
condition: "Coverage thresholds not met"
tools: "bash, grep, read"
---
## User Input
$ARGUMENTS
## Goal
Run the COMPLETE test suite across both backend and frontend, producing a unified pass/fail + coverage report. This is the **final verification gate** before code review or merge.
## Required Skills
MANDATORY USE `skill({name="semantics-testing"})` — test conventions, anti-tautology rules, tier markers.
MANDATORY USE `skill({name="molecular-cot-logging"})` — structured logging during execution.
## Execution Steps
### 1. Pre-flight checks
```bash
# Verify venv exists
ls backend/.venv/bin/activate || echo "MISSING VENV"
# Verify node_modules exists
ls frontend/node_modules/.package-lock.json || echo "MISSING NODE_MODULES"
```
If either is missing, report the issue and STOP — do not attempt to install.
### 2. Run backend unit tests (Tier 1 — fast)
```bash
make test-unit
```
Expected: <120s. If tests fail, collect the failure output and handoff to Fix Test Failures.
### 3. Run backend integration tests (Tier 2 — Docker required)
Only if `--run-integration` is passed in $ARGUMENTS:
```bash
make test-integration
```
Expected: <600s. If Docker is not running or tests time out, report which integration tests passed/failed and continue with partial results.
### 4. Run frontend vitest tests (Tier 1 — fast)
```bash
make test-frontend
```
If tests fail, collect the failure output.
### 5. Run E2E tests (optional — requires running app)
Only if `--e2e` is passed in $ARGUMENTS:
```bash
make test-e2e
```
### 6. Generate coverage reports
```bash
make coverage
```
Review coverage percentages:
- Backend: check `backend/htmlcov/index.html` or term report
- Frontend: check `frontend/coverage/index.html`
### 7. Linting gate
```bash
make lint
```
## Output Format
```
## Full Test Suite Results
### Backend Unit Tests
- Total: N | Passed: N | Failed: N | Skipped: N
- Time: X.Xs
- [PASS/FAIL]
### Backend Integration Tests (if run)
- Total: N | Passed: N | Failed: N | Skipped: N
- Time: X.Xs
### Frontend Tests
- Total: N | Passed: N | Failed: N
- Time: X.Xs
### Coverage
- Backend: XX% (threshold: N/A)
- Frontend: XX% (threshold: 98% stmts, 95% funcs, 80% branches)
### Linting
- Backend (ruff): [PASS/FAIL]
- Frontend (eslint): [PASS/FAIL]
### Overall: [ALL_PASS / FAILURES_DETECTED]
```
## Constraints
- NEVER run `pip install` or `npm install` — report missing deps and stop.
- If a test tier times out, report partial results rather than nothing.
- For integration tests: if Docker is not available, skip gracefully and note "Docker not available".
- Respect the anti-loop protocol: at attempt 3, re-check environment; at attempt 4, escalate.

View File

@@ -0,0 +1,82 @@
---
description: "Generate coverage reports for both backend and frontend, and verify against thresholds."
handoffs:
- label: "Improve Coverage"
agent: "qa-tester"
prompt: "Coverage is below threshold. Identify uncovered critical paths and propose additional tests. Current uncovered areas: $ARGUMENTS"
condition: "Coverage below threshold"
tools: "bash, read, grep"
---
## User Input
$ARGUMENTS
## Goal
Generate test coverage reports for backend (pytest-cov) and frontend (vitest v8), and verify that coverage meets project thresholds.
## Required Skills
MANDATORY USE `skill({name="semantics-testing"})` — coverage conventions.
## Execution Steps
### 1. Generate coverage reports
```bash
make coverage
```
### 2. Review backend coverage
```bash
# Detailed terminal output with uncovered lines
cd backend && source .venv/bin/activate && python -m pytest tests/ --ignore=tests/integration/ --cov=src --cov-report=term-missing 2>&1 | tail -50
```
Key metrics to extract:
- Overall statement coverage (%)
- Files with <80% coverage (list top 5 offenders)
- Files with 0% coverage (untested)
### 3. Review frontend coverage
```bash
# Frontend coverage (also available via make coverage-frontend)
cd frontend && npx vitest run --coverage 2>&1 | tail -50
```
Frontend thresholds in vitest.config.js:
- Statements: 98%
- Lines: 98%
- Functions: 95%
- Branches: 80%
### 4. Check against thresholds
If any threshold is not met, identify the specific files/modules dragging coverage down.
### 5. (Optional) Open HTML reports
```bash
ls backend/htmlcov/index.html && echo "Backend report: backend/htmlcov/index.html"
ls frontend/coverage/index.html && echo "Frontend report: frontend/coverage/index.html"
```
## Output Format
```
## Coverage Report
### Backend (pytest-cov)
- Statement Coverage: XX%
- Files below 80%: N (list top 3-5)
- Untested files: N (list top 3-5)
### Frontend (vitest v8)
- Statement Coverage: XX% (threshold: 98%) [PASS/FAIL]
- Line Coverage: XX% (threshold: 98%) [PASS/FAIL]
- Function Coverage: XX% (threshold: 95%) [PASS/FAIL]
- Branch Coverage: XX% (threshold: 80%) [PASS/FAIL]
### HTML Reports
- Backend: backend/htmlcov/index.html
- Frontend: frontend/coverage/index.html
### Overall: [ALL_THRESHOLDS_MET / BELOW_THRESHOLD]
```
## Constraints
- Coverage is generated from unit tests ONLY (no Docker integration tests).
- If vitest coverage fails with "threshold not met", report which files are below threshold.
- Do NOT modify source code to artificially increase coverage.

View File

@@ -0,0 +1,82 @@
---
description: "Find and run tests related to a specific source file using @RELATION BINDS_TO annotations."
handoffs:
- label: "Fix Related Test Failures"
agent: "fullstack-coder"
prompt: "Fix the test failures in the related tests. The source file that triggered them is: $ARGUMENTS"
condition: "Tests failed"
- label: "Add Missing Test Relations"
agent: "semantic-curator"
prompt: "Add @RELATION BINDS_TO annotations to connect the source file to its test files. The test selector found no matches for: $ARGUMENTS"
condition: "No related tests found"
tools: "bash, grep, axiom_search, read"
---
## User Input
$ARGUMENTS
## Goal
Given a source file path, find and run ONLY the tests that are semantically related to that file. This uses the `@RELATION BINDS_TO -> [ModuleName]` annotations in test files to trace dependencies.
This is the **most efficient verification** — avoid running the full suite when only one module changed.
## Required Skills
MANDATORY USE `skill({name="semantics-testing"})` — BINDS_TO conventions, test contracts.
MANDATORY USE `skill({name="semantics-contracts"})` — relation syntax, verifiable edit loop.
## Execution Steps
### 1. Identify the source file
$ARGUMENTS should be a path to a source file (e.g., `backend/src/plugins/migration.py`). If the user provides a directory, pick the most recently modified file or ask for clarification.
### 2. Run the smart test selector
```bash
make test-related F="$ARGUMENTS"
```
Or directly:
```bash
python3 scripts/find-related-tests.py --file "$ARGUMENTS" --verbose --run
```
This script:
- Extracts module/class names from the source file (#region anchors, class/function defs)
- Searches all test files for `@RELATION BINDS_TO -> [ModuleName]` annotations
- Returns matching test files with confidence scores (exact > case-insensitive > substring > heuristic)
### 3. Interpret results
**If tests are found and pass:** ✅ Report success.
**If tests are found and fail:** Read the failing test code, identify root cause, handoff to Fix Related Test Failures.
**If no related tests found:** Two possibilities:
1. The source file genuinely has no tests — report as coverage gap.
2. The `@RELATION BINDS_TO` annotation is missing from the test file — handoff to semantic-curator for annotation.
### 4. (Optional) Verify with axiom
If the smart selector found 0 results, try axiom's semantic search as a fallback:
```
axiom_search operation="trace_related_tests" contract_id="<module_contract_id>"
```
## Output Format
```
## Related Test Results for `$ARGUMENTS`
### Matched Tests
- [exact] backend/tests/plugins/test_migration_plugin.py (via 'MigrationPlugin')
- [substr] backend/tests/api/test_migration.py (via 'MigrationApi')
### Results
- Total: N | Passed: N | Failed: N
- Time: X.Xs
### Coverage Gap (if no tests found)
- Source file has no linked tests.
- Recommended: create test file with @RELATION BINDS_TO -> [ModuleName]
```
## Constraints
- NEVER run the full test suite as a fallback — only matched tests.
- If the selector finds 20+ related tests, report the count and ask if user wants to run all or narrow scope.
- Heuristic matches (score=0) should be clearly flagged as low-confidence.

View File

@@ -0,0 +1,66 @@
---
description: "Run fast unit tests only (backend SQLite + frontend vitest). Designed for agent verify loop — runs in <30s."
handoffs:
- label: "Fix Test Failures"
agent: "fullstack-coder"
prompt: "Fix the following test failures from the unit test run. Review the error output and implement fixes."
condition: "Tests failed"
tools: "bash, grep, read"
---
## User Input
$ARGUMENTS
## Goal
Run ONLY fast unit tests on both backend and frontend. This is the **default verification step** during development — should complete in <30s with no Docker dependency.
## Required Skills
MANDATORY USE `skill({name="semantics-testing"})` — test conventions, anti-tautology rules.
## Execution Steps
### 1. Run backend unit tests
```bash
make test-unit
```
This excludes `tests/integration/` and uses SQLite in-memory/temp-file databases. No Docker required.
If tests fail:
- Read the failing test file to understand the contract
- Check if the failure is in code you just changed
- Handoff to Fix Test Failures if needed
### 2. Run frontend unit tests
```bash
make test-frontend
```
This runs vitest with jsdom environment. All SvelteKit imports are mocked.
### 3. Linting (quick gate)
```bash
make lint
```
## Output Format
```
## Unit Test Results
### Backend (pytest)
- Total: N | Passed: N | Failed: N | Skipped: N
- Time: X.Xs
### Frontend (vitest)
- Total: N | Passed: N | Failed: N
### Linting
- Backend: [PASS/FAIL]
- Frontend: [PASS/FAIL]
### Overall: [PASS / FAIL]
```
## Constraints
- NEVER run `pip install` or `npm install`.
- This target MUST complete in <120s (enforced by timeout wrapper).
- If tests time out, report which files passed and which timed out.
- For agent-driven fix loops: run `make test-unit` after every backend change, `make test-frontend` after every frontend change.

87
Makefile Normal file
View File

@@ -0,0 +1,87 @@
# ss-tools test suite
# ─────────────────────────────────────────────────────────────
# Tiered test targets designed for agent-driven development:
# Tier 1 (fast, <30s): make test
# Tier 2 (slow, <5min): make test-integration
# Tier 3 (e2e, <10min): make test-e2e
#
# Smart selection: make test-related F=path/to/file.py
# Coverage: make coverage
# ─────────────────────────────────────────────────────────────
ROOT := $(CURDIR)
BACKEND := $(ROOT)/backend
FRONTEND := $(ROOT)/frontend
VENV := $(BACKEND)/.venv/bin/activate
TIMEOUT_FAST := 120
TIMEOUT_SLOW := 600
.PHONY: help test test-unit test-frontend test-related test-integration test-e2e test-all
.PHONY: coverage coverage-backend coverage-frontend
.PHONY: lint lint-backend lint-frontend
# ── Help ───────────────────────────────────────────────────
help: ## Show this help message
@grep -E '^[a-zA-Z_-]+:.*?## .*$$' $(MAKEFILE_LIST) | sort | \
awk 'BEGIN {FS = ":.*?## "}; {printf "\033[36m%-22s\033[0m %s\n", $$1, $$2}'
# ── Tier 1: Fast tests (no Docker, SQLite + jsdom) ─────────
test: test-unit test-frontend ## Run fast unit tests (backend + frontend, <30s)
@echo " ✅ All fast tests passed"
test-unit: ## Run backend unit tests (SQLite, no Docker)
@echo " ▶ Backend unit tests (SQLite)..."
@cd $(BACKEND) && . $(VENV) && timeout $(TIMEOUT_FAST) python -m pytest tests/ --ignore=tests/integration/ -v --tb=short
test-frontend: ## Run frontend vitest tests
@echo " ▶ Frontend vitest tests..."
@cd $(FRONTEND) && npx vitest run
# ── Tier 2: Smart selection ────────────────────────────────
test-related: ## Run tests related to a changed file (make test-related F=path/to/file.py)
@if [ -z "$(F)" ]; then echo "Usage: make test-related F=path/to/file.py"; exit 1; fi
@echo " ▶ Finding related tests for $(F)..."
@python3 $(ROOT)/scripts/find-related-tests.py --file "$(F)" --run
# ── Tier 3: Slow tests (requires Docker) ───────────────────
test-integration: ## Run backend integration tests (Docker + testcontainers)
@echo " ▶ Backend integration tests (Docker)..."
@cd $(BACKEND) && . $(VENV) && timeout $(TIMEOUT_SLOW) python -m pytest tests/integration/ --run-integration -v --tb=short
test-e2e: ## Run Playwright E2E tests (requires running app)
@echo " ▶ Playwright E2E tests..."
@cd $(FRONTEND) && npx playwright test
# ── Full suite ─────────────────────────────────────────────
test-all: ## Run full suite: fast tests + integration (skip installs)
@$(MAKE) test
@echo ""
@echo " ▶ Integration tests (may take several minutes)..."
@cd $(BACKEND) && . $(VENV) && timeout $(TIMEOUT_SLOW) python -m pytest tests/integration/ --run-integration -v --tb=short || echo " ⚠ Integration tests skipped (Docker not available or timed out)"
@echo ""
@echo " ✅ Full test suite complete"
# ── Coverage ───────────────────────────────────────────────
coverage: coverage-backend coverage-frontend ## Generate coverage (backend + frontend)
@echo " ✅ Coverage reports ready"
@echo " Backend: $(BACKEND)/htmlcov/index.html"
@echo " Frontend: $(FRONTEND)/coverage/index.html"
coverage-backend: ## Backend coverage (unit tests + --cov)
@echo " ▶ Backend coverage..."
@cd $(BACKEND) && . $(VENV) && timeout $(TIMEOUT_FAST) python -m pytest tests/ --ignore=tests/integration/ \
--cov=src --cov-report=term-missing --cov-report=html
coverage-frontend: ## Frontend coverage (vitest --coverage)
@echo " ▶ Frontend coverage..."
@cd $(FRONTEND) && npx vitest run --coverage
# ── Linting ────────────────────────────────────────────────
lint: lint-backend lint-frontend ## Run all linters
lint-backend: ## Backend ruff check
@cd $(BACKEND) && . $(VENV) && python -m ruff check .
lint-frontend: ## Frontend eslint
@cd $(FRONTEND) && npx eslint .

View File

@@ -12,6 +12,7 @@
"test:e2e": "playwright test",
"test:e2e:ui": "playwright test --ui",
"test:e2e:debug": "playwright test --debug",
"coverage": "vitest run --coverage",
"lint": "eslint .",
"lint:fix": "eslint . --fix"
},

270
scripts/find-related-tests.py Executable file
View File

@@ -0,0 +1,270 @@
#!/usr/bin/env python3
"""
Smart test selector — finds tests related to a source file.
Algorithm:
1. Extract module/class names from the source file
(from #region anchors, class/function definitions, filename)
2. Search all test files for @RELATION BINDS_TO -> [ModuleName] annotations
3. Return matching test files with confidence scores
4. Optionally run pytest on matched tests
Usage:
python3 scripts/find-related-tests.py --file backend/src/plugins/migration.py
python3 scripts/find-related-tests.py --file path/to/file.py --run
python3 scripts/find-related-tests.py --file path/to/file.py --verbose
"""
from __future__ import annotations
import argparse
import os
import re
import subprocess
import sys
from pathlib import Path
WORKSPACE = Path(__file__).resolve().parent.parent
# ── Regex patterns ─────────────────────────────────────────
REGION_RE = re.compile(r'#region\s+([\w.]+)')
CLASS_RE = re.compile(r'^class\s+(\w+)', re.MULTILINE)
DEF_RE = re.compile(r'^def\s+(\w+)', re.MULTILINE)
BINDSTO_RE = re.compile(r'@RELATION\s+BINDS_TO\s*->\s*\[([^\]]+)\]')
# Frontend: test files may contain @TEST_CONTRACT / @RELATION
FRONTEND_BINDSTO_RE = re.compile(r'@(?:RELATION\s+BINDS_TO|TEST_CONTRACT|TEST_INVARIANT)[^\n]*')
# ── Helpers ────────────────────────────────────────────────
def extract_names(filepath: Path) -> set[str]:
"""Extract candidate module names from a source file."""
names: set[str] = set()
try:
content = filepath.read_text(encoding='utf-8')
except Exception:
return names
# #region anchors
for m in REGION_RE.finditer(content):
names.add(m.group(1))
# class names (PascalCase)
for m in CLASS_RE.finditer(content):
name = m.group(1)
if name[0].isupper():
names.add(name)
# function names (snake_case)
for m in DEF_RE.finditer(content):
names.add(m.group(1))
# filename stem (strip test_ prefix for test files, otherwise use as-is)
stem = filepath.stem
if stem.startswith('test_'):
stem = stem[5:]
# camelCase or snake_case variants
names.add(stem)
# PascalCase variant
pascal = ''.join(w.capitalize() for w in stem.replace('-', '_').split('_'))
names.add(pascal)
names.add(pascal + 'Module')
names.add(pascal + 'Router')
names.add(pascal + 'Api')
names.add(pascal + 'Routes')
return {n for n in names if len(n) > 1}
def build_index(test_dirs: list[Path]) -> dict[str, list[Path]]:
"""Build reverse index: module_name -> [test_file_paths].
Scans all test_*.py files in the given directories.
"""
index: dict[str, list[Path]] = {}
for test_dir in test_dirs:
if not test_dir.exists():
continue
for test_file in test_dir.rglob('test_*.py'):
try:
content = test_file.read_text(encoding='utf-8')
except Exception:
continue
for m in BINDSTO_RE.finditer(content):
targets = [t.strip() for t in m.group(1).split(',')]
for target in targets:
if target:
index.setdefault(target, []).append(test_file)
return index
def match(source_names: set[str], index: dict[str, list[Path]]) -> list[tuple[Path, str, int]]:
"""Find matching test files with confidence scores.
Returns list of (test_path, matched_name, score) sorted by score desc.
Score: 3 = exact match, 2 = case-insensitive exact, 1 = substring match.
"""
results: list[tuple[Path, str, int]] = []
seen: set[str] = set()
for source_name in source_names:
source_lower = source_name.lower()
for idx_key, test_files in index.items():
idx_lower = idx_key.lower()
score = 0
if idx_key == source_name:
score = 3 # exact
elif idx_lower == source_lower:
score = 2 # case-insensitive
elif idx_lower in source_lower or source_lower in idx_lower:
score = 1 # substring
if score > 0:
for tf in test_files:
key = str(tf)
if key not in seen:
seen.add(key)
results.append((tf, idx_key, score))
# Deduplicate: keep highest score per file
best: dict[str, tuple[Path, str, int]] = {}
for tf, key, score in results:
tf_str = str(tf)
if tf_str not in best or score > best[tf_str][2]:
best[tf_str] = (tf, key, score)
return sorted(best.values(), key=lambda x: (-x[2], str(x[0])))
# ── Main ───────────────────────────────────────────────────
def main() -> None:
parser = argparse.ArgumentParser(
description='Find tests related to a source file via @RELATION BINDS_TO'
)
parser.add_argument('--file', '-f', required=True, help='Source file path')
parser.add_argument('--run', action='store_true', help='Run found tests with pytest')
parser.add_argument('--verbose', '-v', action='store_true', help='Verbose output')
args = parser.parse_args()
source_file = Path(args.file).resolve()
if not source_file.exists():
print(f"Error: file not found: {args.file}", file=sys.stderr)
sys.exit(1)
# ── Determine which directories to scan ────────────────
try:
rel = source_file.relative_to(WORKSPACE)
rel_str = str(rel)
except ValueError:
rel = source_file
rel_str = str(source_file)
test_dirs: list[Path] = []
if 'backend' in rel_str:
test_dirs = [
WORKSPACE / 'backend' / 'tests',
# Co-located __tests__ directories
WORKSPACE / 'backend' / 'src',
]
elif 'frontend' in rel_str:
test_dirs = [
WORKSPACE / 'frontend' / 'src',
]
elif 'agent' in rel_str:
test_dirs = [
WORKSPACE / 'agent' / 'tests',
]
else:
# Default: scan everything
test_dirs = [
WORKSPACE / 'backend' / 'tests',
WORKSPACE / 'backend' / 'src',
WORKSPACE / 'agent' / 'tests',
]
# ── Build index and match ──────────────────────────────
source_names = extract_names(source_file)
if args.verbose:
print(f"[find-related-tests] Source: {source_file}")
print(f"[find-related-tests] Extracted names ({len(source_names)}):")
for n in sorted(source_names):
print(f" - {n}")
index = build_index(test_dirs)
if args.verbose:
print(f"[find-related-tests] BINDS_TO index: {len(index)} entries")
sample = dict(sorted(index.items())[:5])
for k, v in sample.items():
print(f" {k}: {len(v)} test(s)")
matches = match(source_names, index)
# ── Fallback: filename-based heuristic ─────────────────
if not matches:
stem_lower = source_file.stem.lower()
if stem_lower.startswith('test_'):
stem_lower = stem_lower[5:]
for test_dir in test_dirs:
if not test_dir.exists():
continue
for test_file in test_dir.rglob(f'*{stem_lower}*test*.py'):
matches.append((test_file, 'heuristic', 0))
for test_file in test_dir.rglob(f'test_*{stem_lower}*.py'):
matches.append((test_file, 'heuristic', 0))
for test_file in test_dir.rglob(f'__tests__/{stem_lower}*.py'):
matches.append((test_file, 'heuristic', 0))
# Deduplicate heuristic results
seen_heuristic: set[str] = set()
unique_matches: list[tuple[Path, str, int]] = []
for tf, key, score in matches:
tf_str = str(tf)
if tf_str not in seen_heuristic:
seen_heuristic.add(tf_str)
unique_matches.append((tf, key, score))
matches = unique_matches
# ── Output ─────────────────────────────────────────────
if not matches:
print(f"No related tests found for {args.file}", file=sys.stderr)
sys.exit(2)
print(f"Found {len(matches)} related test file(s):")
for tf, key, score in matches:
score_label = {3: 'exact', 2: 'case', 1: 'substr', 0: 'heur'}.get(score, '?')
try:
rel_path = tf.relative_to(WORKSPACE)
except ValueError:
rel_path = tf
print(f" [{score_label}] {rel_path} (via '{key}')")
# ── Run tests (optional) ───────────────────────────────
if args.run:
test_paths = [str(tf.relative_to(WORKSPACE / 'backend') if 'backend' in str(tf) else tf) for tf, _, _ in matches]
# Run from backend dir for consistency
backend_dir = WORKSPACE / 'backend'
cmd = [
'timeout', '120',
'python', '-m', 'pytest', '-v', '--tb=short',
] + test_paths
print(f"\nRunning: {' '.join(cmd)}")
env = os.environ.copy()
env.setdefault('DATABASE_URL', 'sqlite:///tmp/ss_tools_test.db')
result = subprocess.run(
cmd,
cwd=backend_dir,
env=env,
)
sys.exit(result.returncode)
if __name__ == '__main__':
main()