django-pytest setup_method database issue
我在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中进行了测试]
以及以下测试代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | 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 |
尽管该类被标记为使用django数据库,但在构造函数中创建的数据到达主(生产)数据库(名称取自settings.py)。
将
在setup_method中创建的数据保留在主数据库中,不会按原样回滚,如果使用
单独运行测试时,会发生此行为。在测试套件中运行它时,setup_method db调用失败并显示:失败:不允许数据库访问,请使用
尽管装饰器显然在那里(这意味着此错误消息不是100%受信任的)。
pytest是一个很棒的框架,如果数据库调用是从标记为
似乎在特殊的pytest方法(例如
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
不幸的是,setup_X方法不能与pytest固定装置配合使用。 pytest-django的数据库设置基于pytest固定装置,因此不起作用。
我建议您将setup_method设置为自动使用的固定装置,要求使用db固定装置:
1 2 3 4 5 6 7 8 9 | @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