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

1 if = 1 More Test

A rule of thumb for these sorts of tests: any

if

means an extra test, and any

try/

except

means an extra test, so this should be about four tests. Let’s start with one:

accounts/tests/test_authentication.py.

from

unittest.mock

import

patch

from

django.test

import

TestCase

from

accounts.authentication

import

(

PERSONA_VERIFY_URL

,

DOMAIN

,

PersonaAuthenticationBackend

)

class

AuthenticateTest

(

TestCase

):

@patch

(

'accounts.authentication.requests.post'

)

def

test_sends_assertion_to_mozilla_with_domain

(

self

,

mock_post

):

backend

=

PersonaAuthenticationBackend

()

backend

.

authenticate

(

'an assertion'

)

mock_post

.

assert_called_once_with

(

PERSONA_VERIFY_URL

,

data

=

{

'assertion'

:

'an assertion'

,

'audience'

:

DOMAIN

}

)

In

authenticate.py

we’ll just have a few placeholders:

accounts/authentication.py.

import

requests

PERSONA_VERIFY_URL

=

'https://verifier.login.persona.org/verify'

DOMAIN

=

'localhost'

class

PersonaAuthenticationBackend

(

object

):

def

authenticate

(

self

,

assertion

):

pass

At this point we’ll need to:

(virtualenv)$

pip install requests

Don’t forget to add

requests

to

requirements.txt

too, or the next

deploy won’t work…

Then let’s see how the tests get on!

$

python3 manage.py test accounts

[...]

AssertionError: Expected 'post' to be called once. Called 0 times.

286

|

Chapter 16: Server-Side Authentication and Mocking in Python