Created
July 2, 2021 10:54
-
-
Save sirrobot01/64577716b6891287db7d830440fd13fc to your computer and use it in GitHub Desktop.
Pytest auto_login fixture
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytest | |
@pytest.fixture | |
def password(): | |
return 'my-password-is-stronger-than-yours' | |
@pytest.fixture | |
def create_user(db, django_user_model, password): | |
def _user(**kwargs): | |
kwargs['password'] = password | |
if 'username' not in kwargs: | |
kwargs['username'] = "test_user" | |
# Un-comment if you use email as USERNAME_FIELD | |
# if 'email' not in kwargs: | |
# kwargs['email'] = "[email protected]" | |
return django_user_model.objects.create_user(**kwargs) | |
return _user | |
@pytest.fixture | |
def auto_login_user(db, client, create_user): | |
def _login(user=None): | |
if user is None: | |
# pass is_superuser, is_staff or other user fields to create_user() | |
user = create_user() | |
login = client.login(username=user.username, email=user.email, password=user.password) | |
if not login: | |
# Login failed, force login | |
client.force_login(user) | |
return client, user | |
return _login |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment