"""司命台治理种子数据测试。""" from collections.abc import AsyncGenerator import pytest from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession from app.db.governance_seed import _GOALS, ensure_governance_seed from app.db.session import AsyncSessionLocal from app.models.governance import Goal @pytest.fixture async def db_session() -> AsyncGenerator[AsyncSession, None]: async with AsyncSessionLocal() as session: yield session class TestGoalSeedsHaveCharacterId: """_GOALS 每条 seed 都包含 character_id 与 type 字段。""" def test_all_goals_have_character_id_key(self) -> None: for item in _GOALS: assert "character_id" in item, f"{item['id']} 缺少 character_id" def test_all_goals_have_type_key(self) -> None: for item in _GOALS: assert "type" in item, f"{item['id']} 缺少 type" @pytest.mark.asyncio async def test_seed_goals_persist_with_new_fields( db_session: AsyncSession, ) -> None: """验证种子写入数据库后 character_id / type 字段被正确持久化。""" # 先清理已有数据,确保从头写入种子 await db_session.execute(Goal.__table__.delete()) await db_session.commit() await ensure_governance_seed(db_session) result = await db_session.execute(select(Goal)) goals = result.scalars().all() assert len(goals) > 0 for g in goals: assert hasattr(g, "character_id"), f"{g.id} 缺少 character_id 属性" assert hasattr(g, "type"), f"{g.id} 缺少 type 属性" # character_id 在 seed 中全为 None,确保字段可空 assert g.character_id is None # type 应与 seed 定义一致 assert g.type == "mission", f"{g.id} type 应为 mission,实际 {g.type}"