1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393
|
#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.
from six.moves.urllib.parse import urlparse
import six
import unittest
import time
import pytest
import azure.cosmos.cosmos_client as cosmos_client
import azure.cosmos.documents as documents
import azure.cosmos.errors as errors
import azure.cosmos.global_endpoint_manager as global_endpoint_manager
import azure.cosmos.endpoint_discovery_retry_policy as endpoint_discovery_retry_policy
import azure.cosmos.retry_utility as retry_utility
from azure.cosmos.http_constants import HttpHeaders, StatusCodes, SubStatusCodes
import test.test_config as test_config
#IMPORTANT NOTES:
# Most test cases in this file create collections in your Azure Cosmos account.
# Collections are billing entities. By running these test cases, you may incur monetary costs on your account.
# To Run the test, replace the two member fields (masterKey and host) with values
# associated with your Azure Cosmos account.
@pytest.mark.usefixtures("teardown")
class Test_globaldb_tests(unittest.TestCase):
host = test_config._test_config.global_host
write_location_host = test_config._test_config.write_location_host
read_location_host = test_config._test_config.read_location_host
read_location2_host = test_config._test_config.read_location2_host
masterKey = test_config._test_config.global_masterKey
write_location = test_config._test_config.write_location
read_location = test_config._test_config.read_location
read_location2 = test_config._test_config.read_location2
test_database_id = 'testdb'
test_collection_id = 'testcoll'
def __AssertHTTPFailureWithStatus(self, status_code, sub_status, func, *args, **kwargs):
"""Assert HTTP failure with status.
:Parameters:
- `status_code`: int
- `sub_status`: int
- `func`: function
"""
try:
func(*args, **kwargs)
self.assertFalse(True, 'function should fail.')
except errors.HTTPFailure as inst:
self.assertEqual(inst.status_code, status_code)
self.assertEqual(inst.sub_status, sub_status)
@classmethod
def setUpClass(cls):
if (cls.masterKey == '[YOUR_KEY_HERE]' or
cls.host == '[YOUR_GLOBAL_ENDPOINT_HERE]'):
raise Exception(
"You must specify your Azure Cosmos account values for "
"'masterKey' and 'host' at the top of this class to run the "
"tests.")
def setUp(self):
self.client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey})
# Create the test database only when it's not already present
query_iterable = self.client.QueryDatabases('SELECT * FROM root r WHERE r.id=\'' + Test_globaldb_tests.test_database_id + '\'')
it = iter(query_iterable)
self.test_db = next(it, None)
if self.test_db is None:
self.test_db = self.client.CreateDatabase({'id' : Test_globaldb_tests.test_database_id})
# Create the test collection only when it's not already present
query_iterable = self.client.QueryContainers(self.test_db['_self'], 'SELECT * FROM root r WHERE r.id=\'' + Test_globaldb_tests.test_collection_id + '\'')
it = iter(query_iterable)
self.test_coll = next(it, None)
if self.test_coll is None:
self.test_coll = self.client.CreateContainer(self.test_db['_self'], {'id' : Test_globaldb_tests.test_collection_id})
def tearDown(self):
# Delete all the documents created by the test case for clean up purposes
docs = list(self.client.ReadItems(self.test_coll['_self']))
for doc in docs:
self.client.DeleteItem(doc['_self'])
def test_globaldb_read_write_endpoints(self):
connection_policy = documents.ConnectionPolicy()
connection_policy.EnableEndpointDiscovery = False
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
document_definition = { 'id': 'doc',
'name': 'sample document',
'key': 'value'}
# When EnableEndpointDiscovery is False, WriteEndpoint is set to the endpoint passed while creating the client instance
created_document = client.CreateItem(self.test_coll['_self'], document_definition)
self.assertEqual(client.WriteEndpoint, Test_globaldb_tests.host)
# Delay to get these resources replicated to read location due to Eventual consistency
time.sleep(5)
client.ReadItem(created_document['_self'])
content_location = str(client.last_response_headers[HttpHeaders.ContentLocation])
content_location_url = urlparse(content_location)
host_url = urlparse(Test_globaldb_tests.host)
# When EnableEndpointDiscovery is False, ReadEndpoint is set to the endpoint passed while creating the client instance
self.assertEqual(str(content_location_url.hostname), str(host_url.hostname))
self.assertEqual(client.ReadEndpoint, Test_globaldb_tests.host)
connection_policy.EnableEndpointDiscovery = True
document_definition['id'] = 'doc2'
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
# When EnableEndpointDiscovery is True, WriteEndpoint is set to the write endpoint
created_document = client.CreateItem(self.test_coll['_self'], document_definition)
self.assertEqual(client.WriteEndpoint, Test_globaldb_tests.write_location_host)
# Delay to get these resources replicated to read location due to Eventual consistency
time.sleep(5)
client.ReadItem(created_document['_self'])
content_location = str(client.last_response_headers[HttpHeaders.ContentLocation])
content_location_url = urlparse(content_location)
write_location_url = urlparse(Test_globaldb_tests.write_location_host)
# If no preferred locations is set, we return the write endpoint as ReadEndpoint for better latency performance
self.assertEqual(str(content_location_url.hostname), str(write_location_url.hostname))
self.assertEqual(client.ReadEndpoint, Test_globaldb_tests.write_location_host)
def test_globaldb_endpoint_discovery(self):
connection_policy = documents.ConnectionPolicy()
connection_policy.EnableEndpointDiscovery = False
read_location_client = cosmos_client.CosmosClient(Test_globaldb_tests.read_location_host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
document_definition = { 'id': 'doc',
'name': 'sample document',
'key': 'value'}
# Create Document will fail for the read location client since it has EnableEndpointDiscovery set to false, and hence the request will directly go to
# the endpoint that was used to create the client instance(which happens to be a read endpoint)
self.__AssertHTTPFailureWithStatus(
StatusCodes.FORBIDDEN,
SubStatusCodes.WRITE_FORBIDDEN,
read_location_client.CreateItem,
self.test_coll['_self'],
document_definition)
# Query databases will pass for the read location client as it's a GET operation
list(read_location_client.QueryDatabases({
'query': 'SELECT * FROM root r WHERE r.id=@id',
'parameters': [
{ 'name':'@id', 'value': self.test_db['id'] }
]
}))
connection_policy.EnableEndpointDiscovery = True
read_location_client = cosmos_client.CosmosClient(Test_globaldb_tests.read_location_host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
# CreateDocument call will go to the WriteEndpoint as EnableEndpointDiscovery is set to True and client will resolve the right endpoint based on the operation
created_document = read_location_client.CreateItem(self.test_coll['_self'], document_definition)
self.assertEqual(created_document['id'], document_definition['id'])
def test_globaldb_preferred_locations(self):
connection_policy = documents.ConnectionPolicy()
connection_policy.EnableEndpointDiscovery = True
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
document_definition = { 'id': 'doc',
'name': 'sample document',
'key': 'value'}
created_document = client.CreateItem(self.test_coll['_self'], document_definition)
self.assertEqual(created_document['id'], document_definition['id'])
# Delay to get these resources replicated to read location due to Eventual consistency
time.sleep(5)
client.ReadItem(created_document['_self'])
content_location = str(client.last_response_headers[HttpHeaders.ContentLocation])
content_location_url = urlparse(content_location)
write_location_url = urlparse(Test_globaldb_tests.write_location_host)
# If no preferred locations is set, we return the write endpoint as ReadEndpoint for better latency performance
self.assertEqual(str(content_location_url.hostname), str(write_location_url.hostname))
self.assertEqual(client.ReadEndpoint, Test_globaldb_tests.write_location_host)
connection_policy.PreferredLocations = [Test_globaldb_tests.read_location2]
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
document_definition['id'] = 'doc2'
created_document = client.CreateItem(self.test_coll['_self'], document_definition)
# Delay to get these resources replicated to read location due to Eventual consistency
time.sleep(5)
client.ReadItem(created_document['_self'])
content_location = str(client.last_response_headers[HttpHeaders.ContentLocation])
content_location_url = urlparse(content_location)
read_location2_url = urlparse(Test_globaldb_tests.read_location2_host)
# Test that the preferred location is set as ReadEndpoint instead of default write endpoint when no preference is set
self.assertEqual(str(content_location_url.hostname), str(read_location2_url.hostname))
self.assertEqual(client.ReadEndpoint, Test_globaldb_tests.read_location2_host)
def test_globaldb_endpoint_assignments(self):
connection_policy = documents.ConnectionPolicy()
connection_policy.EnableEndpointDiscovery = False
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
# When EnableEndpointDiscovery is set to False, both Read and Write Endpoints point to endpoint passed while creating the client instance
self.assertEqual(client._global_endpoint_manager.WriteEndpoint, Test_globaldb_tests.host)
self.assertEqual(client._global_endpoint_manager.ReadEndpoint, Test_globaldb_tests.host)
connection_policy.EnableEndpointDiscovery = True
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
# If no preferred locations is set, we return the write endpoint as ReadEndpoint for better latency performance, write endpoint is set as expected
self.assertEqual(client._global_endpoint_manager.WriteEndpoint, Test_globaldb_tests.write_location_host)
self.assertEqual(client._global_endpoint_manager.ReadEndpoint, Test_globaldb_tests.write_location_host)
connection_policy.PreferredLocations = [Test_globaldb_tests.read_location2]
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
# Test that the preferred location is set as ReadEndpoint instead of default write endpoint when no preference is set
self.assertEqual(client._global_endpoint_manager.WriteEndpoint, Test_globaldb_tests.write_location_host)
self.assertEqual(client._global_endpoint_manager.ReadEndpoint, Test_globaldb_tests.read_location2_host)
def test_globaldb_update_locations_cache(self):
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey})
writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}]
readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}, {'name' : Test_globaldb_tests.read_location2, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location2_host}]
write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)
# If no preferred locations is set, we return the write endpoint as ReadEndpoint for better latency performance, write endpoint is set as expected
self.assertEqual(write_endpoint, Test_globaldb_tests.write_location_host)
self.assertEqual(read_endpoint, Test_globaldb_tests.write_location_host)
writable_locations = []
readable_locations = []
write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)
# If writable_locations and readable_locations are empty, both Read and Write Endpoints point to endpoint passed while creating the client instance
self.assertEqual(write_endpoint, Test_globaldb_tests.host)
self.assertEqual(read_endpoint, Test_globaldb_tests.host)
writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}]
readable_locations = []
write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)
# If there are no readable_locations, we use the write endpoint as ReadEndpoint
self.assertEqual(write_endpoint, Test_globaldb_tests.write_location_host)
self.assertEqual(read_endpoint, Test_globaldb_tests.write_location_host)
writable_locations = []
readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}]
write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)
# If there are no writable_locations, both Read and Write Endpoints point to endpoint passed while creating the client instance
self.assertEqual(write_endpoint, Test_globaldb_tests.host)
self.assertEqual(read_endpoint, Test_globaldb_tests.host)
writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}]
readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}, {'name' : Test_globaldb_tests.read_location2, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location2_host}]
connection_policy = documents.ConnectionPolicy()
connection_policy.PreferredLocations = [Test_globaldb_tests.read_location2]
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)
# Test that the preferred location is set as ReadEndpoint instead of default write endpoint when no preference is set
self.assertEqual(write_endpoint, Test_globaldb_tests.write_location_host)
self.assertEqual(read_endpoint, Test_globaldb_tests.read_location2_host)
writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}, {'name' : Test_globaldb_tests.read_location2, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location2_host}]
readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}]
connection_policy = documents.ConnectionPolicy()
connection_policy.PreferredLocations = [Test_globaldb_tests.read_location2]
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)
# Test that the preferred location is chosen from the WriteLocations if it's not present in the ReadLocations
self.assertEqual(write_endpoint, Test_globaldb_tests.write_location_host)
self.assertEqual(read_endpoint, Test_globaldb_tests.read_location2_host)
writable_locations = [{'name' : Test_globaldb_tests.write_location, 'databaseAccountEndpoint' : Test_globaldb_tests.write_location_host}]
readable_locations = [{'name' : Test_globaldb_tests.read_location, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location_host}, {'name' : Test_globaldb_tests.read_location2, 'databaseAccountEndpoint' : Test_globaldb_tests.read_location2_host}]
connection_policy.EnableEndpointDiscovery = False
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey}, connection_policy)
write_endpoint, read_endpoint = client._global_endpoint_manager.UpdateLocationsCache(writable_locations, readable_locations)
# If EnableEndpointDiscovery is False, both Read and Write Endpoints point to endpoint passed while creating the client instance
self.assertEqual(write_endpoint, Test_globaldb_tests.host)
self.assertEqual(read_endpoint, Test_globaldb_tests.host)
def test_globaldb_locational_endpoint_parser(self):
url_endpoint='https://contoso.documents.azure.com:443/'
location_name='East US'
# Creating a locational endpoint from the location name using the parser method
locational_endpoint = global_endpoint_manager._GlobalEndpointManager.GetLocationalEndpoint(url_endpoint, location_name)
self.assertEqual(locational_endpoint, 'https://contoso-EastUS.documents.azure.com:443/')
url_endpoint='https://Contoso.documents.azure.com:443/'
location_name='East US'
# Note that the host name gets lowercased as the urlparser in Python doesn't retains the casing
locational_endpoint = global_endpoint_manager._GlobalEndpointManager.GetLocationalEndpoint(url_endpoint, location_name)
self.assertEqual(locational_endpoint, 'https://contoso-EastUS.documents.azure.com:443/')
def test_globaldb_endpoint_discovery_retry_policy_mock(self):
client = cosmos_client.CosmosClient(Test_globaldb_tests.host, {'masterKey': Test_globaldb_tests.masterKey})
self.OriginalExecuteFunction = retry_utility._ExecuteFunction
retry_utility._ExecuteFunction = self._MockExecuteFunction
self.OriginalGetDatabaseAccount = client.GetDatabaseAccount
client.GetDatabaseAccount = self._MockGetDatabaseAccount
max_retry_attempt_count = 10
retry_after_in_milliseconds = 500
endpoint_discovery_retry_policy._EndpointDiscoveryRetryPolicy.Max_retry_attempt_count = max_retry_attempt_count
endpoint_discovery_retry_policy._EndpointDiscoveryRetryPolicy.Retry_after_in_milliseconds = retry_after_in_milliseconds
document_definition = { 'id': 'doc',
'name': 'sample document',
'key': 'value'}
self.__AssertHTTPFailureWithStatus(
StatusCodes.FORBIDDEN,
SubStatusCodes.WRITE_FORBIDDEN,
client.CreateItem,
self.test_coll['_self'],
document_definition)
retry_utility._ExecuteFunction = self.OriginalExecuteFunction
def _MockExecuteFunction(self, function, *args, **kwargs):
raise errors.HTTPFailure(StatusCodes.FORBIDDEN, "Write Forbidden", {'x-ms-substatus' : SubStatusCodes.WRITE_FORBIDDEN})
def _MockGetDatabaseAccount(self, url_conection):
database_account = documents.DatabaseAccount()
return database_account
if __name__ == '__main__':
unittest.main()
|