How can I use pytest-django to create a user object only once per session?
Asked Answered
C

1

7

First, I tired this:

@pytest.mark.django_db
@pytest.fixture(scope='session')
def created_user(django_db_blocker):
    with django_db_blocker.unblock():
        return CustomUser.objects.create_user("User", "UserPassword")

def test_api_create(created_user):
    user = created_user()
    assert user is not None

But I got an UndefinedTable error. So marking my fixture with @pytest.mark.django_db somehow didn’t actually register my Django DB. So next I tried pass the db object directly to the fixture:

@pytest.fixture(scope='session')
def created_user(db, django_db_blocker):
    with django_db_blocker.unblock():
        return CustomUser.objects.create_user("User", "UserPassword")

def test_api_create(created_user):
    user = created_user()
    assert user is not None

But then I got an error

ScopeMismatch: You tried to access the 'function' scoped fixture 'db' with a 'session' scoped request object, involved factories

So finally, just to confirm everything was working, I tried:

@pytest.fixture
def created_user(db, django_db_blocker):
    with django_db_blocker.unblock():
        return CustomUser.objects.create_user("User", "UserPassword")

def test_api_create(created_user):
    user = created_user()
    assert user is not None

This works just fine, but now my create_user function is being called every single time my function is being setup or torn down. Whats the solution here?

Crissie answered 3/7, 2020 at 20:56 Comment(2)
Use django_db_setup instead of the db fixture?Magnetism
Perfect, this worked, I posted the answer belowCrissie
C
10

@hoefling had the answer, I needed to pass django_db_setup instead.

@pytest.fixture(scope='session')
def created_user(django_db_setup, django_db_blocker):
    with django_db_blocker.unblock():
        return CustomUser.objects.create_user("User", "UserPassword")
Crissie answered 3/7, 2020 at 21:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.