微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在Django TestCase中使用pytest固定装置

如何解决如何在Django TestCase中使用pytest固定装置

如何在 TestCase 方法中使用pytest固定装置?对类似问题的几个答案似乎暗示我的示例应该起作用:

import pytest

from django.test import TestCase
from myapp.models import Category
  
pytestmark = pytest.mark.django_db

@pytest.fixture
def category():
    return Category.objects.create()
  
class MyappTests(TestCase):
    def test1(self,category):
        assert isinstance(category,Category)

但这总是会导致错误

TypeError: test1() missing 1 required positional argument: 'category'

我意识到我可以将这个简单的示例转换为一个函数,并且可以正常工作。我更喜欢使用django的 TestCase ,因为它支持导入传统的“ django灯具” 文件,这是我的一些测试所必需的。将测试转换为函数将需要重新实现此逻辑,因为没有使用pytest(或pytest-django)导入“ django固定装置” 的书面方法

软件包版本

Django==3.1.2
pytest==6.1.1
pytest-django==4.1.0

解决方法

我发现使用“ usefixtures”方法更容易。它没有显示该函数的神奇的第二个参数,它明确标记了具有固定装置的类。

@pytest.mark.usefixtures("category")
class CategoryTest(TestCase):
    def test1(self):
        assert Category.objects.count() == 1
,

我选择使用 session 范围内的“ pytest夹具” 重写django的夹具逻辑。您需要做的只是在测试目录根目录下的 conftest.py 文件中安装一个夹具:

import pytest

from django.core.management import call_command

@pytest.fixture(scope='session')
def django_db_setup(django_db_setup,django_db_blocker):
    fixtures = [
        'myapp/channel','myapp/country',...
    ]

    with django_db_blocker.unblock():
        call_command('loaddata',*fixtures)

这使我完全放弃了基于类的测试,而只使用了基于函数的测试。

docs

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。