![Show Menu](styles/mobile-menu.png)
![Page Background](./../common/page-substrates/page0315.png)
And we can get that to passing in three steps (make sure the Goat sees you doing each
one individually!):
accounts/authentication.py.
def
authenticate
(
self
,
assertion
):
requests
.
post
(
PERSONA_VERIFY_URL
,
data
=
{
'assertion'
:
assertion
,
'audience'
:
DOMAIN
}
)
Grand:
$
python3 manage.py test accounts
[...]
Ran 5 tests in 0.023s
OK
Next let’s check that
authenticate
should return
None
if it sees an error fromthe request:
accounts/tests/test_authentication.py (ch16l020).
@patch
(
'accounts.authentication.requests.post'
)
def
test_returns_none_if_response_errors
(
self
,
mock_post
):
mock_post
.
return_value
.
ok
=
False
backend
=
PersonaAuthenticationBackend
()
user
=
backend
.
authenticate
(
'an assertion'
)
self
.
assertIsNone
(
user
)
And that passes straight away—we currently return
None
in all cases!
Patching at the Class Level
Next we want to check that the response JSON has
status=okay
. Adding this test would
involve a bit of duplication—let’s apply the “three strikes” rule:
accounts/tests/test_authentication.py (ch16l021).
@patch
(
'accounts.authentication.requests.post'
)
#
class
AuthenticateTest
(
TestCase
):
def
setUp
(
self
):
self
.
backend
=
PersonaAuthenticationBackend
()
#
def
test_sends_assertion_to_mozilla_with_domain
(
self
,
mock_post
):
self
.
backend
.
authenticate
(
'an assertion'
)
mock_post
.
assert_called_once_with
(
PERSONA_VERIFY_URL
,
data
=
{
'assertion'
:
'an assertion'
,
'audience'
:
DOMAIN
}
)
def
test_returns_none_if_response_errors
(
self
,
mock_post
):
De-spiking Our Custom Authentication Backend: Mocking Out an Internet Request
|
287