File: test_excluded_locations_async.py

package info (click to toggle)
python-azure 20250603%2Bgit-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 851,724 kB
  • sloc: python: 7,362,925; ansic: 804; javascript: 287; makefile: 195; sh: 145; xml: 109
file content (346 lines) | stat: -rw-r--r-- 16,746 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
# The MIT License (MIT)
# Copyright (c) Microsoft Corporation. All rights reserved.

import logging
import time
import unittest
import uuid
import test_config
import pytest
import pytest_asyncio

from azure.cosmos.aio import CosmosClient
from azure.cosmos.partition_key import PartitionKey
from test_excluded_locations import (TestDataType, set_test_data_type,
                                     read_item_test_data, write_item_test_data, read_and_write_item_test_data,
                                     verify_endpoint)


class MockHandler(logging.Handler):
    def __init__(self):
        super(MockHandler, self).__init__()
        self.messages = []

    def reset(self):
        self.messages = []

    def emit(self, record):
        self.messages.append(record.msg)

# Test configurations
MOCK_HANDLER = MockHandler()
CONFIG = test_config.TestConfig()
HOST = CONFIG.host
KEY = CONFIG.masterKey
DATABASE_ID = CONFIG.TEST_DATABASE_ID
CONTAINER_ID = CONFIG.TEST_MULTI_PARTITION_PREFIX_PK_CONTAINER_ID
PARTITION_KEY = CONFIG.TEST_CONTAINER_PREFIX_PARTITION_KEY
ITEM_ID = 'doc1'
PARTITION_KEY_VALUES = [f'value{i+1}' for i in range(len(PARTITION_KEY))]
PREFIX_PARTITION_KEY = [PARTITION_KEY_VALUES[0]]
PARTITION_KEY_ITEMS = dict(zip(PARTITION_KEY, PARTITION_KEY_VALUES))
TEST_ITEM = {'id': ITEM_ID}
TEST_ITEM.update(PARTITION_KEY_ITEMS)

set_test_data_type(TestDataType.ALL_TESTS)

async def create_item_with_excluded_locations_async(container, body, excluded_locations):
    if excluded_locations is None:
        await container.create_item(body=body)
    else:
        await container.create_item(body=body, excluded_locations=excluded_locations)

async def init_container_async(client):
    db = client.get_database_client(DATABASE_ID)
    container = db.get_container_client(CONTAINER_ID)
    MOCK_HANDLER.reset()

    return db, container

@pytest_asyncio.fixture(scope="class", autouse=True)
async def setup_and_teardown_async():
    print("Setup: This runs before any tests")
    logger = logging.getLogger("azure")
    logger.addHandler(MOCK_HANDLER)
    logger.setLevel(logging.DEBUG)

    test_client = CosmosClient(HOST, KEY)
    container = test_client.get_database_client(DATABASE_ID).get_container_client(CONTAINER_ID)
    await container.upsert_item(body=TEST_ITEM)
    # Waiting some time for the new items to be replicated to other regions
    time.sleep(3)
    yield
    # Code to run after tests
    print("Teardown: This runs after all tests")

