1+ import os
12import json
23import pytest
34from requests_oauthlib import OAuth2Session
@@ -22,7 +23,6 @@ class TestPlatformApiClient:
2223 @pytest .fixture
2324 def test_instance (self , requests_mock ):
2425 token_url = 'https://oauth.example.com/oauth/token'
25-
2626 requests_mock .post (token_url , text = json .dumps (_TOKEN_RESPONSE ))
2727
2828 return PlatformApiClient (base_url = BASE_URL ,
@@ -31,6 +31,25 @@ def test_instance(self, requests_mock):
3131 client_secret = 'clientsecret'
3232 )
3333
34+ def test_uses_env_vars (self ):
35+ env = {
36+ 'NYPL_API_CLIENT_ID' : 'env client id' ,
37+ 'NYPL_API_CLIENT_SECRET' : 'env client secret' ,
38+ 'NYPL_API_TOKEN_URL' : 'env token url' ,
39+ 'NYPL_API_BASE_URL' : 'env base url'
40+ }
41+ for key , value in env .items ():
42+ os .environ [key ] = value
43+
44+ client = PlatformApiClient ()
45+ assert client .client_id == 'env client id'
46+ assert client .client_secret == 'env client secret'
47+ assert client .token_url == 'env token url'
48+ assert client .base_url == 'env base url'
49+
50+ for key , value in env .items ():
51+ os .environ [key ] = ''
52+
3453 def test_generate_access_token (self , test_instance ):
3554 test_instance ._generate_access_token ()
3655 assert test_instance .token ['access_token' ]\
@@ -44,3 +63,29 @@ def test_do_http_method(self, requests_mock, test_instance):
4463 requests_mock .get (f'{ BASE_URL } /foo' , json = {'foo' : 'bar' })
4564 resp = test_instance ._do_http_method ('GET' , 'foo' )
4665 assert resp == {'foo' : 'bar' }
66+
67+ def test_token_expiration (self , requests_mock , test_instance ):
68+ api_get_mock = requests_mock .get (f'{ BASE_URL } /foo' ,
69+ json = {'foo' : 'bar' })
70+
71+ # Perform first request to auto-authenticate:
72+ resp = test_instance ._do_http_method ('GET' , 'foo' )
73+ assert api_get_mock .request_history [0 ]._request \
74+ .headers ['Authorization' ] == 'Bearer super-secret-token'
75+
76+ # Emulate token expiration:
77+ test_instance .token ['expires_at' ] = 0
78+
79+ token_post_mock = requests_mock .post (
80+ test_instance .token_url ,
81+ text = json .dumps (_TOKEN_RESPONSE )
82+ )
83+
84+ # Perform second request, which should detect token expiration and
85+ # re-authenticate:
86+ resp = test_instance ._do_http_method ('GET' , 'foo' )
87+
88+ assert token_post_mock .called is True
89+ assert api_get_mock .request_history [1 ]._request \
90+ .headers ['Authorization' ] == 'Bearer super-secret-token'
91+ assert resp == {'foo' : 'bar' }
0 commit comments