|
| 1 | +import os |
1 | 2 | from contextlib import asynccontextmanager |
2 | 3 |
|
3 | 4 | import pytest |
| 5 | +from _pytest.config import Config |
| 6 | +from _pytest.nodes import Item |
4 | 7 | from fastapi import FastAPI |
5 | 8 | from fastapi.testclient import TestClient |
6 | 9 | from sqlmodel import Session, delete |
|
10 | 13 | from app.resource_adapters.persistence.sqlmodel.issues import Issue |
11 | 14 |
|
12 | 15 |
|
| 16 | +def pytest_configure(config: Config) -> None: |
| 17 | + """Register env marker.""" |
| 18 | + config.addinivalue_line( |
| 19 | + "markers", "env(name): mark test to run only on named environment" |
| 20 | + ) |
| 21 | + |
| 22 | + |
| 23 | +def pytest_runtest_setup(item: Item) -> None: |
| 24 | + """Set up environment for each test based on env marker.""" |
| 25 | + envnames = [mark.args[0] for mark in item.iter_markers(name="env")] |
| 26 | + if envnames: |
| 27 | + # Set environment to the first env marker found |
| 28 | + os.environ["APP_ENV"] = envnames[0] |
| 29 | + else: |
| 30 | + # Default to testing environment if no env marker |
| 31 | + os.environ["APP_ENV"] = "testing" |
| 32 | + |
| 33 | + |
| 34 | +def pytest_unconfigure(config: Config) -> None: |
| 35 | + """Clean up after each test.""" |
| 36 | + # Remove test database if it exists |
| 37 | + if os.path.exists("test.db"): |
| 38 | + os.remove("test.db") |
| 39 | + |
| 40 | + |
13 | 41 | @asynccontextmanager |
14 | 42 | async def test_lifespan(app: FastAPI): |
| 43 | + """Test-specific lifespan that sets up and tears down test resources.""" |
15 | 44 | yield |
| 45 | + # Cleanup will happen in pytest_unconfigure |
16 | 46 |
|
17 | 47 |
|
18 | 48 | # Create test app using the factory with test lifespan |
19 | 49 | app = create_app(lifespan_handler=test_lifespan) |
20 | 50 |
|
21 | 51 |
|
22 | 52 | @pytest.fixture(name="session", autouse=True) |
23 | | -def session_fixture(): |
| 53 | +@pytest.mark.env("testing") |
| 54 | +def test_session(): |
| 55 | + """Session fixture for testing environment using test database.""" |
24 | 56 | with Session(get_engine()) as session: |
25 | 57 | yield session |
26 | 58 | statement = delete(Issue) |
27 | 59 | session.exec(statement) |
28 | 60 | session.commit() |
29 | 61 |
|
30 | 62 |
|
| 63 | +@pytest.fixture(name="session", autouse=True) |
| 64 | +@pytest.mark.env("development") |
| 65 | +def dev_session(): |
| 66 | + """Session fixture for development environment.""" |
| 67 | + with Session(get_engine()) as session: |
| 68 | + yield session |
| 69 | + # In development, we might want to keep the data |
| 70 | + # or handle cleanup differently |
| 71 | + |
| 72 | + |
31 | 73 | @pytest.fixture(name="client") |
32 | 74 | def client_fixture(): |
33 | 75 | with TestClient(app) as client: |
|
0 commit comments