File: test_retry_policy_async.py

package info (click to toggle)
python-azure 20251118%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 783,356 kB
  • sloc: python: 6,474,533; ansic: 804; javascript: 287; sh: 205; makefile: 198; xml: 109
file content (712 lines) | stat: -rw-r--r-- 39,923 bytes parent folder | download | duplicates (2)
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
# The MIT License (MIT)
# Copyright (c) Microsoft Corporation. All rights reserved.
import asyncio
import os
import unittest
import uuid

import pytest

from azure.cosmos import documents

import azure.cosmos._retry_options as retry_options
import azure.cosmos.exceptions as exceptions
from azure.core.exceptions import ServiceRequestError
import test_config
from azure.cosmos.partition_key import PartitionKey
from azure.cosmos.http_constants import HttpHeaders, StatusCodes
from azure.cosmos.aio import CosmosClient
from azure.cosmos.aio import DatabaseProxy, ContainerProxy
import azure.cosmos.aio._retry_utility_async as _retry_utility
from azure.cosmos._retry_options import RetryOptions
from _fault_injection_transport_async import FaultInjectionTransportAsync
from azure.cosmos.http_constants import ResourceType
from azure.cosmos._constants import _Constants
from azure.cosmos._health_check_retry_policy import HealthCheckRetryPolicy

class ConnectionMode:
    """Represents the connection mode to be used by the client."""
    Gateway: int = 0
    """Use the Azure Cosmos gateway to route all requests. The gateway proxies
    requests to the right data partition.
    """

class ConnectionPolicy:
    #Represents the Connection policy associated with a CosmosClientConnection.
    __defaultRequestTimeout: int = 5  # seconds
    __defaultDBAConnectionTimeout: int = 3  # seconds
    __defaultReadTimeout: int = 65  # seconds
    __defaultDBAReadTimeout: int = 3 # seconds
    __defaultMaxBackoff: int = 1 # seconds

    def __init__(self) -> None:
        self.RequestTimeout: int = self.__defaultRequestTimeout
        self.DBAConnectionTimeout: int = self.__defaultDBAConnectionTimeout
        self.ReadTimeout: int = self.__defaultReadTimeout
        self.DBAReadTimeout: int = self.__defaultDBAReadTimeout
        self.MaxBackoff: int = self.__defaultMaxBackoff
        self.ConnectionMode: int = ConnectionMode.Gateway
        self.SSLConfiguration: Optional[SSLConfiguration] = None
        self.ProxyConfiguration: Optional[ProxyConfiguration] = None
        self.EnableEndpointDiscovery: bool = True
        self.PreferredLocations: List[str] = []
        self.ExcludedLocations = []
        self.RetryOptions: RetryOptions = RetryOptions()
        self.DisableSSLVerification: bool = False
        self.UseMultipleWriteLocations: bool = False
        self.ConnectionRetryConfiguration: Optional["ConnectionRetryPolicy"] = None
        self.ResponsePayloadOnWriteDisabled: bool = False

async def setup_method_with_custom_transport(
        custom_transport,
        **kwargs):
    connection_policy = ConnectionPolicy()
    connection_retry_policy = test_config.MockConnectionRetryPolicyAsync(resource_type="docs")
    connection_policy.ConnectionRetryConfiguration = connection_retry_policy
    client = CosmosClient(test_config.TestConfig.host, test_config.TestConfig.masterKey,
                          transport=custom_transport, connection_policy=connection_policy, **kwargs)
    db = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
    container = db.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
    return {"client": client, "db": db, "col": container, "retry_policy": connection_retry_policy}

