Fixtures are not meant to be called directly

Viewed 2627

I'm using Django 3.0.5, pytest 5.4.1 and pytest-django 3.9.0. I want to create a fixture that returns a User object to use in my tests. Here is my conftest.py

import pytest
from django.contrib.auth import get_user_model


@pytest.fixture
def create_user(db):
    return get_user_model().objects.create_user('user@gmail.com', 'password')

Here is my api_students_tests.py

import pytest
from rest_framework.test import APITestCase, APIClient


    class StudentViewTests(APITestCase):

        user = None

        @pytest.fixture(scope="session")
        def setUp(self, create_user):
            self.user = create_user

        def test_create_student(self):
            assert self.user.email == 'user@gmail.com'  
            # other stuff ...

I keep getting the following error

Fixture "setUp" called directly. Fixtures are not meant to be called directly,
but are created automatically when test functions request them as parameters.

I read and read again this previous question but I cannot find out a solution. Furthermore, in that question the fixture wasn't returning nothing, while in my case it should return an object (don't know if it can make any difference)

1 Answers

Just skip the setUp:

@pytest.fixture(scope='session')
def create_user(db):
    return get_user_model().objects.create_user('user@gmail.com', 'password')


class StudentViewTests(APITestCase):

    def test_create_student(self, create_user):
        assert user.email == 'user@gmail.com'  
        # other stuff ...
Related