django-pytest setup_method数据库问题

Zde*_*axa 6 python django unit-testing pytest pytest-django

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

  • python 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
Run Code Online (Sandbox Code Playgroud)
  1. 虽然该类被标记为使用django数据库,但构造函数中创建的数据到达主(生产)数据库(名称取自settings.py)

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

  3. 在setup_method创建该数据保留在主数据库,不回滚如果数据创建调用是在做他们应该和他们是test_case方法

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

pytest是一个很棒的框架,如果数据库调用是从django_db标记的测试用例方法发生的,那么django-pytest很有用.

它看起来像没有数据库交互应该永远存在于特殊的pytest方法,如setup_method,teardown_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

and*_*lme 15

不幸的是,setup_X方法与pytest fixtures不太搭配.pytest-django的数据库设置基于pytest fixture,因此它不起作用.

我建议你让你的setup_method成为一个autouse fixture,它要求db fixture:

@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()
Run Code Online (Sandbox Code Playgroud)

pytest-django给出的错误信息令人困惑和误导,我打开了一个问题来跟踪/解决这个问题:https://github.com/pytest-dev/pytest-django/issues/297

  • setup_X 和 teardown_X 可能随时中断。您应该使用夹具进行所有测试设置和拆卸。https://pytest.org/latest/fixture.html#fixture-finalization-executing-teardown-code 描述了如何注册要在拆卸期间运行的函数。它将具有适当的数据库访问权限。如果您对此感到满意,请将答案标记为已接受。 (2认同)