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.
@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.
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.
Django provides a test framework with a small hierarchy of classes that build on the Python standard unittest library.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With