Production
This commit is contained in:
@@ -0,0 +1,187 @@
|
||||
"""Test fixtures.
|
||||
|
||||
Tests run against a REAL PostgreSQL database, never SQLite. This system depends on
|
||||
constraints that SQLite does not implement the same way — partial unique indexes,
|
||||
composite uniques, jsonb — so testing on SQLite would mean testing a different system
|
||||
from the one that ships.
|
||||
|
||||
Set TEST_DATABASE_URL to point at a scratch database. Docker Compose provides one:
|
||||
postgresql+asyncpg://pharma:pharma@localhost:5432/pharma_test
|
||||
"""
|
||||
|
||||
import os
|
||||
import uuid
|
||||
from collections.abc import AsyncGenerator
|
||||
from datetime import date
|
||||
|
||||
import pytest
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
|
||||
|
||||
os.environ.setdefault("SECRET_KEY", "test-secret-not-for-production")
|
||||
os.environ.setdefault("ENVIRONMENT", "test")
|
||||
|
||||
TEST_DATABASE_URL = os.environ.get(
|
||||
"TEST_DATABASE_URL", "postgresql+asyncpg://pharma:pharma@127.0.0.1:5432/pharma_test"
|
||||
)
|
||||
|
||||
from app.auth.security import hash_password # noqa: E402
|
||||
from app.common.enums import Role # noqa: E402
|
||||
from app.database.all_models import Base # noqa: E402
|
||||
from app.database.session import get_db # noqa: E402
|
||||
from app.main import app as fastapi_app # noqa: E402
|
||||
from app.organization.models import AMHeadquarters, Company, Headquarters # noqa: E402
|
||||
from app.users.models import User # noqa: E402
|
||||
|
||||
TABLES = [
|
||||
"audit_log",
|
||||
"product",
|
||||
"doctor_call",
|
||||
"chemist_call",
|
||||
"daily_call_report",
|
||||
"doctor_assignment",
|
||||
"chemist_assignment",
|
||||
"doctor",
|
||||
"chemist",
|
||||
"am_headquarters",
|
||||
"form_approval",
|
||||
"refresh_token",
|
||||
'"user"',
|
||||
"headquarters",
|
||||
"company",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def anyio_backend() -> str:
|
||||
return "asyncio"
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
async def engine():
|
||||
eng = create_async_engine(TEST_DATABASE_URL, poolclass=None)
|
||||
async with eng.begin() as conn:
|
||||
await conn.run_sync(Base.metadata.create_all)
|
||||
yield eng
|
||||
await eng.dispose()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def session_factory(engine):
|
||||
factory = async_sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
|
||||
async with engine.begin() as conn:
|
||||
await conn.execute(text(f"TRUNCATE {', '.join(TABLES)} RESTART IDENTITY CASCADE"))
|
||||
return factory
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def db(session_factory) -> AsyncGenerator[AsyncSession, None]:
|
||||
async with session_factory() as s:
|
||||
yield s
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def client(session_factory, tmp_path) -> AsyncGenerator[AsyncClient, None]:
|
||||
from app.config.settings import settings
|
||||
|
||||
settings.PDF_STORAGE_PATH = str(tmp_path / "pdf")
|
||||
|
||||
async def _override_get_db() -> AsyncGenerator[AsyncSession, None]:
|
||||
async with session_factory() as s:
|
||||
try:
|
||||
yield s
|
||||
except Exception:
|
||||
await s.rollback()
|
||||
raise
|
||||
|
||||
fastapi_app.dependency_overrides[get_db] = _override_get_db
|
||||
transport = ASGITransport(app=fastapi_app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as ac:
|
||||
yield ac
|
||||
fastapi_app.dependency_overrides.clear()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Organisation fixture: the minimum MVP system — 1 company, 2 HQs, GM, 2 AMs, 2 MRs.
|
||||
# The second HQ/AM/MR exist purely so the negative-scope tests (X1, X2) have someone
|
||||
# to be denied.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
DEFAULT_PASSWORD = "Str0ngPassw0rd!"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def org(db: AsyncSession) -> dict:
|
||||
company = Company(id=uuid.uuid4(), name="Acme Pharma Pvt Ltd")
|
||||
db.add(company)
|
||||
await db.flush()
|
||||
|
||||
hq1 = Headquarters(
|
||||
id=uuid.uuid4(), company_id=company.id, code="BBSR", name="Bhubaneswar",
|
||||
district="Khordha", state="Odisha",
|
||||
)
|
||||
hq2 = Headquarters(
|
||||
id=uuid.uuid4(), company_id=company.id, code="SBP", name="Sambalpur",
|
||||
district="Sambalpur", state="Odisha",
|
||||
)
|
||||
db.add_all([hq1, hq2])
|
||||
await db.flush()
|
||||
|
||||
def make(role: Role, name: str, code: str, hq_id=None) -> User:
|
||||
return User(
|
||||
id=uuid.uuid4(),
|
||||
company_id=company.id,
|
||||
email=f"{code.lower()}@acmepharma.in",
|
||||
password_hash=hash_password(DEFAULT_PASSWORD),
|
||||
full_name=name,
|
||||
employee_code=code,
|
||||
role=role,
|
||||
headquarters_id=hq_id,
|
||||
)
|
||||
|
||||
admin = make(Role.ADMIN, "System Admin", "ADM001")
|
||||
gm = make(Role.GM, "Anita Mohanty", "GM001")
|
||||
am1 = make(Role.AM, "Suresh Behera", "AM001")
|
||||
am2 = make(Role.AM, "Rakesh Sahu", "AM002")
|
||||
mr1 = make(Role.MR, "Ravi Das", "MR001", hq1.id)
|
||||
mr2 = make(Role.MR, "Priya Nayak", "MR002", hq2.id)
|
||||
db.add_all([admin, gm, am1, am2, mr1, mr2])
|
||||
await db.flush()
|
||||
|
||||
db.add_all(
|
||||
[
|
||||
AMHeadquarters(
|
||||
area_manager_user_id=am1.id, headquarters_id=hq1.id,
|
||||
effective_from=date.today(),
|
||||
),
|
||||
AMHeadquarters(
|
||||
area_manager_user_id=am2.id, headquarters_id=hq2.id,
|
||||
effective_from=date.today(),
|
||||
),
|
||||
]
|
||||
)
|
||||
await db.commit()
|
||||
|
||||
return {
|
||||
"company": company, "hq1": hq1, "hq2": hq2,
|
||||
"admin": admin, "gm": gm, "am1": am1, "am2": am2, "mr1": mr1, "mr2": mr2,
|
||||
}
|
||||
|
||||
|
||||
async def login(client: AsyncClient, user: User) -> dict[str, str]:
|
||||
resp = await client.post(
|
||||
"/api/v1/auth/login",
|
||||
json={"email": user.email, "password": DEFAULT_PASSWORD},
|
||||
)
|
||||
assert resp.status_code == 200, resp.text
|
||||
return {"Authorization": f"Bearer {resp.json()['access_token']}"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
async def auth(client: AsyncClient, org: dict) -> dict[str, dict[str, str]]:
|
||||
"""Ready-made Authorization headers for every role."""
|
||||
return {
|
||||
key: await login(client, org[key])
|
||||
for key in ("admin", "gm", "am1", "am2", "mr1", "mr2")
|
||||
}
|
||||
Reference in New Issue
Block a user