52 lines
2.3 KiB
Python
52 lines
2.3 KiB
Python
"""防止 schema 与 ORM 列不一致导致平台资产创建接口 500。
|
||
|
||
历史故障:PlatformCharacterCreate 继承 CharacterCreate 带来了 gender 字段,
|
||
而 PlatformCharacter 没有该列,`PlatformCharacter(**data.model_dump())`
|
||
直接抛 TypeError,让「新建平台人物」以及 30 个相关测试全部失败。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import pytest
|
||
|
||
from app import schemas
|
||
from app.models import assets as asset_models
|
||
from app.models import platform_assets as platform_models
|
||
|
||
CASES = [
|
||
(schemas.PlatformCharacterCreate, platform_models.PlatformCharacter),
|
||
(schemas.PlatformCharacterUpdate, platform_models.PlatformCharacter),
|
||
(schemas.PlatformSceneCreate, platform_models.PlatformScene),
|
||
(schemas.PlatformSceneUpdate, platform_models.PlatformScene),
|
||
(schemas.PlatformVoiceCreate, platform_models.PlatformVoice),
|
||
(schemas.PlatformVoiceUpdate, platform_models.PlatformVoice),
|
||
(schemas.CharacterCreate, asset_models.Character),
|
||
(schemas.CharacterUpdate, asset_models.Character),
|
||
(schemas.SceneCreate, asset_models.Scene),
|
||
(schemas.SceneUpdate, asset_models.Scene),
|
||
]
|
||
|
||
|
||
def _dumped_keys(schema_cls) -> set[str]:
|
||
"""按 API 真实提交路径取键:创建走全量 dump,更新走 exclude_unset。"""
|
||
return set(schema_cls.model_construct().model_dump(exclude_unset=True).keys())
|
||
|
||
|
||
@pytest.mark.parametrize(("schema_cls", "model_cls"), CASES,
|
||
ids=[f"{s.__name__}->{m.__name__}" for s, m in CASES])
|
||
def test_schema_keys_are_model_columns(schema_cls, model_cls):
|
||
columns = set(model_cls.__table__.columns.keys())
|
||
extra = _dumped_keys(schema_cls) - columns
|
||
assert not extra, f"{schema_cls.__name__} 产出了 {model_cls.__name__} 不存在的字段:{sorted(extra)}"
|
||
|
||
|
||
def test_platform_character_create_has_no_gender():
|
||
"""gender 只属于项目人物与声线,平台人物母版不接收该字段。"""
|
||
row = platform_models.PlatformCharacter(**schemas.PlatformCharacterCreate(name="母版").model_dump())
|
||
assert not hasattr(type(row), "gender")
|
||
assert "gender" not in schemas.PlatformCharacterCreate(name="母版").model_dump()
|
||
|
||
|
||
def test_platform_character_update_ignores_gender_payload():
|
||
patch = schemas.PlatformCharacterUpdate.model_validate({"name": "改名", "gender": "female"})
|
||
assert patch.model_dump(exclude_unset=True) == {"name": "改名"}
|