Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a similar to "setUp" method in unittest using pytest fixtures and django

I have the code below in my test files and trying to refactor it. I am new to pytest and i am trying to achieve the similar method setUp available with unittest to be able to retrieve the object created in the db to other function instead of repeating the codes.

In this case I want to reuse month from test_setup to the other functions.

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

I would appreciate the help.

like image 773
Curtis Banks Avatar asked Nov 04 '19 01:11

Curtis Banks


People also ask

Can you use pytest fixtures with unittest?

pytest supports running Python unittest -based tests out of the box. It's meant for leveraging existing unittest -based test suites to use pytest as a test runner and also allow to incrementally adapt the test suite to take full advantage of pytest's features.

Does Django use pytest or unittest?

Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library.

Can a pytest fixture use another fixture?

fixtures have explicit names and are activated by declaring their use from test functions, modules, classes or whole projects. fixtures are implemented in a modular manner, as each fixture name triggers a fixture function which can itself use other fixtures.


1 Answers

The pytest equivalent would be like this, using a fixture:

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
like image 97
wim Avatar answered Sep 20 '22 23:09

wim