File: test_retryable_writes.py

package info (click to toggle)
python-azure 20251014%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 766,472 kB
  • sloc: python: 6,314,744; ansic: 804; javascript: 287; makefile: 198; sh: 198; xml: 109
file content (720 lines) | stat: -rw-r--r-- 37,100 bytes parent folder | download
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
713
714
715
716
717
718
719
720
# The MIT License (MIT)
# Copyright (c) Microsoft Corporation. All rights reserved.

import pytest
import unittest
import uuid
from azure.core.exceptions import ServiceResponseError
from azure.core.rest import HttpRequest
from azure.core.pipeline.transport._requests_basic import RequestsTransport
from azure.cosmos import CosmosClient, ContainerProxy, DatabaseProxy, _retry_utility, exceptions
from azure.cosmos.partition_key import PartitionKey
from _fault_injection_transport import FaultInjectionTransport
from typing import Callable
import test_config  # Import test_config for configuration details

HPK_CONTAINER = "TestContainerHPK"

@pytest.fixture(scope="class")
def setup():
    config = test_config.TestConfig()
    if config.masterKey == '[YOUR_KEY_HERE]' or config.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.")
    test_client = CosmosClient(config.host, config.masterKey)
    database = test_client.create_database_if_not_exists(id=config.TEST_DATABASE_ID)
    created_container = database.create_container_if_not_exists(
        id=config.TEST_SINGLE_PARTITION_CONTAINER_ID,
        partition_key=PartitionKey(path="/pk")
    )
    container_hpk = database.create_container_if_not_exists(
        id=HPK_CONTAINER,
        partition_key=PartitionKey(path=["/state", "/city"], kind="MultiHash")
    )
    yield {"database": database, "container": created_container, "container_hpk": container_hpk}

