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

That gets our new test passing, but still, none of the other tests are failing:

$

python3 manage.py test accounts

[...]

Ran 8 tests in 0.030s

OK

They’re passing because

objects.first()

returns

None

if there are no users in the

database. Let’s make our other cases more realistic, by making sure there’s always at least

one user in the database for all our tests:

accounts/tests/test_authentication.py (ch16l022-2).

def

setUp

(

self

):

self

.

backend

=

PersonaAuthenticationBackend

()

user

=

User

(

email

=

'other@user.com

'

)

user

.

username

=

'otheruser'

#

user

.

save

()

By default, Django’s users have a

username

attribute, which has to be unique, so

this value is just a placeholder to allow us to create multiple users. Later on, we’ll

get rid of usernames in favour of using emails as the primary key.

That gives us three failures:

FAIL: test_finds_existing_user_with_email

AssertionError: <User: otheruser> != <User: >

[...]

FAIL: test_returns_none_if_response_errors

AssertionError: <User: otheruser> is not None

[...]

FAIL: test_returns_none_if_status_not_okay

AssertionError: <User: otheruser> is not None

Let’s start building our guards for cases where authentication should fail—if the response

errors, or if the status is not

okay

. Suppose we start with this:

accounts/authentication.py (ch16l024-1).

def

authenticate

(

self

,

assertion

):

response

=

requests

.

post

(

PERSONA_VERIFY_URL

,

data

=

{

'assertion'

:

assertion

,

'audience'

:

DOMAIN

}

)

if

response

.

json

()[

'status'

]

==

'okay'

:

return

User

.

objects

.

first

()

That actually fixes two of the tests, slightly surprisingly:

AssertionError: <User: otheruser> != <User: >

FAILED (failures=1)

De-spiking Our Custom Authentication Backend: Mocking Out an Internet Request

|

289