小编Mat*_*ham的帖子

无法在使用 Fixtures 的 Pytest 函数内实例化 Python 数据类(冻结)

我正在关注 Harry Percival 和 Bob Gregory 的《Python 中的架构模式》。

围绕第三(3)章介绍了SQLAlchemy的ORM测试。

一个需要session夹具的新测试,AttributeError, FrozenInstanceError由于cannot assign to field '_sa_instance_state'

需要注意的是,在创建 的实例时,其他测试不会失败OrderLine,但如果我只是将它们包含session到测试参数中,它们就会失败。

无论如何,我会直接进入代码。

conftest.py

@pytest.fixture
def local_db():
    engine = create_engine('sqlite:///:memory:')
    metadata.create_all(engine)
    return engine


@pytest.fixture
def session(local_db):
    start_mappers()
    yield sessionmaker(bind=local_db)()
    clear_mappers()
Run Code Online (Sandbox Code Playgroud)

模型.py

@dataclass(frozen=True)
class OrderLine:
    id: str
    sku: str
    quantity: int
Run Code Online (Sandbox Code Playgroud)

test_orm.py

def test_orderline_mapper_can_load_lines(session):
    session.execute(
        'INSERT INTO order_lines (order_id, sku, quantity) VALUES '
        '("order1", "RED-CHAIR", 12),'
        '("order1", "RED-TABLE", 13),'
        '("order2", "BLUE-LIPSTICK", 14)'
    )
    expected = [
        model.OrderLine("order1", …
Run Code Online (Sandbox Code Playgroud)

python sqlalchemy pytest python-dataclasses

6
推荐指数
1
解决办法
781
查看次数

标签 统计

pytest ×1

python ×1

python-dataclasses ×1

sqlalchemy ×1