简体   繁体   English

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

[英]How to explicitly instruct PyTest to drop a database after some tests?

I am writing unit-tests with pytest-django for a django app.我正在使用 pytest-django 为 django 应用程序编写单元测试。 I want to make my tests more performant and doing so is requiring me to keep data saved in database for a certain time and not drop it after one test only.我想让我的测试更高效,这样做要求我将数据保存在数据库中一段时间,而不是仅在一次测试后丢弃它。 For example:例如:

@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"
    

What I want is to know how to keep both tests separated but both will use the same test database for some time and drop it thereafter.我想知道如何将两个测试分开,但两者都将使用相同的测试数据库一段时间,然后将其删除。

I think what you need are pytest fixtures.我认为您需要的是 pytest 夹具。 They allow you yo create objects (stored in database if needed) that will be used during tests.它们允许您创建将在测试期间使用的对象(如果需要,存储在数据库中)。 You can have a look at pytest fixtures scope that you can set so that the fixture is not deleted from database and reloading for each test that requires it but instead is created once for a bunch of tests and deleted afterwards.您可以查看 pytest 固定装置 scope ,您可以设置该固定装置,以便不会从数据库中删除固定装置并为每个需要它的测试重新加载,而是为一堆测试创建一次并在之后删除。

You should read the documentation of pytest fixtures ( https://docs.pytest.org/en/6.2.x/fixture.html ) and the section dedicated to fixtures' scope ( https://docs.pytest.org/en/6.2.x/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session ). You should read the documentation of pytest fixtures ( https://docs.pytest.org/en/6.2.x/fixture.html ) and the section dedicated to fixtures' scope ( https://docs.pytest.org/en/ 6.2.x/fixture.html#scope-sharing-fixtures-across-classes-modules-packages-or-session )。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM