gpt4 book ai didi

python - 如何在 django TestCase 中使用 pytest 固定装置

转载 作者:行者123 更新时间:2023-12-03 16:10:06 28 4
gpt4 key购买 nike

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

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 fixture”文件,这是我的几个测试所需要的。将我的测试转换为函数需要重新实现这个逻辑,因为没有记录的方式使用 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

关于python - 如何在 django TestCase 中使用 pytest 固定装置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64528957/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com