Skip to content

Commit 79b7754

Browse files
authored
Merge pull request #881 from bluetech/admin_client_login
Force login admin user in admin_client
2 parents bb9e86e + d9b66a2 commit 79b7754

File tree

3 files changed

+18
-3
lines changed

3 files changed

+18
-3
lines changed

docs/helpers.rst

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -158,14 +158,18 @@ Example
158158
response = client.get('/')
159159
assert response.content == 'Foobar'
160160

161-
To use `client` as an authenticated standard user, call its `login()` method before accessing a URL:
161+
To use `client` as an authenticated standard user, call its `force_login()` or
162+
`login()` method before accessing a URL:
162163

163164
::
164165

165166
def test_with_authenticated_client(client, django_user_model):
166167
username = "user1"
167168
password = "bar"
168-
django_user_model.objects.create_user(username=username, password=password)
169+
user = django_user_model.objects.create_user(username=username, password=password)
170+
# Use this:
171+
client.force_login(user)
172+
# Or this:
169173
client.login(username=username, password=password)
170174
response = client.get('/private')
171175
assert response.content == 'Protected Area'

pytest_django/fixtures.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -308,7 +308,7 @@ def admin_client(db, admin_user):
308308
from django.test.client import Client
309309

310310
client = Client()
311-
client.login(username=admin_user.username, password="password")
311+
client.force_login(admin_user)
312312
return client
313313

314314

tests/test_fixtures.py

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,17 @@ def test_admin_client_no_db_marker(admin_client):
4949
assert force_str(resp.content) == "You are an admin"
5050

5151

52+
# For test below.
53+
@pytest.fixture
54+
def existing_admin_user(django_user_model):
55+
return django_user_model._default_manager.create_superuser('admin', None, None)
56+
57+
58+
def test_admin_client_existing_user(db, existing_admin_user, admin_user, admin_client):
59+
resp = admin_client.get("/admin-required/")
60+
assert force_str(resp.content) == "You are an admin"
61+
62+
5263
@pytest.mark.django_db
5364
def test_admin_user(admin_user, django_user_model):
5465
assert isinstance(admin_user, django_user_model)

0 commit comments

Comments
 (0)