|
| 1 | +"""Pytest fixtures: a fresh schema + deterministic alert data per test. |
| 2 | +
|
| 3 | +Requires a reachable PostgreSQL. Locally: |
| 4 | + docker run -d --name soc-pg -e POSTGRES_PASSWORD=postgres \ |
| 5 | + -e POSTGRES_DB=soc_test -p 5433:5432 postgres:16 |
| 6 | + export DATABASE_URL=postgresql://postgres:postgres@localhost:5433/soc_test |
| 7 | +CI sets DATABASE_URL to a postgres service container. |
| 8 | +""" |
| 9 | +import os |
| 10 | +import sys |
| 11 | +from pathlib import Path |
| 12 | + |
| 13 | +import pytest |
| 14 | + |
| 15 | +ROOT = Path(__file__).resolve().parents[1] |
| 16 | +sys.path.insert(0, str(ROOT)) |
| 17 | + |
| 18 | +# Must be set before importing app (it reads DATABASE_URL at import time). |
| 19 | +os.environ.setdefault( |
| 20 | + "DATABASE_URL", "postgresql://postgres:postgres@localhost:5433/soc_test" |
| 21 | +) |
| 22 | + |
| 23 | +import psycopg2 # noqa: E402 |
| 24 | + |
| 25 | +SCHEMA = (ROOT / "schema.sql").read_text() |
| 26 | + |
| 27 | +# Deterministic fixtures. SLA targets: CRITICAL 900s, HIGH 3600s, LOW 86400s. |
| 28 | +# alert 1: CRITICAL, triaged in 100s -> within SLA |
| 29 | +# alert 2: CRITICAL, triaged in 2000s -> BREACH |
| 30 | +# alert 3: LOW, open, aged 2 days -> BREACH (overdue) |
| 31 | +# alert 4: HIGH, open, just created -> within SLA |
| 32 | +# => 2 breaches / 4 considered = 50% |
| 33 | +FIXTURES = """ |
| 34 | +INSERT INTO alerts (id, title, category, severity, status, created_at) VALUES |
| 35 | + (1, 'crit fast', 'brute_force', 'CRITICAL', 'true_positive', now() - interval '1 hour'), |
| 36 | + (2, 'crit slow', 'malware', 'CRITICAL', 'true_positive', now() - interval '1 hour'), |
| 37 | + (3, 'low old open', 'anomaly', 'LOW', 'open', now() - interval '2 days'), |
| 38 | + (4, 'high new open', 'phishing', 'HIGH', 'open', now()); |
| 39 | +INSERT INTO analyst_actions (alert_id, analyst_name, action, response_time_seconds) VALUES |
| 40 | + (1, 'alice', 'classify_tp', 100), |
| 41 | + (2, 'bob', 'classify_tp', 2000); |
| 42 | +""" |
| 43 | + |
| 44 | + |
| 45 | +@pytest.fixture() |
| 46 | +def client(): |
| 47 | + import app as soc_app |
| 48 | + |
| 49 | + conn = psycopg2.connect(os.environ["DATABASE_URL"]) |
| 50 | + conn.autocommit = True |
| 51 | + with conn.cursor() as cur: |
| 52 | + cur.execute(SCHEMA) |
| 53 | + cur.execute(FIXTURES) |
| 54 | + conn.close() |
| 55 | + |
| 56 | + soc_app.app.config.update(TESTING=True) |
| 57 | + return soc_app.app.test_client() |
0 commit comments