【问题标题】:How to create a similar to "setUp" method in unittest using pytest fixtures and django如何使用 pytest 固定装置和 django 在 unittest 中创建类似于“setUp”的方法
【发布时间】:2020-02-29 08:22:43
【问题描述】:

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

在这种情况下,我想将 test_setup 中的 month 重用于其他函数。

test_models.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

我将不胜感激。

【问题讨论】:

    标签: python django python-3.x unit-testing pytest


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多