diff --git a/sdk/cosmos/azure-cosmos/HISTORY.md b/sdk/cosmos/azure-cosmos/HISTORY.md index 46198db224a1..ef98bba54d26 100644 --- a/sdk/cosmos/azure-cosmos/HISTORY.md +++ b/sdk/cosmos/azure-cosmos/HISTORY.md @@ -1,5 +1,9 @@ # Change Log azure-cosmos +## Version 4.0.0b5 + +- azure.cosmos.errors module deprecated and replaced by azure.cosmos.exceptions + ## Version 4.0.0b4: - Added support for a `timeout` keyword argument to all operations to specify an absolute timeout in seconds diff --git a/sdk/cosmos/azure-cosmos/README.md b/sdk/cosmos/azure-cosmos/README.md index bfb8b304d3e4..b9eb642a9669 100644 --- a/sdk/cosmos/azure-cosmos/README.md +++ b/sdk/cosmos/azure-cosmos/README.md @@ -63,7 +63,7 @@ export ACCOUNT_KEY=$(az cosmosdb list-keys --resource-group $RES_GROUP --name $A Once you've populated the `ACCOUNT_URI` and `ACCOUNT_KEY` environment variables, you can create the [CosmosClient][ref_cosmosclient]. ```Python -from azure.cosmos import CosmosClient, PartitionKey, errors +from azure.cosmos import CosmosClient, PartitionKey, exceptions import os url = os.environ['ACCOUNT_URI'] @@ -104,7 +104,7 @@ After authenticating your [CosmosClient][ref_cosmosclient], you can work with an database_name = 'testDatabase' try: database = client.create_database(database_name) -except errors.CosmosResourceExistsError: +except exceptions.CosmosResourceExistsError: database = client.get_database_client(database_name) ``` @@ -116,9 +116,9 @@ This example creates a container with default settings. If a container with the container_name = 'products' try: container = database.create_container(id=container_name, partition_key=PartitionKey(path="/productName")) -except errors.CosmosResourceExistsError: +except exceptions.CosmosResourceExistsError: container = database.get_container_client(container_name) -except errors.CosmosHttpResponseError: +except exceptions.CosmosHttpResponseError: raise ``` @@ -230,7 +230,7 @@ For more information on TTL, see [Time to Live for Azure Cosmos DB data][cosmos_ ### General -When you interact with Cosmos DB using the Python SDK, errors returned by the service correspond to the same HTTP status codes returned for REST API requests: +When you interact with Cosmos DB using the Python SDK, exceptions returned by the service correspond to the same HTTP status codes returned for REST API requests: [HTTP Status Codes for Azure Cosmos DB][cosmos_http_status_codes] @@ -239,7 +239,7 @@ For example, if you try to create a container using an ID (name) that's already ```Python try: database.create_container(id=container_name, partition_key=PartitionKey(path="/productName") -except errors.CosmosResourceExistsError: +except exceptions.CosmosResourceExistsError: print("""Error creating container HTTP status code 409: The ID (name) provided for the container is already in use. The container name must be unique within the database.""") @@ -279,7 +279,7 @@ For more extensive documentation on the Cosmos DB service, see the [Azure Cosmos [ref_cosmosclient_create_database]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.html#azure.cosmos.CosmosClient.create_database [ref_cosmosclient]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.html#azure.cosmos.CosmosClient [ref_database]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.html#azure.cosmos.DatabaseProxy -[ref_httpfailure]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.errors.html#azure.cosmos.errors.CosmosHttpResponseError +[ref_httpfailure]: https://azure.github.io/azure-sdk-for-python/ref/azure.cosmos.exceptions.html#azure.cosmos.exceptions.CosmosHttpResponseError [sample_database_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/cosmos/azure-cosmos/samples/DatabaseManagement [sample_document_mgmt]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/cosmos/azure-cosmos/samples/DocumentManagement [sample_examples_misc]: https://github.com/Azure/azure-sdk-for-python/tree/master/sdk/cosmos/azure-cosmos/samples/examples.py diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_default_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_default_retry_policy.py index 0d8a8c7eb9ac..225c69f54775 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_default_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_default_retry_policy.py @@ -67,7 +67,7 @@ def needsRetry(self, error_code): def ShouldRetry(self, exception): """Returns true if should retry based on the passed-in exception. - :param (errors.CosmosHttpResponseError instance) exception: + :param (exceptions.CosmosHttpResponseError instance) exception: :rtype: boolean diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_endpoint_discovery_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_endpoint_discovery_retry_policy.py index 2f773de8735a..2ab110a5e8c8 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_endpoint_discovery_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_endpoint_discovery_retry_policy.py @@ -61,7 +61,7 @@ def __init__(self, connection_policy, global_endpoint_manager, *args): def ShouldRetry(self, exception): # pylint: disable=unused-argument """Returns true if should retry based on the passed-in exception. - :param (errors.CosmosHttpResponseError instance) exception: + :param (exceptions.CosmosHttpResponseError instance) exception: :rtype: boolean diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/execution_dispatcher.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/execution_dispatcher.py index 49a5c14befb5..5884887c9d29 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/execution_dispatcher.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_execution_context/execution_dispatcher.py @@ -24,7 +24,7 @@ import json from six.moves import xrange -from azure.cosmos.errors import CosmosHttpResponseError +from azure.cosmos.exceptions import CosmosHttpResponseError from azure.cosmos._execution_context import multi_execution_aggregator from azure.cosmos._execution_context.base_execution_context import _QueryExecutionContextBase from azure.cosmos._execution_context.base_execution_context import _DefaultQueryExecutionContext diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py index acfab1059022..64964bfb1fcf 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_global_endpoint_manager.py @@ -27,7 +27,7 @@ from six.moves.urllib.parse import urlparse from . import _constants as constants -from . import errors +from . import exceptions from ._location_cache import LocationCache # pylint: disable=protected-access @@ -126,13 +126,13 @@ def _GetDatabaseAccount(self, **kwargs): # specified (by creating a locational endpoint) and keeping eating the exception # until we get the database account and return None at the end, if we are not able # to get that info from any endpoints - except errors.CosmosHttpResponseError: + except exceptions.CosmosHttpResponseError: for location_name in self.PreferredLocations: locational_endpoint = _GlobalEndpointManager.GetLocationalEndpoint(self.DefaultEndpoint, location_name) try: database_account = self._GetDatabaseAccountStub(locational_endpoint, **kwargs) return database_account - except errors.CosmosHttpResponseError: + except exceptions.CosmosHttpResponseError: pass return None diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_resource_throttle_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_resource_throttle_retry_policy.py index e21454ec7792..7abdbe27de5f 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_resource_throttle_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_resource_throttle_retry_policy.py @@ -36,7 +36,7 @@ def __init__(self, max_retry_attempt_count, fixed_retry_interval_in_milliseconds def ShouldRetry(self, exception): """Returns true if should retry based on the passed-in exception. - :param (errors.CosmosHttpResponseError instance) exception: + :param (exceptions.CosmosHttpResponseError instance) exception: :rtype: boolean diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py index ef67a7b69fbd..4360ab740c36 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_retry_utility.py @@ -27,7 +27,7 @@ from azure.core.exceptions import AzureError, ClientAuthenticationError from azure.core.pipeline.policies import RetryPolicy -from . import errors +from . import exceptions from . import _endpoint_discovery_retry_policy from . import _resource_throttle_retry_policy from . import _default_retry_policy @@ -85,7 +85,7 @@ def Execute(client, global_endpoint_manager, function, *args, **kwargs): ] = resourceThrottle_retry_policy.cummulative_wait_time_in_milliseconds return result - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: retry_policy = None if e.status_code == StatusCodes.FORBIDDEN and e.sub_status == SubStatusCodes.WRITE_FORBIDDEN: retry_policy = endpointDiscovery_retry_policy @@ -121,7 +121,7 @@ def Execute(client, global_endpoint_manager, function, *args, **kwargs): if client_timeout: kwargs['timeout'] = client_timeout - (time.time() - start_time) if kwargs['timeout'] <= 0: - raise errors.CosmosClientTimeoutError() + raise exceptions.CosmosClientTimeoutError() def ExecuteFunction(function, *args, **kwargs): @@ -134,7 +134,7 @@ def _configure_timeout(request, absolute, per_request): # type: (azure.core.pipeline.PipelineRequest, Optional[int], int) -> Optional[AzureError] if absolute is not None: if absolute <= 0: - raise errors.CosmosClientTimeoutError() + raise exceptions.CosmosClientTimeoutError() if per_request: # Both socket timeout and client timeout have been provided - use the shortest value. request.context.options['connection_timeout'] = min(per_request, absolute) @@ -161,7 +161,7 @@ def send(self, request): :return: Returns the PipelineResponse or raises error if maximum retries exceeded. :rtype: ~azure.core.pipeline.PipelineResponse :raises ~azure.core.exceptions.AzureError: Maximum retries exceeded. - :raises ~azure.cosmos.errors.CosmosClientTimeoutError: Specified timeout exceeded. + :raises ~azure.cosmos.exceptions.CosmosClientTimeoutError: Specified timeout exceeded. :raises ~azure.core.exceptions.ClientAuthenticationError: Authentication failed. """ absolute_timeout = request.context.options.pop('timeout', None) @@ -187,7 +187,7 @@ def send(self, request): # the authentication policy failed such that the client's request can't # succeed--we'll never have a response to it, so propagate the exception raise - except errors.CosmosClientTimeoutError as timeout_error: + except exceptions.CosmosClientTimeoutError as timeout_error: timeout_error.inner_exception = retry_error timeout_error.response = response timeout_error.history = retry_settings['history'] diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_session.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_session.py index dd1a573eaa4a..4b31eb59d857 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_session.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_session.py @@ -29,7 +29,7 @@ from . import _base from . import http_constants from ._vector_session_token import VectorSessionToken -from .errors import CosmosHttpResponseError +from .exceptions import CosmosHttpResponseError class SessionContainer(object): diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_session_retry_policy.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_session_retry_policy.py index 01ae7778a7f4..a0b3718a1652 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_session_retry_policy.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_session_retry_policy.py @@ -62,7 +62,7 @@ def __init__(self, endpoint_discovery_enable, global_endpoint_manager, *args): def ShouldRetry(self, _exception): """Returns true if should retry based on the passed-in exception. - :param (errors.CosmosHttpResponseError instance) exception: + :param (exceptions.CosmosHttpResponseError instance) exception: :rtype: boolean diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py index f697f72f66c8..00716020cc97 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_synchronized_request.py @@ -30,7 +30,7 @@ from azure.core.exceptions import DecodeError # type: ignore from . import documents -from . import errors +from . import exceptions from . import http_constants from . import _retry_utility @@ -103,7 +103,7 @@ def _Request(global_endpoint_manager, request_params, connection_policy, pipelin if client_timeout is not None: kwargs['timeout'] = client_timeout - (time.time() - start_time) if kwargs['timeout'] <= 0: - raise errors.CosmosClientTimeoutError() + raise exceptions.CosmosClientTimeoutError() if request_params.endpoint_override: base_url = request_params.endpoint_override @@ -161,13 +161,13 @@ def _Request(global_endpoint_manager, request_params, connection_policy, pipelin data = data.decode("utf-8") if response.status_code == 404: - raise errors.CosmosResourceNotFoundError(message=data, response=response) + raise exceptions.CosmosResourceNotFoundError(message=data, response=response) if response.status_code == 409: - raise errors.CosmosResourceExistsError(message=data, response=response) + raise exceptions.CosmosResourceExistsError(message=data, response=response) if response.status_code == 412: - raise errors.CosmosAccessConditionFailedError(message=data, response=response) + raise exceptions.CosmosAccessConditionFailedError(message=data, response=response) if response.status_code >= 400: - raise errors.CosmosHttpResponseError(message=data, response=response) + raise exceptions.CosmosHttpResponseError(message=data, response=response) result = None if is_media: diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/_vector_session_token.py b/sdk/cosmos/azure-cosmos/azure/cosmos/_vector_session_token.py index 675f0801632d..378377efeddc 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/_vector_session_token.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/_vector_session_token.py @@ -22,7 +22,7 @@ """Session Consistency Tracking in the Azure Cosmos database service. """ -from . import errors +from . import exceptions from .http_constants import StatusCodes @@ -120,7 +120,7 @@ def merge(self, other): raise ValueError("Invalid Session Token (should not be None)") if self.version == other.version and len(self.local_lsn_by_region) != len(other.local_lsn_by_region): - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.INTERNAL_SERVER_ERROR, message=("Compared session tokens '%s' and '%s' have unexpected regions." % (self.session_token, other.session_token)) @@ -147,7 +147,7 @@ def merge(self, other): if local_lsn2 is not None: highest_local_lsn_by_region[region_id] = max(local_lsn1, local_lsn2) elif self.version == other.version: - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.INTERNAL_SERVER_ERROR, message=("Compared session tokens '%s' and '%s' have unexpected regions." % (self.session_token, other.session_token)) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/container.py b/sdk/cosmos/azure-cosmos/azure/cosmos/container.py index 875c4e65335a..fa0a2be31330 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/container.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/container.py @@ -29,7 +29,7 @@ from ._cosmos_client_connection import CosmosClientConnection from ._base import build_options -from .errors import CosmosResourceNotFoundError +from .exceptions import CosmosResourceNotFoundError from .http_constants import StatusCodes from .offer import Offer from .scripts import ScriptsProxy @@ -127,7 +127,7 @@ def read( :param populate_quota_info: Enable returning collection storage quota information in response headers. :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata - :raises ~azure.cosmos.errors.CosmosHttpResponseError: Raised if the container couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Raised if the container couldn't be retrieved. This includes if the container does not exist. :returns: Dict representing the retrieved container. :rtype: dict[str, Any] @@ -173,7 +173,7 @@ def read_item( :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: Dict representing the item to be retrieved. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The given item couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given item couldn't be retrieved. :rtype: dict[str, Any] .. admonition:: Example: @@ -392,7 +392,7 @@ def replace_item( :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A dict representing the item after replace went through. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The replace failed or the item with + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The replace failed or the item with given id does not exist. :rtype: dict[str, Any] """ @@ -438,7 +438,7 @@ def upsert_item( :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A dict representing the upserted item. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The given item could not be upserted. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given item could not be upserted. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -483,7 +483,7 @@ def create_item( :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A dict representing the new item. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: Item with the given ID already exists. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Item with the given ID already exists. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -530,8 +530,8 @@ def delete_item( :param post_trigger_include: trigger id to be used as post operation trigger. :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The item wasn't deleted successfully. - :raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The item does not exist in the container. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The item wasn't deleted successfully. + :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The item does not exist in the container. :rtype: None """ request_options = build_options(kwargs) @@ -558,7 +558,7 @@ def read_offer(self, **kwargs): :param response_hook: a callable invoked with the response metadata :returns: Offer for the container. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: No offer exists for the container or + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No offer exists for the container or the offer could not be retrieved. :rtype: ~azure.cosmos.Offer """ @@ -589,7 +589,7 @@ def replace_throughput(self, throughput, **kwargs): :param throughput: The throughput to be set (an integer). :param response_hook: a callable invoked with the response metadata :returns: Offer for the container, updated with new throughput. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: No offer exists for the container + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: No offer exists for the container or the offer could not be updated. :rtype: ~azure.cosmos.Offer """ @@ -694,7 +694,7 @@ def get_conflict(self, conflict, partition_key, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A dict representing the retrieved conflict. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The given conflict couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The given conflict couldn't be retrieved. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -719,8 +719,8 @@ def delete_conflict(self, conflict, partition_key, **kwargs): :param partition_key: Partition key for the conflict to delete. :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The conflict wasn't deleted successfully. - :raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The conflict does not exist in the container. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The conflict wasn't deleted successfully. + :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The conflict does not exist in the container. :rtype: None """ request_options = build_options(kwargs) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py b/sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py index c7065f8f8e5b..5258b4d3196f 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/cosmos_client.py @@ -32,7 +32,7 @@ from ._retry_utility import ConnectionRetryPolicy from .database import DatabaseProxy from .documents import ConnectionPolicy, DatabaseAccount -from .errors import CosmosResourceNotFoundError +from .exceptions import CosmosResourceNotFoundError __all__ = ("CosmosClient",) @@ -261,7 +261,7 @@ def create_database( # pylint: disable=redefined-builtin :param Callable response_hook: a callable invoked with the response metadata :returns: A DatabaseProxy instance representing the new database. :rtype: ~azure.cosmos.DatabaseProxy - :raises ~azure.cosmos.errors.CosmosResourceExistsError: Database with the given ID already exists. + :raises ~azure.cosmos.exceptions.CosmosResourceExistsError: Database with the given ID already exists. .. admonition:: Example: @@ -315,7 +315,7 @@ def create_database_if_not_exists( # pylint: disable=redefined-builtin :param Callable response_hook: a callable invoked with the response metadata :returns: A DatabaseProxy instance representing the database. :rtype: ~azure.cosmos.DatabaseProxy - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The database read or creation failed. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The database read or creation failed. """ try: database_proxy = self.get_database_client(id) @@ -461,7 +461,7 @@ def delete_database( :param request_options: Dictionary of additional properties to be used for the request. :type request_options: dict[str, Any] :param Callable response_hook: a callable invoked with the response metadata - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the database couldn't be deleted. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the database couldn't be deleted. :rtype: None """ request_options = build_options(kwargs) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/database.py b/sdk/cosmos/azure-cosmos/azure/cosmos/database.py index 41eef9799339..cb12fb47fcd5 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/database.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/database.py @@ -32,7 +32,7 @@ from .container import ContainerProxy from .offer import Offer from .http_constants import StatusCodes -from .errors import CosmosResourceNotFoundError +from .exceptions import CosmosResourceNotFoundError from .user import UserProxy __all__ = ("DatabaseProxy",) @@ -121,7 +121,7 @@ def read(self, populate_query_metrics=None, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :rtype: Dict[Str, Any] - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given database couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given database couldn't be retrieved. """ # TODO this helper function should be extracted from CosmosClient from .cosmos_client import CosmosClient @@ -174,7 +174,7 @@ def create_container( :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A `ContainerProxy` instance representing the new container. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The container creation failed. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The container creation failed. :rtype: ~azure.cosmos.ContainerProxy .. admonition:: Example: @@ -258,7 +258,7 @@ def create_container_if_not_exists( :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A `ContainerProxy` instance representing the container. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The container read or creation failed. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The container read or creation failed. :rtype: ~azure.cosmos.ContainerProxy """ @@ -301,7 +301,7 @@ def delete_container( :param populate_query_metrics: Enable returning query metrics in response headers. :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the container couldn't be deleted. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the container couldn't be deleted. :rtype: None """ request_options = build_options(kwargs) @@ -451,7 +451,7 @@ def replace_container( :param populate_query_metrics: Enable returning query metrics in response headers. :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata - :raises ~azure.cosmos.errors.CosmosHttpResponseError: Raised if the container couldn't be replaced. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: Raised if the container couldn't be replaced. This includes if the container with given id does not exist. :returns: A `ContainerProxy` instance representing the container after replace completed. :rtype: ~azure.cosmos.ContainerProxy @@ -557,7 +557,7 @@ def get_user_client(self, user): :param user: The ID (name), dict representing the properties or :class:`UserProxy` instance of the user to be retrieved. :returns: A `UserProxy` instance representing the retrieved user. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given user couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given user couldn't be retrieved. :rtype: ~azure.cosmos.UserProxy """ if isinstance(user, UserProxy): @@ -581,7 +581,7 @@ def create_user(self, body, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A `UserProxy` instance representing the new user. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given user couldn't be created. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given user couldn't be created. :rtype: ~azure.cosmos.UserProxy .. admonition:: Example: @@ -618,7 +618,7 @@ def upsert_user(self, body, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A `UserProxy` instance representing the upserted user. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given user could not be upserted. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given user could not be upserted. :rtype: ~azure.cosmos.UserProxy """ request_options = build_options(kwargs) @@ -652,7 +652,7 @@ def replace_user( :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A `UserProxy` instance representing the user after replace went through. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the replace failed or the user with given + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the user with given id does not exist. :rtype: ~azure.cosmos.UserProxy """ @@ -683,8 +683,8 @@ def delete_user(self, user, **kwargs): instance of the user to be deleted. :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The user wasn't deleted successfully. - :raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The user does not exist in the container. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The user wasn't deleted successfully. + :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The user does not exist in the container. :rtype: None """ request_options = build_options(kwargs) @@ -704,7 +704,7 @@ def read_offer(self, **kwargs): :param response_hook: a callable invoked with the response metadata :returns: Offer for the database. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If no offer exists for the database or if the + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If no offer exists for the database or if the offer could not be retrieved. :rtype: ~azure.cosmos.Offer """ @@ -735,7 +735,7 @@ def replace_throughput(self, throughput, **kwargs): :param throughput: The throughput to be set (an integer). :param response_hook: a callable invoked with the response metadata :returns: Offer for the database, updated with new throughput. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If no offer exists for the database or if the + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If no offer exists for the database or if the offer could not be updated. :rtype: ~azure.cosmos.Offer """ diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/errors.py b/sdk/cosmos/azure-cosmos/azure/cosmos/errors.py index 698924ef3013..a158e9bb32d4 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/errors.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/errors.py @@ -19,57 +19,13 @@ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE # SOFTWARE. -"""PyCosmos Exceptions in the Azure Cosmos database service. +"""PyCosmos Exceptions in the Azure Cosmos database service. (Deprecated module) """ -from azure.core.exceptions import ( # type: ignore # pylint: disable=unused-import - AzureError, - HttpResponseError, - ResourceExistsError, - ResourceNotFoundError -) -from . import http_constants - - -class CosmosHttpResponseError(HttpResponseError): - """Raised when a HTTP request to the Azure Cosmos has failed.""" - - def __init__(self, status_code=None, message=None, response=None, **kwargs): - """ - :param int status_code: HTTP response code. - :param str message: Error message. - """ - self.headers = response.headers if response else {} - self.sub_status = None - self.http_error_message = message - status = status_code or (int(response.status_code) if response else 0) - - if http_constants.HttpHeaders.SubStatus in self.headers: - self.sub_status = int(self.headers[http_constants.HttpHeaders.SubStatus]) - formatted_message = "Status code: %d Sub-status: %d\n%s" % (status, self.sub_status, str(message)) - else: - formatted_message = "Status code: %d\n%s" % (status, str(message)) - - super(CosmosHttpResponseError, self).__init__(message=formatted_message, response=response, **kwargs) - self.status_code = status - +import warnings -class CosmosResourceNotFoundError(ResourceNotFoundError, CosmosHttpResponseError): - """An error response with status code 404.""" +from .exceptions import * # pylint: disable=wildcard-import, unused-wildcard-import - -class CosmosResourceExistsError(ResourceExistsError, CosmosHttpResponseError): - """An error response with status code 409.""" - - -class CosmosAccessConditionFailedError(CosmosHttpResponseError): - """An error response with status code 412.""" - - -class CosmosClientTimeoutError(AzureError): - """An operation failed to complete within the specified timeout.""" - - def __init__(self, **kwargs): - message = "Client operation failed to complete within specified timeout." - self.response = None - self.history = None - super(CosmosClientTimeoutError, self).__init__(message, **kwargs) +warnings.warn( + "azure.cosmos.errors modeuls is deprecated, use azure.cosmos.exceptions instead", + DeprecationWarning +) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/exceptions.py b/sdk/cosmos/azure-cosmos/azure/cosmos/exceptions.py new file mode 100644 index 000000000000..698924ef3013 --- /dev/null +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/exceptions.py @@ -0,0 +1,75 @@ +# The MIT License (MIT) +# Copyright (c) 2014 Microsoft Corporation + +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# in the Software without restriction, including without limitation the rights +# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +# copies of the Software, and to permit persons to whom the Software is +# furnished to do so, subject to the following conditions: + +# The above copyright notice and this permission notice shall be included in all +# copies or substantial portions of the Software. + +# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +# SOFTWARE. + +"""PyCosmos Exceptions in the Azure Cosmos database service. +""" +from azure.core.exceptions import ( # type: ignore # pylint: disable=unused-import + AzureError, + HttpResponseError, + ResourceExistsError, + ResourceNotFoundError +) +from . import http_constants + + +class CosmosHttpResponseError(HttpResponseError): + """Raised when a HTTP request to the Azure Cosmos has failed.""" + + def __init__(self, status_code=None, message=None, response=None, **kwargs): + """ + :param int status_code: HTTP response code. + :param str message: Error message. + """ + self.headers = response.headers if response else {} + self.sub_status = None + self.http_error_message = message + status = status_code or (int(response.status_code) if response else 0) + + if http_constants.HttpHeaders.SubStatus in self.headers: + self.sub_status = int(self.headers[http_constants.HttpHeaders.SubStatus]) + formatted_message = "Status code: %d Sub-status: %d\n%s" % (status, self.sub_status, str(message)) + else: + formatted_message = "Status code: %d\n%s" % (status, str(message)) + + super(CosmosHttpResponseError, self).__init__(message=formatted_message, response=response, **kwargs) + self.status_code = status + + +class CosmosResourceNotFoundError(ResourceNotFoundError, CosmosHttpResponseError): + """An error response with status code 404.""" + + +class CosmosResourceExistsError(ResourceExistsError, CosmosHttpResponseError): + """An error response with status code 409.""" + + +class CosmosAccessConditionFailedError(CosmosHttpResponseError): + """An error response with status code 412.""" + + +class CosmosClientTimeoutError(AzureError): + """An operation failed to complete within the specified timeout.""" + + def __init__(self, **kwargs): + message = "Client operation failed to complete within specified timeout." + self.response = None + self.history = None + super(CosmosClientTimeoutError, self).__init__(message, **kwargs) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/scripts.py b/sdk/cosmos/azure-cosmos/azure/cosmos/scripts.py index 8cb9e95d3b82..2cc4cb4efcef 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/scripts.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/scripts.py @@ -107,7 +107,7 @@ def get_stored_procedure(self, sproc, **kwargs): :param sproc: The ID (name) or dict representing stored procedure to retrieve. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the retrieved stored procedure. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given stored procedure couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given stored procedure couldn't be retrieved. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -125,7 +125,7 @@ def create_stored_procedure(self, body, **kwargs): :param body: A dict-like object representing the sproc to create. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the new stored procedure. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given stored procedure couldn't be created. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given stored procedure couldn't be created. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -143,7 +143,7 @@ def replace_stored_procedure(self, sproc, body, **kwargs): :param body: A dict-like object representing the sproc to replace. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the stored procedure after replace went through. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the replace failed or the stored + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the stored procedure with given id does not exist. :rtype: dict[str, Any] """ @@ -163,8 +163,8 @@ def delete_stored_procedure(self, sproc, **kwargs): :param sproc: The ID (name) or dict representing stored procedure to be deleted. :param request_options: Dictionary of additional properties to be used for the request. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The sproc wasn't deleted successfully. - :raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The sproc does not exist in the container. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The sproc wasn't deleted successfully. + :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The sproc does not exist in the container. :rtype: None """ request_options = build_options(kwargs) @@ -191,7 +191,7 @@ def execute_stored_procedure( :param partition_key: Specifies the partition key to indicate which partition the sproc should execute on. :param request_options: Dictionary of additional properties to be used for the request. :returns: Result of the executed stored procedure for the given parameters. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the stored procedure execution failed + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the stored procedure execution failed or if the stored procedure with given id does not exists in the container. :rtype: dict[str, Any] """ @@ -262,7 +262,7 @@ def get_trigger(self, trigger, **kwargs): :param trigger: The ID (name) or dict representing trigger to retrieve. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the retrieved trigger. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given trigger couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given trigger couldn't be retrieved. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -280,7 +280,7 @@ def create_trigger(self, body, **kwargs): :param body: A dict-like object representing the trigger to create. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the new trigger. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given trigger couldn't be created. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given trigger couldn't be created. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -298,7 +298,7 @@ def replace_trigger(self, trigger, body, **kwargs): :param body: A dict-like object representing the trigger to replace. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the trigger after replace went through. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the replace failed or the trigger with given + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the trigger with given id does not exist. :rtype: dict[str, Any] """ @@ -318,8 +318,8 @@ def delete_trigger(self, trigger, **kwargs): :param trigger: The ID (name) or dict representing trigger to be deleted. :param request_options: Dictionary of additional properties to be used for the request. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The trigger wasn't deleted successfully. - :raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The trigger does not exist in the container. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The trigger wasn't deleted successfully. + :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The trigger does not exist in the container. :rtype: None """ request_options = build_options(kwargs) @@ -377,7 +377,7 @@ def get_user_defined_function(self, udf, **kwargs): :param udf: The ID (name) or dict representing udf to retrieve. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the retrieved user defined function. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given user defined function couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the user defined function couldn't be retrieved. :rtype: Iterable[dict[str, Any]] """ request_options = build_options(kwargs) @@ -395,7 +395,7 @@ def create_user_defined_function(self, body, **kwargs): :param body: A dict-like object representing the udf to create. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the new user defined function. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given user defined function couldn't be created. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the user defined function couldn't be created. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -413,8 +413,8 @@ def replace_user_defined_function(self, udf, body, **kwargs): :param body: A dict-like object representing the udf to replace. :param request_options: Dictionary of additional properties to be used for the request. :returns: A dict representing the user defined function after replace went through. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the replace failed or the user defined function with - given id does not exist. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the user defined function + with the given id does not exist. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -433,8 +433,8 @@ def delete_user_defined_function(self, udf, **kwargs): :param udf: The ID (name) or dict representing udf to be deleted. :param request_options: Dictionary of additional properties to be used for the request. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The udf wasn't deleted successfully. - :raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The UDF does not exist in the container. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The udf wasn't deleted successfully. + :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The UDF does not exist in the container. :rtype: None """ request_options = build_options(kwargs) diff --git a/sdk/cosmos/azure-cosmos/azure/cosmos/user.py b/sdk/cosmos/azure-cosmos/azure/cosmos/user.py index 9352d6755582..601713957345 100644 --- a/sdk/cosmos/azure-cosmos/azure/cosmos/user.py +++ b/sdk/cosmos/azure-cosmos/azure/cosmos/user.py @@ -72,7 +72,7 @@ def read(self, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A :class:`UserProxy` instance representing the retrieved user. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given user couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given user couldn't be retrieved. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -157,7 +157,7 @@ def get_permission(self, permission, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A dict representing the retrieved permission. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given permission couldn't be retrieved. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given permission couldn't be retrieved. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -189,7 +189,7 @@ def create_permission(self, body, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A dict representing the new permission. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given permission couldn't be created. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given permission couldn't be created. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -221,7 +221,7 @@ def upsert_permission(self, body, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A dict representing the upserted permission. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the given permission could not be upserted. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the given permission could not be upserted. :rtype: dict[str, Any] """ request_options = build_options(kwargs) @@ -254,7 +254,7 @@ def replace_permission(self, permission, body, **kwargs): :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata :returns: A dict representing the permission after replace went through. - :raises ~azure.cosmos.errors.CosmosHttpResponseError: If the replace failed or the permission + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: If the replace failed or the permission with given id does not exist. :rtype: dict[str, Any] """ @@ -286,8 +286,8 @@ def delete_permission(self, permission, **kwargs): instance of the permission to be replaced. :param request_options: Dictionary of additional properties to be used for the request. :param response_hook: a callable invoked with the response metadata - :raises ~azure.cosmos.errors.CosmosHttpResponseError: The permission wasn't deleted successfully. - :raises ~azure.cosmos.errors.CosmosResourceNotFoundError: The permission does not exist for the user. + :raises ~azure.cosmos.exceptions.CosmosHttpResponseError: The permission wasn't deleted successfully. + :raises ~azure.cosmos.exceptions.CosmosResourceNotFoundError: The permission does not exist for the user. :rtype: None """ request_options = build_options(kwargs) diff --git a/sdk/cosmos/azure-cosmos/samples/ChangeFeedManagement/Program.py b/sdk/cosmos/azure-cosmos/samples/ChangeFeedManagement/Program.py index 1056c146bdbd..4b5aa8306020 100644 --- a/sdk/cosmos/azure-cosmos/samples/ChangeFeedManagement/Program.py +++ b/sdk/cosmos/azure-cosmos/samples/ChangeFeedManagement/Program.py @@ -1,6 +1,6 @@ import azure.cosmos.documents as documents import azure.cosmos.cosmos_client as cosmos_client -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions import azure.cosmos.partition_key as partition_key import datetime import uuid @@ -74,7 +74,7 @@ def run_sample(): # setup database for this sample try: db = client.create_database(id=DATABASE_ID) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: pass # setup container for this sample @@ -85,7 +85,7 @@ def run_sample(): ) print('Container with id \'{0}\' created'.format(CONTAINER_ID)) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('Container with id \'{0}\' was found'.format(CONTAINER_ID)) ChangeFeedManagement.CreateItems(container, 100) @@ -94,10 +94,10 @@ def run_sample(): # cleanup database after sample try: client.delete_database(db) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: pass - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: print('\nrun_sample has caught an error. {0}'.format(e.message)) finally: diff --git a/sdk/cosmos/azure-cosmos/samples/CollectionManagement/Program.py b/sdk/cosmos/azure-cosmos/samples/CollectionManagement/Program.py index fa877125c4e0..55fc594e2b1d 100644 --- a/sdk/cosmos/azure-cosmos/samples/CollectionManagement/Program.py +++ b/sdk/cosmos/azure-cosmos/samples/CollectionManagement/Program.py @@ -1,5 +1,5 @@ import azure.cosmos.cosmos_client as cosmos_client -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.partition_key import PartitionKey import samples.Shared.config as cfg @@ -92,7 +92,7 @@ def create_Container(db, id): db.create_container(id=id, partition_key=partition_key) print('Container with id \'{0}\' created'.format(id)) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('A container with id \'{0}\' already exists'.format(id)) print("\n2.2 Create Container - With custom index policy") @@ -116,7 +116,7 @@ def create_Container(db, id): print('IndexPolicy Mode - \'{0}\''.format(properties['indexingPolicy']['indexingMode'])) print('IndexPolicy Automatic - \'{0}\''.format(properties['indexingPolicy']['automatic'])) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('A container with id \'{0}\' already exists'.format(coll['id'])) print("\n2.3 Create Container - With custom offer throughput") @@ -130,7 +130,7 @@ def create_Container(db, id): ) print('Container with id \'{0}\' created'.format(container.id)) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('A container with id \'{0}\' already exists'.format(coll['id'])) print("\n2.4 Create Container - With Unique keys") @@ -146,7 +146,7 @@ def create_Container(db, id): print('Container with id \'{0}\' created'.format(container.id)) print('Unique Key Paths - \'{0}\', \'{1}\''.format(unique_key_paths[0], unique_key_paths[1])) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('A container with id \'container_unique_keys\' already exists') print("\n2.5 Create Collection - With Partition key V2 (Default)") @@ -160,7 +160,7 @@ def create_Container(db, id): print('Container with id \'{0}\' created'.format(container.id)) print('Partition Key - \'{0}\''.format(properties['partitionKey'])) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('A container with id \'collection_partition_key_v2\' already exists') print("\n2.6 Create Collection - With Partition key V1") @@ -174,7 +174,7 @@ def create_Container(db, id): print('Container with id \'{0}\' created'.format(container.id)) print('Partition Key - \'{0}\''.format(properties['partitionKey'])) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('A container with id \'collection_partition_key_v1\' already exists') @staticmethod @@ -195,7 +195,7 @@ def manage_offer_throughput(db, id): print('Found Offer \'{0}\' for Container \'{1}\' and its throughput is \'{2}\''.format(offer.properties['id'], container.id, offer.properties['content']['offerThroughput'])) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('A container with id \'{0}\' does not exist'.format(id)) print("\n3.2 Change Offer Throughput of Container") @@ -214,7 +214,7 @@ def read_Container(db, id): container = db.get_container_client(id) print('Container with id \'{0}\' was found, it\'s link is {1}'.format(container.id, container.container_link)) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print('A container with id \'{0}\' does not exist'.format(id)) @staticmethod @@ -240,7 +240,7 @@ def delete_Container(db, id): print('Container with id \'{0}\' was deleted'.format(id)) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print('A container with id \'{0}\' does not exist'.format(id)) def run_sample(): @@ -251,7 +251,7 @@ def run_sample(): try: db = client.create_database(id=DATABASE_ID) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: db = client.get_database_client(DATABASE_ID) # query for a container @@ -276,10 +276,10 @@ def run_sample(): try: client.delete_database(db) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: pass - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: print('\nrun_sample has caught an error. {0}'.format(e.message)) finally: diff --git a/sdk/cosmos/azure-cosmos/samples/DatabaseManagement/Program.py b/sdk/cosmos/azure-cosmos/samples/DatabaseManagement/Program.py index f1535c93961b..b5ca2c6ad29e 100644 --- a/sdk/cosmos/azure-cosmos/samples/DatabaseManagement/Program.py +++ b/sdk/cosmos/azure-cosmos/samples/DatabaseManagement/Program.py @@ -1,5 +1,5 @@ import azure.cosmos.cosmos_client as cosmos_client -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions import samples.Shared.config as cfg @@ -68,7 +68,7 @@ def create_database(client, id): client.create_database(id=id) print('Database with id \'{0}\' created'.format(id)) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('A database with id \'{0}\' already exists'.format(id)) @staticmethod @@ -79,7 +79,7 @@ def read_database(client, id): database = client.get_database_client(id) print('Database with id \'{0}\' was found, it\'s link is {1}'.format(id, database.database_link)) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print('A database with id \'{0}\' does not exist'.format(id)) @staticmethod @@ -105,7 +105,7 @@ def delete_database(client, id): print('Database with id \'{0}\' was deleted'.format(id)) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print('A database with id \'{0}\' does not exist'.format(id)) def run_sample(): @@ -126,7 +126,7 @@ def run_sample(): # delete database by id DatabaseManagement.delete_database(client, DATABASE_ID) - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: print('\nrun_sample has caught an error. {0}'.format(e.message)) finally: diff --git a/sdk/cosmos/azure-cosmos/samples/DocumentManagement/Program.py b/sdk/cosmos/azure-cosmos/samples/DocumentManagement/Program.py index 31f2953f3dae..6e666fc77fe5 100644 --- a/sdk/cosmos/azure-cosmos/samples/DocumentManagement/Program.py +++ b/sdk/cosmos/azure-cosmos/samples/DocumentManagement/Program.py @@ -1,5 +1,5 @@ import azure.cosmos.cosmos_client as cosmos_client -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.partition_key import PartitionKey import datetime @@ -179,7 +179,7 @@ def run_sample(): try: db = client.create_database(id=DATABASE_ID) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: pass # setup container for this sample @@ -187,7 +187,7 @@ def run_sample(): container = db.create_container(id=CONTAINER_ID, partition_key=PartitionKey(path='/id', kind='Hash')) print('Container with id \'{0}\' created'.format(CONTAINER_ID)) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('Container with id \'{0}\' was found'.format(CONTAINER_ID)) ItemManagement.CreateItems(container) @@ -202,10 +202,10 @@ def run_sample(): try: client.delete_database(db) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: pass - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: print('\nrun_sample has caught an error. {0}'.format(e.message)) finally: diff --git a/sdk/cosmos/azure-cosmos/samples/IndexManagement/Program.py b/sdk/cosmos/azure-cosmos/samples/IndexManagement/Program.py index d4a945ac699b..44d75cc56760 100644 --- a/sdk/cosmos/azure-cosmos/samples/IndexManagement/Program.py +++ b/sdk/cosmos/azure-cosmos/samples/IndexManagement/Program.py @@ -1,6 +1,6 @@ import azure.cosmos.documents as documents import azure.cosmos.cosmos_client as cosmos_client -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.partition_key import PartitionKey import requests import traceback @@ -72,7 +72,7 @@ def Query_Entities(parent, entity_type, id = None): entities = list(parent.read_all_items()) else: entities = list(parent.query_items(find_entity_by_id_query)) - except errors.AzureError as e: + except exceptions.AzureError as e: print("The following error occured while querying for the entity / entities ", entity_type, id if id != None else "") print(e) raise @@ -90,7 +90,7 @@ def CreateDatabaseIfNotExists(client, database_id): return client.create_database(id=database_id) else: return client.get_database_client(database_id) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: pass @@ -98,9 +98,9 @@ def DeleteContainerIfExists(db, collection_id): try: db.delete_container(collection_id) print('Collection with id \'{0}\' was deleted'.format(collection_id)) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: pass - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: if e.status_code == 400: print("Bad request for collection link", collection_id) raise @@ -128,9 +128,9 @@ def QueryDocumentsWithCustomQuery(container, query_with_optional_parameters, mes for doc in results: print(doc) return results - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Document doesn't exist") - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: if e.status_code == 400: # Can occur when we are trying to query on excluded paths print("Bad Request exception occured: ", e) @@ -194,9 +194,9 @@ def ExplicitlyExcludeFromIndex(db): # Cleanup db.delete_container(created_Container) print("\n") - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print("Entity already exists") - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Entity doesn't exist") @@ -256,9 +256,9 @@ def UseManualIndexing(db): # Cleanup db.delete_container(created_Container) print("\n") - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print("Entity already exists") - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Entity doesn't exist") @@ -329,9 +329,9 @@ def ExcludePathsFromIndex(db): # Cleanup db.delete_container(created_Container) print("\n") - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print("Entity already exists") - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Entity doesn't exist") @@ -391,9 +391,9 @@ def RangeScanOnHashIndex(db): # Cleanup db.delete_container(created_Container) print("\n") - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print("Entity already exists") - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Entity doesn't exist") @@ -478,9 +478,9 @@ def UseRangeIndexesOnStrings(db): # Cleanup db.delete_container(created_Container) print("\n") - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print("Entity already exists") - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Entity doesn't exist") @@ -537,9 +537,9 @@ def PerformIndexTransformations(db): # Cleanup db.delete_container(created_Container) print("\n") - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print("Entity already exists") - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Entity doesn't exist") @@ -628,9 +628,9 @@ def PerformMultiOrderbyQuery(db): # Cleanup db.delete_container(created_container) print("\n") - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print("Entity already exists") - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Entity doesn't exist") @@ -664,7 +664,7 @@ def RunIndexDemo(): # 8. Perform Multi Orderby queries using composite indexes PerformMultiOrderbyQuery(created_db) - except errors.AzureError as e: + except exceptions.AzureError as e: raise e if __name__ == '__main__': diff --git a/sdk/cosmos/azure-cosmos/samples/MultiMasterOperations/ConflictWorker.py b/sdk/cosmos/azure-cosmos/samples/MultiMasterOperations/ConflictWorker.py index 40f64026ebec..6bdc3b2e6cc7 100644 --- a/sdk/cosmos/azure-cosmos/samples/MultiMasterOperations/ConflictWorker.py +++ b/sdk/cosmos/azure-cosmos/samples/MultiMasterOperations/ConflictWorker.py @@ -2,7 +2,7 @@ import time from multiprocessing.pool import ThreadPool import json -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.http_constants import StatusCodes class ConflictWorker(object): @@ -27,7 +27,7 @@ def initialize_async(self): database = None try: database = create_client.ReadDatabase("dbs/" + self.database_name) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("database not found, needs to be created.") if not database: @@ -119,14 +119,14 @@ def initialize_async(self): } try: lww_sproc = create_client.CreateStoredProcedure("dbs/" + self.database_name+ "/colls/" + self.udp_collection_name, lww_sproc) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: return def try_create_document_collection (self, client, database, collection): read_collection = None try: read_collection = client.ReadContainer("dbs/" + database['id'] + "/colls/" + collection['id']) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("collection not found, needs to be created.") if read_collection == None: @@ -473,14 +473,14 @@ def run_delete_conflict_on_UDP_async(self): def try_insert_document(self, client, collection_uri, document): try: return client.CreateItem(collection_uri, document) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: return None def try_update_document(self, client, collection_uri, document, options): try: options['partitionKey'] = document['id'] return client.ReplaceItem(collection_uri + "/docs/" + document['id'], document, options); - except (errors.CosmosResourceNotFoundError, errors.CosmosAccessConditionFailedError): + except (exceptions.CosmosResourceNotFoundError, exceptions.CosmosAccessConditionFailedError): # Lost synchronously or no document yet. No conflict is induced. return None @@ -489,7 +489,7 @@ def try_delete_document(self, client, collection_uri, document, options): options['partitionKey'] = document['id'] client.DeleteItem(collection_uri + "/docs/" + document['id'], options) return document - except (errors.CosmosResourceNotFoundError, errors.CosmosAccessConditionFailedError): + except (exceptions.CosmosResourceNotFoundError, exceptions.CosmosAccessConditionFailedError): #Lost synchronously. No conflict is induced. return None @@ -591,10 +591,10 @@ def validate_LWW_async_internal(self, client, conflict_document, has_delete_conf (conflict_document[0]['id'], client.ReadEndpoint)) time.sleep(0.5) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Delete conflict won @ %s" % client.ReadEndpoint) return - except errors.CosmosHttpResponseError: + except exceptions.CosmosHttpResponseError: self.trace_error("Delete conflict for document %s didnt win @ %s" % (conflict_document[0]['id'], client.ReadEndpoint)) @@ -622,7 +622,7 @@ def validate_LWW_async_internal(self, client, conflict_document, has_delete_conf (int(winner_document["regionId"]), client.WriteEndpoint)) time.sleep(0.5) - except errors.AzureError as e: + except exceptions.AzureError as e: self.trace_error("Winner document from region %d is not found @ %s, retrying..." % (int(winner_document["regionId"]), client.WriteEndpoint)) @@ -655,10 +655,10 @@ def validate_UDP_async_internal(self, client, conflict_document, has_delete_conf (conflict_document[0]['id'], client.ReadEndpoint)) time.sleep(0.5) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: print("Delete conflict won @ %s" % client.ReadEndpoint) return - except errors.CosmosHttpResponseError: + except exceptions.CosmosHttpResponseError: self.trace_error("Delete conflict for document %s didnt win @ %s" % (conflict_document[0]['id'], client.ReadEndpoint)) time.sleep(0.5) @@ -685,7 +685,7 @@ def validate_UDP_async_internal(self, client, conflict_document, has_delete_conf (int(winner_document['regionId']), client.WriteEndpoint)) time.sleep(0.5) - except errors.AzureError: + except exceptions.AzureError: self.trace_error("Winner document from region %d is not found @ %s, retrying..." % (int(winner_document['regionId']), client.WriteEndpoint)) time.sleep(0.5) diff --git a/sdk/cosmos/azure-cosmos/samples/MultiMasterOperations/Worker.py b/sdk/cosmos/azure-cosmos/samples/MultiMasterOperations/Worker.py index 38af9a920314..c8d1dc1640bf 100644 --- a/sdk/cosmos/azure-cosmos/samples/MultiMasterOperations/Worker.py +++ b/sdk/cosmos/azure-cosmos/samples/MultiMasterOperations/Worker.py @@ -1,6 +1,6 @@ import uuid import time -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.http_constants import StatusCodes class Worker(object): @@ -62,9 +62,9 @@ def delete_all_async(self): while doc: try: self.client.DeleteItem(doc['_self'], {'partitionKey': doc['id']}) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: raise - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: print("Error occurred while deleting document from %s" % self.client.WriteEndpoint) doc = next(it, None) diff --git a/sdk/cosmos/azure-cosmos/samples/NonPartitionedCollectionOperations/Program.py b/sdk/cosmos/azure-cosmos/samples/NonPartitionedCollectionOperations/Program.py index 5be4ad1345a9..cdc75f3723c1 100644 --- a/sdk/cosmos/azure-cosmos/samples/NonPartitionedCollectionOperations/Program.py +++ b/sdk/cosmos/azure-cosmos/samples/NonPartitionedCollectionOperations/Program.py @@ -20,7 +20,7 @@ #SOFTWARE. import azure.cosmos.cosmos_client as cosmos_client -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions import requests import six import json @@ -285,7 +285,7 @@ def run_sample(): # setup database for this sample try: db = client.create_database(id=DATABASE_ID) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: db = client.get_database_client(DATABASE_ID) # setup container for this sample @@ -293,7 +293,7 @@ def run_sample(): container, document = ItemManagement.CreateNonPartitionedCollection(db) print('Container with id \'{0}\' created'.format(CONTAINER_ID)) - except errors.CosmosResourceExistsError: + except exceptions.CosmosResourceExistsError: print('Container with id \'{0}\' was found'.format(CONTAINER_ID)) # Read Item created in non partitioned collection using older API version @@ -308,10 +308,10 @@ def run_sample(): # cleanup database after sample try: client.delete_database(db) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: pass - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: print('\nrun_sample has caught an error. {0}'.format(e.message)) finally: diff --git a/sdk/cosmos/azure-cosmos/samples/examples.py b/sdk/cosmos/azure-cosmos/samples/examples.py index ef20ef5f31bc..162203071c62 100644 --- a/sdk/cosmos/azure-cosmos/samples/examples.py +++ b/sdk/cosmos/azure-cosmos/samples/examples.py @@ -5,7 +5,7 @@ # All interaction with Cosmos DB starts with an instance of the CosmosClient # [START create_client] -from azure.cosmos import errors, CosmosClient, PartitionKey +from azure.cosmos import exceptions, CosmosClient, PartitionKey import os @@ -21,7 +21,7 @@ database_name = "testDatabase" try: database = client.create_database(id=database_name) -except errors.CosmosResourceExistsError: +except exceptions.CosmosResourceExistsError: database = client.get_database_client(database=database_name) # [END create_database] @@ -33,7 +33,7 @@ container = database.create_container( id=container_name, partition_key=PartitionKey(path="/productName") ) -except errors.CosmosResourceExistsError: +except exceptions.CosmosResourceExistsError: container = database.get_container_client(container_name) # [END create_container] @@ -47,7 +47,7 @@ partition_key=PartitionKey(path="/city"), default_ttl=200, ) -except errors.CosmosResourceExistsError: +except exceptions.CosmosResourceExistsError: customer_container = database.get_container_client(customer_container_name) # [END create_container_with_settings] @@ -138,8 +138,8 @@ # [START create_user] try: database.create_user(dict(id="Walter Harp")) -except errors.CosmosResourceExistsError: +except exceptions.CosmosResourceExistsError: print("A user with that ID already exists.") -except errors.CosmosHttpResponseError as failure: +except exceptions.CosmosHttpResponseError as failure: print("Failed to create user. Status code:{}".format(failure.status_code)) # [END create_user] diff --git a/sdk/cosmos/azure-cosmos/test/aggregate_tests.py b/sdk/cosmos/azure-cosmos/test/aggregate_tests.py index 15e7f687d765..dc32684aa057 100644 --- a/sdk/cosmos/azure-cosmos/test/aggregate_tests.py +++ b/sdk/cosmos/azure-cosmos/test/aggregate_tests.py @@ -31,7 +31,7 @@ import azure.cosmos.cosmos_client as cosmos_client import azure.cosmos.documents as documents import test_config -from azure.cosmos.errors import CosmosHttpResponseError +from azure.cosmos.exceptions import CosmosHttpResponseError from azure.cosmos.partition_key import PartitionKey pytestmark = pytest.mark.cosmosEmulator diff --git a/sdk/cosmos/azure-cosmos/test/conftest.py b/sdk/cosmos/azure-cosmos/test/conftest.py index cbb2191bc775..a838918fcbb0 100644 --- a/sdk/cosmos/azure-cosmos/test/conftest.py +++ b/sdk/cosmos/azure-cosmos/test/conftest.py @@ -24,7 +24,7 @@ import pytest import test_config import azure.cosmos.cosmos_client as cosmos_client -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.http_constants import StatusCodes database_ids_to_delete = [] @@ -48,7 +48,7 @@ def delete_database(): for database_id in database_ids_to_delete: try: client.delete_database(database_id) - except errors.CosmosResourceNotFoundError: + except exceptions.CosmosResourceNotFoundError: pass del database_ids_to_delete[:] print("Clean up completed!") diff --git a/sdk/cosmos/azure-cosmos/test/crud_tests.py b/sdk/cosmos/azure-cosmos/test/crud_tests.py index 4bb00b7c78de..dd751cf223d2 100644 --- a/sdk/cosmos/azure-cosmos/test/crud_tests.py +++ b/sdk/cosmos/azure-cosmos/test/crud_tests.py @@ -45,7 +45,7 @@ from azure.core.pipeline.transport import RequestsTransport, RequestsTransportResponse from azure.cosmos import _consistent_hash_ring import azure.cosmos.documents as documents -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.http_constants import HttpHeaders, StatusCodes, SubStatusCodes import azure.cosmos._murmur_hash as _murmur_hash import test_config @@ -110,7 +110,7 @@ def __AssertHTTPFailureWithStatus(self, status_code, func, *args, **kwargs): try: func(*args, **kwargs) self.assertFalse(True, 'function should fail.') - except errors.CosmosHttpResponseError as inst: + except exceptions.CosmosHttpResponseError as inst: self.assertEqual(inst.status_code, status_code) @classmethod @@ -2066,7 +2066,7 @@ def initialize_client_with_connection_core_retry_config(self, retries): return end_time - start_time def test_absolute_client_timeout(self): - with self.assertRaises(errors.CosmosClientTimeoutError): + with self.assertRaises(exceptions.CosmosClientTimeoutError): cosmos_client.CosmosClient( "https://localhost:9999", CRUDTests.masterKey, @@ -2079,29 +2079,29 @@ def test_absolute_client_timeout(self): client = cosmos_client.CosmosClient( self.host, self.masterKey, "Session", transport=timeout_transport, passthrough=True) - with self.assertRaises(errors.CosmosClientTimeoutError): + with self.assertRaises(exceptions.CosmosClientTimeoutError): client.create_database_if_not_exists("test", timeout=2) status_response = 500 # Users connection level retry timeout_transport = TimeoutTransport(status_response) client = cosmos_client.CosmosClient( self.host, self.masterKey, "Session", transport=timeout_transport, passthrough=True) - with self.assertRaises(errors.CosmosClientTimeoutError): + with self.assertRaises(exceptions.CosmosClientTimeoutError): client.create_database("test", timeout=2) databases = client.list_databases(timeout=2) - with self.assertRaises(errors.CosmosClientTimeoutError): + with self.assertRaises(exceptions.CosmosClientTimeoutError): list(databases) status_response = 429 # Uses Cosmos custom retry timeout_transport = TimeoutTransport(status_response) client = cosmos_client.CosmosClient( self.host, self.masterKey, "Session", transport=timeout_transport, passthrough=True) - with self.assertRaises(errors.CosmosClientTimeoutError): + with self.assertRaises(exceptions.CosmosClientTimeoutError): client.create_database_if_not_exists("test", timeout=2) databases = client.list_databases(timeout=2) - with self.assertRaises(errors.CosmosClientTimeoutError): + with self.assertRaises(exceptions.CosmosClientTimeoutError): list(databases) def test_query_iterable_functionality(self): diff --git a/sdk/cosmos/azure-cosmos/test/globaldb_mock_tests.py b/sdk/cosmos/azure-cosmos/test/globaldb_mock_tests.py index 98e9e2e68bb7..0cf275108644 100644 --- a/sdk/cosmos/azure-cosmos/test/globaldb_mock_tests.py +++ b/sdk/cosmos/azure-cosmos/test/globaldb_mock_tests.py @@ -25,7 +25,7 @@ import azure.cosmos._cosmos_client_connection as cosmos_client_connection import azure.cosmos.documents as documents -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions import azure.cosmos._constants as constants from azure.cosmos.http_constants import StatusCodes import azure.cosmos._global_endpoint_manager as global_endpoint_manager @@ -152,13 +152,13 @@ def MockExecuteFunction(self, function, *args, **kwargs): else: self.endpoint_discovery_retry_count += 1 location_changed = True - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.FORBIDDEN, message="Forbidden", response=test_config.FakeResponse({'x-ms-substatus' : 3})) def MockGetDatabaseAccountStub(self, endpoint): - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.SERVICE_UNAVAILABLE, message="Service unavailable") def MockCreateDatabase(self, client, database): diff --git a/sdk/cosmos/azure-cosmos/test/globaldb_tests.py b/sdk/cosmos/azure-cosmos/test/globaldb_tests.py index 00c29b334532..467a0de40e6d 100644 --- a/sdk/cosmos/azure-cosmos/test/globaldb_tests.py +++ b/sdk/cosmos/azure-cosmos/test/globaldb_tests.py @@ -28,7 +28,7 @@ import azure.cosmos._cosmos_client_connection as cosmos_client_connection import azure.cosmos.documents as documents -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions import azure.cosmos._global_endpoint_manager as global_endpoint_manager from azure.cosmos import _endpoint_discovery_retry_policy from azure.cosmos import _retry_utility @@ -72,7 +72,7 @@ def __AssertHTTPFailureWithStatus(self, status_code, sub_status, func, *args, ** try: func(*args, **kwargs) self.assertFalse(True, 'function should fail.') - except errors.CosmosHttpResponseError as inst: + except exceptions.CosmosHttpResponseError as inst: self.assertEqual(inst.status_code, status_code) self.assertEqual(inst.sub_status, sub_status) @@ -386,7 +386,7 @@ def test_globaldb_endpoint_discovery_retry_policy_mock(self): def _MockExecuteFunction(self, function, *args, **kwargs): response = test_config.FakeResponse({'x-ms-substatus' : SubStatusCodes.WRITE_FORBIDDEN}) - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.FORBIDDEN, message="Write Forbidden", response=response) diff --git a/sdk/cosmos/azure-cosmos/test/location_cache_tests.py b/sdk/cosmos/azure-cosmos/test/location_cache_tests.py index 7b5479bf22bf..9d53303ca4ea 100644 --- a/sdk/cosmos/azure-cosmos/test/location_cache_tests.py +++ b/sdk/cosmos/azure-cosmos/test/location_cache_tests.py @@ -8,7 +8,7 @@ import azure.cosmos.documents as documents from azure.cosmos._request_object import RequestObject from azure.cosmos._location_cache import LocationCache -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.http_constants import StatusCodes, SubStatusCodes, HttpHeaders from azure.cosmos import _retry_utility import test_config @@ -89,7 +89,7 @@ def validate_retry_on_session_not_availabe_with_endpoint_discovery_disabled(self else: client.CreateItem("dbs/mydb/colls/mycoll/", {'id':'1'}) self.fail() - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: # not retried self.assertEqual(self.counter, 1) self.counter = 0 @@ -102,7 +102,7 @@ def validate_retry_on_session_not_availabe_with_endpoint_discovery_disabled(self def _MockExecuteFunctionSessionReadFailureOnce(self, function, *args, **kwargs): self.counter += 1 response = test_config.FakeResponse({HttpHeaders.SubStatus: SubStatusCodes.READ_SESSION_NOTAVAILABLE}) - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.NOT_FOUND, message="Read Session not available", response=response) @@ -134,7 +134,7 @@ def validate_retry_on_session_not_availabe(self, is_preferred_locations_list_emp try: client.ReadItem("dbs/mydb/colls/mycoll/docs/1") - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: # not retried self.assertEqual(self.counter, 4 if use_multiple_write_locations else 2) self.counter = 0 @@ -167,7 +167,7 @@ def _MockExecuteFunctionSessionReadFailureTwice(self, function, *args, **kwargs) self.assertEqual(expected_endpoint, request.location_endpoint_to_route) self.counter += 1 response = test_config.FakeResponse({HttpHeaders.SubStatus: SubStatusCodes.READ_SESSION_NOTAVAILABLE}) - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.NOT_FOUND, message="Read Session not available", response=response) diff --git a/sdk/cosmos/azure-cosmos/test/retry_policy_tests.py b/sdk/cosmos/azure-cosmos/test/retry_policy_tests.py index 3523f9b6489e..e6e73698dec9 100644 --- a/sdk/cosmos/azure-cosmos/test/retry_policy_tests.py +++ b/sdk/cosmos/azure-cosmos/test/retry_policy_tests.py @@ -24,7 +24,7 @@ import azure.cosmos.cosmos_client as cosmos_client import pytest import azure.cosmos.documents as documents -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions import azure.cosmos._retry_options as retry_options from azure.cosmos.http_constants import HttpHeaders, StatusCodes, SubStatusCodes from azure.cosmos import _retry_utility @@ -58,7 +58,7 @@ def __AssertHTTPFailureWithStatus(self, status_code, func, *args, **kwargs): try: func(*args, **kwargs) self.assertFalse(True, 'function should fail.') - except errors.CosmosHttpResponseError as inst: + except exceptions.CosmosHttpResponseError as inst: self.assertEqual(inst.status_code, status_code) @classmethod @@ -88,7 +88,7 @@ def test_resource_throttle_retry_policy_default_retry_after(self): try: self.created_collection.create_item(body=document_definition) - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS) self.assertEqual(connection_policy.RetryOptions.MaxRetryAttemptCount, self.created_collection.client_connection.last_response_headers[HttpHeaders.ThrottleRetryCount]) self.assertGreaterEqual( self.created_collection.client_connection.last_response_headers[HttpHeaders.ThrottleRetryWaitTimeInMs], @@ -110,7 +110,7 @@ def test_resource_throttle_retry_policy_fixed_retry_after(self): try: self.created_collection.create_item(body=document_definition) - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS) self.assertEqual(connection_policy.RetryOptions.MaxRetryAttemptCount, self.created_collection.client_connection.last_response_headers[HttpHeaders.ThrottleRetryCount]) self.assertGreaterEqual(self.created_collection.client_connection.last_response_headers[HttpHeaders.ThrottleRetryWaitTimeInMs], @@ -133,7 +133,7 @@ def test_resource_throttle_retry_policy_max_wait_time(self): try: self.created_collection.create_item(body=document_definition) - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS) self.assertGreaterEqual(self.created_collection.client_connection.last_response_headers[HttpHeaders.ThrottleRetryWaitTimeInMs], connection_policy.RetryOptions.MaxWaitTimeInSeconds * 1000) @@ -162,7 +162,7 @@ def test_resource_throttle_retry_policy_query(self): { 'name':'@id', 'value':document_definition['id'] } ] })) - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS) self.assertEqual(connection_policy.RetryOptions.MaxRetryAttemptCount, self.created_collection.client_connection.last_response_headers[HttpHeaders.ThrottleRetryCount]) @@ -238,7 +238,7 @@ def test_default_retry_policy_for_create(self): created_document = {} try : created_document = self.created_collection.create_item(body=document_definition) - except errors.CosmosHttpResponseError as err: + except exceptions.CosmosHttpResponseError as err: self.assertEqual(err.status_code, 10054) self.assertDictEqual(created_document, {}) @@ -250,7 +250,7 @@ def test_default_retry_policy_for_create(self): def _MockExecuteFunction(self, function, *args, **kwargs): response = test_config.FakeResponse({HttpHeaders.RetryAfterInMilliseconds: self.retry_after_in_milliseconds}) - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.TOO_MANY_REQUESTS, message="Request rate is too large", response=response) @@ -267,7 +267,7 @@ def __call__(self, func, *args, **kwargs): if self.counter % 3 == 0: return self.org_func(func, *args, **kwargs) else: - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=10054, message="Connection was reset", response=test_config.FakeResponse({})) diff --git a/sdk/cosmos/azure-cosmos/test/session_tests.py b/sdk/cosmos/azure-cosmos/test/session_tests.py index c74506248f6f..85ef48ae531a 100644 --- a/sdk/cosmos/azure-cosmos/test/session_tests.py +++ b/sdk/cosmos/azure-cosmos/test/session_tests.py @@ -7,7 +7,7 @@ import azure.cosmos.cosmos_client as cosmos_client import azure.cosmos.documents as documents import test_config -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.http_constants import StatusCodes, SubStatusCodes, HttpHeaders import azure.cosmos._synchronized_request as synchronized_request from azure.cosmos import _retry_utility @@ -58,7 +58,7 @@ def test_session_token_not_sent_for_master_resource_ops (self): def _MockExecuteFunctionSessionReadFailureOnce(self, function, *args, **kwargs): response = test_config.FakeResponse({HttpHeaders.SubStatus: SubStatusCodes.READ_SESSION_NOTAVAILABLE}) - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.NOT_FOUND, message="Read Session not available", response=response) @@ -70,7 +70,7 @@ def test_clear_session_token(self): _retry_utility.ExecuteFunction = self._MockExecuteFunctionSessionReadFailureOnce try: self.created_collection.read_item(item=created_document['id'], partition_key='mypk') - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: self.assertEqual(self.client.client_connection.session.get_session_token( 'dbs/' + self.created_db.id + '/colls/' + self.created_collection.id), "") self.assertEqual(e.status_code, StatusCodes.NOT_FOUND) @@ -88,7 +88,7 @@ def test_internal_server_error_raised_for_invalid_session_token_received_from_se try: self.created_collection.create_item(body={'id': '1' + str(uuid.uuid4()), 'pk': 'mypk'}) self.fail() - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: self.assertEqual(e.http_error_message, "Could not parse the received session token: 2") self.assertEqual(e.status_code, StatusCodes.INTERNAL_SERVER_ERROR) _retry_utility.ExecuteFunction = self.OriginalExecuteFunction diff --git a/sdk/cosmos/azure-cosmos/test/session_token_unit_tests.py b/sdk/cosmos/azure-cosmos/test/session_token_unit_tests.py index 91fec45ade57..f9bdbd8f3bae 100644 --- a/sdk/cosmos/azure-cosmos/test/session_token_unit_tests.py +++ b/sdk/cosmos/azure-cosmos/test/session_token_unit_tests.py @@ -1,7 +1,7 @@ import unittest import pytest from azure.cosmos._vector_session_token import VectorSessionToken -from azure.cosmos.errors import CosmosHttpResponseError +from azure.cosmos.exceptions import CosmosHttpResponseError pytestmark = pytest.mark.cosmosEmulator diff --git a/sdk/cosmos/azure-cosmos/test/streaming_failover_test.py b/sdk/cosmos/azure-cosmos/test/streaming_failover_test.py index 2f92dd8a92f5..e984199609da 100644 --- a/sdk/cosmos/azure-cosmos/test/streaming_failover_test.py +++ b/sdk/cosmos/azure-cosmos/test/streaming_failover_test.py @@ -2,7 +2,7 @@ import azure.cosmos._cosmos_client_connection as cosmos_client_connection import pytest import azure.cosmos.documents as documents -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions import test_config from azure.cosmos.http_constants import HttpHeaders, StatusCodes, SubStatusCodes from azure.cosmos import _retry_utility @@ -85,7 +85,7 @@ def _MockExecuteFunctionEndpointDiscover(self, function, *args, **kwargs): else: self.endpoint_sequence.append(args[1].location_endpoint_to_route) response = test_config.FakeResponse({HttpHeaders.SubStatus: SubStatusCodes.WRITE_FORBIDDEN}) - raise errors.CosmosHttpResponseError( + raise exceptions.CosmosHttpResponseError( status_code=StatusCodes.FORBIDDEN, message="Request is not permitted in this region", response=response) @@ -112,7 +112,7 @@ def test_retry_policy_does_not_mark_null_locations_unavailable(self): self._write_counter = 0 request = RequestObject(http_constants.ResourceType.Document, documents._OperationType.Read) endpointDiscovery_retry_policy = _endpoint_discovery_retry_policy.EndpointDiscoveryRetryPolicy(documents.ConnectionPolicy(), endpoint_manager, request) - endpointDiscovery_retry_policy.ShouldRetry(errors.CosmosHttpResponseError( + endpointDiscovery_retry_policy.ShouldRetry(exceptions.CosmosHttpResponseError( status_code=http_constants.StatusCodes.FORBIDDEN)) self.assertEqual(self._read_counter, 0) self.assertEqual(self._write_counter, 0) @@ -121,7 +121,7 @@ def test_retry_policy_does_not_mark_null_locations_unavailable(self): self._write_counter = 0 request = RequestObject(http_constants.ResourceType.Document, documents._OperationType.Create) endpointDiscovery_retry_policy = _endpoint_discovery_retry_policy.EndpointDiscoveryRetryPolicy(documents.ConnectionPolicy(), endpoint_manager, request) - endpointDiscovery_retry_policy.ShouldRetry(errors.CosmosHttpResponseError( + endpointDiscovery_retry_policy.ShouldRetry(exceptions.CosmosHttpResponseError( status_code=http_constants.StatusCodes.FORBIDDEN)) self.assertEqual(self._read_counter, 0) self.assertEqual(self._write_counter, 0) diff --git a/sdk/cosmos/azure-cosmos/test/test_config.py b/sdk/cosmos/azure-cosmos/test/test_config.py index 82dcafff145a..832bc609fd15 100644 --- a/sdk/cosmos/azure-cosmos/test/test_config.py +++ b/sdk/cosmos/azure-cosmos/test/test_config.py @@ -23,7 +23,7 @@ import time import uuid import azure.cosmos.documents as documents -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.http_constants import StatusCodes from azure.cosmos.database import DatabaseProxy from azure.cosmos.cosmos_client import CosmosClient @@ -87,7 +87,7 @@ def try_delete_database(cls, client): # type: (CosmosClient) -> None try: client.delete_database(cls.TEST_DATABASE_ID) - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: if e.status_code != StatusCodes.NOT_FOUND: raise e @@ -162,7 +162,7 @@ def remove_all_documents(cls, document_collection, use_custom_partition_key): # sleep to ensure deletes are propagated for multimaster enabled accounts time.sleep(2) break - except errors.CosmosHttpResponseError as e: + except exceptions.CosmosHttpResponseError as e: print("Error occurred while deleting documents:" + str(e) + " \nRetrying...") diff --git a/sdk/cosmos/azure-cosmos/test/ttl_tests.py b/sdk/cosmos/azure-cosmos/test/ttl_tests.py index d14a189bf08b..699cae76be56 100644 --- a/sdk/cosmos/azure-cosmos/test/ttl_tests.py +++ b/sdk/cosmos/azure-cosmos/test/ttl_tests.py @@ -25,7 +25,7 @@ import pytest import azure.cosmos.cosmos_client as cosmos_client -import azure.cosmos.errors as errors +import azure.cosmos.exceptions as exceptions from azure.cosmos.http_constants import StatusCodes import test_config from azure.cosmos.partition_key import PartitionKey @@ -60,7 +60,7 @@ def __AssertHTTPFailureWithStatus(self, status_code, func, *args, **kwargs): try: func(*args, **kwargs) self.assertFalse(True, 'function should fail.') - except errors.CosmosHttpResponseError as inst: + except exceptions.CosmosHttpResponseError as inst: self.assertEqual(inst.status_code, status_code) @classmethod