def
test_logs_non_okay_responses_from_persona
(
self
,
mock_post
):
response_json
=
{
'status'
:
'not okay'
,
'reason'
:
'eg, audience mismatch'
}
mock_post
.
return_value
.
ok
=
True
mock_post
.
return_value
.
json
.
return_value
=
response_json
#
logger
=
logging
.
getLogger
(
'accounts.authentication'
)
#
with
patch
.
object
(
logger
,
'warning'
)
as
mock_log_warning
:
#
self
.
backend
.
authenticate
(
'an assertion'
)
mock_log_warning
.
assert_called_once_with
(
'Persona says no. Json was: {}'
.
format
(
response_json
)
#
)
We set up our test with some data that should cause some logging.
We retrieve the actual logger for the module we’re testing.
We use
patch.object
to temporarily mock out its warning function, by using
with
to make it a
context manager
around the function we’re testing.
And then it’s available for us to make assertions against.
That gives us:
AssertionError: Expected 'warning' to be called once. Called 0 times.
Let’s just try it out, to make sure we really are testing what we think we are:
accounts/authentication.py (ch17l024).
import
logging
logger
=
logging
.
getLogger
(
__name__
)
[
...
]
if
response
.
ok
and
response
.
json
()[
'status'
]
==
'okay'
:
[
...
]
else
:
logger
.
warning
(
'foo'
)
We get the expected failure:
AssertionError: Expected call: warning("Persona says no. Json was: {'status':
'not okay', 'reason': 'eg, audience mismatch'}")
Actual call: warning('foo')
And so we settle in with our real implementation:
accounts/authentication.py (ch17l025).
else
:
logger
.
warning
(
'Persona says no. Json was: {}'
.
format
(
response
.
json
())
)
$
python3 manage.py test accounts
[...]
Baking In Our Logging Code
|
319