@pytest.mark.cosmosEmulator
class TestRetryPolicyAsync(unittest.IsolatedAsyncioTestCase):
    created_database: DatabaseProxy = None
    created_collection: ContainerProxy = None
    client: CosmosClient = None
    host = test_config.TestConfig.host
    masterKey = test_config.TestConfig.masterKey
    connectionPolicy = ConnectionPolicy()
    counter = 0
    TEST_DATABASE_ID = test_config.TestConfig.TEST_DATABASE_ID
    TEST_CONTAINER_SINGLE_PARTITION_ID = "test-retry-policy-container-" + str(uuid.uuid4())
    retry_after_in_milliseconds = 1000

    def __AssertHTTPFailureWithStatus(self, status_code, func, *args, **kwargs):
        """Assert HTTP failure with status.

        :Parameters:
            - `status_code`: int
            - `func`: function
        """
        try:
            func(*args, **kwargs)
            self.assertFalse(True, 'function should fail.')
        except exceptions.CosmosHttpResponseError as inst:
            self.assertEqual(inst.status_code, status_code)

    @classmethod
    def setUpClass(cls):
        if (cls.masterKey == '[YOUR_KEY_HERE]' or
                cls.host == '[YOUR_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.")

    async def test_resource_throttle_retry_policy_default_retry_after_async(self):
        connection_policy = TestRetryPolicyAsync.connectionPolicy
        connection_policy.RetryOptions = retry_options.RetryOptions(5)
        async with CosmosClient(self.host, self.masterKey, connection_policy=connection_policy) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)

            self.original_execute_function = _retry_utility.ExecuteFunctionAsync
            try:
                _retry_utility.ExecuteFunctionAsync = self._MockExecuteFunction

                document_definition = {'id': str(uuid.uuid4()),
                                       'pk': 'pk',
                                       'name': 'sample document',
                                       'key': 'value'}

                try:
                    await container.create_item(body=document_definition)
                except exceptions.CosmosHttpResponseError as e:
                    self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS)
                    self.assertEqual(connection_policy.RetryOptions.MaxRetryAttemptCount,
                                     container.client_connection.last_response_headers[
                                         HttpHeaders.ThrottleRetryCount])
                    self.assertGreaterEqual(container.client_connection.last_response_headers[
                                                HttpHeaders.ThrottleRetryWaitTimeInMs],
                                            connection_policy.RetryOptions.MaxRetryAttemptCount *
                                            self.retry_after_in_milliseconds)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_retry_policy_fixed_retry_after_async(self):
        connection_policy = TestRetryPolicyAsync.connectionPolicy
        connection_policy.RetryOptions = retry_options.RetryOptions(5, 2000)
        async with CosmosClient(self.host, self.masterKey, connection_policy=connection_policy) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            self.original_execute_function = _retry_utility.ExecuteFunctionAsync
            try:
                _retry_utility.ExecuteFunctionAsync = self._MockExecuteFunction

                document_definition = {'id': str(uuid.uuid4()),
                                       'pk': 'pk',
                                       'name': 'sample document',
                                       'key': 'value'}

                try:
                    await container.create_item(body=document_definition)
                except exceptions.CosmosHttpResponseError as e:
                    self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS)
                    self.assertEqual(connection_policy.RetryOptions.MaxRetryAttemptCount,
                                     container.client_connection.last_response_headers[
                                         HttpHeaders.ThrottleRetryCount])
                    self.assertGreaterEqual(container.client_connection.last_response_headers[
                                                HttpHeaders.ThrottleRetryWaitTimeInMs],
                                            connection_policy.RetryOptions.MaxRetryAttemptCount * connection_policy.RetryOptions.FixedRetryIntervalInMilliseconds)

            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_retry_policy_max_wait_time_async(self):
        connection_policy = TestRetryPolicyAsync.connectionPolicy
        connection_policy.RetryOptions = retry_options.RetryOptions(5, 2000, 3)
        async with CosmosClient(self.host, self.masterKey, connection_policy=connection_policy) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            self.original_execute_function = _retry_utility.ExecuteFunctionAsync
            try:
                _retry_utility.ExecuteFunctionAsync = self._MockExecuteFunction

                document_definition = {'id': str(uuid.uuid4()),
                                       'pk': 'pk',
                                       'name': 'sample document',
                                       'key': 'value'}

                try:
                    await container.create_item(body=document_definition)
                except exceptions.CosmosHttpResponseError as e:
                    self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS)
                    self.assertGreaterEqual(container.client_connection.last_response_headers[
                                                HttpHeaders.ThrottleRetryWaitTimeInMs],
                                            connection_policy.RetryOptions.MaxWaitTimeInSeconds * 1000)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_retry_policy_query_async(self):
        connection_policy = TestRetryPolicyAsync.connectionPolicy
        connection_policy.RetryOptions = retry_options.RetryOptions(5)

        document_definition = {'id': str(uuid.uuid4()),
                               'pk': 'pk',
                               'name': 'sample document',
                               'key': 'value'}
        async with CosmosClient(self.host, self.masterKey, connection_policy=connection_policy) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            await container.create_item(body=document_definition)

            self.original_execute_function = _retry_utility.ExecuteFunctionAsync
            try:
                _retry_utility.ExecuteFunctionAsync = self._MockExecuteFunction

                try:
                    query_results = container.query_items(
                        {
                            'query': 'SELECT * FROM root r WHERE r.id=@id',
                            'parameters': [
                                {'name': '@id', 'value': document_definition['id']}
                            ]
                        })
                    async for item in query_results:
                        pass
                except exceptions.CosmosHttpResponseError as e:
                    self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS)
                    self.assertEqual(connection_policy.RetryOptions.MaxRetryAttemptCount,
                                     container.client_connection.last_response_headers[
                                         HttpHeaders.ThrottleRetryCount])
                    self.assertGreaterEqual(container.client_connection.last_response_headers[
                                                HttpHeaders.ThrottleRetryWaitTimeInMs],
                                            connection_policy.RetryOptions.MaxRetryAttemptCount * self.retry_after_in_milliseconds)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    # TODO: Need to validate the query retries
    @pytest.mark.skip
    async def test_default_retry_policy_for_query_async(self):
        document_definition_1 = {'id': str(uuid.uuid4()),
                                 'pk': 'pk',
                                 'name': 'sample document',
                                 'key': 'value'}
        document_definition_2 = {'id': str(uuid.uuid4()),
                                 'pk': 'pk',
                                 'name': 'sample document',
                                 'key': 'value'}

        self.created_collection.create_item(body=document_definition_1)
        self.created_collection.create_item(body=document_definition_2)
        self.original_execute_function = _retry_utility.ExecuteFunctionAsync
        try:
            mf = self.MockExecuteFunctionConnectionReset(self.original_execute_function)
            _retry_utility.ExecuteFunctionAsync = mf

            docs = await self.created_collection.query_items(query="Select * from c order by c._ts", max_item_count=1,
                                                             enable_cross_partition_query=True)

            result_docs = list(docs)
            self.assertEqual(result_docs[0]['id'], document_definition_1['id'])
            self.assertEqual(result_docs[1]['id'], document_definition_2['id'])

            self.assertEqual(mf.counter, 27)
        finally:
            _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_default_retry_policy_for_create_async(self):
        document_definition = {'id': str(uuid.uuid4()),
                               'pk': 'pk',
                               'name': 'sample document',
                               'key': 'value'}
        async with CosmosClient(self.host, self.masterKey) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = await database.create_container_if_not_exists(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID,
                                                                      partition_key=PartitionKey("/pk"))
            try:
                self.original_execute_function = _retry_utility.ExecuteFunctionAsync
                mf = self.MockExecuteFunctionConnectionReset(self.original_execute_function)
                _retry_utility.ExecuteFunctionAsync = mf

                created_document = {}
                try:
                    created_document = await container.create_item(body=document_definition)
                except exceptions.CosmosHttpResponseError as err:
                    self.assertEqual(err.status_code, 10054)

                self.assertDictEqual(created_document, {})

                self.assertEqual(mf.counter, 1)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_timeout_failover_retry_policy_for_read_async(self):
        document_definition = {'id': 'failoverDoc',
                               'pk': 'pk',
                               'name': 'sample document',
                               'key': 'value'}
        async with CosmosClient(self.host, self.masterKey) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            created_document = await container.create_item(body=document_definition)
            self.original_execute_function = _retry_utility.ExecuteFunctionAsync
            try:
                mf = self.MockExecuteFunctionTimeout(self.original_execute_function)
                _retry_utility.ExecuteFunctionAsync = mf
                try:
                    await container.read_item(item=created_document['id'], partition_key=created_document['pk'])
                except exceptions.CosmosHttpResponseError as err:
                    self.assertEqual(err.status_code, 408)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_retry_policy_with_retry_total_async(self):
        # Testing the kwarg retry_total still has ability to set throttle's max retry attempt count
        max_total_retries = 15
        async with CosmosClient(self.host, self.masterKey, retry_total=max_total_retries) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            try:
                self.original_execute_function = _retry_utility.ExecuteFunctionAsync
                _retry_utility.ExecuteFunctionAsync = self._MockExecuteFunction
                document_definition = {'id': str(uuid.uuid4()),
                                       'pk': 'pk',
                                       'name': 'sample document',
                                       'key': 'value'}
                await container.create_item(body=document_definition)
            except exceptions.CosmosHttpResponseError as e:
                self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS)
                self.assertEqual(container.client_connection.connection_policy.RetryOptions.MaxRetryAttemptCount,
                                 container.client_connection.last_response_headers[
                                     HttpHeaders.ThrottleRetryCount])
                self.assertEqual(
                    container.client_connection.connection_policy.ConnectionRetryConfiguration.total_retries,
                    max_total_retries)
                self.assertGreaterEqual(container.client_connection.last_response_headers[
                                            HttpHeaders.ThrottleRetryWaitTimeInMs],
                                        container.client_connection.connection_policy.RetryOptions.MaxRetryAttemptCount *
                                        self.retry_after_in_milliseconds)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_retry_policy_with_retry_throttle_total_async(self):
        # Testing the kwarg retry_throttle_total is behaving as expected
        async with CosmosClient(self.host, self.masterKey, retry_throttle_total=5) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            try:
                self.original_execute_function = _retry_utility.ExecuteFunctionAsync
                _retry_utility.ExecuteFunctionAsync = self._MockExecuteFunction
                document_definition = {'id': str(uuid.uuid4()),
                                       'pk': 'pk',
                                       'name': 'sample document',
                                       'key': 'value'}

                await container.create_item(body=document_definition)
            except exceptions.CosmosHttpResponseError as e:
                self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS)
                self.assertEqual(container.client_connection.connection_policy.RetryOptions.MaxRetryAttemptCount,
                                 container.client_connection.last_response_headers[
                                     HttpHeaders.ThrottleRetryCount])
                self.assertGreaterEqual(container.client_connection.last_response_headers[
                                            HttpHeaders.ThrottleRetryWaitTimeInMs],
                                        container.client_connection.connection_policy.RetryOptions.MaxRetryAttemptCount *
                                        self.retry_after_in_milliseconds)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_retry_policy_precedence_async(self):
        # Tests if retry_throttle_total and retry_total are specified then retry_throttle_total should take precedence retry_total
        max_retry_throttle_retries = 15
        max_total_retries = 20

        async with CosmosClient(self.host, self.masterKey, retry_throttle_total=max_retry_throttle_retries,
                                retry_total=max_total_retries) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            try:
                self.original_execute_function = _retry_utility.ExecuteFunctionAsync
                _retry_utility.ExecuteFunctionAsync = self._MockExecuteFunction
                document_definition = {'id': str(uuid.uuid4()),
                                       'pk': 'pk',
                                       'name': 'sample document',
                                       'key': 'value'}
                await container.create_item(body=document_definition)
            except exceptions.CosmosHttpResponseError as e:
                self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS)
                self.assertEqual(container.client_connection.connection_policy.RetryOptions.MaxRetryAttemptCount,
                                 container.client_connection.last_response_headers[
                                     HttpHeaders.ThrottleRetryCount])
                self.assertEqual(
                    container.client_connection.connection_policy.ConnectionRetryConfiguration.total_retries,
                    max_total_retries)
                self.assertGreaterEqual(container.client_connection.last_response_headers[
                                            HttpHeaders.ThrottleRetryWaitTimeInMs],
                                        container.client_connection.connection_policy.RetryOptions.MaxRetryAttemptCount *
                                        self.retry_after_in_milliseconds)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_connection_retry_policy_max_backoff_async(self):
        # Tests that kwarg retry_max_backoff sets both throttle and connection retry policy
        max_backoff_in_seconds = 10

        async with CosmosClient(self.host, self.masterKey, retry_backoff_max=max_backoff_in_seconds,
                                retry_total=5) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            document_definition = {'id': str(uuid.uuid4()),
                                   'pk': 'pk',
                                   'name': 'sample document',
                                   'key': 'value'}
            try:
                self.original_execute_function = _retry_utility.ExecuteFunctionAsync
                mf = self.MockExecuteFunctionConnectionReset(self.original_execute_function)
                _retry_utility.ExecuteFunctionAsync = mf
                created_document = {}
                created_document = await container.create_item(body=document_definition)
            except exceptions.CosmosHttpResponseError as err:
                self.assertEqual(err.status_code, 10054)
                self.assertEqual(container.client_connection.connection_policy.ConnectionRetryConfiguration.backoff_max,
                                 max_backoff_in_seconds)
                self.assertEqual(container.client_connection.connection_policy.RetryOptions._max_wait_time_in_seconds,
                                 max_backoff_in_seconds)
                self.assertDictEqual(created_document, {})
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_retry_policy_max_throttle_backoff_async(self):
        # Tests that kwarg retry_throttle_backoff_max sets the throttle max backoff retry independent of connection max backoff retry
        max_throttle_backoff_in_seconds = 10

        async with CosmosClient(self.host, self.masterKey,
                                retry_throttle_backoff_max=max_throttle_backoff_in_seconds) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            document_definition = {'id': str(uuid.uuid4()),
                                   'pk': 'pk',
                                   'name': 'sample document',
                                   'key': 'value'}
            try:
                self.original_execute_function = _retry_utility.ExecuteFunctionAsync
                mf = self.MockExecuteFunctionConnectionReset(self.original_execute_function)
                _retry_utility.ExecuteFunctionAsync = mf
                created_document = {}
                created_document = await container.create_item(body=document_definition)
            except exceptions.CosmosHttpResponseError as err:
                self.assertEqual(err.status_code, 10054)
                self.assertEqual(container.client_connection.connection_policy.RetryOptions._max_wait_time_in_seconds,
                                 max_throttle_backoff_in_seconds)
                self.assertDictEqual(created_document, {})
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_retry_policy_max_backoff_precedence_async(self):
        # Tests to ensure kwargs precedence is being respected between retry_backoff_max and retry_throttle_backoff_max
        max_backoff_in_seconds = 10
        max_throttle_backoff_in_seconds = 5

        async with CosmosClient(self.host, self.masterKey, retry_backoff_max=max_backoff_in_seconds,
                                retry_throttle_backoff_max=max_throttle_backoff_in_seconds) as client:
            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            document_definition = {'id': str(uuid.uuid4()),
                                   'pk': 'pk',
                                   'name': 'sample document',
                                   'key': 'value'}
            try:
                self.original_execute_function = _retry_utility.ExecuteFunctionAsync
                mf = self.MockExecuteFunctionConnectionReset(self.original_execute_function)
                _retry_utility.ExecuteFunctionAsync = mf
                created_document = {}
                created_document = await container.create_item(body=document_definition)
            except exceptions.CosmosHttpResponseError as err:
                self.assertEqual(err.status_code, 10054)
                self.assertEqual(container.client_connection.connection_policy.ConnectionRetryConfiguration.backoff_max,
                                 max_backoff_in_seconds)
                self.assertEqual(container.client_connection.connection_policy.RetryOptions._max_wait_time_in_seconds,
                                 max_throttle_backoff_in_seconds)
                self.assertDictEqual(created_document, {})
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_resource_throttle_and_connection_retry_total_retry_with_max_backoff_async(self):
        # Tests kwarg precedence respect with both max total retries and max backoff for both throttle and connection retry policies
        max_retry_throttle_retries = 5
        max_total_retries = 10
        max_throttle_backoff_in_seconds = 15
        max_backoff_in_seconds = 20

        async with CosmosClient(self.host, self.masterKey, retry_backoff_max=max_backoff_in_seconds,
                                retry_throttle_backoff_max=max_throttle_backoff_in_seconds,
                                retry_throttle_total=max_retry_throttle_retries,
                                retry_total=max_total_retries) as client:

            database = client.get_database_client(test_config.TestConfig.TEST_DATABASE_ID)
            container = database.get_container_client(test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID)
            self.original_execute_function = _retry_utility.ExecuteFunctionAsync

            try:
                _retry_utility.ExecuteFunctionAsync = self._MockExecuteFunction
                document_definition = {'id': str(uuid.uuid4()),
                                       'pk': 'pk',
                                       'name': 'sample document',
                                       'key': 'value'}
                await container.create_item(body=document_definition)
            except exceptions.CosmosHttpResponseError as e:
                self.assertEqual(e.status_code, StatusCodes.TOO_MANY_REQUESTS)
                self.assertEqual(container.client_connection.connection_policy.RetryOptions.MaxRetryAttemptCount,
                                 container.client_connection.last_response_headers[
                                     HttpHeaders.ThrottleRetryCount])
                self.assertEqual(container.client_connection.connection_policy.ConnectionRetryConfiguration.backoff_max,
                                 max_backoff_in_seconds)
                self.assertEqual(container.client_connection.connection_policy.RetryOptions._max_wait_time_in_seconds,
                                 max_throttle_backoff_in_seconds)
                self.assertEqual(
                    container.client_connection.connection_policy.ConnectionRetryConfiguration.total_retries,
                    max_total_retries)
            finally:
                _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_patch_replace_no_retry_async(self):
        doc = {'id': str(uuid.uuid4()),
               'pk': str(uuid.uuid4()),
               'name': 'sample document',
               'key': 'value'}
        custom_transport =  FaultInjectionTransportAsync()
        predicate = lambda r: (FaultInjectionTransportAsync.predicate_is_operation_type(r, documents._OperationType.Patch)
                               or FaultInjectionTransportAsync.predicate_is_operation_type(r, documents._OperationType.Replace))
        custom_transport.add_fault(predicate, lambda r: asyncio.create_task(FaultInjectionTransportAsync.error_after_delay(
            0,
            exceptions.CosmosHttpResponseError(
                status_code=502,
                message="Some random reverse proxy error."))))

        initialized_objects = await setup_method_with_custom_transport(
            custom_transport,
        )
        container = initialized_objects["col"]
        connection_retry_policy = initialized_objects["retry_policy"]
        await container.create_item(body=doc)
        operations = [{"op": "incr", "path": "/company", "value": 3}]
        with self.assertRaises(exceptions.CosmosHttpResponseError):
            await container.patch_item(item=doc['id'], partition_key=doc['pk'], patch_operations=operations)
        assert connection_retry_policy.counter == 0
        with self.assertRaises(exceptions.CosmosHttpResponseError):
            doc['name'] = "something else"
            await container.replace_item(item=doc['id'], body=doc)
        assert connection_retry_policy.counter == 0
        # Cleanup
        await initialized_objects["client"].close()

    async def test_health_check_retry_policy_async(self):
        os.environ['AZURE_COSMOS_HEALTH_CHECK_MAX_RETRIES'] = '5'
        os.environ['AZURE_COSMOS_HEALTH_CHECK_RETRY_AFTER_MS'] = '2'
        max_retries = int(os.environ['AZURE_COSMOS_HEALTH_CHECK_MAX_RETRIES'])
        retry_after_ms = int(os.environ['AZURE_COSMOS_HEALTH_CHECK_RETRY_AFTER_MS'])
        self.original_execute_function = _retry_utility.ExecuteFunctionAsync
        mock_execute = self.MockExecuteFunctionHealthCheck(self.original_execute_function)
        _retry_utility.ExecuteFunctionAsync = mock_execute

        try:
            with self.assertRaises(exceptions.CosmosHttpResponseError) as context:
                async with CosmosClient( self.host,
                        self.masterKey):
                   pass

            self.assertEqual(context.exception.status_code, 503)
            # The total number of calls will be the initial call + the number of retries
            self.assertEqual(mock_execute.counter, max_retries + 1)
            # Assert retry interval from environment variable
            policy = HealthCheckRetryPolicy(ConnectionPolicy())
            self.assertEqual(policy.retry_after_in_milliseconds, retry_after_ms)
        finally:
            del os.environ["AZURE_COSMOS_HEALTH_CHECK_MAX_RETRIES"]
            del os.environ["AZURE_COSMOS_HEALTH_CHECK_RETRY_AFTER_MS"]
            _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_health_check_retry_policy_defaults_async(self):

        self.original_execute_function = _retry_utility.ExecuteFunctionAsync
        mock_execute = self.MockExecuteFunctionHealthCheckServiceRequestError(self.original_execute_function)
        _retry_utility.ExecuteFunctionAsync = mock_execute

        try:
            with self.assertRaises(ServiceRequestError):
                async with CosmosClient(self.host, self.masterKey):
                   pass

            # Should use default retry attempts from _constants.py
            self.assertEqual(
                mock_execute.counter,
                _Constants.AZURE_COSMOS_HEALTH_CHECK_MAX_RETRIES_DEFAULT + 1
            )

            # Verify default retry time in ms
            policy = HealthCheckRetryPolicy(ConnectionPolicy())
            self.assertEqual(
                policy.retry_after_in_milliseconds,
                _Constants.AZURE_COSMOS_HEALTH_CHECK_RETRY_AFTER_MS_DEFAULT
            )
        finally:
            _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    async def test_health_check_retry_with_service_request_error_async(self):
        self.original_execute_function = _retry_utility.ExecuteFunctionAsync
        mock_execute = self.MockExecuteFunctionHealthCheckServiceRequestError(self.original_execute_function)
        _retry_utility.ExecuteFunctionAsync = mock_execute

        try:
            with self.assertRaises(ServiceRequestError):
                async with CosmosClient(self.host, self.masterKey):
                   pass # Triggers database account read

            # Should use default retry attempts from _constants.py
            self.assertEqual(
                mock_execute.counter,
                _Constants.AZURE_COSMOS_HEALTH_CHECK_MAX_RETRIES_DEFAULT + 1
            )
            # Verify default retry time in ms
            policy = HealthCheckRetryPolicy(ConnectionPolicy())
            self.assertEqual(
                policy.retry_after_in_milliseconds,
                _Constants.AZURE_COSMOS_HEALTH_CHECK_RETRY_AFTER_MS_DEFAULT
            )
        finally:
            _retry_utility.ExecuteFunctionAsync = self.original_execute_function

    class MockExecuteFunctionHealthCheckServiceRequestError(object):
        def __init__(self, org_func):
            self.org_func = org_func
            self.counter = 0

        async def __call__(self, func, *args, **kwargs):
            # The second argument to the internal _request function is the RequestObject.
            request_object = args[1]
            if (request_object.operation_type == documents._OperationType.Read and
                    request_object.resource_type == ResourceType.DatabaseAccount):
                self.counter += 1
                raise ServiceRequestError("mocked service request error")
            return await self.org_func(func, *args, **kwargs)

    class MockExecuteFunctionDBAError(object):
        def __init__(self, org_func, error):
            self.org_func = org_func
            self.counter = 0
            self.error = error

        async def __call__(self, func, *args, **kwargs):
            # The second argument to the internal _request function is the RequestObject.
            request_object = args[1]
            if (request_object.operation_type == documents._OperationType.Read and
                    request_object.resource_type == ResourceType.DatabaseAccount):
                self.counter += 1
                raise self.error
            return await self.org_func(func, *args, **kwargs)

    class MockExecuteFunctionDBA(object):
        def __init__(self, org_func):
            self.org_func = org_func
            self.counter = 0

        async def __call__(self, func, *args, **kwargs):
            # The second argument to the internal _request function is the RequestObject.
            request_object = args[1]
            if (request_object.operation_type == documents._OperationType.Read and
                    request_object.resource_type == ResourceType.DatabaseAccount):
                self.counter += 1
            return await self.org_func(func, *args, **kwargs)

    async def _MockExecuteFunction(self, function, *args, **kwargs):
        response = test_config.FakeResponse({HttpHeaders.RetryAfterInMilliseconds: self.retry_after_in_milliseconds})
        raise exceptions.CosmosHttpResponseError(
            status_code=StatusCodes.TOO_MANY_REQUESTS,
            message="Request rate is too large",
            response=response)

    class MockExecuteFunctionTimeout(object):
        def __init__(self, org_func):
            self.org_func = org_func
            self.counter = 0

        async def __call__(self, func, *args, **kwargs):
            raise exceptions.CosmosHttpResponseError(
                status_code=408,
                message="Timeout",
                response=test_config.FakeResponse({}))

    class MockExecuteFunctionConnectionReset(object):
        def __init__(self, org_func):
            self.org_func = org_func
            self.counter = 0

        async def __call__(self, func, *args, **kwargs):
            self.counter = self.counter + 1
            if self.counter % 3 == 0:
                return await self.org_func(func, *args, **kwargs)
            else:
                raise exceptions.CosmosHttpResponseError(
                    status_code=10054,
                    message="Connection was reset",
                    response=test_config.FakeResponse({}))

    class MockExecuteFunctionHealthCheck(object):
        def __init__(self, org_func):
            self.org_func = org_func
            self.counter = 0

        async def __call__(self, func, *args, **kwargs):
            # The second argument to the internal _request function is the RequestObject.
            request_object = args[1]
            if (request_object.operation_type == documents._OperationType.Read and
                    request_object.resource_type == ResourceType.DatabaseAccount):
                self.counter += 1
                raise exceptions.CosmosHttpResponseError(
                    status_code=503,
                    message="Service Unavailable.")
            return await self.org_func(func, *args, **kwargs)

if __name__ == '__main__':
    unittest.main()