-
Notifications
You must be signed in to change notification settings - Fork 3k
/
Copy pathtest_crud_async.py
2514 lines (2112 loc) · 112 KB
/
test_crud_async.py
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
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# The MIT License (MIT)
# Copyright (c) Microsoft Corporation. All rights reserved.
"""End-to-end test.
"""
import json
import logging
import os.path
import time
import unittest
import urllib.parse as urllib
import uuid
import pytest
import requests
from azure.core import MatchConditions
from azure.core.exceptions import AzureError, ServiceResponseError
from azure.core.pipeline.transport import AsyncioRequestsTransport, AsyncioRequestsTransportResponse
import azure.cosmos._base as base
import azure.cosmos.documents as documents
import azure.cosmos.exceptions as exceptions
import test_config
from azure.cosmos.aio import CosmosClient, _retry_utility_async, DatabaseProxy
from azure.cosmos.http_constants import HttpHeaders, StatusCodes
from azure.cosmos.partition_key import PartitionKey
from azure.identity.aio import DefaultAzureCredential
class TimeoutTransport(AsyncioRequestsTransport):
def __init__(self, response):
self._response = response
super(TimeoutTransport, self).__init__()
async def send(self, *args, **kwargs):
if kwargs.pop("passthrough", False):
return super(TimeoutTransport, self).send(*args, **kwargs)
time.sleep(5)
if isinstance(self._response, Exception):
raise self._response
current_response = await self._response
output = requests.Response()
output.status_code = current_response
response = AsyncioRequestsTransportResponse(None, output)
return response
@pytest.mark.cosmosLong
class TestCRUDOperationsAsync(unittest.IsolatedAsyncioTestCase):
"""Python CRUD Tests.
"""
client: CosmosClient = None
configs = test_config.TestConfig
host = configs.host
masterKey = configs.masterKey
connectionPolicy = configs.connectionPolicy
last_headers = []
database_for_test: DatabaseProxy = None
async def __assert_http_failure_with_status(self, status_code, func, *args, **kwargs):
"""Assert HTTP failure with status.
:Parameters:
- `status_code`: int
- `func`: function
"""
try:
await func(*args, **kwargs)
self.fail('function should fail.')
except exceptions.CosmosHttpResponseError as inst:
assert 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 asyncSetUp(self):
credentials = DefaultAzureCredential()
self.client = CosmosClient(self.host, credentials)
self.database_for_test = self.client.get_database_client(self.configs.TEST_DATABASE_ID)
async def asyncTearDown(self):
await self.client.close()
async def test_database_crud_async(self):
database_id = str(uuid.uuid4())
created_db = await self.client.create_database(database_id)
assert created_db.id == database_id
# query databases.
databases = [database async for database in self.client.query_databases(
query='SELECT * FROM root r WHERE r.id=@id',
parameters=[
{'name': '@id', 'value': database_id}
]
)]
assert len(databases) > 0
# read database.
self.client.get_database_client(created_db.id)
await created_db.read()
# delete database.
await self.client.delete_database(created_db.id)
# read database after deletion
read_db = self.client.get_database_client(created_db.id)
await self.__assert_http_failure_with_status(StatusCodes.NOT_FOUND, read_db.read)
database_proxy = await self.client.create_database_if_not_exists(id=database_id, offer_throughput=5000)
assert database_id == database_proxy.id
db_throughput = await database_proxy.get_throughput()
assert 5000 == db_throughput.offer_throughput
database_proxy = await self.client.create_database_if_not_exists(id=database_id, offer_throughput=6000)
assert database_id == database_proxy.id
db_throughput = await database_proxy.get_throughput()
assert 5000 == db_throughput.offer_throughput
# delete database.
await self.client.delete_database(database_id)
async def test_database_level_offer_throughput_async(self):
# Create a database with throughput
offer_throughput = 1000
database_id = str(uuid.uuid4())
created_db = await self.client.create_database(
id=database_id,
offer_throughput=offer_throughput
)
assert created_db.id == database_id
# Verify offer throughput for database
offer = await created_db.get_throughput()
assert offer.offer_throughput == offer_throughput
# Update database offer throughput
new_offer_throughput = 2000
offer = await created_db.replace_throughput(new_offer_throughput)
assert offer.offer_throughput == new_offer_throughput
await self.client.delete_database(database_id)
async def test_sql_query_crud_async(self):
# create two databases.
db1 = await self.client.create_database('database 1' + str(uuid.uuid4()))
db2 = await self.client.create_database('database 2' + str(uuid.uuid4()))
# query with parameters.
databases = [database async for database in self.client.query_databases(
query='SELECT * FROM root r WHERE r.id=@id',
parameters=[
{'name': '@id', 'value': db1.id}
]
)]
assert 1 == len(databases)
# query without parameters.
databases = [database async for database in self.client.query_databases(
query='SELECT * FROM root r WHERE r.id="database non-existing"'
)]
assert 0 == len(databases)
# query with a string.
query_string = 'SELECT * FROM root r WHERE r.id="' + db2.id + '"'
databases = [database async for database in
self.client.query_databases(query=query_string)]
assert 1 == len(databases)
await self.client.delete_database(db1.id)
await self.client.delete_database(db2.id)
async def test_collection_crud_async(self):
created_db = self.database_for_test
collections = [collection async for collection in created_db.list_containers()]
# create a collection
before_create_collections_count = len(collections)
collection_id = 'test_collection_crud ' + str(uuid.uuid4())
collection_indexing_policy = {'indexingMode': 'consistent'}
created_collection = await created_db.create_container(id=collection_id,
indexing_policy=collection_indexing_policy,
partition_key=PartitionKey(path="/pk", kind="Hash"))
assert collection_id == created_collection.id
created_properties = await created_collection.read()
assert 'consistent' == created_properties['indexingPolicy']['indexingMode']
assert PartitionKey(path='/pk', kind='Hash') == created_properties['partitionKey']
# read collections after creation
collections = [collection async for collection in created_db.list_containers()]
assert len(collections) == before_create_collections_count + 1
# query collections
collections = [collection async for collection in created_db.query_containers(
query='SELECT * FROM root r WHERE r.id=@id',
parameters=[
{'name': '@id', 'value': collection_id}
]
)]
assert len(collections) > 0
# delete collection
await created_db.delete_container(created_collection.id)
# read collection after deletion
created_container = created_db.get_container_client(created_collection.id)
await self.__assert_http_failure_with_status(StatusCodes.NOT_FOUND,
created_container.read)
async def test_partitioned_collection_async(self):
created_db = self.database_for_test
collection_definition = {'id': 'test_partitioned_collection ' + str(uuid.uuid4()),
'partitionKey':
{
'paths': ['/id'],
'kind': documents.PartitionKind.Hash
}
}
offer_throughput = 10100
created_collection = await created_db.create_container(id=collection_definition['id'],
partition_key=collection_definition['partitionKey'],
offer_throughput=offer_throughput)
assert collection_definition.get('id') == created_collection.id
created_collection_properties = await created_collection.read()
assert collection_definition.get('partitionKey').get('paths')[0] == \
created_collection_properties['partitionKey']['paths'][0]
assert collection_definition.get('partitionKey').get('kind') == created_collection_properties['partitionKey'][
'kind']
expected_offer = await created_collection.get_throughput()
assert expected_offer is not None
assert expected_offer.offer_throughput == offer_throughput
await created_db.delete_container(created_collection.id)
async def test_partitioned_collection_quota_async(self):
created_db = self.database_for_test
created_collection = self.database_for_test.get_container_client(
self.configs.TEST_MULTI_PARTITION_CONTAINER_ID)
retrieved_collection_properties = await created_collection.read(
populate_partition_key_range_statistics=True,
populate_quota_info=True)
assert retrieved_collection_properties.get("statistics") is not None
assert created_db.client_connection.last_response_headers.get("x-ms-resource-usage") is not None
async def test_partitioned_collection_partition_key_extraction_async(self):
created_db = self.database_for_test
collection_id = 'test_partitioned_collection_partition_key_extraction ' + str(uuid.uuid4())
created_collection = await created_db.create_container(
id=collection_id,
partition_key=PartitionKey(path='/address/state', kind=documents.PartitionKind.Hash)
)
document_definition = {'id': 'document1',
'address': {'street': '1 Microsoft Way',
'city': 'Redmond',
'state': 'WA',
'zip code': 98052
}
}
self.OriginalExecuteFunction = _retry_utility_async.ExecuteFunctionAsync
_retry_utility_async.ExecuteFunctionAsync = self._mock_execute_function
# create document without partition key being specified
created_document = await created_collection.create_item(body=document_definition)
_retry_utility_async.ExecuteFunctionAsync = self.OriginalExecuteFunction
assert self.last_headers[0] == '["WA"]'
del self.last_headers[:]
assert created_document.get('id') == document_definition.get('id')
assert created_document.get('address').get('state') == document_definition.get('address').get('state')
collection_id = 'test_partitioned_collection_partition_key_extraction1 ' + str(uuid.uuid4())
created_collection1 = await created_db.create_container(
id=collection_id,
partition_key=PartitionKey(path='/address', kind=documents.PartitionKind.Hash)
)
self.OriginalExecuteFunction = _retry_utility_async.ExecuteFunctionAsync
_retry_utility_async.ExecuteFunctionAsync = self._mock_execute_function
# Create document with partitionkey not present as a leaf level property but a dict
await created_collection1.create_item(document_definition)
_retry_utility_async.ExecuteFunctionAsync = self.OriginalExecuteFunction
assert self.last_headers[0] == [{}]
del self.last_headers[:]
collection_id = 'test_partitioned_collection_partition_key_extraction2 ' + str(uuid.uuid4())
created_collection2 = await created_db.create_container(
id=collection_id,
partition_key=PartitionKey(path='/address/state/city', kind=documents.PartitionKind.Hash)
)
self.OriginalExecuteFunction = _retry_utility_async.ExecuteFunctionAsync
_retry_utility_async.ExecuteFunctionAsync = self._mock_execute_function
# Create document with partitionkey not present in the document
await created_collection2.create_item(document_definition)
_retry_utility_async.ExecuteFunctionAsync = self.OriginalExecuteFunction
assert self.last_headers[0] == [{}]
del self.last_headers[:]
await created_db.delete_container(created_collection.id)
await created_db.delete_container(created_collection1.id)
await created_db.delete_container(created_collection2.id)
async def test_partitioned_collection_partition_key_extraction_special_chars_async(self):
created_db = self.database_for_test
collection_id = 'test_partitioned_collection_partition_key_extraction_special_chars1 ' + str(uuid.uuid4())
created_collection1 = await created_db.create_container(
id=collection_id,
partition_key=PartitionKey(path='/\"level\' 1*()\"/\"le/vel2\"', kind=documents.PartitionKind.Hash)
)
document_definition = {'id': 'document1',
"level' 1*()": {"le/vel2": 'val1'}
}
self.OriginalExecuteFunction = _retry_utility_async.ExecuteFunctionAsync
_retry_utility_async.ExecuteFunctionAsync = self._mock_execute_function
await created_collection1.create_item(body=document_definition)
_retry_utility_async.ExecuteFunctionAsync = self.OriginalExecuteFunction
assert self.last_headers[0] == '["val1"]'
del self.last_headers[:]
collection_id = 'test_partitioned_collection_partition_key_extraction_special_chars2 ' + str(uuid.uuid4())
created_collection2 = await created_db.create_container(
id=collection_id,
partition_key=PartitionKey(path='/\'level\" 1*()\'/\'le/vel2\'', kind=documents.PartitionKind.Hash)
)
document_definition = {'id': 'document2',
'level\" 1*()': {'le/vel2': 'val2'}
}
self.OriginalExecuteFunction = _retry_utility_async.ExecuteFunctionAsync
_retry_utility_async.ExecuteFunctionAsync = self._mock_execute_function
# create document without partition key being specified
await created_collection2.create_item(body=document_definition)
_retry_utility_async.ExecuteFunctionAsync = self.OriginalExecuteFunction
assert self.last_headers[0] == '["val2"]'
del self.last_headers[:]
await created_db.delete_container(created_collection1.id)
await created_db.delete_container(created_collection2.id)
def test_partitioned_collection_path_parser(self):
test_dir = os.path.dirname(os.path.abspath(__file__))
with open(os.path.join(test_dir, "BaselineTest.PathParser.json")) as json_file:
entries = json.loads(json_file.read())
for entry in entries:
parts = base.ParsePaths([entry['path']])
assert parts == entry['parts']
paths = ["/\"Ke \\ \\\" \\\' \\? \\a \\\b \\\f \\\n \\\r \\\t \\v y1\"/*"]
parts = ["Ke \\ \\\" \\\' \\? \\a \\\b \\\f \\\n \\\r \\\t \\v y1", "*"]
assert parts == base.ParsePaths(paths)
paths = ["/'Ke \\ \\\" \\\' \\? \\a \\\b \\\f \\\n \\\r \\\t \\v y1'/*"]
parts = ["Ke \\ \\\" \\\' \\? \\a \\\b \\\f \\\n \\\r \\\t \\v y1", "*"]
assert parts == base.ParsePaths(paths)
async def test_partitioned_collection_document_crud_and_query_async(self):
created_collection = await self.database_for_test.create_container(str(uuid.uuid4()), PartitionKey(path="/id"))
document_definition = {'id': 'document',
'key': 'value'}
created_document = await created_collection.create_item(body=document_definition)
assert created_document.get('id') == document_definition.get('id')
assert created_document.get('key') == document_definition.get('key')
# read document
read_document = await created_collection.read_item(
item=created_document.get('id'),
partition_key=created_document.get('id')
)
assert read_document.get('id') == created_document.get('id')
assert read_document.get('key') == created_document.get('key')
# Read document feed doesn't require partitionKey as it's always a cross partition query
document_list = [document async for document in created_collection.read_all_items()]
assert 1 == len(document_list)
# replace document
document_definition['key'] = 'new value'
replaced_document = await created_collection.replace_item(
item=read_document,
body=document_definition
)
assert replaced_document.get('key') == document_definition.get('key')
# upsert document(create scenario)
document_definition['id'] = 'document2'
document_definition['key'] = 'value2'
upserted_document = await created_collection.upsert_item(body=document_definition)
assert upserted_document.get('id') == document_definition.get('id')
assert upserted_document.get('key') == document_definition.get('key')
document_list = [document async for document in created_collection.read_all_items()]
assert len(document_list) == 2
# delete document
await created_collection.delete_item(item=upserted_document, partition_key=upserted_document.get('id'))
# query document on the partition key specified in the predicate will pass even without setting enableCrossPartitionQuery or passing in the partitionKey value
document_list = [document async for document in created_collection.query_items(
query='SELECT * FROM root r WHERE r.id=\'' + replaced_document.get('id') + '\'' # nosec
)]
assert len(document_list) == 1
# cross partition query
document_list = [document async for document in created_collection.query_items(
query='SELECT * FROM root r WHERE r.key=\'' + replaced_document.get('key') + '\'')]
assert len(document_list) == 1
# query document by providing the partitionKey value
document_list = [document async for document in created_collection.query_items(
query='SELECT * FROM root r WHERE r.key=\'' + replaced_document.get('key') + '\'', # nosec
partition_key=replaced_document.get('id')
)]
assert len(document_list) == 1
await self.database_for_test.delete_container(created_collection.id)
async def test_partitioned_collection_permissions_async(self):
created_db = self.database_for_test
collection_id = 'test_partitioned_collection_permissions all collection' + str(uuid.uuid4())
all_collection = await created_db.create_container(
id=collection_id,
partition_key=PartitionKey(path='/key', kind=documents.PartitionKind.Hash)
)
collection_id = 'test_partitioned_collection_permissions read collection' + str(uuid.uuid4())
read_collection = await created_db.create_container(
id=collection_id,
partition_key=PartitionKey(path='/key', kind=documents.PartitionKind.Hash)
)
user = await created_db.create_user(body={'id': 'user' + str(uuid.uuid4())})
permission_definition = {
'id': 'all permission',
'permissionMode': documents.PermissionMode.All,
'resource': all_collection.container_link,
'resourcePartitionKey': [1]
}
all_permission = await user.create_permission(body=permission_definition)
permission_definition = {
'id': 'read permission',
'permissionMode': documents.PermissionMode.Read,
'resource': read_collection.container_link,
'resourcePartitionKey': [1]
}
read_permission = await user.create_permission(body=permission_definition)
resource_tokens = {}
# storing the resource tokens based on Resource IDs
resource_tokens["dbs/" + created_db.id + "/colls/" + all_collection.id] = (all_permission.properties['_token'])
resource_tokens["dbs/" + created_db.id + "/colls/" + read_collection.id] = (
read_permission.properties['_token'])
async with CosmosClient(TestCRUDOperationsAsync.host, resource_tokens) as restricted_client:
print('Async Initialization')
document_definition = {'id': 'document1',
'key': 1
}
all_collection.client_connection = restricted_client.client_connection
read_collection.client_connection = restricted_client.client_connection
# Create document in all_collection should succeed since the partitionKey is 1 which is what specified as resourcePartitionKey in permission object and it has all permissions
created_document = await all_collection.create_item(body=document_definition)
# Create document in read_collection should fail since it has only read permissions for this collection
await self.__assert_http_failure_with_status(
StatusCodes.FORBIDDEN,
read_collection.create_item,
document_definition)
document_definition['key'] = 2
# Create document should fail since the partitionKey is 2 which is different that what is specified as resourcePartitionKey in permission object
await self.__assert_http_failure_with_status(
StatusCodes.FORBIDDEN,
all_collection.create_item,
document_definition)
document_definition['key'] = 1
# Delete document should succeed since the partitionKey is 1 which is what specified as resourcePartitionKey in permission object
await all_collection.delete_item(item=created_document['id'],
partition_key=document_definition['key'])
# Delete document in read_collection should fail since it has only read permissions for this collection
await self.__assert_http_failure_with_status(
StatusCodes.FORBIDDEN,
read_collection.delete_item,
document_definition['id'],
document_definition['id']
)
await self.database_for_test.delete_container(all_collection.id)
await self.database_for_test.delete_container(read_collection.id)
async def test_partitioned_collection_execute_stored_procedure_async(self):
created_collection = self.database_for_test.get_container_client(self.configs.TEST_MULTI_PARTITION_CONTAINER_ID)
document_id = str(uuid.uuid4())
sproc = {
'id': 'storedProcedure' + str(uuid.uuid4()),
'body': (
'function () {' +
' var client = getContext().getCollection();' +
' client.createDocument(client.getSelfLink(), { id: "' + document_id + '", pk : 2}, ' +
' {}, function(err, docCreated, options) { ' +
' if(err) throw new Error(\'Error while creating document: \' + err.message);' +
' else {' +
' getContext().getResponse().setBody(1);' +
' }' +
' });}')
}
created_sproc = await created_collection.scripts.create_stored_procedure(body=sproc)
# Partiton Key value same as what is specified in the stored procedure body
result = await created_collection.scripts.execute_stored_procedure(sproc=created_sproc['id'], partition_key=2)
assert result == 1
# Partiton Key value different than what is specified in the stored procedure body will cause a bad request(400) error
await self.__assert_http_failure_with_status(
StatusCodes.BAD_REQUEST,
created_collection.scripts.execute_stored_procedure,
created_sproc['id'])
async def test_partitioned_collection_partition_key_value_types_async(self):
created_db = self.database_for_test
created_collection = created_db.get_container_client(self.configs.TEST_MULTI_PARTITION_CONTAINER_ID)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk': None,
'spam': 'eggs'}
# create document with partitionKey set as None here
await created_collection.create_item(body=document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'spam': 'eggs'}
# create document with partitionKey set as Undefined here
await created_collection.create_item(body=document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk': True,
'spam': 'eggs'}
# create document with bool partitionKey
await created_collection.create_item(body=document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk': 'value',
'spam': 'eggs'}
# create document with string partitionKey
await created_collection.create_item(body=document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk': 100,
'spam': 'eggs'}
# create document with int partitionKey
await created_collection.create_item(body=document_definition)
document_definition = {'id': 'document1' + str(uuid.uuid4()),
'pk': 10.50,
'spam': 'eggs'}
# create document with float partitionKey
await created_collection.create_item(body=document_definition)
document_definition = {'name': 'sample document',
'spam': 'eggs',
'pk': 'value'}
# Should throw an error because automatic id generation is disabled always.
await self.__assert_http_failure_with_status(
StatusCodes.BAD_REQUEST,
created_collection.create_item,
document_definition
)
async def test_partitioned_collection_conflict_crud_and_query_async(self):
created_collection = self.database_for_test.get_container_client(self.configs.TEST_MULTI_PARTITION_CONTAINER_ID)
conflict_definition = {'id': 'new conflict',
'resourceId': 'doc1',
'operationType': 'create',
'resourceType': 'document'
}
# read conflict here will return resource not found(404) since there is no conflict here
await self.__assert_http_failure_with_status(
StatusCodes.NOT_FOUND,
created_collection.get_conflict,
conflict_definition['id'],
conflict_definition['id']
)
# Read conflict feed doesn't require partitionKey to be specified as it's a cross partition thing
conflict_list = [conflict async for conflict in created_collection.list_conflicts()]
assert len(conflict_list) == 0
# delete conflict here will return resource not found(404) since there is no conflict here
await self.__assert_http_failure_with_status(
StatusCodes.NOT_FOUND,
created_collection.delete_conflict,
conflict_definition['id'],
conflict_definition['id']
)
conflict_list = [conflict async for conflict in created_collection.query_conflicts(
query='SELECT * FROM root r WHERE r.resourceType=\'' + conflict_definition.get('resourceType') + '\'')]
assert len(conflict_list) == 0
# query conflicts by providing the partitionKey value
options = {'partitionKey': conflict_definition.get('id')}
conflict_list = [conflict async for conflict in created_collection.query_conflicts(
query='SELECT * FROM root r WHERE r.resourceType=\'' + conflict_definition.get('resourceType') + '\'',
# nosec
partition_key=conflict_definition['id']
)]
assert len(conflict_list) == 0
async def test_document_crud_async(self):
# create collection
created_collection = self.database_for_test.get_container_client(self.configs.TEST_MULTI_PARTITION_CONTAINER_ID)
# read documents
document_list = [document async for document in created_collection.read_all_items()]
# create a document
before_create_documents_count = len(document_list)
# create a document with auto ID generation
document_definition = {'name': 'sample document',
'spam': 'eggs',
'key': 'value',
'pk': 'pk'}
created_document = await created_collection.create_item(body=document_definition,
enable_automatic_id_generation=True)
assert created_document.get('name') == document_definition['name']
document_definition = {'name': 'sample document',
'spam': 'eggs',
'key': 'value',
'pk': 'pk',
'id': str(uuid.uuid4())}
created_document = await created_collection.create_item(body=document_definition)
assert created_document.get('name') == document_definition['name']
assert created_document.get('id') == document_definition['id']
# duplicated documents are not allowed when 'id' is provided.
duplicated_definition_with_id = document_definition.copy()
await self.__assert_http_failure_with_status(StatusCodes.CONFLICT,
created_collection.create_item,
duplicated_definition_with_id)
# read documents after creation
document_list = [document async for document in created_collection.read_all_items()]
assert len(document_list) == before_create_documents_count + 2
# query documents
document_list = [document async for document in created_collection.query_items(
query='SELECT * FROM root r WHERE r.name=@name',
parameters=[{'name': '@name', 'value': document_definition['name']}]
)]
assert document_list is not None
document_list = [document async for document in created_collection.query_items(
query='SELECT * FROM root r WHERE r.name=@name',
parameters=[
{'name': '@name', 'value': document_definition['name']}
],
enable_scan_in_query=True
)]
assert document_list is not None
# replace document.
created_document['name'] = 'replaced document'
created_document['spam'] = 'not eggs'
old_etag = created_document['_etag']
replaced_document = await created_collection.replace_item(
item=created_document['id'],
body=created_document
)
assert replaced_document['name'] == 'replaced document'
assert replaced_document['spam'] == 'not eggs'
assert created_document['id'] == replaced_document['id']
# replace document based on condition
replaced_document['name'] = 'replaced document based on condition'
replaced_document['spam'] = 'new spam field'
# should fail for stale etag
await self.__assert_http_failure_with_status(
StatusCodes.PRECONDITION_FAILED,
created_collection.replace_item,
replaced_document['id'],
replaced_document,
if_match=old_etag,
)
# should fail if only etag specified
try:
await created_collection.replace_item(
etag=replaced_document['_etag'],
item=replaced_document['id'],
body=replaced_document)
self.fail("should fail if only etag specified")
except ValueError:
pass
# should fail if only match condition specified
try:
await created_collection.replace_item(
match_condition=MatchConditions.IfNotModified,
item=replaced_document['id'],
body=replaced_document)
self.fail("should fail if only match condition specified")
except ValueError:
pass
try:
await created_collection.replace_item(
match_condition=MatchConditions.IfModified,
item=replaced_document['id'],
body=replaced_document)
self.fail("should fail if only match condition specified")
except ValueError:
pass
# should fail if invalid match condition specified
try:
await created_collection.replace_item(
match_condition=replaced_document['_etag'],
item=replaced_document['id'],
body=replaced_document)
self.fail("should fail if invalid match condition specified")
except TypeError:
pass
# should pass for most recent etag
replaced_document_conditional = await created_collection.replace_item(
match_condition=MatchConditions.IfNotModified,
etag=replaced_document['_etag'],
item=replaced_document['id'],
body=replaced_document
)
assert replaced_document_conditional['name'] == 'replaced document based on condition'
assert replaced_document_conditional['spam'] == 'new spam field'
assert replaced_document_conditional['id'] == replaced_document['id']
# read document
one_document_from_read = await created_collection.read_item(
item=replaced_document['id'],
partition_key=replaced_document['pk']
)
assert replaced_document['id'] == one_document_from_read['id']
# delete document
await created_collection.delete_item(
item=replaced_document,
partition_key=replaced_document['pk']
)
# read documents after deletion
await self.__assert_http_failure_with_status(StatusCodes.NOT_FOUND,
created_collection.read_item,
replaced_document['id'],
replaced_document['id'])
async def test_document_upsert_async(self):
# create collection
created_collection = self.database_for_test.get_container_client(self.configs.TEST_MULTI_PARTITION_CONTAINER_ID)
# read documents and check count
document_list = [document async for document in created_collection.read_all_items()]
before_create_documents_count = len(document_list)
# create document definition
document_definition = {'id': 'doc',
'name': 'sample document',
'spam': 'eggs',
'key': 'value',
'pk': 'pk'}
# create document using Upsert API
created_document = await created_collection.upsert_item(body=document_definition)
# verify id property
assert created_document['id'] == document_definition['id']
# test error for non-string id
with self.assertRaises(TypeError):
document_definition['id'] = 7
await created_collection.upsert_item(body=document_definition)
# read documents after creation and verify updated count
document_list = [document async for document in created_collection.read_all_items()]
assert len(document_list) == before_create_documents_count + 1
# update document
created_document['name'] = 'replaced document'
created_document['spam'] = 'not eggs'
# should replace document since it already exists
upserted_document = await created_collection.upsert_item(body=created_document)
# verify the changed properties
assert upserted_document['name'] == created_document['name']
assert upserted_document['spam'] == created_document['spam']
# verify id property
assert upserted_document['id'] == created_document['id']
# read documents after upsert and verify count doesn't increases again
document_list = [document async for document in created_collection.read_all_items()]
assert len(document_list) == before_create_documents_count + 1
created_document['id'] = 'new id'
# Upsert should create new document since the id is different
new_document = await created_collection.upsert_item(body=created_document)
# Test modified access conditions
created_document['spam'] = 'more eggs'
await created_collection.upsert_item(body=created_document)
with self.assertRaises(exceptions.CosmosHttpResponseError):
await created_collection.upsert_item(
body=created_document,
match_condition=MatchConditions.IfNotModified,
etag=new_document['_etag'])
# verify id property
assert created_document['id'] == new_document['id']
# read documents after upsert and verify count increases
document_list = [document async for document in created_collection.read_all_items()]
assert len(document_list) == before_create_documents_count + 2
# delete documents
await created_collection.delete_item(item=upserted_document, partition_key=upserted_document['pk'])
await created_collection.delete_item(item=new_document, partition_key=new_document['pk'])
# read documents after delete and verify count is same as original
document_list = [document async for document in created_collection.read_all_items()]
assert len(document_list) == before_create_documents_count
async def test_geospatial_index_async(self):
db = self.database_for_test
# partial policy specified
collection = await db.create_container(
id='collection with spatial index ' + str(uuid.uuid4()),
indexing_policy={
'includedPaths': [
{
'path': '/"Location"/?',
'indexes': [
{
'kind': 'Spatial',
'dataType': 'Point'
}
]
},
{
'path': '/'
}
]
},
partition_key=PartitionKey(path='/id', kind='Hash')
)
await collection.create_item(
body={
'id': 'loc1',
'Location': {
'type': 'Point',
'coordinates': [20.0, 20.0]
}
}
)
await collection.create_item(
body={
'id': 'loc2',
'Location': {
'type': 'Point',
'coordinates': [100.0, 100.0]
}
}
)
results = [result async for result in collection.query_items(
query="SELECT * FROM root WHERE (ST_DISTANCE(root.Location, {type: 'Point', coordinates: [20.1, 20]}) < 20000)")]
assert len(results) == 1
assert 'loc1' == results[0]['id']
# CRUD test for User resource
async def test_user_crud_async(self):
# Should do User CRUD operations successfully.
# create database
db = self.database_for_test
# list users
users = [user async for user in db.list_users()]
before_create_count = len(users)
# create user
user_id = 'new user' + str(uuid.uuid4())
user = await db.create_user(body={'id': user_id})
assert user.id == user_id
# list users after creation
users = [user async for user in db.list_users()]
assert len(users) == before_create_count + 1
# query users
results = [user async for user in db.query_users(
query='SELECT * FROM root r WHERE r.id=@id',
parameters=[
{'name': '@id', 'value': user_id}
]
)]
assert results is not None
# replace user
replaced_user_id = 'replaced user' + str(uuid.uuid4())
user_properties = await user.read()
user_properties['id'] = replaced_user_id
replaced_user = await db.replace_user(user_id, user_properties)
assert replaced_user.id == replaced_user_id
assert user_properties['id'] == replaced_user.id
# read user
user = db.get_user_client(replaced_user.id)
assert replaced_user.id == user.id
# delete user
await db.delete_user(user.id)
# read user after deletion
deleted_user = db.get_user_client(user.id)
await self.__assert_http_failure_with_status(StatusCodes.NOT_FOUND,
deleted_user.read)
async def test_user_upsert_async(self):
# create database
db = self.database_for_test
# read users and check count
users = [user async for user in db.list_users()]
before_create_count = len(users)
# create user using Upsert API
user_id = 'user' + str(uuid.uuid4())
user = await db.upsert_user(body={'id': user_id})
# verify id property
assert user.id == user_id
# read users after creation and verify updated count
users = [user async for user in db.list_users()]
assert len(users) == before_create_count + 1
# Should replace the user since it already exists, there is no public property to change here