python - django-pytest setup_method 数据库问题

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

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

  3. 在 setup_method 中创建的数据保留在主数据库中,不会像在 test_case 方法中进行数据创建调用时那样回滚。/p>

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

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

看起来在特殊的 pytest 方法(例如 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

最佳答案

不幸的是,setup_X 方法不适用于 pytest fixtures。 pytest-django 的数据库设置基于 pytest fixtures,因此它不起作用。

我建议你让你的 setup_method 成为一个自动使用的 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()

pytest-django 给出的错误消息令人困惑和误导,我已经打开一个问题来跟踪/修复此问题:https://github.com/pytest-dev/pytest-django/issues/297

关于python - django-pytest setup_method 数据库问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34089425/

相关文章:

python - 如何在 Scikit-Learn 中重用 LabelBinarizer 进行输入预测

Django Celery 多次运行一个函数?

Django prefetch_related - 使用来自不同表的 or 子句过滤

Typescript - 找不到名称 'By'

python - 如何使用 await 表达式?

python - 打开(树) View 时的 Odoo 8 函数调用

python - 如何从 setup_requires 依赖项覆盖 setuptools 命令?

python - 每次在 django 中生成 View 时更新模型

c# - 带过期时间的字典缓存

javascript - AngularJS——如何在 Jasmine 中为输入事件指令编写单元测试