【发布时间】:2015-12-04 13:25:04
【问题描述】:
我在 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
虽然该类被标记为使用 django 数据库,但在构造函数中创建的数据到达主(生产)数据库(名称取自 settings.py)
将
django_db装饰器放在setup_method之上没有任何区别-
在 setup_method 中创建的这些数据保留在主数据库中,不会按应有的方式回滚,如果在
李>test_case方法中进行数据创建调用,则不会回滚 当测试单独运行时会发生此行为。在测试套件中运行它时,setup_method db 调用失败:失败:不允许访问数据库,使用
django_db标记启用 尽管装饰器显然在那里(这意味着此错误消息不是 100% 受信任的)。
pytest 是一个很棒的框架,如果数据库调用发生在 django_db 标记的测试用例方法中,那么 django-pytest 就可以很好地工作。
看起来像setup_method、teardown_method 等特殊的 pytest 方法中不应该存在任何 db 交互。虽然文档没有说明任何内容:
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
【问题讨论】:
-
装饰器应该在方法上,而不是在类上。
-
如果是,则没有任何区别。并且根据 django-pytest 文档,模块、类、方法或函数级别都是可能的。
标签: python django unit-testing pytest pytest-django