unis_hrms/tests/conftest.py

110 lines
3.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

"""Pytest 夹具:使用独立的 SQLite 测试库(``data/test_hrms-<pid>.db``),
启动时自动建表 + 播种演示数据,不污染开发库。
库名带 PID 是因为同一个工作区里可能同时跑多个 pytest(两个终端 / CI / 编码代理),
共用一个 ``test_hrms.db`` 会互相删表,报 ``table sys_role already exists``
或 ``disk I/O error``,看错误根本联想不到「有人在同时跑测试」。
环境变量必须在 ``app.core.config`` 被导入之前写入 —— Settings 在模块导入时
就会被实例化并缓存。
"""
from __future__ import annotations
import os
import pathlib
import shutil
import sys
import pytest
ROOT = pathlib.Path(__file__).resolve().parents[1]
DATA = ROOT / "data"
TEST_DB = DATA / f"test_hrms-{os.getpid()}.db"
TEST_JOURNAL = TEST_DB.with_name(TEST_DB.name + "-journal")
TEST_UPLOADS = DATA / f"test_uploads-{os.getpid()}"
sys.path.insert(0, str(ROOT))
os.chdir(ROOT)
DATA.mkdir(parents=True, exist_ok=True)
for _name in (TEST_DB, TEST_JOURNAL):
pathlib.Path(_name).unlink(missing_ok=True)
shutil.rmtree(TEST_UPLOADS, ignore_errors=True)
os.environ["DATABASE_URL"] = f"sqlite+aiosqlite:///{TEST_DB}"
os.environ["AUTO_CREATE_SCHEMA"] = "true"
os.environ["AUTO_SEED"] = "true"
os.environ["UPLOAD_DIR"] = str(TEST_UPLOADS)
os.environ["SECRET_KEY"] = "pytest-secret"
from fastapi.testclient import TestClient # noqa: E402
from app.main import app # noqa: E402
ACCOUNTS = {
"admin": "admin123",
"hr": "hr123456",
"payroll": "pay123456",
"recruiter": "rec123456",
"manager": "mgr123456",
"emp": "emp123456",
"emp00001": "emp123456",
}
@pytest.fixture(scope="session", autouse=True)
def _clean_test_files():
"""跑完把自己的测试库/上传目录清掉,data/ 里不会留下一次性垃圾。"""
yield
pathlib.Path(TEST_DB).unlink(missing_ok=True)
pathlib.Path(TEST_JOURNAL).unlink(missing_ok=True)
shutil.rmtree(TEST_UPLOADS, ignore_errors=True)
@pytest.fixture(scope="session")
def client():
"""One app boot for the whole suite (lifespan creates + seeds the schema)."""
with TestClient(app) as test_client:
yield test_client
@pytest.fixture(scope="session")
def login(client):
"""``login("hr")`` -> auth headers for a seeded account."""
def _login(username: str = "admin", password: str | None = None) -> dict[str, str]:
resp = client.post("/api/v1/auth/login",
json={"username": username,
"password": password or ACCOUNTS.get(username, "emp123456")})
assert resp.status_code == 200, resp.text
body = resp.json()
assert body.get("access_token"), body
return {"Authorization": f"Bearer {body['access_token']}"}
return _login
@pytest.fixture(scope="session")
def admin(login) -> dict[str, str]:
return login("admin")
@pytest.fixture(scope="session")
def hr(login) -> dict[str, str]:
return login("hr")
@pytest.fixture(scope="session")
def payroll(login) -> dict[str, str]:
return login("payroll")
@pytest.fixture(scope="session")
def manager(login) -> dict[str, str]:
return login("manager")
@pytest.fixture(scope="session")
def employee(login) -> dict[str, str]:
return login("emp00001")