98 lines
2.7 KiB
Python
98 lines
2.7 KiB
Python
"""pytest runner for the existing test_*.py scripts.
|
|
|
|
Each file stays one case (`main()`) until it is split into native pytest
|
|
functions. Schema is loaded once per session; each integration file only
|
|
truncates data so kansho_dev is never the target and CI does not reload
|
|
schema.sql twenty times.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
import pytest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
if str(ROOT) not in sys.path:
|
|
sys.path.insert(0, str(ROOT))
|
|
|
|
from tests.harness import ( # noqa: E402
|
|
apply_module_env,
|
|
is_postgres_test_database,
|
|
prepare_test_env,
|
|
reset_postgres_data,
|
|
reset_postgres_schema,
|
|
)
|
|
|
|
UNIT_MODULES = frozenset(
|
|
{
|
|
"test_sql_compat",
|
|
"test_local_backup",
|
|
"test_provenance",
|
|
"test_model_catalog",
|
|
"test_privacy_detect_eval",
|
|
"test_journal_shape",
|
|
"test_journal_body",
|
|
"test_writing_profile",
|
|
}
|
|
)
|
|
|
|
|
|
def pytest_configure(config: pytest.Config) -> None:
|
|
prepare_test_env()
|
|
|
|
|
|
def pytest_collect_file(file_path: Path, parent: pytest.Collector):
|
|
if file_path.suffix == ".py" and file_path.name.startswith("test_"):
|
|
return KanshoScriptModule.from_parent(parent, path=file_path)
|
|
return None
|
|
|
|
|
|
def pytest_collection_modifyitems(config: pytest.Config, items: list[pytest.Item]) -> None:
|
|
for item in items:
|
|
stem = Path(str(item.path)).stem
|
|
marker = pytest.mark.unit if stem in UNIT_MODULES else pytest.mark.integration
|
|
item.add_marker(marker)
|
|
|
|
|
|
class KanshoScriptModule(pytest.Module):
|
|
def collect(self):
|
|
module = self.obj
|
|
main = getattr(module, "main", None)
|
|
if main is None or not callable(main):
|
|
pytest.fail(f"{self.path.name} has no callable main()")
|
|
yield pytest.Function.from_parent(self, name="test_main", callobj=main)
|
|
|
|
|
|
@pytest.fixture(scope="session")
|
|
def _session_postgres():
|
|
if not is_postgres_test_database():
|
|
pytest.skip(
|
|
"integration requires KANSHO_DB_BACKEND=postgres and DB_NAME ending _test "
|
|
"(Gitea: kansho_test on the Dev Postgres, never kansho_dev)"
|
|
)
|
|
reset_postgres_schema()
|
|
from db import init_db
|
|
|
|
init_db()
|
|
yield
|
|
|
|
|
|
@pytest.fixture(scope="module", autouse=True)
|
|
def _module_backend(request: pytest.FixtureRequest):
|
|
source = Path(str(request.path))
|
|
stem = source.stem
|
|
saved = dict(os.environ)
|
|
try:
|
|
apply_module_env(source)
|
|
if stem in UNIT_MODULES:
|
|
yield
|
|
return
|
|
request.getfixturevalue("_session_postgres")
|
|
reset_postgres_data()
|
|
yield
|
|
finally:
|
|
os.environ.clear()
|
|
os.environ.update(saved)
|