如何明确指示PyTest在一些测试之后删除数据库?

2024-04-26 02:43:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在用pytest django为django应用程序编写单元测试。我想让我的测试更高效,这样做需要我将数据保存在数据库中一段时间,而不是只在一次测试后就删除它。例如:

@pytest.mark.django_db
def test_save():
    p1 = MyModel.objects.create(description="some description") # this object has the id 1
    p1.save()

@pytest.mark.django_db
def test_modify():
    p1 = MyModel.objects.get(id=1)
    p1.description = "new description"
    

我想知道的是如何将两个测试分开,但两者都将在一段时间内使用同一个测试数据库,然后将其删除


Tags: djangotestid数据库应用程序dbobjectspytest
1条回答
网友
1楼 · 发布于 2024-04-26 02:43:56

我想你需要的是最新的设备。它们允许您创建将在测试期间使用的对象(如果需要,存储在数据库中)。您可以查看pytest fixtures的作用域,您可以设置该作用域,以便该装置不会从数据库中删除,也不会为每个需要它的测试重新加载,而是为一组测试创建一次,然后删除

您应该阅读pytest fixture(https://docs.pytest.org/en/6.2.x/fixture.html)的文档和fixture的作用域(https://docs.pytest.org/en/6.2.x/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session)的专用部分

相关问题 更多 >