@pytest.mark.cosmosEmulator
@pytest.mark.usefixtures("setup")
class TestRetryableWrites:
    host = test_config.TestConfig.host
    master_key = test_config.TestConfig.masterKey
    TEST_DATABASE_ID = test_config.TestConfig.TEST_DATABASE_ID
    TEST_CONTAINER_SINGLE_PARTITION_ID = test_config.TestConfig.TEST_SINGLE_PARTITION_CONTAINER_ID
    TEST_CONTAINER_MULTI_PARTITION_ID = test_config.TestConfig.TEST_MULTI_PARTITION_CONTAINER_ID
    client: CosmosClient = None

    @staticmethod
    def setup_method_with_custom_transport(
            custom_transport: RequestsTransport,
            default_endpoint: str = host,
            key: str = master_key,
            database_id: str = TEST_DATABASE_ID,
            container_id: str = TEST_CONTAINER_SINGLE_PARTITION_ID,
            **kwargs):
        client = CosmosClient(default_endpoint, key, consistency_level="Session",
                              transport=custom_transport, **kwargs)
        db: DatabaseProxy = client.create_database_if_not_exists(database_id)
        container: ContainerProxy = db.create_container_if_not_exists(container_id, PartitionKey(path="/pk"))
        return {"client": client, "db": db, "col": container}

    def test_retryable_writes_request_level(self, setup):
        # Create a container for testing
        container = setup["container"]

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Test without retry_write for upsert_item
        test_item = {"id": "1", "pk": "test", "data": "retryable write test"}
        try:
            container.upsert_item(test_item)
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries without retry_write"

        # Test with retry_write for upsert_item
        me.counter = 0  # Reset counter
        try:
            container.upsert_item(test_item, retry_write=2)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was written
        read_item = container.read_item(item=test_item['id'], partition_key=test_item['pk'])
        assert read_item['id'] == test_item['id'], "Item was not written successfully after retries"

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Test without retry_write for create_item
        test_item_create = {"id": "2", "pk": "test", "data": "retryable create test"}
        me.counter = 0  # Reset counter
        try:
            container.create_item(test_item_create)
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries without retry_write"

        # Test with retry_write for create_item
        me.counter = 0  # Reset counter
        try:
            container.create_item(test_item_create, retry_write=2)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was created
        read_item_create = container.read_item(item=test_item_create['id'],
                                               partition_key=test_item_create['pk'])
        assert read_item_create['id'] == test_item_create['id'], "Item was not created successfully after retries"

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me
        # Test without retry_write for patch_item
        test_patch_operations = [
            {"op": "add", "path": "/data", "value": "patched retryable write test"}
        ]
        try:
            container.patch_item(item=test_item['id'], partition_key=test_item['pk'],
                                 patch_operations=test_patch_operations)
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries without retry_write"

        # Test with retry_write for patch_item
        me.counter = 0  # Reset counter
        try:
            container.patch_item(item=test_item['id'], partition_key=test_item['pk'],
                                 patch_operations=test_patch_operations, retry_write=2)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was patched
        patched_item = container.read_item(item=test_item['id'], partition_key=test_item['pk'])
        assert patched_item['data'] == "patched retryable write test", "Item was not patched successfully after retries"

        # Verify original execution function is used to upsert an item
        test_item = {"id": "1", "pk": "test", "data": "retryable write test"}
        container.upsert_item(test_item)

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Verify delete_item does not retry
        me.counter = 0  # Reset counter
        try:
            container.delete_item(item=test_item['id'], partition_key=test_item['pk'])
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries for delete_item"

        # Verify the item was not deleted
        read_item = container.read_item(item=test_item['id'], partition_key=test_item['pk'])
        assert read_item['id'] == test_item['id'], "Item was unexpectedly deleted"

        me.counter = 0  # Reset counter
        try:
            container.delete_item(item=test_item['id'], partition_key=test_item['pk'], retry_write=2)
        except exceptions.CosmosHttpResponseError:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        try:
            container.read_item(item=test_item['id'], partition_key=test_item['pk'])
            pytest.fail("Expected an exception for item that should have been deleted")
        except exceptions.CosmosHttpResponseError as e:
            assert e.status_code == 404, "Expected item to be deleted but it was not"

        # Test replace item with retry_write

        test_item_replace = {"id": "3", "pk": "test", "data": "original data"}
        container.create_item(test_item_replace)
        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me
        # Test without retry_write for replace_item
        try:
            container.replace_item(item=test_item_replace['id'], body={"id": "3", "pk": "test", "data": "updated data"})
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries without retry_write"
        # Test with retry_write for replace_item
        me.counter = 0  # Reset counter
        try:
            container.replace_item(item=test_item_replace['id'], body={"id": "3", "pk": "test",
                                                                       "data": "updated data"}, retry_write=2)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute
        # Verify the item was replaced
        replaced_item = container.read_item(item=test_item_replace['id'],
                                            partition_key=test_item_replace['pk'])
        assert replaced_item['data'] == "updated data", "Item was not replaced successfully after retries"

    def test_retryable_writes_client_level(self, setup):
        """Test retryable writes for a container with retry_write set at the client level."""
        # Create a client with retry_write enabled
        client_with_retry = CosmosClient(self.host, credential=self.master_key, retry_write=2)
        container = client_with_retry.get_database_client(self.TEST_DATABASE_ID).get_container_client(setup['container'].id)

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Test upsert_item
        test_item = {"id": "4", "pk": "test", "data": "retryable write test"}
        try:
            container.upsert_item(test_item)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"

        # Test create_item
        me.counter = 0  # Reset counter
        test_item_create = {"id": "5", "pk": "test", "data": "retryable create test"}
        try:
            container.create_item(test_item_create)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"

        # Test patch_item
        me.counter = 0  # Reset counter
        test_patch_operations = [
            {"op": "add", "path": "/data", "value": "patched retryable write test"}
        ]
        try:
            container.patch_item(item=test_item['id'], partition_key=test_item['pk'],
                                 patch_operations=test_patch_operations)
            pytest.fail("Expected an exception without retries")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries for patch_item with client_retry_write"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify original execution function is used to upsert an item
        test_item = {"id": "4", "pk": "test", "data": "retryable write test"}
        container.upsert_item(test_item)

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Verify delete_item does not retry
        me.counter = 0  # Reset counter
        try:
            container.delete_item(item=test_item['id'], partition_key=test_item['pk'])
        except exceptions.CosmosHttpResponseError:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was deleted
        try:
            container.read_item(item=test_item['id'], partition_key=test_item['pk'])
            pytest.fail("Expected an exception for item that should have been deleted")
        except exceptions.CosmosHttpResponseError as e:
            assert e.status_code == 404, "Expected item to be deleted but it was not"

        # Test client level retry for service response error
        mf = self.MockExecuteServiceResponseException(Exception)
        try:
            # Reset the function to reset the counter
            _retry_utility.ExecuteFunction = mf
            container.create_item({"id": str(uuid.uuid4()), "pk": str(uuid.uuid4())})
            pytest.fail("Exception was not raised.")
        except ServiceResponseError:
            assert mf.counter == 2
        finally:
            _retry_utility.ExecuteFunction = original_execute

        # Test with replace item
        test_item_replace = {"id": "8", "pk": "test", "data": "original data"}
        container.create_item(test_item_replace)
        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me
        # Test replace item, writes will retry by default with client level retry_write
        try:
            container.replace_item(item=test_item_replace['id'], body={"id": "8", "pk": "test",
                                                                       "data": "updated data"})
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute
        # Verify the item was replaced
        replaced_item = container.read_item(item=test_item_replace['id'],
                                            partition_key=test_item_replace['pk'])
        assert replaced_item['data'] == "updated data", "Item was not replaced successfully after retries"

    def test_retryable_writes_hpk_request_level(self, setup):
        """Test retryable writes for a container with hierarchical partition keys."""
        container = setup["container_hpk"]

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Test without retry_write for upsert_item
        test_item = {"id": "1", "state": "CA", "city": "San Francisco", "data": "retryable write test"}
        try:
            container.upsert_item(test_item)
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries without retry_write"

        # Test with retry_write for upsert_item
        me.counter = 0  # Reset counter
        try:
            container.upsert_item(test_item, retry_write=2)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was written
        read_item = container.read_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']])
        assert read_item['id'] == test_item['id'], "Item was not written successfully after retries"

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Test without retry_write for create_item
        test_item_create = {"id": "2", "state": "NY", "city": "New York", "data": "retryable create test"}
        try:
            container.create_item(test_item_create)
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries without retry_write"

        # Test with retry_write for create_item
        me.counter = 0  # Reset counter
        try:
            container.create_item(test_item_create, retry_write=2)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was created
        read_item_create = container.read_item(item=test_item_create['id'],
                                               partition_key=[test_item_create['state'], test_item_create['city']])
        assert read_item_create['id'] == test_item_create['id'], "Item was not created successfully after retries"

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Test without retry_write for patch_item
        test_patch_operations_hpk = [
            {"op": "add", "path": "/data", "value": "patched retryable write test"}
        ]
        try:
            container.patch_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']],
                                 patch_operations=test_patch_operations_hpk)
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries without retry_write"

        # Test with retry_write for patch_item
        me.counter = 0  # Reset counter
        try:
            container.patch_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']],
                                 patch_operations=test_patch_operations_hpk, retry_write=2)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was patched
        patched_item_hpk = container.read_item(item=test_item['id'],
                                               partition_key=[test_item['state'], test_item['city']])
        assert patched_item_hpk[
                   'data'] == "patched retryable write test", "Item was not patched successfully after retries"

        # Verify original execution function is used to upsert an item
        test_item = {"id": "1", "state": "CA", "city": "San Francisco", "data": "retryable write test"}
        container.upsert_item(test_item)

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Verify delete_item does not retry
        me.counter = 0  # Reset counter
        try:
            container.delete_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']])
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries for delete_item"

        me.counter = 0  # Reset counter
        try:
            container.delete_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']],
                                  retry_write=2)
        except exceptions.CosmosHttpResponseError:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was deleted
        try:
            container.read_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']])
            pytest.fail("Expected an exception for item that should have been deleted")
        except exceptions.CosmosHttpResponseError as e:
            assert e.status_code == 404, "Expected item to be deleted but it was not"

        # Test with replace item
        test_item_replace = {"id": "6", "state": "CA", "city": "San Francisco", "data": "original data"}
        container.create_item(test_item_replace)
        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me
        # Test replace item without retry_write
        try:
            container.replace_item(item=test_item_replace['id'], body={"id": "6", "state": "CA", "city": "San Francisco",
                                                                       "data": "updated data"})
            pytest.fail("Expected an exception without retry_write")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries without retry_write"
        # Test replace item with retry_write
        me.counter = 0  # Reset counter
        try:
            container.replace_item(item=test_item_replace['id'], body={"id": "6", "state": "CA",
                                                                       "city": "San Francisco",
                                                                       "data": "updated data"}, retry_write=2)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute
        # Verify the item was replaced
        replaced_item_hpk = container.read_item(item=test_item_replace['id'],
                                                partition_key=[test_item_replace['state'], test_item_replace['city']])
        assert replaced_item_hpk['data'] == "updated data", "Item was not replaced successfully after retries"

    def test_retryable_writes_hpk_client_level(self, setup):
        """Test retryable writes for a container with hierarchical partition keys and
        retry_write set at the client level."""
        # Create a client with retry_write enabled
        client_with_retry = CosmosClient(self.host, credential=self.master_key, retry_write=2)
        container = client_with_retry.get_database_client(self.TEST_DATABASE_ID).get_container_client(
            setup['container_hpk'].id)

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Test upsert_item
        test_item = {"id": "6", "state": "CA", "city": "San Francisco", "data": "retryable write test"}
        try:
            container.upsert_item(test_item)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"

        # Test create_item
        me.counter = 0  # Reset counter
        test_item_create = {"id": "7", "state": "NY", "city": "New York", "data": "retryable create test"}
        try:
            container.create_item(test_item_create)
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"

        # Test patch_item
        me.counter = 0  # Reset counter
        test_patch_operations_hpk = [
            {"op": "add", "path": "/data", "value": "patched retryable write test"}
        ]
        try:
            container.patch_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']],
                                 patch_operations=test_patch_operations_hpk)
            pytest.fail("Expected an exception without retries")
        except exceptions.CosmosHttpResponseError:
            assert me.counter == 1, "Expected no retries for patch_item with client_retry_write"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify original execution function is used to upsert an item
        test_item = {"id": "6", "state": "CA", "city": "San Francisco", "data": "retryable write test"}
        container.upsert_item(test_item)

        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me

        # Verify delete_item does not retry
        me.counter = 0  # Reset counter
        try:
            container.delete_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']])
        except exceptions.CosmosHttpResponseError:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute

        # Verify the item was deleted
        try:
            container.read_item(item=test_item['id'], partition_key=[test_item['state'], test_item['city']])
            pytest.fail("Expected an exception for item that should have been deleted")
        except exceptions.CosmosHttpResponseError as e:
            assert e.status_code == 404, "Expected item to be deleted but it was not"

        # Test client level retry for replace item
        test_item_replace = {"id": "8", "state": "CA", "city": "San Francisco", "data": "original data"}
        container.create_item(test_item_replace)
        # Mock retry_utility.execute to track retries
        original_execute = _retry_utility.ExecuteFunction
        me = self.MockExecuteFunction(original_execute)
        _retry_utility.ExecuteFunction = me
        # Test replace item, writes will retry by default with client level retry_write
        try:
            container.replace_item(item=test_item_replace['id'], body={"id": "8", "state": "CA",
                                                                       "city": "San Francisco",
                                                                       "data": "updated data"})
        except exceptions.CosmosHttpResponseError as e:
            assert me.counter > 1, "Expected multiple retries due to simulated errors"
        finally:
            # Restore the original retry_utility.execute function
            _retry_utility.ExecuteFunction = original_execute
        # Verify the item was replaced
        replaced_item_hpk = container.read_item(item=test_item_replace['id'],
                                                partition_key=[test_item_replace['state'], test_item_replace['city']])
        assert replaced_item_hpk['data'] == "updated data", "Item was not replaced successfully after retries"


    @pytest.mark.parametrize("injected_error", [FaultInjectionTransport.error_request_timeout(),
                             FaultInjectionTransport.error_internal_server_error(),
                             FaultInjectionTransport.error_service_response()])
    def test_retryable_writes_mrw_request_level(self, injected_error):
        # Verify cross regional retries when using retryable writes at request level with multiple write locations.
        # Need to test for 408s, 500s, and ServiceResponseError.
        first_region_uri: str = test_config.TestConfig.local_host.replace("localhost", "127.0.0.1")
        second_region_uri: str = test_config.TestConfig.local_host
        custom_transport = FaultInjectionTransport()

        # Inject topology transformation that would make Emulator look like a multiple write region account
        is_get_account_predicate: Callable[[HttpRequest], bool] = lambda \
            r: FaultInjectionTransport.predicate_is_database_account_call(r)
        emulator_as_multi_write_region_account_transformation = \
            lambda r, inner: FaultInjectionTransport.transform_topology_mwr(
                first_region_name="First Region",
                second_region_name="Second Region",
                inner=inner)
        custom_transport.add_response_transformation(
            is_get_account_predicate,
            emulator_as_multi_write_region_account_transformation)

        # Inject rule to simulate regional outage in "First Region" to test retry happens in next region
        is_request_to_first_region: Callable[[HttpRequest], bool] = lambda \
                r: FaultInjectionTransport.predicate_targets_region(r, first_region_uri) and \
                   FaultInjectionTransport.predicate_is_document_operation(r)

        custom_transport.add_fault(
            is_request_to_first_region,
            lambda r: injected_error)

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

        initialized_objects = self.setup_method_with_custom_transport(
            custom_transport,
            preferred_locations=["First Region", "Second Region"],
            multiple_write_locations=True
        )
        container: ContainerProxy = initialized_objects["col"]

        create_document = container.create_item(body=document_definition, retry_write=2)
        request = create_document.get_response_headers()["_request"]
        assert request.url.startswith(second_region_uri)

        upsert_document = container.upsert_item(body=document_definition, retry_write=2)
        request = upsert_document.get_response_headers()["_request"]
        assert request.url.startswith(second_region_uri)

        replace_document = container.replace_item(item=document_definition['id'], body=document_definition, retry_write=2)
        request = replace_document.get_response_headers()["_request"]
        assert request.url.startswith(second_region_uri)

        operations = [{"op": "add", "path": "/favorite_color", "value": "red"},]
        patch_document = container.patch_item(item=document_definition['id'], partition_key=document_definition['pk'],
                                                patch_operations=operations, retry_write=2)
        request = patch_document.get_response_headers()["_request"]
        assert request.url.startswith(second_region_uri)

    @pytest.mark.parametrize("injected_error", [FaultInjectionTransport.error_request_timeout(),
                             FaultInjectionTransport.error_internal_server_error(),
                             FaultInjectionTransport.error_service_response()])
    def test_retryable_writes_mrw_client_level(self, injected_error):
        # Verify cross regional retries when using retryable writes at client level with multiple write locations.
        # Need to test for 408s, 500s, and ServiceResponseError.
        first_region_uri: str = test_config.TestConfig.local_host.replace("localhost", "127.0.0.1")
        second_region_uri: str = test_config.TestConfig.local_host
        custom_transport = FaultInjectionTransport()

        # Inject topology transformation that would make Emulator look like a multiple write region account
        is_get_account_predicate: Callable[[HttpRequest], bool] = lambda \
            r: FaultInjectionTransport.predicate_is_database_account_call(r)
        emulator_as_multi_write_region_account_transformation = \
            lambda r, inner: FaultInjectionTransport.transform_topology_mwr(
                first_region_name="First Region",
                second_region_name="Second Region",
                inner=inner)
        custom_transport.add_response_transformation(
            is_get_account_predicate,
            emulator_as_multi_write_region_account_transformation)

        # Inject rule to simulate regional outage in "First Region" to test retry happens in next region
        is_request_to_first_region: Callable[[HttpRequest], bool] = lambda \
                r: FaultInjectionTransport.predicate_targets_region(r, first_region_uri) and \
                   FaultInjectionTransport.predicate_is_document_operation(r)

        custom_transport.add_fault(
            is_request_to_first_region,
            lambda r: injected_error)

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

        initialized_objects = self.setup_method_with_custom_transport(
            custom_transport,
            preferred_locations=["First Region", "Second Region"],
            multiple_write_locations=True,
            retry_write=2
        )
        container: ContainerProxy = initialized_objects["col"]

        create_document = container.create_item(body=document_definition)
        request = create_document.get_response_headers()["_request"]
        assert request.url.startswith(second_region_uri)

        upsert_document = container.upsert_item(body=document_definition)
        request = upsert_document.get_response_headers()["_request"]
        assert request.url.startswith(second_region_uri)

        replace_document = container.replace_item(item=document_definition['id'], body=document_definition)
        request = replace_document.get_response_headers()["_request"]
        assert request.url.startswith(second_region_uri)

        # Patch operation should not retry
        operations = [{"op": "add", "path": "/favorite_color", "value": "red"},]
        try:
            container.patch_item(item=document_definition['id'], partition_key=document_definition['pk'],
                                    patch_operations=operations)
        except (ServiceResponseError, exceptions.CosmosHttpResponseError) as e:
            if isinstance(e, exceptions.CosmosHttpResponseError):
                assert e.status_code in [408, 500], "Expected a retryable error for patch_item"

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

        def __call__(self, func, *args, **kwargs):
            self.counter = self.counter + 1
            if self.counter < 2:
                # Simulate a retryable error on the second call
                raise exceptions.CosmosHttpResponseError(
                    status_code=408,
                    message="Simulated timeout error."
                )
            else:
                return self.org_func(func, *args, **kwargs)

    class MockExecuteServiceResponseException(object):
        def __init__(self, err_type):
            self.err_type = err_type
            self.counter = 0

        def __call__(self, func, *args, **kwargs):
            self.counter = self.counter + 1
            exception = ServiceResponseError("mock exception")
            exception.exc_type = self.err_type
            raise exception

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