【问题标题】:django-pytest setup_method database issuedjango-pytest setup_method 数据库问题
【发布时间】: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
  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 就可以很好地工作。

看起来像setup_methodteardown_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


【解决方案1】:

不幸的是,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

【讨论】:

  • 谢谢。实际上,这可以按预期在 setup_method 上工作,但仍然失败:不允许数据库访问,使用“django_db”标记以标记def teardown_method(self, db): 的相同方式启用感谢您的解释,我假设避免在 pytest 特殊的 db 交互方法。
  • setup_X 和 teardown_X 可能随时中断。您应该使用固定装置进行所有测试设置和拆除。 pytest.org/latest/… 描述了如何注册一个函数以在拆卸期间运行。它将具有适当的数据库访问权限。如果您对答案满意,请将答案标记为已接受。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-08
  • 1970-01-01
  • 2022-06-13
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多