【问题标题】:How to properly clear database using fixtures when testing with pytest使用 pytest 进行测试时如何使用夹具正确清除数据库
【发布时间】:2020-02-03 14:51:03
【问题描述】:

我有一个测试数据库。假设其中创建了三个表:

create table users (
    id serial constraint users_pkey primary key,
    name text not null
);
create table roles (
    id serial constraint roles_pkey primary key,
    name text not null
);
create table users_roles (
    user_id int constraint users_roles_users_fkey references users(id),
    role_id int constraint users_roles_roles_fkey references roles(id)
);

每个测试都从使用 factory_boy 工厂的数据填充数据库开始。典型的测试如下所示:

def test_get_user_roles(api_client):
    user = UserFactory.create(id=1)
    role = RolesFactory.create(id=1)
    users_roles = UsersRolesFactory.create(user_id=1, role_id=1)
    response = api_client.get(f"/users/{user.id}/roles")
    assert ...

我可以使用 @pytest.mark.usefixtures("clear_users_roles", "clear_users", "clear_roles") 清除表,其中 "clear_users_roles"、"clear_users"、"clear_roles" 是如果没有明显清除表的装置表之间的关系。 但是在上面的示例中,表 users_roles 和用户之间以及 users_roles 和角色之间存在关系(外键),问题是固定装置无序运行。 因此,当我运行我的测试时,我得到一个完整性错误,因为,例如,夹具“clear_users”在“clear_users_roles”之前执行,并且我的 RDBMS 无法删除记录,因为该记录仍然引用表“users”。有没有按特定顺序运行固定装置的正确方法?或者对于这样的案例可能有一些模式/最佳实践?

【问题讨论】:

  • 你能用 Docker 之类的东西来启动和关闭你的数据库实例吗?
  • 您能详细说明您正在使用的 ORM 层吗?其中大多数都带有助手来管理围绕测试用例的事务。
  • 您似乎只需要从“clear_users”和“clear_roles”夹具中添加对“clear_users_roles”夹具的依赖即可保证执行顺序。在 pytest 中,只需将依赖项作为参数添加到夹具函数即可。

标签: python python-3.x testing pytest factory-boy


【解决方案1】:

您是否尝试过在带有 yield 关键字的夹具中使用拆卸代码?

来自pytest documentation的示例:

# content of conftest.py

import smtplib
import pytest


@pytest.fixture(scope="module")
def smtp_connection():
    smtp_connection = smtplib.SMTP("smtp.gmail.com", 587, timeout=5)
    yield smtp_connection  # provide the fixture value
    print("teardown smtp")
    smtp_connection.close()

【讨论】:

  • 是的,我有。问题是,我对不同的用例有很多不同的测试。所以我不能对所有测试使用一个拆卸夹具,因为对未在特定测试中使用的表执行清理查询似乎有点多余。对我来说最好的解决方案是在特定测试中使用特定的拆卸装置。例如,如果我在测试中创建用户和角色,我想明确指定之后我只需要从表“用户”和“角色”中删除数据。
  • @IvanDenisovich 您可以通过使用@pytest.mark.usefixtures('myfixturename')标记测试来将固定装置应用于单个测试
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多