django-pytest setup_method 数据库问题

django-pytest setup_method database issue

我在 Ubuntu 14.04 上进行了以下设置:

以及以下测试代码:

import pytest
from django.db import connection

import settings
from pollsapp.models import Question

original_db_name = settings.DATABASES["default"]["NAME"]

@pytest.mark.django_db
class TestExperiment(object):

    def setup_method(self, method):
        # it's not using the "test_" + DATABASE_NAME !
        assert connection.settings_dict["NAME"] == \ 
        settings.DATABASES["default"]["NAME"]
        Question.objects.create(question_text="How are you?")
        # this data remains in the main database
  1. 虽然 class 被标记为使用 django 数据库,但在构造函数中创建的数据到达主(生产)数据库(名称取自 settings.py)

  2. django_db 装饰器放在 setup_method 之上没有任何区别

  3. 在 setup_method 中创建的这些数据保留在主数据库中,不会像在 [=] 中进行数据创建调用时那样回滚。 14=]方法

  4. 当测试单独 运行 时会发生此行为。当 运行 在测试套件中使用它时,setup_method 数据库调用失败并显示:失败:不允许访问数据库,使用 django_db 标记启用 尽管装饰器显然在那里(顺便说一句,这意味着该错误消息不是 100% 可信的)。

pytest 是一个很棒的框架,如果数据库调用发生在 django_db 标记的测试用例方法中,django-pytest 会很好用。

看起来像 setup_methodteardown_method 等特殊的 pytest 方法中不应该存在任何数据库交互。尽管文档没有说明任何内容:

https://pytest-django.readthedocs.org/en/latest/database.html

我在 Django 1.7 和 1.9(最新稳定版)中都遇到了这种行为。

这里是整个测试模块的link:https://github.com/zdenekmaxa/examples/blob/master/python/django-testing/tests/pytest_djangodb_only.py

不幸的是,setup_X 方法不能很好地与 pytest 固定装置一起使用。 pytest-django 的数据库设置基于 pytest fixtures,因此它不起作用。

我建议您将 setup_method 设为自动使用装置,它请求数据库装置:

@pytest.mark.django_db
class TestExperiment(object):

    @pytest.fixture(autouse=True)
    def setup_stuff(self, db):
        Question.objects.create(question_text="How are you?")

    def test_something(self):
        assert Question.objects.filter(question_text="How are you?").exists()

pytest-django 给出的错误消息令人困惑和误导,我已经向 track/fix 提出了一个问题:https://github.com/pytest-dev/pytest-django/issues/297