|
5 | 5 | from requests_oauthlib import OAuth2Session |
6 | 6 | from requests import HTTPError |
7 | 7 |
|
8 | | -from nypl_py_utils import Oauth2ApiClient |
| 8 | +from nypl_py_utils import (Oauth2ApiClient, Oauth2ApiClientError) |
9 | 9 |
|
10 | 10 | _TOKEN_RESPONSE = { |
11 | 11 | 'access_token': 'super-secret-token', |
@@ -110,3 +110,28 @@ def test_error_status_raises_error(self, requests_mock, test_instance, |
110 | 110 |
|
111 | 111 | with pytest.raises(HTTPError): |
112 | 112 | test_instance._do_http_method('GET', 'foo') |
| 113 | + |
| 114 | + def test_token_refresh_failure_raises_error(self, requests_mock, |
| 115 | + test_instance, token_server_post): |
| 116 | + """ |
| 117 | + Failure to fetch a token can raise a number of errors including: |
| 118 | + - requests.exceptions.HTTPError for invalid access_token |
| 119 | + - oauthlib.oauth2.rfc6749.errors.InvalidClientError for invalid |
| 120 | + credentials |
| 121 | + - oauthlib.oauth2.rfc6749.errors.MissingTokenError for failure to |
| 122 | + fetch a token |
| 123 | + One error that can arise from this client itself is failure to fetch |
| 124 | + a new valid token in response to token expiration. This test asserts |
| 125 | + that the client will not allow more than successive 3 retries. |
| 126 | + """ |
| 127 | + requests_mock.get(f'{BASE_URL}/foo', json={'foo': 'bar'}) |
| 128 | + |
| 129 | + token_response = dict(_TOKEN_RESPONSE) |
| 130 | + token_response['expires_in'] = 0 |
| 131 | + token_server_post = requests_mock\ |
| 132 | + .post(TOKEN_URL, text=json.dumps(token_response)) |
| 133 | + |
| 134 | + with pytest.raises(Oauth2ApiClientError): |
| 135 | + test_instance._do_http_method('GET', 'foo') |
| 136 | + # Expect 1 initial token fetch, plus 3 retries: |
| 137 | + assert len(token_server_post.request_history) == 4 |
0 commit comments