8

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

  • 蟒蛇2.7.6
  • django 1.7 [虽然我也用 django 1.9 重现了相同的行为]
  • pytest-django 2.8.0 [也用 2.9.1 测试过]
  • pytest 2.7.2 [也用 2.8.3 测试过]

以及以下测试代码:

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. 尽管该类被标记为使用 django 数据库,但在构造函数中创建的数据到达主(生产)数据库(名称取自 settings.py)

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

  3. 在 setup_method 中创建的此数据保留在主数据库中,不会按应有的方式回滚,如果在test_case方法中进行数据创建调用,则不会回滚

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

pytest 是一个很棒的框架,如果数据库调用发生在django_db标记的测试用例方法中,那么 django-pytest 就可以很好地工作。

看起来像 , 等特殊的 pytest 方法中不应该出现任何 db 交互setup_methodteardown_method尽管文档没有说明任何内容:

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

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

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

4

1 回答 1

18

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

我建议您将 setup_method 设置为自动使用夹具,它请求 db 夹具:

@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 给出的错误消息令人困惑和误导,我已经打开了一个问题来跟踪/修复这个问题:https ://github.com/pytest-dev/pytest-django/issues/297

于 2015-12-07T10:17:16.567 回答