Skip to content

Commit

Permalink
#5 add connect and socket timeouts (1.25s/2.25s slightly higher than …
Browse files Browse the repository at this point in the history
…Java tokens lib)
  • Loading branch information
hjacobs committed Feb 9, 2016
1 parent a06a66f commit fa16cfc
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 3 deletions.
9 changes: 8 additions & 1 deletion tests/test_tokens.py
Original file line number Diff line number Diff line change
Expand Up @@ -102,13 +102,20 @@ def test_refresh_invalid_response(monkeypatch, tmpdir):

response = MagicMock()
response.json.return_value = {'foo': 'bar'}
monkeypatch.setattr('requests.post', lambda url, **kwargs: response)
post = MagicMock()
post.return_value = response
monkeypatch.setattr('requests.post', post)
monkeypatch.setattr('tokens.read_credentials', lambda path: (VALID_USER_JSON, VALID_CLIENT_JSON))

with pytest.raises(tokens.InvalidTokenResponse) as exc_info:
tokens.get('mytok')
assert str(exc_info.value) == """Invalid token response: Expected a JSON object with keys "expires_in" and "access_token": 'expires_in'"""

# verify that we use a proper HTTP timeout..
post.assert_called_with('https://example.org',
data={'username': 'app', 'scope': 'myscope', 'password': 'pass', 'grant_type': 'password'},
timeout=(1.25, 2.25), auth=('cid', 'sec'))

response.json.return_value = {'access_token': '', 'expires_in': 100}
with pytest.raises(tokens.InvalidTokenResponse) as exc_info:
tokens.get('mytok')
Expand Down
10 changes: 8 additions & 2 deletions tokens/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,13 @@
EXPIRATION_TOLERANCE_SECS = 60
# TODO: make time value configurable (20 minutes)?
REFRESH_BEFORE_SECS_LEFT = 20 * 60
DEFAULT_HTTP_CONNECT_TIMEOUT = 1.25
DEFAULT_HTTP_SOCKET_TIMEOUT = 2.25

CONFIG = {'url': os.environ.get('OAUTH2_ACCESS_TOKEN_URL', os.environ.get('OAUTH_ACCESS_TOKEN_URL')),
'dir': os.environ.get('CREDENTIALS_DIR', '')}
'dir': os.environ.get('CREDENTIALS_DIR', ''),
'connect_timeout': DEFAULT_HTTP_CONNECT_TIMEOUT,
'socket_timeout': DEFAULT_HTTP_SOCKET_TIMEOUT}

TOKENS = {}

Expand Down Expand Up @@ -90,6 +94,8 @@ def refresh(token_name):
token = TOKENS[token_name]
path = CONFIG['dir']
url = CONFIG['url']
# http://requests.readthedocs.org/en/master/user/advanced/#timeouts
request_timeout = CONFIG['connect_timeout'], CONFIG['socket_timeout']

if not url:
raise ConfigurationError('Missing OAuth access token URL. ' +
Expand All @@ -107,7 +113,7 @@ def refresh(token_name):
except KeyError as e:
raise InvalidCredentialsError('Missing key: {}'.format(e))

r = requests.post(url, data=body, auth=auth)
r = requests.post(url, data=body, auth=auth, timeout=request_timeout)
r.raise_for_status()
try:
data = r.json()
Expand Down

0 comments on commit fa16cfc

Please sign in to comment.