gpt4 book ai didi

django - pytest,如何在测试之间保持数据库更改

转载 作者:行者123 更新时间:2023-12-04 16:45:17 33 4
gpt4 key购买 nike

我正在使用以下内容 conftest.py

@pytest.fixture(scope='session')
def django_db_setup():
settings.DATABASES['default'] = {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'NAME': 'my_db',
'HOST': 'localhost',
}

它从现有的数据库中读取数据很好。
现在我想运行两个测试,并希望我在前面的测试中所做的更改持续到 test2(直到文件中的整个测试完成)
def test_1():

user = User.objects.get(email='a@example.com')
user.username = 'hello'
user.save()


def test_2():

user = User.objects.get(email='a@example.com')
print(user.username) # expect 'hello' but it's not
  • 有范围“ session /模块”,想知道它是什么意思, session 意味着整个测试运行?

  • 以下是我尝试过的,但不起作用..
    (从 https://github.com/pytest-dev/pytest-django/blob/master/docs/database.rst 底部)

    在比赛.py
    @pytest.fixture(scope='session')
    def django_db_setup():
    settings.DATABASES['default'] = {
    'ENGINE': 'django.db.backends.postgresql_psycopg2',
    'NAME': 'my_db',
    'HOST': 'localhost',
    }

    @pytest.fixture
    def db_no_rollback(request, django_db_setup, django_db_blocker):
    # https://github.com/pytest-dev/pytest-django/blob/master/docs/database.rst
    django_db_blocker.unblock()
    request.addfinalizer(django_db_blocker.restore)

    在 test.py 中
    def test_1(db_no_rollback):

    user = User.objects.get(email='a@example.com')
    user.username = 'hello'
    user.save()


    def test_2(db_no_rollback):

    user = User.objects.get(email='a@example.com')
    print(user.username) # expect 'hello' but it's not

    最佳答案

    您可以使用 pytest 'fixtures'

    import pytest

    @pytest.fixture()
    @pytest.mark.django_db(transaction=True)
    def test_1():

    user = User.objects.get(email='a@example.com')
    user.username = 'hello'
    user.save()

    @pytest.mark.django_db(transaction=True)
    def test_2(test_1):

    user = User.objects.get(email='a@example.com')
    assert user.username == 'hello'

    在这种情况下,test_2 将拥有来自 test_1(fixture) 的所有数据库数据

    关于django - pytest,如何在测试之间保持数据库更改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59195531/

    33 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com