@pytest.mark.cosmosMultiRegion
@pytest.mark.asyncio
@pytest.mark.usefixtures("setup_and_teardown_async")
class TestExcludedLocationsAsync:
    @pytest.mark.parametrize('test_data', read_item_test_data())
    async def test_read_item_async(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        # Client setup
        async with CosmosClient(HOST, KEY,
                              preferred_locations=preferred_locations,
                              excluded_locations=client_excluded_locations,
                              multiple_write_locations=True) as client:
            db, container = await init_container_async(client)

            # API call: read_item
            if request_excluded_locations is None:
                await container.read_item(ITEM_ID, PARTITION_KEY_VALUES)
            else:
                await container.read_item(ITEM_ID, PARTITION_KEY_VALUES, excluded_locations=request_excluded_locations)

            # Verify endpoint locations
            verify_endpoint(MOCK_HANDLER.messages, client, expected_locations)

    @pytest.mark.parametrize('test_data', read_item_test_data())
    async def test_read_all_items_async(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        # Client setup
        async with CosmosClient(HOST, KEY,
                                preferred_locations=preferred_locations,
                                excluded_locations=client_excluded_locations,
                                multiple_write_locations=True) as client:
            db, container = await init_container_async(client)

            # API call: read_all_items
            if request_excluded_locations is None:
                all_items = [item async for item in container.read_all_items()]
            else:
                all_items = [item async for item in container.read_all_items(excluded_locations=request_excluded_locations)]

            # Verify endpoint locations
            verify_endpoint(MOCK_HANDLER.messages, client, expected_locations)

    @pytest.mark.parametrize('test_data', read_item_test_data())
    async def test_query_items_with_partition_key_async(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        # Client setup
        async with CosmosClient(HOST, KEY,
                                preferred_locations=preferred_locations,
                                excluded_locations=client_excluded_locations,
                                multiple_write_locations=True) as client:
            db, container = await init_container_async(client)

            # API call: query_items
            query = 'select * from c'
            if request_excluded_locations is None:
                all_items = [item async for item in container.query_items(query, partition_key=PREFIX_PARTITION_KEY)]
            else:
                all_items = [item async for item in container.query_items(query, partition_key=PREFIX_PARTITION_KEY, excluded_locations=request_excluded_locations)]

            # Verify endpoint locations
            verify_endpoint(MOCK_HANDLER.messages, client, expected_locations)

    @pytest.mark.parametrize('test_data', read_item_test_data())
    async def test_query_items_with_query_plan_async(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        # Client setup
        async with CosmosClient(HOST, KEY,
                                preferred_locations=preferred_locations,
                                excluded_locations=client_excluded_locations,
                                multiple_write_locations=True) as client:
            db, container = await init_container_async(client)

            # API call: query_items
            query = 'Select top 10 value count(c.id) from c'
            if request_excluded_locations is None:
                all_items = [item async for item in container.query_items(query)]
            else:
                all_items = [item async for item in container.query_items(query, excluded_locations=request_excluded_locations)]

            # Verify endpoint locations
            verify_endpoint(MOCK_HANDLER.messages, client, expected_locations)

    @pytest.mark.parametrize('test_data', read_item_test_data())
    async def test_query_items_change_feed_async(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data


        # Client setup
        async with CosmosClient(HOST, KEY,
                                preferred_locations=preferred_locations,
                                excluded_locations=client_excluded_locations,
                                multiple_write_locations=True) as client:
            db, container = await init_container_async(client)
            # API call: query_items_change_feed
            if request_excluded_locations is None:
                all_items = [item async for item in container.query_items_change_feed(start_time="Beginning", partition_key=PREFIX_PARTITION_KEY)]
            else:
                all_items = [item async for item in container.query_items_change_feed(start_time="Beginning", partition_key=PREFIX_PARTITION_KEY, excluded_locations=request_excluded_locations)]

            # Verify endpoint locations
            verify_endpoint(MOCK_HANDLER.messages, client, expected_locations)


    @pytest.mark.parametrize('test_data', read_and_write_item_test_data())
    async def test_replace_item(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        for multiple_write_locations in [True, False]:
            # Client setup
            async with CosmosClient(HOST, KEY,
                                    preferred_locations=preferred_locations,
                                    excluded_locations=client_excluded_locations,
                                    multiple_write_locations=multiple_write_locations) as client:
                db, container = await init_container_async(client)

                # API call: replace_item
                if request_excluded_locations is None:
                    await container.replace_item(ITEM_ID, body=TEST_ITEM)
                else:
                    await container.replace_item(ITEM_ID, body=TEST_ITEM, excluded_locations=request_excluded_locations)

                # Verify endpoint locations
                verify_endpoint(MOCK_HANDLER.messages, client, expected_locations, multiple_write_locations)

    @pytest.mark.parametrize('test_data', read_and_write_item_test_data())
    async def test_upsert_item(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        for multiple_write_locations in [True, False]:
            # Client setup
            async with CosmosClient(HOST, KEY,
                                    preferred_locations=preferred_locations,
                                    excluded_locations=client_excluded_locations,
                                    multiple_write_locations=multiple_write_locations) as client:
                db, container = await init_container_async(client)

                # API call: upsert_item
                body = {'id': f'doc2-{str(uuid.uuid4())}'}
                body.update(PARTITION_KEY_ITEMS)
                if request_excluded_locations is None:
                    await container.upsert_item(body=body)
                else:
                    await container.upsert_item(body=body, excluded_locations=request_excluded_locations)

                # get location from mock_handler
                verify_endpoint(MOCK_HANDLER.messages, client, expected_locations, multiple_write_locations)

    @pytest.mark.parametrize('test_data', read_and_write_item_test_data())
    async def test_create_item(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        for multiple_write_locations in [True, False]:
            # Client setup
            async with CosmosClient(HOST, KEY,
                                    preferred_locations=preferred_locations,
                                    excluded_locations=client_excluded_locations,
                                    multiple_write_locations=multiple_write_locations) as client:
                db, container = await init_container_async(client)

                # API call: create_item
                body = {'id': f'doc2-{str(uuid.uuid4())}'}
                body.update(PARTITION_KEY_ITEMS)
                await create_item_with_excluded_locations_async(container, body, request_excluded_locations)

                # get location from mock_handler
                verify_endpoint(MOCK_HANDLER.messages, client, expected_locations, multiple_write_locations)

    @pytest.mark.parametrize('test_data', read_and_write_item_test_data())
    async def test_patch_item_async(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        for multiple_write_locations in [True, False]:
            # Client setup
            async with CosmosClient(HOST, KEY,
                                    preferred_locations=preferred_locations,
                                    excluded_locations=client_excluded_locations,
                                    multiple_write_locations=multiple_write_locations) as client:
                db, container = await init_container_async(client)

                # API call: patch_item
                operations = [
                    {"op": "add", "path": "/test_data", "value": f'Data-{str(uuid.uuid4())}'},
                ]
                if request_excluded_locations is None:
                    await container.patch_item(item=ITEM_ID, partition_key=PARTITION_KEY_VALUES,
                                         patch_operations=operations)
                else:
                    await container.patch_item(item=ITEM_ID, partition_key=PARTITION_KEY_VALUES,
                                         patch_operations=operations,
                                         excluded_locations=request_excluded_locations)

                # get location from mock_handler
                verify_endpoint(MOCK_HANDLER.messages, client, expected_locations, multiple_write_locations)

    @pytest.mark.parametrize('test_data', read_and_write_item_test_data())
    async def test_execute_item_batch_async(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        for multiple_write_locations in [True, False]:
            # Client setup
            async with CosmosClient(HOST, KEY,
                                    preferred_locations=preferred_locations,
                                    excluded_locations=client_excluded_locations,
                                    multiple_write_locations=multiple_write_locations) as client:
                db, container = await init_container_async(client)

                # API call: execute_item_batch
                batch_operations = []
                for i in range(3):
                    body = {'id': f'doc2-{str(uuid.uuid4())}'}
                    body.update(PARTITION_KEY_ITEMS)
                    batch_operations.append(("create", (
                        body,
                    )))

                if request_excluded_locations is None:
                    await container.execute_item_batch(batch_operations=batch_operations,
                                                partition_key=PARTITION_KEY_VALUES,)
                else:
                    await container.execute_item_batch(batch_operations=batch_operations,
                                                partition_key=PARTITION_KEY_VALUES,
                                         excluded_locations=request_excluded_locations)

                # get location from mock_handler
                verify_endpoint(MOCK_HANDLER.messages, client, expected_locations, multiple_write_locations)

    @pytest.mark.parametrize('test_data', write_item_test_data())
    async def test_delete_item_async(self, test_data):
        # Init test variables
        preferred_locations, client_excluded_locations, request_excluded_locations, expected_locations = test_data

        for multiple_write_locations in [True, False]:
            # Client setup
            async with CosmosClient(HOST, KEY,
                                    preferred_locations=preferred_locations,
                                    excluded_locations=client_excluded_locations,
                                    multiple_write_locations=multiple_write_locations) as client:
                db, container = await init_container_async(client)

                # create before delete
                item_id = f'doc2-{str(uuid.uuid4())}'
                body = {'id': item_id}
                body.update(PARTITION_KEY_ITEMS)
                await create_item_with_excluded_locations_async(container, body, request_excluded_locations)
                MOCK_HANDLER.reset()

                # API call: delete_item
                if request_excluded_locations is None:
                    await container.delete_item(item_id, PARTITION_KEY_VALUES)
                else:
                    await container.delete_item(item_id, PARTITION_KEY_VALUES, excluded_locations=request_excluded_locations)

                # Verify endpoint locations
                verify_endpoint(MOCK_HANDLER.messages, client, expected_locations, multiple_write_locations)

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