File: test_table_aad_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 (326 lines) | stat: -rw-r--r-- 13,235 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
# coding: utf-8

# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
import pytest
from datetime import datetime

from devtools_testutils import AzureRecordedTestCase, set_custom_default_matcher
from devtools_testutils.aio import recorded_by_proxy_async

from azure.data.tables.aio import TableServiceClient, TableClient

from azure.core.exceptions import HttpResponseError, ResourceNotFoundError
from azure.data.tables import (
    TableAnalyticsLogging,
    TableMetrics,
    TableRetentionPolicy,
    EntityProperty,
    EdmType,
    TableEntity,
    TransactionOperation,
    UpdateMode,
)

from _shared.asynctestcase import AsyncTableTestCase
from async_preparers import tables_decorator_async


class TestTableAADAsync(AzureRecordedTestCase, AsyncTableTestCase):
    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_create_table(self, tables_storage_account_name):
        try:
            account_url = self.account_url(tables_storage_account_name, "table")
            ts = TableServiceClient(credential=self.get_token_credential(), endpoint=account_url)
            table_name = self._get_table_reference()
            await ts.create_table(table_name)

            if table_name not in [t.name async for t in ts.list_tables()]:
                raise AssertionError("Table could not be found")

            await ts.delete_table(table_name)
            if table_name in [t.name async for t in ts.list_tables()]:
                raise AssertionError("Table was not deleted")

        finally:
            await ts.delete_table(table_name)

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_query_list_tables(self, tables_storage_account_name):
        try:
            account_url = self.account_url(tables_storage_account_name, "table")
            ts = TableServiceClient(credential=self.get_token_credential(), endpoint=account_url)
            table_name1 = self._get_table_reference(prefix="table1")
            table_name2 = self._get_table_reference(prefix="table2")
            table_name3 = self._get_table_reference(prefix="table3")
            table_name4 = self._get_table_reference(prefix="table4")
            await ts.create_table(table_name1)
            await ts.create_table(table_name2)
            await ts.create_table(table_name3)
            await ts.create_table(table_name4)

            count = 0
            async for table in ts.list_tables():
                count += 1

            assert count == 4

            query_filter = "TableName eq '{}'".format(table_name2)
            count = 0
            async for table in ts.query_tables(query_filter):
                count += 1
                assert table.name == table_name2
            assert count == 1

        finally:
            async for table in ts.list_tables():
                await ts.delete_table(table.name)

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_create_table_tc(self, tables_storage_account_name):
        try:
            account_url = self.account_url(tables_storage_account_name, "table")
            ts = TableServiceClient(credential=self.get_token_credential(), endpoint=account_url)
            table_name = self._get_table_reference()
            table_client = TableClient(
                credential=self.get_token_credential(), endpoint=account_url, table_name=table_name
            )
            await table_client.create_table()

            if table_name not in [t.name async for t in ts.list_tables()]:
                raise AssertionError("Table could not be found")

            await table_client.delete_table()
            if table_name in [t.name async for t in ts.list_tables()]:
                raise AssertionError("Table was not deleted")

        finally:
            await ts.delete_table(table_name)

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_service_properties(self, tables_storage_account_name):
        try:
            account_url = self.account_url(tables_storage_account_name, "table")
            ts = TableServiceClient(credential=self.get_token_credential(), endpoint=account_url)
            table_name = self._get_table_reference()
            created = await ts.create_table(table_name)

            assert created.table_name == table_name

            properties = await ts.get_service_properties()
            await ts.set_service_properties(analytics_logging=TableAnalyticsLogging(write=True))
            # have to wait async for return to service
            p = await ts.get_service_properties()
            # have to wait async for return to service
            await ts.set_service_properties(
                minute_metrics=TableMetrics(
                    enabled=True, include_apis=True, retention_policy=TableRetentionPolicy(enabled=True, days=5)
                )
            )

            ps = await ts.get_service_properties()
        finally:
            await ts.delete_table(table_name)

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_table_service_stats(self, tables_storage_account_name):
        tsc = TableServiceClient(
            self.account_url(tables_storage_account_name, "table"), credential=self.get_token_credential()
        )
        stats = await tsc.get_service_stats(raw_response_hook=self.override_response_body_with_live_status)
        self._assert_stats_default(stats)

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_insert_entity_dictionary(self, tables_storage_account_name):

        await self._set_up(tables_storage_account_name, self.get_token_credential())
        try:
            entity = self._create_random_entity_dict()
            resp = await self.table.create_entity(entity=entity)

            self._assert_valid_metadata(resp)
        finally:
            await self._tear_down()

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_query_user_filter(self, tables_storage_account_name):

        await self._set_up(tables_storage_account_name, self.get_token_credential())
        try:
            entity, _ = await self._insert_two_opposite_entities()

            entities = self.table.query_entities("married eq @my_param", parameters={"my_param": entity["married"]})

            assert entities is not None
            length = 0
            async for e in entities:
                self._assert_default_entity(e)
                length += 1

            assert length == 1
        finally:
            await self._tear_down()

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_batch_all_operations_together(self, tables_storage_account_name):
        # this can be reverted to set_bodiless_matcher() after tests are re-recorded and don't contain these headers
        set_custom_default_matcher(
            compare_bodies=False, excluded_headers="Authorization,Content-Length,x-ms-client-request-id,x-ms-request-id"
        )

        await self._set_up(tables_storage_account_name, self.get_token_credential())
        try:

            entity = TableEntity()
            entity["PartitionKey"] = "003"
            entity["RowKey"] = "batch_all_operations_together-1"
            entity["test"] = EntityProperty(True, EdmType.BOOLEAN)
            entity["test2"] = "value"
            entity["test3"] = 3
            entity["test4"] = EntityProperty(1234567890, EdmType.INT32)
            entity["test5"] = datetime.utcnow()

            await self.table.create_entity(entity)
            entity["RowKey"] = "batch_all_operations_together-2"
            await self.table.create_entity(entity)
            entity["RowKey"] = "batch_all_operations_together-3"
            await self.table.create_entity(entity)
            entity["RowKey"] = "batch_all_operations_together-4"
            await self.table.create_entity(entity)
            transaction_count = 0

            batch = []
            entity["RowKey"] = "batch_all_operations_together"
            batch.append((TransactionOperation.CREATE, entity.copy()))
            transaction_count += 1

            entity["RowKey"] = "batch_all_operations_together-1"
            batch.append((TransactionOperation.DELETE, entity.copy()))
            transaction_count += 1

            entity["RowKey"] = "batch_all_operations_together-2"
            entity["test3"] = 10
            batch.append((TransactionOperation.UPDATE, entity.copy()))
            transaction_count += 1

            entity["RowKey"] = "batch_all_operations_together-3"
            entity["test3"] = 100
            batch.append((TransactionOperation.UPDATE, entity.copy(), {"mode": UpdateMode.REPLACE}))
            transaction_count += 1

            entity["RowKey"] = "batch_all_operations_together-4"
            entity["test3"] = 10
            batch.append((TransactionOperation.UPSERT, entity.copy()))
            transaction_count += 1

            entity["RowKey"] = "batch_all_operations_together-5"
            batch.append((TransactionOperation.UPSERT, entity.copy(), {"mode": UpdateMode.REPLACE}))
            transaction_count += 1

            transaction_result = await self.table.submit_transaction(batch)

            self._assert_valid_batch_transaction(transaction_result, transaction_count)
            assert "etag" in transaction_result[0]
            assert "etag" not in transaction_result[1]
            assert "etag" in transaction_result[2]
            assert "etag" in transaction_result[3]
            assert "etag" in transaction_result[4]
            assert "etag" in transaction_result[5]

            entity_count = 0
            async for e in self.table.query_entities("PartitionKey eq '003'"):
                entity_count += 1
            assert 5 == entity_count
        finally:
            await self._tear_down()

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_access_policy_error(self, tables_storage_account_name):
        account_url = self.account_url(tables_storage_account_name, "table")
        table_name = self._get_table_reference()
        table_client = TableClient(credential=self.get_token_credential(), endpoint=account_url, table_name=table_name)

        with pytest.raises(HttpResponseError):
            await table_client.get_table_access_policy()

        with pytest.raises(HttpResponseError):
            await table_client.set_table_access_policy(signed_identifiers={})

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_delete_entities(self, tables_storage_account_name):
        await self._set_up(tables_storage_account_name, self.get_token_credential())
        try:
            entity, _ = await self._insert_random_entity()
            await self.table.delete_entity(entity)

            with pytest.raises(ResourceNotFoundError):
                await self.table.get_entity(entity["PartitionKey"], entity["RowKey"])

        finally:
            await self._tear_down()

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_query_user_filter(self, tables_storage_account_name):

        await self._set_up(tables_storage_account_name, self.get_token_credential())
        try:
            entity, _ = await self._insert_two_opposite_entities()

            entities = self.table.query_entities("married eq @my_param", parameters={"my_param": entity["married"]})

            assert entities is not None
            length = 0
            async for e in entities:
                self._assert_default_entity(e)
                length += 1

            assert length == 1
        finally:
            await self._tear_down()

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_aad_list_entities(self, tables_storage_account_name):
        await self._set_up(tables_storage_account_name, self.get_token_credential())
        try:
            table = await self._create_query_table(2)

            entities = table.list_entities()

            count = 0
            async for entity in entities:
                self._assert_default_entity(entity)
                count += 1
            assert count == 2
        finally:
            await self._tear_down()

    @tables_decorator_async
    @recorded_by_proxy_async
    async def test_merge_entity(self, tables_storage_account_name):
        await self._set_up(tables_storage_account_name, self.get_token_credential())
        try:
            entity, _ = await self._insert_random_entity()

            sent_entity = self._create_updated_entity_dict(entity["PartitionKey"], entity["RowKey"])
            resp = await self.table.update_entity(mode=UpdateMode.MERGE, entity=sent_entity)

            self._assert_valid_metadata(resp)
            received_entity = await self.table.get_entity(entity["PartitionKey"], entity["RowKey"])
            self._assert_merged_entity(received_entity)
        finally:
            await self._tear_down()