Skip to content

Instantly share code, notes, and snippets.

@sirrobot01
Created July 2, 2021 10:54
Show Gist options
  • Save sirrobot01/64577716b6891287db7d830440fd13fc to your computer and use it in GitHub Desktop.
Save sirrobot01/64577716b6891287db7d830440fd13fc to your computer and use it in GitHub Desktop.
Pytest auto_login fixture
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'] = "test_user@email.com"
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