Background Image
Table of Contents Table of Contents
Previous Page  312 / 478 Next Page
Information
Show Menu
Previous Page 312 / 478 Next Page
Page Background

request.session

inside any view, and it works as a dict. There’s more information in

the

Django docs on sessions .

That gives us two failures:

$

python3 manage.py test accounts

[...]

self.assertEqual(self.client.session[SESSION_KEY], user.pk)

KeyError: '_auth_user_id'

[...]

AssertionError: '' != 'OK'

+ OK

The Django function that takes care of logging in a user, by marking their session, is

available at

django.contrib.auth.login

. So we go through another couple of TDD

cycles, until:

accounts/views.py.

from

django.contrib.auth

import

authenticate

,

login

from

django.http

import

HttpResponse

def

persona_login

(

request

):

user

=

authenticate

(

assertion

=

request

.

POST

[

'assertion'

])

if

user

:

login

(

request

,

user

)

return

HttpResponse

(

'OK'

)

OK

We now have a working login view.

Testing Login with Mocks

An alternative way of testing that the Django login function was called correctly would

be to mock it out too:

accounts/tests/test_views.py.

from

django.http

import

HttpRequest

from

accounts.views

import

persona_login

[

...

]

@patch

(

'accounts.views.login'

)

@patch

(

'accounts.views.authenticate'

)

def

test_calls_auth_login_if_authenticate_returns_a_user

(

self

,

mock_authenticate

,

mock_login

):

request

=

HttpRequest

()

request

.

POST

[

'assertion'

]

=

'asserted'

284

|

Chapter 16: Server-Side Authentication and Mocking in Python