import os import sys from pathlib import Path import pytest from dotenv import load_dotenv from sqlalchemy import create_engine from testcontainers.postgres import PostgresContainer # Permetti `pytest` lanciato da qualsiasi directory di trovare il package `tht` # (installato in modalità editable nella venv, ma utile anche senza attivazione). _ROOT = Path(__file__).resolve().parent.parent if str(_ROOT) not in sys.path: sys.path.insert(0, str(_ROOT)) # Directory sessions/ risolta relativamente alla root harness (per i test che creano sessioni) os.environ.setdefault("THT_HARNESS_ROOT", str(_ROOT)) # L2 tests need the remote credentials from harness/.env (gitignored). Loaded once, # autouse, before any test. L0/L1 tests don't read these vars; missing .env only # affects the L2 skip guard below, so L0/L1 never break for missing credentials. load_dotenv(_ROOT / ".env") # L2 connection prerequisites (spec Testing Strategy). If any is missing/empty, L2 # tests are SKIPPED (not failed) so the default run (pytest = L0+L1) stays green. # NOTE: THT_SSL_CA is NOT required -- the DWH endpoint presents a public cert # signed by a public CA (GoDaddy), already in the certifi bundle, so # the clients fall back to verify=True and TLS validates without a CA file. REQUIRED_L2 = ["THT_DWH_API_KEY", "THT_VEC_API_KEY", "THT_VEC_WRITE_API_KEY"] @pytest.fixture(scope="session") def l2_env(): """Skip the test (not fail) when L2 credentials are absent. Use in every L2 test: `def test_x(l2_env): ...`. Returns True so the test body runs once env is confirmed.""" missing = [v for v in REQUIRED_L2 if not os.environ.get(v, "").strip()] if missing: pytest.skip( f"L2 skipped -- missing env vars: {', '.join(missing)} " f"(populate harness/.env and connect via VPN)" ) return True # --- L0 fixtures (testcontainers, real Postgres) -------------------------------- # Session-scoped: un solo container per tutta la run L0. Schema fixture caricato una # volta (crea schema dw + dati + ruolo psd_ro read-only). Salta automaticamente se # Docker non e' disponibile. @pytest.fixture(scope="session") def pg_container(): with PostgresContainer("postgres:16-alpine") as pg: yield pg @pytest.fixture(scope="session") def admin_engine(pg_container): engine = create_engine(pg_container.get_connection_url()) schema_sql = (Path(__file__).parent / "fixtures" / "schema.sql").read_text() with engine.begin() as conn: conn.exec_driver_sql(schema_sql) yield engine engine.dispose() @pytest.fixture(scope="session") def ro_url(pg_container, admin_engine) -> str: host = pg_container.get_container_host_ip() port = pg_container.get_exposed_port(5432) return f"postgresql+psycopg2://psd_ro:psd_ro@{host}:{port}/{pg_container.dbname}"