Skip to content

Commit ba46ced

Browse files
committed
Add tests of 5xx error handling.
1 parent bb90460 commit ba46ced

File tree

1 file changed

+35
-4
lines changed

1 file changed

+35
-4
lines changed

tests/test_oauth2_session.py

Lines changed: 35 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,16 +22,17 @@
2222
import requests
2323

2424
from requests.auth import _basic_auth_str
25+
from requests.exceptions import HTTPError
2526

2627

2728
fake_time = time.time()
2829
CODE = "asdf345xdf"
2930

3031

31-
def fake_token(token):
32+
def fake_token(token, status_code: int = 200):
3233
def fake_send(r, **kwargs):
3334
resp = mock.MagicMock()
34-
resp.status_code = 200
35+
resp.status_code = status_code
3536
resp.text = json.dumps(token)
3637
return resp
3738

@@ -133,11 +134,11 @@ def test_refresh_token_request(self):
133134
self.expired_token["expires_in"] = "-1"
134135
del self.expired_token["expires_at"]
135136

136-
def fake_refresh(r, **kwargs):
137+
def fake_refresh(r, status_code: int = 200, **kwargs):
137138
if "/refresh" in r.url:
138139
self.assertNotIn("Authorization", r.headers)
139140
resp = mock.MagicMock()
140-
resp.status_code = 200
141+
resp.status_code = status_code
141142
resp.text = json.dumps(self.token)
142143
return resp
143144

@@ -170,6 +171,19 @@ def token_updater(token):
170171
sess.send = fake_refresh
171172
sess.get("https://i.b")
172173

174+
# test 5xx error handler
175+
for client in self.clients:
176+
sess = OAuth2Session(
177+
client=client,
178+
token=self.expired_token,
179+
auto_refresh_url="https://i.b/refresh",
180+
token_updater=token_updater,
181+
)
182+
sess.send = lambda r, **kwargs: fake_refresh(
183+
r=r, status_code=503, kwargs=kwargs,
184+
)
185+
self.assertRaises(HTTPError, sess.get, "https://i.b")
186+
173187
def fake_refresh_with_auth(r, **kwargs):
174188
if "/refresh" in r.url:
175189
self.assertIn("Authorization", r.headers)
@@ -256,6 +270,23 @@ def test_fetch_token(self):
256270
else:
257271
self.assertRaises(OAuth2Error, sess.fetch_token, url)
258272

273+
# test 5xx error responses
274+
error = {"error": "server error!"}
275+
for client in self.clients:
276+
sess = OAuth2Session(client=client, token=self.token)
277+
sess.send = fake_token(error, status_code=500)
278+
if isinstance(client, LegacyApplicationClient):
279+
# this client requires a username+password
280+
self.assertRaises(
281+
HTTPError,
282+
sess.fetch_token,
283+
url,
284+
username="username1",
285+
password="password1",
286+
)
287+
else:
288+
self.assertRaises(HTTPError, sess.fetch_token, url)
289+
259290
# there are different scenarios in which the `client_id` can be specified
260291
# reference `oauthlib.tests.oauth2.rfc6749.clients.test_web_application.WebApplicationClientTest.test_prepare_request_body`
261292
# this only needs to test WebApplicationClient

0 commit comments

Comments
 (0)