Opened 9 months ago

Closed 9 months ago

Last modified 9 months ago

#22771 closed Uncategorized (fixed)

TestCase.client.logout fails when using custom authentication backend not based on AUTH_USER_MODEL

Reported by: xafer Owned by: nobody
Component: Testing framework Version: 1.6
Severity: Normal Keywords: logout test AUTH_USER_MODEL
Cc: Triage Stage: Unreviewed
Has patch: yes Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

Hello !

I'm not sure if it's a bug or a new feature:

TestCase.client.login calls django.contrib.auth.login(request, user)
which stores the user id and its backend in the request's session:

request.session[SESSION_KEY] = user.pk
request.session[BACKEND_SESSION_KEY] = user.backend

But in TestCase.client.logout calls, Django tries to get the authenticated user with:

uid = self.session.get(SESSION_KEY)
request.user = UserModel._default_manager.get(pk=uid)

assuming user is a AUTH_USER_MODEL and without checking its BACKEND_SESSION_KEY...

It would seem cleaner to actually rly on django.contrib.auth.get_user to find the correct user (whatever its type) and allow the concurrent use of multiple user models (typically user model and customer model...).

See https://github.com/xavfernandez/django_test_client_bugreport for a failing example.

Attachments (2)

test_client_22771 (1.1 KB) - added by xafer 9 months ago.
Patch of django/test/client.py
test_client_22771_v2 (1.1 KB) - added by xafer 9 months ago.
Patch of django/test/client.py - v2

Download all attachments as: .zip

Change History (8)

comment:1 Changed 9 months ago by xafer

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset

To backup the change, using django.contrib.auth.get_user is also what's done by the AuthenticationMiddleware (cf https://github.com/django/django/blob/1.6.5/django/contrib/auth/middleware.py#L18)

Changed 9 months ago by xafer

Patch of django/test/client.py

comment:2 Changed 9 months ago by xafer

  • Has patch set

Changed 9 months ago by xafer

Patch of django/test/client.py - v2

comment:4 Changed 9 months ago by Tim Graham <timograham@…>

  • Resolution set to fixed
  • Status changed from new to closed

In 50b9313e0a0739dfe1ac699449b66ed3e62add51:

Fixed #22771 -- Fixed test.Client.logout when using custom auth backend.

comment:5 Changed 9 months ago by xafer

Thanks for the quick fix !
Any chance this could make it into 1.7 ?

comment:6 Changed 9 months ago by Tim Graham <timograham@…>

In 183e9d20294dec28df8ae5ea8ed7acc712adcd2b:

[1.7.x] Fixed #22771 -- Fixed test.Client.logout when using custom auth backend.

Backport of 50b9313e0a from master

Note: See TracTickets for help on using tickets.
Back to Top