File size: 1,894 Bytes
6a0ff33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
"""
Shared test fixtures for the AutoForge test suite.
"""

import os
import pytest
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

# Force test database before importing anything else
os.environ["DATABASE_URL"] = "sqlite:///data/test_autoforge.db"
os.environ["SECRET_KEY"] = "test-secret-key-not-for-production"

from backend.db.database import Base, get_db
from backend.main import app


# ── Test DB Engine ───────────────────────────

TEST_DATABASE_URL = "sqlite:///data/test_autoforge.db"
test_engine = create_engine(TEST_DATABASE_URL, connect_args={"check_same_thread": False})
TestSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=test_engine)


def override_get_db():
    db = TestSessionLocal()
    try:
        yield db
    finally:
        db.close()


app.dependency_overrides[get_db] = override_get_db


# ── Fixtures ─────────────────────────────────

@pytest.fixture(autouse=True)
def setup_database():
    """Create tables before each test, drop after."""
    os.makedirs("data", exist_ok=True)
    Base.metadata.create_all(bind=test_engine)
    yield
    Base.metadata.drop_all(bind=test_engine)


@pytest.fixture
def client():
    """FastAPI test client."""
    return TestClient(app)


@pytest.fixture
def auth_headers(client):
    """Sign up a test user and return Authorization headers."""
    client.post("/api/auth/signup", json={
        "username": "testuser",
        "email": "test@example.com",
        "password": "testpass123",
    })
    resp = client.post("/api/auth/login", json={
        "username": "testuser",
        "password": "testpass123",
    })
    token = resp.json()["access_token"]
    return {"Authorization": f"Bearer {token}"}