【问题标题】:Database is cleaned up after each test in pytest-django在 pytest-django 中的每次测试后清理数据库
【发布时间】:2020-02-21 10:05:24
【问题描述】:

我正在努力实现的目标。
我正在 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 django-rest-framework pytest-django


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

      是的,pytest-django 在每次测试运行后都会清除您的数据库。

      为了解决这个问题,在你的根目录下添加一个名为pytest.ini的pytest配置文件并添加如下

      [pytest]
      addopts = --reuse-db
      

      正如这个配置文件所暗示的,它重用当前数据库而不创建新数据库。

      所以如果你需要为你的测试创建一个数据库,你必须在pytest --create-db的命令中指定它

      【讨论】:

      • 我试过这个。不幸的是,它在测试运行之间重用了数据库(不是测试用例):(
      • 在这种情况下,请尝试从固定装置更改会话范围。使用@pytest.fixture()
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-30
      • 2019-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-07
      • 1970-01-01
      相关资源
      最近更新 更多