如何防止django test runner在每次测试后刷新数据库?

ca1c2owp  于 2023-11-20  发布在  Go
关注(0)|答案(1)|浏览(122)

我使用pytest-django插件运行测试,我需要防止数据库在每次测试后被刷新,这是测试定义如下时的默认行为。注意:我在运行测试之前填充User表,这就是为什么下面的工作。

class TestViews:
    @staticmethod
    def test1(django_user_model):
        assert django_user_model.objects.count() > 0

    @staticmethod
    def test2(django_user_model):
        assert django_user_model.objects.count() > 0

字符串
结果:

============================= test session starts ==============================
collecting ... collected 2 items

test_live_server.py::TestViews::test1 
test_live_server.py::TestViews::test2 

============================== 2 passed in 7.86s ===============================

Process finished with exit code 0


但是,当包含live_server fixture时:

class TestViews:
    @staticmethod
    def test1(django_user_model, live_server):
        assert django_user_model.objects.count() > 0

    @staticmethod
    def test2(django_user_model, live_server):
        assert django_user_model.objects.count() > 0


在每次测试之后刷新所有模型表。

============================= test session starts ==============================
collecting ... collected 2 items

test_live_server.py::TestViews::test1 
test_live_server.py::TestViews::test2
  
PASSED                             [ 50%]  # records ok
FAILED                             [100%]  # records dropped
tests/test_live_server.py:5 (TestViews.test2)
0 != 0

Expected :0
Actual   :0
<Click to see difference>

django_user_model = <class 'django.contrib.auth.models.User'>
live_server = <LiveServer listening at http://localhost:61926>

    @staticmethod
    def test2(django_user_model, live_server):
>       assert django_user_model.objects.count() > 0
E       AssertionError: assert 0 > 0
E        +  where 0 = <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>>()
E        +    where <bound method BaseManager._get_queryset_methods.<locals>.create_method.<locals>.manager_method of <django.contrib.auth.models.UserManager object at 0x10d83fc90>> = <django.contrib.auth.models.UserManager object at 0x10d83fc90>.count
E        +      where <django.contrib.auth.models.UserManager object at 0x10d83fc90> = <class 'django.contrib.auth.models.User'>.objects

test_live_server.py:8: AssertionError

========================= 1 failed, 1 passed in 7.63s ==========================


通过进一步挖掘,我发现call_command('flush',...)在每次测试之后都会被调用,当live_server不存在于函数参数中时就不会发生这种情况。
所以我尝试设置-reuse-db或将其添加到pytest.ini,当我使用django_db_keepdb检查时,当指定标志时,它的计算结果为True,但无论如何,数据库都会被刷新。而且@pytest.mark.django_db(transaction=true)也不工作。

4nkexdtk

4nkexdtk1#

这对我很有效,把它放在你的Django设置文件中


的数据
我相信你可以找到一种方法来设置它在您的测试conftest.py文件,如果你让我知道如何,谢谢

相关问题