53 lines
1.4 KiB
Python
53 lines
1.4 KiB
Python
|
|
"""persistence 适配器层单元测试共享 fixture。
|
|||
|
|
|
|||
|
|
提供:
|
|||
|
|
- ``crypto_with_key``:注入带密钥的 CryptoHelper,使 encrypt/decrypt 真实往返,
|
|||
|
|
测试后自动 reset。
|
|||
|
|
- ``orm_factory``:用 ``SimpleNamespace`` 构造类 ORM 对象,按字段覆盖。
|
|||
|
|
"""
|
|||
|
|
|
|||
|
|
from __future__ import annotations
|
|||
|
|
|
|||
|
|
from types import SimpleNamespace
|
|||
|
|
from typing import Any
|
|||
|
|
|
|||
|
|
import pytest
|
|||
|
|
from cryptography.fernet import Fernet
|
|||
|
|
|
|||
|
|
from yuxi.utils.crypto import CryptoHelper, reset_crypto_helper, set_crypto_helper
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.fixture
|
|||
|
|
def crypto_with_key() -> str:
|
|||
|
|
"""注入带密钥的 CryptoHelper,返回密钥字符串。
|
|||
|
|
|
|||
|
|
使用后自动 reset 为无密钥实例,保证测试隔离。
|
|||
|
|
"""
|
|||
|
|
key = Fernet.generate_key().decode()
|
|||
|
|
set_crypto_helper(CryptoHelper(key=key))
|
|||
|
|
yield key
|
|||
|
|
reset_crypto_helper()
|
|||
|
|
|
|||
|
|
|
|||
|
|
def make_orm(**fields: Any) -> SimpleNamespace:
|
|||
|
|
"""构造类 ORM 对象(SimpleNamespace),按字段覆盖。
|
|||
|
|
|
|||
|
|
mapper 直接读 ORM 属性,SimpleNamespace 足以模拟 ORM 实例,
|
|||
|
|
无需依赖真实 SQLAlchemy 模型。
|
|||
|
|
"""
|
|||
|
|
return SimpleNamespace(**fields)
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.fixture
|
|||
|
|
def orm_factory() -> type[SimpleNamespace]:
|
|||
|
|
"""返回 ORM 工厂,调用时按需传字段。"""
|
|||
|
|
return make_orm
|
|||
|
|
|
|||
|
|
|
|||
|
|
@pytest.fixture
|
|||
|
|
def mock_db() -> Any:
|
|||
|
|
"""返回 AsyncSession mock(仅作为仓储构造参数占位,实际由 repo._repo mock 接管)。"""
|
|||
|
|
from unittest.mock import AsyncMock
|
|||
|
|
|
|||
|
|
return AsyncMock()
|