I'm testing a view function in Flask that requires authentication. I want to remove the effect of authentication, and so I wrote a test like so:
@patch('auth0_.decode_jwt')
@patch('auth0_.get_token_auth_header')
def test_list_cards_endpoint(self, get_token_header, decode_jwt):
decode_jwt.return_value = {
'sub': 'auth0|123',
}
headers = {
'Authorization': 'Bearer 123'
}
with current_app.test_request_context('/pay/list-cards', headers=headers):
list_cards_endpoint()
Which works completely fine. Next I wanted to abstract the above code so I can re-use it all tests and so I turned it into a decorator:
def fake_auth0(f):
@patch('auth0_.decode_jwt')
@patch('auth0_.get_token_auth_header')
def decorated(get_token_header, decode_jwt, *args, **kwargs):
decode_jwt.return_value = {
'sub': 'auth0|123',
}
headers = {
'Authorization': 'Bearer 123'
}
with current_app.test_request_context('/pay/list-cards', headers=headers):
return f(*args, **kwargs)
return decorated
And tried calling it:
@fake_auth0
def test_list_cards_endpoint(self):
list_cards_endpoint()
And I'm getting an error back, the essence of which is that @patch
statements are not working correctly. More specifically, they're not assigning the return_value
to be what I want and instead I simply get <MagicMock name='decode_jwt().__getitem__()' id='4540406656'>
as a return value for decode_jwt
.
So it's like - the mock is working, but the return value is not.
Why might this be?
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…