):
user
=
User
.
objects
.
create
(
=
'
a@b.com'
)
user
.
backend
=
''
# required for auth_login to work
mock_authenticate
.
return_value
=
user
self
.
client
.
post
(
'/accounts/login'
, {
'assertion'
:
'a'
})
self
.
assertEqual
(
self
.
client
.
session
[
SESSION_KEY
],
user
.
pk
)
#
@patch
(
'accounts.views.authenticate'
)
def
test_does_not_get_logged_in_if_authenticate_returns_None
(
self
,
mock_authenticate
):
mock_authenticate
.
return_value
=
None
self
.
client
.
post
(
'/accounts/login'
, {
'assertion'
:
'a'
})
self
.
assertNotIn
(
SESSION_KEY
,
self
.
client
.
session
)
#
The Django test client keeps track of the session for its user. For the case where
the user gets authenticated successfully, we check that their user ID (the primary
key, or pk) is associated with their session.
In the case where the user should not be authenticated, the
SESSION_KEY
should
not appear in their session.
Django Sessions: How a User’s Cookies Tell the Server She Is
Authenticated
Being an attempt to explain sessions, cookies, and authentication in Django.
Because HTTP is stateless, servers need a way of recognising different clients with
every
single request
. IP addresses can be shared, so the usual solution is to give each client a
unique session ID, which it will store in a cookie, and submit with every request. The
server will store that ID somewhere (by default, in the database), and then it can rec‐
ognise each request that comes in as being from a particular client.
If you log in to the site using the dev server, you can actually take a look at your session
ID by hand if you like. It’s stored under the key
sessionid
by default. See
Figure 16-1 .282
|
Chapter 16: Server-Side Authentication and Mocking in Python