如何使用 pytest 装置和 django 在unittest中创建类似于“setUp”的方法

2024-01-13

我的测试文件中有下面的代码并尝试重构它。我是 pytest 的新手,我正在尝试实现与 unittest 可用的类似方法 setUp ,以便能够将数据库中创建的对象检索到其他函数,而不是重复代码。

在这种情况下我想重用month from 测试设置到其他功能。

测试模型.py

@pytest.mark.django_db
class TestMonth:
    # def test_setup(self):
    #     month = Month.objects.create(name="january", slug="january")
    #     month.save()

    def test_month_model_save(self):
        month = Month.objects.create(name="january", slug="january")
        month.save()
        assert month.name == "january"
        assert month.name == month.slug

    def test_month_get_absolute_url(self, client):
        month = Month.objects.create(name="january", slug="january")
        month.save()
        response = client.get(reverse('core:month_detail', kwargs={'slug': month.slug}))
        assert response.status_code == 200

我将不胜感激的帮助。


使用固定装置, pytest 等效项将如下所示:

import pytest

@pytest.fixture
def month(self):
    obj = Month.objects.create(name="january", slug="january")
    obj.save()
    # everything before the "yield" is like setUp
    yield obj
    # everything after the "yield" is like tearDown

def test_month_model_save(month):
    assert month.name == "january"
    assert month.name == month.slug

def test_month_get_absolute_url(month, client):
    response = client.get(reverse('core:month_detail', kwargs={'slug': month.slug}))
    assert response.status_code == 200
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 pytest 装置和 django 在unittest中创建类似于“setUp”的方法 的相关文章

随机推荐