azure-sdk-for-python
azure-sdk-for-python copied to clipboard
Question: Advice for mocking datetime
- Package Name: azure-cosmos
- Package Version: 4.2.0
- Operating System: Ubuntu 20.04
- Python Version: 3.8
Describe the bug
[May not be a bug]
What is the advice for mocking date or datetime objects whilst interacting with Cosmos?
Currently, attempts to fix the date are generating a CosmosHttpResponseError:
E azure.cosmos.exceptions.CosmosHttpResponseError: (Forbidden) The authorization token is not valid at the current time. Please create another token and retry (token start time: Sat, 01 Jan 2000 00:00:00 GMT, token expiry time: Sat, 01 Jan 2000 00:15:00 GMT, current server time: Thu, 10 Nov 2022 13:08:20 GMT).
To Reproduce Steps to reproduce the behavior:
- Install dependencies:
$ pip install azure-cosmos pytest time-machine - Create a simple test script
import time_machine
from uuid import uuid4
from azure.cosmos import CosmosClient, PartitionKey, exceptions
@time_machine.travel("2000-01-01", tick=False)
def test_fixing_a_date():
cosmos_client = CosmosClient(<URL HERE>, credential=<ACCESS KEY HERE>)
# Set database
try:
database = cosmos_client.create_database(
"ExampleDatabase"
)
except exceptions.CosmosResourceExistsError:
database = cosmos_client.get_database_client(
"ExampleDatabase"
)
# Set container
try:
container = database.create_container(
id="ExampleContainer",
partition_key=PartitionKey(path="/id")
)
except exceptions.CosmosResourceExistsError:
container = database.get_container_client(
"ExampleContainer"
)
except exceptions.CosmosHttpResponseError:
raise
item_added = container.upsert_item(
{
"id": str(uuid4()),
"example_key": "example_value"
}
)
query_result = container.query_items(
query=f'SELECT * FROM ExampleContainer c WHERE c.id="{item_added["id"]}"',
enable_cross_partition_query=True
)
document = query_result.next()
assert document["example_key"] == "example_value"
- Run with pytest:
$ pytest - Observe failure with stacktrace:
E azure.cosmos.exceptions.CosmosHttpResponseError: (Forbidden) The authorization token is not valid at the current time. Please create another token and retry (token start time: Sat, 01 Jan 2000 00:00:00 GMT, token expiry time: Sat, 01 Jan 2000 00:15:00 GMT, current server time: Thu, 10 Nov 2022 13:08:20 GMT).
E ActivityId: cc051814-4ee6-412f-96f7-d4e0bfbe065b, Microsoft.Azure.Documents.Common/2.14.0
E Code: Forbidden
E Message: The authorization token is not valid at the current time. Please create another token and retry (token start time: Sat, 01 Jan 2000 00:00:00 GMT, token expiry time: Sat, 01 Jan 2000 00:15:00 GMT, current server time: Thu, 10 Nov 2022 13:08:20 GMT).
E ActivityId: cc051814-4ee6-412f-96f7-d4e0bfbe065b, Microsoft.Azure.Documents.Common/2.14.0
venv/lib/python3.8/site-packages/azure/cosmos/_synchronized_request.py:158: CosmosHttpResponseError
Expected behavior
I would like some way of mocking date or datetime objects in unit tests that interact with Cosmos.