From f4748cc2a7e57d05774ab440e2fdbb7444d6b29c Mon Sep 17 00:00:00 2001 From: Diogo Baeder de Paula Pinto Date: Fri, 18 Dec 2015 18:52:15 -0200 Subject: [PATCH] Cleaning the previous token before fetching a new one, to avoid a TokenExpiredError --- requests_oauthlib/oauth2_session.py | 1 + tests/test_oauth2_session.py | 37 ++++++++++++++++++++++++----- 2 files changed, 32 insertions(+), 6 deletions(-) diff --git a/requests_oauthlib/oauth2_session.py b/requests_oauthlib/oauth2_session.py index 05bc24d5..9aa2e02b 100644 --- a/requests_oauthlib/oauth2_session.py +++ b/requests_oauthlib/oauth2_session.py @@ -206,6 +206,7 @@ def fetch_token(self, token_url, code=None, authorization_response=None, 'Accept': 'application/json', 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', } + self.token = {} if method.upper() == 'POST': r = self.post(token_url, data=dict(urldecode(body)), timeout=timeout, headers=headers, auth=auth, diff --git a/tests/test_oauth2_session.py b/tests/test_oauth2_session.py index 3547de1e..bb5201e9 100644 --- a/tests/test_oauth2_session.py +++ b/tests/test_oauth2_session.py @@ -2,6 +2,7 @@ import json import mock import time +from copy import deepcopy try: from unittest2 import TestCase except ImportError: @@ -18,6 +19,15 @@ fake_time = time.time() + +def fake_token(token): + def fake_send(r, **kwargs): + resp = mock.MagicMock() + resp.text = json.dumps(token) + return resp + return fake_send + + class OAuth2SessionTest(TestCase): def setUp(self): @@ -117,12 +127,6 @@ def test_token_from_fragment(self): @mock.patch("time.time", new=lambda: fake_time) def test_fetch_token(self): - def fake_token(token): - def fake_send(r, **kwargs): - resp = mock.MagicMock() - resp.text = json.dumps(token) - return resp - return fake_send url = 'https://example.com/token' for client in self.clients: @@ -136,6 +140,27 @@ def fake_send(r, **kwargs): auth.send = fake_token(error) self.assertRaises(OAuth2Error, auth.fetch_token, url) + def test_cleans_previous_token_before_fetching_new_one(self): + """Makes sure the previous token is cleaned before fetching a new one. + + The reason behind it is that, if the previous token is expired, this + method shouldn't fail with a TokenExpiredError, since it's attempting + to get a new one (which shouldn't be expired). + + """ + new_token = deepcopy(self.token) + past = time.time() - 7200 + now = time.time() + self.token['expires_at'] = past + new_token['expires_at'] = now + 3600 + url = 'https://example.com/token' + + with mock.patch('time.time', lambda: now): + for client in self.clients: + auth = OAuth2Session(client=client, token=self.token) + auth.send = fake_token(new_token) + self.assertEqual(auth.fetch_token(url), new_token) + def test_web_app_fetch_token(self): # Ensure the state parameter is used, see issue #105.