def test_initializer(access_token, api_key, disable_auth): client = OAuth2Client(access_token=access_token, api_key=api_key, disable_auth=disable_auth) assert client.access_token is None assert client.api_key is None assert client.options["disable_auth"] is True
def test_refresh_tokens( mock_connection, mock_urlencode, init_kwargs, call_kwargs, expected_data, expected_refresh_token, ): client = OAuth2Client(**init_kwargs) client.options["connection_type"] = Mock(return_value=mock_connection) mock_connection.set_response( 200, json.dumps({ "access_token": "at123", "refresh_token": "rt123", "expires_in": 21600 }), ) client.refresh_tokens(**call_kwargs) data = mock_urlencode.last_return_value mock_connection.assert_num_requests(1) mock_connection.assert_has_request("POST", "/oauth/v1/token?", data) assert all(part in data for part in expected_data) assert client.refresh_token == expected_refresh_token
def _call_raw(self, subpath, params=None, method="GET", data=None, doseq=False, query="", retried=False, **options): opts = self.options.copy() opts.update(options) debug = opts.get("debug") url, headers, data = self._prepare_request(subpath, params, data, opts, doseq=doseq, query=query, retried=retried) if debug: print( json.dumps( { "url": url, "headers": headers, "data": data }, sort_keys=True, indent=2, )) kwargs = {"timeout": opts["timeout"]} num_retries = opts.get("number_retries", 2) # Never retry a POST, PUT, or DELETE unless explicitly told to if method != "GET" and not opts.get("retry_on_post"): num_retries = 0 if num_retries > 6: num_retries = 6 emergency_brake = 10 try_count = 0 while True: emergency_brake -= 1 # avoid getting burned by any mistakes in While loop logic if emergency_brake < 1: break try: try_count += 1 connection = opts["connection_type"](opts["api_base"], **kwargs) request_info = self._create_request(connection, method, url, headers, data) result = self._execute_request_raw(connection, request_info) break except HubspotUnauthorized: self.log.warning("401 Unauthorized response to API request.") if (self.access_token and self.refresh_token and self.client_id and self.client_secret): if retried: self.log.error( "Refreshed token, but request still was not authorized. " "You may need to grant additional permissions.") raise from hubspot3.oauth2 import OAuth2Client self.log.info("Refreshing access token") try: client = OAuth2Client(**self.options) refresh_result = client.refresh_tokens( client_id=self.client_id, client_secret=self.client_secret, refresh_token=self.refresh_token, ) self.access_token = refresh_result["access_token"] self.refresh_token = refresh_result["refresh_token"] self.log.info("Retrying with new token {}".format( self.access_token)) except Exception as exception: self.log.error( "Unable to refresh access_token: {}".format( exception)) raise return self._call_raw(subpath, params=params, method=method, data=data, doseq=doseq, query=query, retried=True, **options) if self.access_token: self.log.warning( "In order to enable automated refreshing of your access token, please " "provide a client ID, client secret and refresh token in addition to the " "access token.") raise except HubspotError as exception: if try_count > num_retries: logging.warning("Too many retries for {}".format(url)) raise # Don't retry errors from 300 to 499 if exception.result and 300 <= exception.result.status < 500: raise self._prepare_request_retry(method, url, headers, data) self.log.warning("HubspotError {} calling {}, retrying".format( exception, url)) # exponential back off # wait 0 seconds, 1 second, 3 seconds, 7 seconds, 15 seconds, etc time.sleep((pow(2, try_count - 1) - 1) * self.sleep_multiplier) return result
def oauth2(self): """returns a hubspot3 OAuth2 client""" from hubspot3.oauth2 import OAuth2Client return OAuth2Client(**self.auth, **self.options)