def setUp(self): self.process = new_server_process() self.host = find_test_server_host( docker_image, find_host_address_potentials(docker_image)) config = Config() print( "RPC test ready:\n\tserver: %s\n\tcloud host: %r\n\tapi key: '***%s'\n\timage: %s" % ( self.host, config.get('host', 'default'), config.get('api_key', 'default')[-5:], docker_image, ))
def test_config_file_from_env(self): # fully define a config at a custom location, and verify it is loaded with TempConf(dict(api_key=self.dummy_key, host=self.dummy_host)): c = Config() self.assertEqual(self.dummy_key, c.get('api_key')) self.assertIn('dummy_host_url', c['host']) # verify custom config reaches the internal api a = ConnectAPI() self.assertIn( self.dummy_key, str(a.apis[EndpointsApi].api_client.configuration.api_key))
def test_config_from_envvar(self): # fully define a config at a custom location # as well as setting config through environment with TempConf(dict(api_key='not this one', host=self.dummy_host)): os.environ.setdefault(configuration.ENVVAR_API_KEY, self.dummy_key) c = Config() self.assertEqual(self.dummy_key, c.get('api_key')) self.assertIn('dummy_host_url', c['host']) # verify custom config reaches the internal api a = ConnectAPI() self.assertIn( self.dummy_key, str(a.apis[EndpointsApi].api_client.configuration.api_key))
class BaseAPI(object): """BaseAPI is parent class for all APIs. Ensuring config is valid and available.""" api_structure = {} def __init__(self, params=None): """Ensure the config is valid and has all required fields.""" self.config = Config(params) self.apis = {} self.api_clients = {} for api_parent_class, child_classes in self.api_structure.items(): self._init_api(api_parent_class, child_classes) def _get_api(self, api_class): return self.apis.get(api_class, None) def _init_api(self, api_parent_class, apis): api_client = api_parent_class.ApiClient() self.api_clients[api_parent_class] = api_client api_client.configuration.__class__._default = None # disable codegen's singleton behaviour api_client.user_agent = "mbed-cloud-sdk-python/{sdk_ver} ({pfm}) Python/{py_ver}".format( sdk_ver=__version__, pfm=platform.platform(), py_ver=platform.python_version()) api_client.configuration.api_key_prefix['Authorization'] = 'Bearer' api_client.configuration.safe_chars_for_path_param = "/" # don't encode (resource paths) self._update_api_client(api_parent_class) self.apis.update({api_cls: api_cls(api_client) for api_cls in apis}) def _update_api_client(self, api_parent_class=None): """Updates the ApiClient object of specified parent api (or all of them)""" clients = ([self.api_clients[api_parent_class]] if api_parent_class else self.api_clients.values()) for api_client in clients: api_client.configuration.host = (self.config.get('host') or api_client.configuration.host) api_client.configuration.api_key['Authorization'] = self.config[ 'api_key'] def _verify_sort_options(self, kwargs): if kwargs.get('order'): order = kwargs.get('order').upper() if order not in ["ASC", "DESC"]: raise ValueError( "Key 'order' needs to be either 'ASC' or 'DESC'. " "Currently: %r" % order) kwargs['order'] = order if kwargs.get('limit') is not None: if kwargs.get('limit') < 2 or kwargs.get('limit') > 1000: raise ValueError("Limit needs to be between 2 and 1000. " "Currently: %r" % kwargs.get('limit')) return kwargs def _verify_filters(self, kwargs, obj, encode=False): """Legacy entrypoint with 'encode' flag""" return (filters.legacy_filter_formatter if encode else filters.filter_formatter)(kwargs, obj._get_attributes_map()) def get_last_api_metadata(self): """Get meta data for the last Mbed Cloud API call. :returns: meta data of the last Mbed Cloud API call :rtype: ApiMetadata """ last_metadata = None for key, api in iteritems(self.apis): api_client = api.api_client if api_client is not None: metadata = api_client.get_last_metadata() if metadata is not None and metadata.get('timestamp', None) is not None: if last_metadata is None: last_metadata = metadata elif metadata["timestamp"] >= last_metadata["timestamp"]: last_metadata = metadata if last_metadata is not None: last_metadata = ApiMetadata(last_metadata.get("url"), last_metadata.get("method"), last_metadata.get("response", None), last_metadata.get("return_data", None), last_metadata.get("exception", None)) return last_metadata
class BaseAPI(object): """BaseAPI is parent class for all APIs. Ensuring config is valid and available.""" api_structure = {} def __init__(self, params=None): """A module to access this section of the Pelion Device Management API. :param params: Dictionary to override configuration values """ self.config = Config(params) self.apis = {} self.api_clients = {} for api_parent_class, child_classes in self.api_structure.items(): self._init_api(api_parent_class, child_classes) def _get_api(self, api_class): return self.apis.get(api_class, None) def _init_api(self, api_parent_class, apis): api_client = api_parent_class.ApiClient() self.api_clients[api_parent_class] = api_client api_client.user_agent = utils.get_user_agent() api_client.configuration.api_key_prefix['Authorization'] = 'Bearer' api_client.configuration.safe_chars_for_path_param = "/" # don't encode (resource paths) self._update_api_client(api_parent_class) self.apis.update({api_cls: api_cls(api_client) for api_cls in apis}) def _update_api_client(self, api_parent_class=None): """Updates the ApiClient object of specified parent api (or all of them)""" clients = ([self.api_clients[api_parent_class]] if api_parent_class else self.api_clients.values()) for api_client in clients: api_client.configuration.host = (self.config.get('host') or api_client.configuration.host) api_client.configuration.api_key['Authorization'] = self.config[ 'api_key'] def _verify_sort_options(self, kwargs): if kwargs.get('order'): order = kwargs.get('order').upper() if order not in ["ASC", "DESC"]: raise ValueError( "Key 'order' needs to be either 'ASC' or 'DESC'. " "Currently: %r" % order) kwargs['order'] = order if kwargs.get('limit') is not None: if kwargs.get('limit') < 2 or kwargs.get('limit') > 1000: raise ValueError("Limit needs to be between 2 and 1000. " "Currently: %r" % kwargs.get('limit')) return kwargs def _verify_filters(self, kwargs, obj, encode=False): """Legacy entrypoint with 'encode' flag""" return (filters.legacy_filter_formatter if encode else filters.filter_formatter)(kwargs, obj._get_attributes_map()) def get_last_api_metadata(self): """Get meta data for the last Pelion Device Management API call. :returns: meta data of the last Pelion Device Management API call :rtype: ApiMetadata """ last_metadata = None for key, api in iteritems(self.apis): api_client = api.api_client if api_client is not None: metadata = api_client.get_last_metadata() if metadata is not None and metadata.get('timestamp', None) is not None: if last_metadata is None: last_metadata = metadata elif metadata["timestamp"] >= last_metadata["timestamp"]: last_metadata = metadata if last_metadata is not None: last_metadata = ApiMetadata(last_metadata.get("url"), last_metadata.get("method"), last_metadata.get("response", None), last_metadata.get("return_data", None), last_metadata.get("exception", None)) return last_metadata