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
|
import locale
import os
import sys
from datetime import datetime, timedelta
import pytest
from devtools_testutils import CachedResourceGroupPreparer, CachedStorageAccountPreparer
from azure.core.exceptions import ResourceNotFoundError, ResourceExistsError, HttpResponseError
from _shared.asynctestcase import AsyncTableTestCase
from azure.data.tables import (
AccessPolicy,
TableAnalyticsLogging,
Metrics,
TableSasPermissions,
ResourceTypes,
RetentionPolicy,
AccountSasPermissions,
TableItem
)
from azure.data.tables.aio import TableServiceClient, TableClient
from azure.data.tables._generated.models import QueryOptions
from azure.data.tables._table_shared_access_signature import generate_account_sas
TEST_TABLE_PREFIX = 'pytableasync'
# ------------------------------------------------------------------------------
class TableTestAsync(AsyncTableTestCase):
# --Helpers-----------------------------------------------------------------
def _get_table_reference(self, prefix=TEST_TABLE_PREFIX):
table_name = self.get_resource_name(prefix)
return table_name
async def _create_table(self, ts, prefix=TEST_TABLE_PREFIX, table_list=None):
table_name = self._get_table_reference(prefix)
try:
table = await ts.create_table(table_name)
if table_list is not None:
table_list.append(table)
except ResourceExistsError:
table = ts.get_table_client(table_name)
return table
async def _delete_table(self, ts, table):
if table is None:
return
try:
await ts.delete_table(table.table_name)
except ResourceNotFoundError:
pass
# --Test cases for tables --------------------------------------------------
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_create_table(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table_name = self._get_table_reference()
# Act
created = await ts.create_table(table_name=table_name)
# Assert
assert created.table_name == table_name
await ts.delete_table(table_name=table_name)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_create_table_fail_on_exist(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table_name = self._get_table_reference()
# Act
created = await ts.create_table(table_name=table_name)
with pytest.raises(ResourceExistsError):
await ts.create_table(table_name=table_name)
name_filter = "TableName eq '{}'".format(table_name)
existing = ts.query_tables(filter=name_filter)
# Assert
assert isinstance(created, TableClient)
await ts.delete_table(table_name=table_name)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_query_tables_per_page(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table_name = "myasynctable"
for i in range(5):
await ts.create_table(table_name + str(i))
query_filter = "TableName eq 'myasynctable0' or TableName eq 'myasynctable1' or TableName eq 'myasynctable2'"
table_count = 0
page_count = 0
async for table_page in ts.query_tables(filter=query_filter, results_per_page=2).by_page():
temp_count = 0
async for table in table_page:
temp_count += 1
assert temp_count <= 2
page_count += 1
table_count += temp_count
assert page_count == 2
assert table_count == 3
for i in range(5):
await ts.delete_table(table_name + str(i))
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_create_table_invalid_name(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
invalid_table_name = "my_table"
with pytest.raises(ValueError) as excinfo:
await ts.create_table(table_name=invalid_table_name)
assert "Table names must be alphanumeric, cannot begin with a number, and must be between 3-63 characters long.""" in str(
excinfo)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_delete_table_invalid_name(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
invalid_table_name = "my_table"
with pytest.raises(ValueError) as excinfo:
await ts.create_table(invalid_table_name)
assert "Table names must be alphanumeric, cannot begin with a number, and must be between 3-63 characters long.""" in str(
excinfo)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_list_tables(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table = await self._create_table(ts)
# Act
tables = []
async for t in ts.list_tables():
tables.append(t)
# Assert
for table_item in tables:
assert isinstance(table_item, TableItem)
assert tables is not None
assert len(tables) >= 1
assert tables[0] is not None
await ts.delete_table(table.table_name)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_query_tables_with_filter(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table = await self._create_table(ts)
# Act
name_filter = "TableName eq '{}'".format(table.table_name)
tables = []
async for t in ts.query_tables(filter=name_filter):
tables.append(t)
# Assert
assert tables is not None
assert len(tables) == 1
for table_item in tables:
assert isinstance(table_item, TableItem)
assert table_item.date is not None
assert table_item.table_name is not None
await ts.delete_table(table.table_name)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_list_tables_with_num_results(self, resource_group, location, storage_account, storage_account_key):
# Arrange
prefix = 'listtable'
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
# Delete any existing tables
async for table in ts.list_tables():
await ts.delete_table(table.table_name)
table_list = []
for i in range(0, 4):
await self._create_table(ts, prefix + str(i), table_list)
# Act
big_page = []
async for t in ts.list_tables():
big_page.append(t)
small_page = []
async for s in ts.list_tables(results_per_page=3).by_page():
small_page.append(s)
assert len(small_page) == 2
assert len(big_page) >= 4
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_list_tables_with_marker(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
prefix = 'listtable'
table_names = []
for i in range(0, 4):
await self._create_table(ts, prefix + str(i), table_names)
# Act
generator1 = ts.list_tables(results_per_page=2).by_page()
await generator1.__anext__()
generator2 = ts.list_tables(results_per_page=2).by_page(
continuation_token=generator1.continuation_token)
await generator2.__anext__()
tables1 = generator1._current_page
tables2 = generator2._current_page
tables1_len = 0
async for _ in tables1:
tables1_len += 1
tables2_len = 0
async for _ in tables2:
tables2_len += 1
# Assert
assert tables1_len == 2
assert tables2_len == 2
assert tables1 != tables2
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_delete_table_with_existing_table(self, resource_group, location, storage_account,
storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table = await self._create_table(ts)
# Act
await ts.delete_table(table_name=table.table_name)
existing = ts.query_tables("TableName eq '{}'".format(table.table_name))
tables = []
async for e in existing:
tables.append(e)
assert tables == []
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_delete_table_with_non_existing_table_fail_not_exist(self, resource_group, location, storage_account,
storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table_name = self._get_table_reference()
# Act
with pytest.raises(ResourceNotFoundError):
await ts.delete_table(table_name)
# Assert
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_unicode_create_table_unicode_name(self, resource_group, location, storage_account,
storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table_name = u'啊齄丂狛狜'
# Act
with pytest.raises(ValueError) as excinfo:
await ts.create_table(table_name)
assert "Table names must be alphanumeric, cannot begin with a number, and must be between 3-63 characters long.""" in str(
excinfo)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_get_table_acl(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table = await self._create_table(ts)
try:
# Act
acl = await table.get_table_access_policy()
# Assert
assert acl is not None
assert len(acl) == 0
finally:
await ts.delete_table(table.table_name)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_set_table_acl_with_empty_signed_identifiers(self, resource_group, location, storage_account,
storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table = await self._create_table(ts)
try:
# Act
await table.set_table_access_policy(signed_identifiers={})
# Assert
acl = await table.get_table_access_policy()
assert acl is not None
assert len(acl) == 0
finally:
await ts.delete_table(table.table_name)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_set_table_acl_with_empty_signed_identifier(self, resource_group, location, storage_account,
storage_account_key):
# Arrange
url = self.account_url(storage_account, "table")
ts = TableServiceClient(url, storage_account_key)
table = await self._create_table(ts)
try:
# Act
await table.set_table_access_policy(signed_identifiers={'empty': None})
# Assert
acl = await table.get_table_access_policy()
assert acl is not None
assert len(acl) == 1
assert acl['empty'] is not None
assert acl['empty'].permission is None
assert acl['empty'].expiry is None
assert acl['empty'].start is None
finally:
# self._delete_table(table)
await ts.delete_table(table.table_name)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_set_table_acl_with_signed_identifiers(self, resource_group, location, storage_account,
storage_account_key):
# Arrange
url = self.account_url(storage_account, "table")
ts = TableServiceClient(url, storage_account_key)
table = await self._create_table(ts)
client = ts.get_table_client(table_name=table.table_name)
# Act
identifiers = dict()
identifiers['testid'] = AccessPolicy(start=datetime.utcnow() - timedelta(minutes=5),
expiry=datetime.utcnow() + timedelta(hours=1),
permission=TableSasPermissions(read=True))
try:
await client.set_table_access_policy(signed_identifiers=identifiers)
# Assert
acl = await client.get_table_access_policy()
assert acl is not None
assert len(acl) == 1
assert 'testid' in acl
finally:
await ts.delete_table(table.table_name)
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_set_table_acl_too_many_ids(self, resource_group, location, storage_account, storage_account_key):
# Arrange
url = self.account_url(storage_account, "table")
ts = TableServiceClient(url, storage_account_key)
table = await self._create_table(ts)
try:
# Act
identifiers = dict()
for i in range(0, 6):
identifiers['id{}'.format(i)] = None
# Assert
with pytest.raises(ValueError):
await table.set_table_access_policy(table_name=table.table_name, signed_identifiers=identifiers)
finally:
await ts.delete_table(table.table_name)
@pytest.mark.live_test_only
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_account_sas(self, resource_group, location, storage_account, storage_account_key):
# SAS URL is calculated from storage key, so this test runs live only
# Arrange
account_url = self.account_url(storage_account, "table")
tsc = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table = await self._create_table(tsc)
try:
entity = {
'PartitionKey': 'test',
'RowKey': 'test1',
'text': 'hello',
}
await table.upsert_entity(entity=entity)
entity['RowKey'] = 'test2'
await table.upsert_entity(entity=entity)
token = generate_account_sas(
storage_account.name,
storage_account_key,
resource_types=ResourceTypes(object=True),
permission=AccountSasPermissions(read=True),
expiry=datetime.utcnow() + timedelta(hours=1),
start=datetime.utcnow() - timedelta(minutes=1),
)
account_url = self.account_url(storage_account, "table")
service = self.create_client_from_credential(TableServiceClient, token, account_url=account_url)
# Act
sas_table = service.get_table_client(table.table_name)
entities = []
async for e in sas_table.list_entities():
entities.append(e)
# Assert
assert len(entities) == 2
assert entities[0].text == u'hello'
assert entities[1].text == u'hello'
finally:
await self._delete_table(table=table, ts=tsc)
@pytest.mark.skip("Test fails on Linux and in Python2. Throws a locale.Error: unsupported locale setting")
@CachedResourceGroupPreparer(name_prefix="tablestest")
@CachedStorageAccountPreparer(name_prefix="tablestest")
async def test_locale(self, resource_group, location, storage_account, storage_account_key):
# Arrange
account_url = self.account_url(storage_account, "table")
ts = self.create_client_from_credential(TableServiceClient, storage_account_key, account_url=account_url)
table = (self._get_table_reference())
init_locale = locale.getlocale()
if os.name == "nt":
culture = "Spanish_Spain"
elif os.name == 'posix':
culture = 'es_ES.UTF-8'
else:
culture = 'es_ES.utf8'
locale.setlocale(locale.LC_ALL, culture)
e = None
# Act
await ts.create_table(table)
resp = ts.list_tables()
e = sys.exc_info()[0]
# Assert
assert e is None
await ts.delete_table(table)
locale.setlocale(locale.LC_ALL, init_locale[0] or 'en_US')
|