简体   繁体   中英

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

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?

@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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM