Mocking boolean __bool__ protocol method in Python 2.7
As part of my unittests, I am testing some of the answers using the fantastic Requests library. Something cool you can do with this library is a test for the 200
OK status code by simply calling:
r = requests.get("http://example.com")
if r:
# success code, do something...
else:
# error code, handle the error.
How it works behind the scenes: Requests updates the __bool__()
response protocol method returned to match the type of status code.
What I would like to do is be able to mock the response object enough requests.get()
so that I can not only fix the methods / attributes I am interested in ( status_code
, json()
), but also the ability to return False
whenever I choose.
The following doesn't work for me: as soon as I call r
from the above example code, it returns a Mock object <Mock id='2998569132'>
that evaluates to True
.
with mock.patch.object(requests, 'get', return_value=mock.MagicMock(
# False, # didn't work
# __bool__=mock.Mock(return_value=False), # throws AttributeError, might be Python2.7 problem
# ok=False, # works if I call if r.ok: instead, but it not what I want
status_code=401,
json=mock.Mock(
return_value={
u'error': {
u'code': 401,
u'message':
u'Request had invalid authentication credentials.',
u'status': u'UNAUTHENTICATED'
}
}
)
)) as mock_account_get_failure:
# mock_account_get_failure.return_value = False # overwrites what I just mocked with json() and status_code
I thought the answer might be Magic Mocking the return value of the protocol method , but read here which __bool__
is only supported for Python 3.0.
No one has answered this question yet
Check out similar questions: