Finance-Accounts/ar-aging-app/backend/tests/conftest.py

73 lines
2.8 KiB
Python

"""Shared test fixtures. Locates the Jan-2026 sample files (large; integration tests)."""
from __future__ import annotations
import os
import tempfile
from pathlib import Path
import pytest
# ---------------------------------------------------------------------------------------
# Redirect ALL test data to a throwaway directory — BEFORE anything imports app.config,
# which reads these variables once at module load and caches the paths.
#
# Without this the suite runs against the real production database: `app/config.py` falls
# back to `backend/data/ar_aging.db`, so every test that created a closing was writing into
# Finance's live data (75 sessions had accumulated there). Tests must never be able to touch
# a real closing.
#
# The names must match app/config.py exactly — AR_DB_PATH / AR_DATA_DIR. A near-miss such as
# "AR_DB_URL" silently does nothing and the tests quietly hit production again.
# ---------------------------------------------------------------------------------------
_TEST_DATA_DIR = Path(tempfile.mkdtemp(prefix="ar-aging-tests-"))
os.environ["AR_DATA_DIR"] = str(_TEST_DATA_DIR)
os.environ["AR_DB_PATH"] = str(_TEST_DATA_DIR / "test.db")
# Default: the project root two levels above ar-aging-app/backend.
_DEFAULT_SAMPLE_DIR = Path(__file__).resolve().parents[3]
SAMPLE_DIR = Path(os.environ.get("AR_SAMPLE_DIR", str(_DEFAULT_SAMPLE_DIR)))
JAN_FILES = [
"USA Amazon Transactions 01 to 10 January,2026.xlsx",
"USA Amazon Transactions 11 to 20 January,2026.xlsx",
"USA Amazon Transactions 21 to 31 January,2026.xlsx",
]
SAMPLE_WORKBOOK = "Accounts Receivable Aging (Jan-26) 1.xlsx"
@pytest.fixture(scope="session")
def jan_files() -> list[str]:
paths = [str(SAMPLE_DIR / f) for f in JAN_FILES]
missing = [p for p in paths if not os.path.exists(p)]
if missing:
pytest.skip(f"Sample Jan-2026 files not found: {missing}")
return paths
@pytest.fixture(scope="session")
def sample_workbook() -> str:
p = str(SAMPLE_DIR / SAMPLE_WORKBOOK)
if not os.path.exists(p):
pytest.skip(f"Sample workbook not found: {p}")
return p
@pytest.fixture(autouse=True, scope="session")
def _never_touch_production_data():
"""
Hard stop if the redirect above ever fails.
The suite creates and deletes closings, so pointing at the real database would destroy
Finance's data. Assert the isolation actually took effect rather than trusting it.
"""
from app.config import DATA_DIR, DB_PATH
assert str(DB_PATH).startswith(str(_TEST_DATA_DIR)), (
f"tests are pointed at {DB_PATH} — expected a temp path under {_TEST_DATA_DIR}. "
f"app/config.py reads AR_DB_PATH / AR_DATA_DIR; check those names."
)
assert str(DATA_DIR).startswith(str(_TEST_DATA_DIR)), (
f"tests would write uploads/exports to {DATA_DIR}, not a temp directory."
)
yield