gpt4 book ai didi

python - 在 pytest-django 中每次测试后都会清理数据库

转载 作者:行者123 更新时间:2023-12-05 08:51:09 25 4
gpt4 key购买 nike

我正在努力实现的目标。
我正在 Django 项目中测试 rest API。我想创建具有相关测试函数的测试类(每个后续测试函数都依赖于前一个)——第一次失败意味着全部失败。在第一个测试函数中,我创建了一个带有“发布”请求的对象。在下一个测试用例中,我想使用“get”请求检查该对象是否确实存在。

工作原理
看起来 Django-pytest 在每次测试后都会清除数据库中的所有记录。
它在 pytest 文档中提到:https://pytest-django.readthedocs.io/en/latest/helpers.html#pytest-mark-django-db-request-database-access
有什么办法可以改变吗?

我的代码:
我的 conftest.py:

import pytest


@pytest.fixture(scope='session')
def django_db_setup():
from django.conf import settings
settings.DATABASES['default'] = {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': 'db_name.sqlite3',
}


@pytest.fixture
def object_data():
return {"some keys": "some values"}


@pytest.fixture
def object_name():
return "some name"

我的tests.py:

import pytest

from rest_framework.test import APIClient
from rest_framework import status


@pytest.mark.django_db
class TestAPI:
def setup(self):
self.client = APIClient()

def test_create_object(self, object_data, object_name):
post_response = self.client.post("/api/object/", data=object_data, format="json")
assert status.is_success(post_response.status_code)
# make sure that report was created
get_response = self.client.get(f"/api/object/{object_name}/")
assert status.is_success(get_response.status_code)
# object exists here (test passes)

def test_get_object(self, object_name):
get_response = self.client.get(f"/api/object/{object_name}/")
assert status.is_success(get_response.status_code)
# object does not exists here (test failes)

最佳答案

您可能不想在测试用例之间保留数据。您应该努力让测试用例能够以任意顺序运行。如果您希望在测试用例之间共享数据,请在夹具中对其进行初始化并跨测试用例重用它,或者将您的测试用例合并为一个以确保一个测试用例中的所有内容都按顺序运行。

关于python - 在 pytest-django 中每次测试后都会清理数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60336287/

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