【发布时间】: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