-
Notifications
You must be signed in to change notification settings - Fork 533
Expand file tree
/
Copy pathContainerSettingsTests.cs
More file actions
1265 lines (1116 loc) · 62.6 KB
/
ContainerSettingsTests.cs
File metadata and controls
1265 lines (1116 loc) · 62.6 KB
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
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.SDK.EmulatorTests
{
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
// Similar tests to CosmosContainerTests but with Fluent syntax
[TestClass]
public class ContainerSettingsTests : BaseCosmosClientHelper
{
private static long ToEpoch(DateTime dateTime) => (long)(dateTime - new DateTime(1970, 1, 1)).TotalSeconds;
[TestInitialize]
public async Task TestInitialize()
{
await base.TestInit();
}
[TestCleanup]
public async Task Cleanup()
{
await base.TestCleanup();
}
[TestMethod]
public async Task ContainerContractTest()
{
DatabaseInlineCore databaseInlineCore = (DatabaseInlineCore)this.database;
await TestCommon.CreateClientEncryptionKey("dekId", databaseInlineCore);
ClientEncryptionIncludedPath clientEncryptionIncludedPath1 = new ClientEncryptionIncludedPath()
{
Path = "/path",
ClientEncryptionKeyId = "dekId",
EncryptionAlgorithm = "AEAD_AES_256_CBC_HMAC_SHA256",
EncryptionType = "Randomized"
};
Collection<ClientEncryptionIncludedPath> paths = new Collection<ClientEncryptionIncludedPath>()
{
clientEncryptionIncludedPath1
};
ContainerProperties containerProperties = new ContainerProperties(Guid.NewGuid().ToString(), "/users")
{
IndexingPolicy = new IndexingPolicy()
{
Automatic = true,
IndexingMode = IndexingMode.Consistent,
IncludedPaths = new Collection<IncludedPath>()
{
new IncludedPath()
{
Path = "/*"
}
},
ExcludedPaths = new Collection<ExcludedPath>()
{
new ExcludedPath()
{
Path = "/test/*"
}
},
CompositeIndexes = new Collection<Collection<CompositePath>>()
{
new Collection<CompositePath>()
{
new CompositePath()
{
Path = "/address/city",
Order = CompositePathSortOrder.Ascending
},
new CompositePath()
{
Path = "/address/zipcode",
Order = CompositePathSortOrder.Descending
}
}
},
SpatialIndexes = new Collection<SpatialPath>()
{
new SpatialPath()
{
Path = "/address/spatial/*",
SpatialTypes = new Collection<SpatialType>()
{
SpatialType.LineString
}
}
}
},
// ComputedProperties = new Collection<ComputedProperty>
// {
// { new ComputedProperty{ Name = "lowerName", Query = "SELECT VALUE LOWER(c.Name) FROM c" } },
// { new ComputedProperty{ Name = "fullName", Query = "SELECT VALUE CONCAT(c.Name, ' ', c.LastName) FROM c" } }
// },
ClientEncryptionPolicy = new ClientEncryptionPolicy(paths)
};
CosmosJsonDotNetSerializer serializer = new CosmosJsonDotNetSerializer();
Stream stream = serializer.ToStream(containerProperties);
ContainerProperties deserialziedTest = serializer.FromStream<ContainerProperties>(stream);
ContainerResponse response = await this.database.CreateContainerAsync(containerProperties);
Assert.IsNotNull(response);
Assert.IsTrue(response.RequestCharge > 0);
Assert.IsNotNull(response.Headers);
Assert.IsNotNull(response.Headers.ActivityId);
ContainerProperties responseProperties = response.Resource;
Assert.IsNotNull(responseProperties.Id);
Assert.IsNotNull(responseProperties.ResourceId);
Assert.IsNotNull(responseProperties.ETag);
Assert.IsTrue(responseProperties.LastModified.HasValue);
Assert.IsTrue(responseProperties.LastModified.Value > new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc), responseProperties.LastModified.Value.ToString());
Assert.AreEqual(1, responseProperties.IndexingPolicy.IncludedPaths.Count);
IncludedPath includedPath = responseProperties.IndexingPolicy.IncludedPaths.First();
Assert.AreEqual("/*", includedPath.Path);
Assert.AreEqual("/test/*", responseProperties.IndexingPolicy.ExcludedPaths.First().Path);
Assert.AreEqual(1, responseProperties.IndexingPolicy.CompositeIndexes.Count);
Assert.AreEqual(2, responseProperties.IndexingPolicy.CompositeIndexes.First().Count);
CompositePath compositePath = responseProperties.IndexingPolicy.CompositeIndexes.First().First();
Assert.AreEqual("/address/city", compositePath.Path);
Assert.AreEqual(CompositePathSortOrder.Ascending, compositePath.Order);
Assert.AreEqual(1, responseProperties.IndexingPolicy.SpatialIndexes.Count);
SpatialPath spatialPath = responseProperties.IndexingPolicy.SpatialIndexes.First();
Assert.AreEqual("/address/spatial/*", spatialPath.Path);
Assert.AreEqual(4, spatialPath.SpatialTypes.Count); // All SpatialTypes are returned
Assert.AreEqual(1, responseProperties.ClientEncryptionPolicy.IncludedPaths.Count());
Assert.IsTrue(responseProperties.ClientEncryptionPolicy.PolicyFormatVersion <= 2);
ClientEncryptionIncludedPath clientEncryptionIncludedPath = responseProperties.ClientEncryptionPolicy.IncludedPaths.First();
Assert.IsTrue(this.VerifyClientEncryptionIncludedPath(clientEncryptionIncludedPath1, clientEncryptionIncludedPath));
ComputedPropertyComparer.AssertAreEqual(containerProperties.ComputedProperties, responseProperties.ComputedProperties);
ComputedPropertyComparer.AssertAreEqual(containerProperties.ComputedProperties, deserialziedTest.ComputedProperties);
}
[Ignore]
[TestMethod]
public async Task ContainerNegativeComputedPropertyTest()
{
string query = "SELECT VALUE LOWER(c.name) FROM c";
var variations = new[]
{
new
{
ComputedProperties = new Collection<ComputedProperty>
{
new ComputedProperty {Name = "lowerName", Query = @"SELECT VALUE LOWER(c.name) FROM c"},
new ComputedProperty {Name = "lowerName", Query = @"SELECT VALUE LOWER(c.lastName) FROM c"}
},
Error = @"""Errors"":[""Computed property name 'lowerName' cannot be used in multiple definitions.""]"
},
new
{
ComputedProperties = new Collection<ComputedProperty>{ new ComputedProperty { Query = query } },
Error = @"""Errors"":[""One of the specified inputs is invalid""]"
},
new
{
ComputedProperties = new Collection<ComputedProperty>{ new ComputedProperty { Name = "", Query = query } },
Error = @"""Errors"":[""Computed property 'name' is either empty or unspecified.""]"
},
new
{
ComputedProperties = new Collection<ComputedProperty>{ new ComputedProperty { Name = "lowerName" } },
Error = @"""Errors"":[""One of the specified inputs is invalid""]"
},
new
{
ComputedProperties = new Collection<ComputedProperty>{ new ComputedProperty { Name = "lowerName", Query = "" } },
Error = @"""Errors"":[""Computed property 'query' is either empty or unspecified.""]"
},
new
{
ComputedProperties = new Collection<ComputedProperty>{ new ComputedProperty { Name = "id", Query = query } },
Error = @"""Errors"":[""The system property name 'id' cannot be used as a computed property name.""]"
},
new
{
ComputedProperties = new Collection<ComputedProperty>{ new ComputedProperty { Name = "spatial", Query = query } },
Error = @"""Errors"":[""Computed property 'spatial' at index (0) has a spatial index. Remove the spatial index on this path.""]"
},
new
{
ComputedProperties = new Collection<ComputedProperty>{ new ComputedProperty {Name = "lowerName", Query = @"SELECT LOWER(c.name) FROM c"} },
Error = @"""Errors"":[""Required VALUE expression missing from computed property query 'SELECT LOWER(c.name) FROM c' at index (0).""]"
},
new
{
ComputedProperties = new Collection<ComputedProperty>{ new ComputedProperty {Name = "lowerName", Query = @"SELECT LOWER(c.name) FROM r"} },
Error = @"""Errors"":[""Computed property at index (0) has a malformed query: 'SELECT LOWER(c.name) FROM r' Error details: '{\""errors\"":[{\""severity\"":\""Error\"",\""code\"":2001,\""message\"":\""Identifier 'c' could not be resolved.\""}]}'""]"
},
};
IndexingPolicy indexingPolicy = new IndexingPolicy
{
SpatialIndexes = new Collection<SpatialPath>
{
new SpatialPath
{
Path = "/spatial/*",
SpatialTypes = new Collection<Cosmos.SpatialType>()
{
Cosmos.SpatialType.LineString,
Cosmos.SpatialType.MultiPolygon,
Cosmos.SpatialType.Point,
Cosmos.SpatialType.Polygon,
}
}
}
};
// Create
foreach (var variation in variations)
{
ContainerProperties containerProperties = new ContainerProperties(Guid.NewGuid().ToString(), "/users")
{
IndexingPolicy = indexingPolicy,
GeospatialConfig = new GeospatialConfig(GeospatialType.Geography),
ComputedProperties = variation.ComputedProperties
};
try
{
ContainerResponse response = await this.database.CreateContainerAsync(containerProperties);
Assert.Fail($@"Computed Property '{variation.ComputedProperties.Last().Name}' Query '{variation.ComputedProperties.Last().Query}' was expected to fail with error '{variation.Error}'.");
}
catch (CosmosException ce) when (ce.StatusCode == HttpStatusCode.BadRequest)
{
Assert.IsTrue(ce.Message.Contains(variation.Error), $"Message expected to contain:'{variation.Error}'{Environment.NewLine}Actual Message: '{ce.Message}'");
}
}
// Replace
Container containerToReplace = await this.database.CreateContainerAsync(new ContainerProperties(Guid.NewGuid().ToString(), "/users"));
foreach (var variation in variations)
{
ContainerProperties containerProperties = new ContainerProperties(Guid.NewGuid().ToString(), "/users")
{
IndexingPolicy = indexingPolicy,
GeospatialConfig = new GeospatialConfig(GeospatialType.Geography),
ComputedProperties = variation.ComputedProperties
};
try
{
ContainerResponse response = await containerToReplace.ReplaceContainerAsync(containerProperties);
Assert.Fail($@"Computed Property '{variation.ComputedProperties.Last().Name}' Query '{variation.ComputedProperties.Last().Query}' was expected to fail with error '{variation.Error}'.");
}
catch (CosmosException ce) when (ce.StatusCode == HttpStatusCode.BadRequest)
{
Assert.IsTrue(ce.Message.Contains(variation.Error), $"Message expected to contain:'{variation.Error}'{Environment.NewLine}Actual Message: '{ce.Message}'");
}
}
}
[TestMethod]
public async Task ContainerNegativeSpatialIndexTest()
{
ContainerProperties containerProperties = new ContainerProperties(Guid.NewGuid().ToString(), "/users")
{
IndexingPolicy = new IndexingPolicy()
{
SpatialIndexes = new Collection<SpatialPath>()
{
new SpatialPath()
{
Path = "/address/spatial/*"
}
}
}
};
try
{
ContainerResponse response = await this.database.CreateContainerAsync(containerProperties);
Assert.Fail("Should require spatial type");
}
catch (CosmosException ce) when (ce.StatusCode == HttpStatusCode.BadRequest)
{
Assert.IsTrue(ce.Message.Contains("The spatial data types array cannot be empty. Assign at least one spatial type for the 'types' array for the path"));
}
}
[TestMethod]
public async Task ContainerMigrationTest()
{
string containerName = "MigrationIndexTest";
Documents.Index index1 = new Documents.RangeIndex(Documents.DataType.String, -1);
Documents.Index index2 = new Documents.RangeIndex(Documents.DataType.Number, -1);
Documents.DocumentCollection documentCollection = new Microsoft.Azure.Documents.DocumentCollection()
{
Id = containerName,
IndexingPolicy = new Documents.IndexingPolicy()
{
IncludedPaths = new Collection<Documents.IncludedPath>()
{
new Documents.IncludedPath()
{
Path = "/*",
Indexes = new Collection<Documents.Index>()
{
index1,
index2
}
}
}
}
};
Documents.DocumentCollection createResponse = await NonPartitionedContainerHelper.CreateNonPartitionedContainer(this.database, documentCollection);
// Verify the collection was created with deprecated Index objects
Assert.AreEqual(2, createResponse.IndexingPolicy.IncludedPaths.First().Indexes.Count);
Documents.Index createIndex = createResponse.IndexingPolicy.IncludedPaths.First().Indexes.First();
Assert.AreEqual(index1.Kind, createIndex.Kind);
// Verify v3 can add composite indexes and update the container
Container container = this.database.GetContainer(containerName);
ContainerProperties containerProperties = await container.ReadContainerAsync();
Assert.IsNotNull(containerProperties.SelfLink);
string cPath0 = "/address/city";
string cPath1 = "/address/state";
containerProperties.IndexingPolicy.CompositeIndexes.Add(new Collection<CompositePath>()
{
new CompositePath()
{
Path= cPath0,
Order = CompositePathSortOrder.Descending
},
new CompositePath()
{
Path= cPath1,
Order = CompositePathSortOrder.Ascending
}
});
containerProperties.IndexingPolicy.SpatialIndexes.Add(
new SpatialPath()
{
Path = "/address/test/*",
SpatialTypes = new Collection<SpatialType>() { SpatialType.Point }
});
// List<ComputedProperty> computedProperties = new List<ComputedProperty>
// {
// new ComputedProperty() { Name = "lowerName", Query = "SELECT VALUE LOWER(c.name) FROM c" },
// new ComputedProperty() { Name = "estimatedTax", Query = "SELECT VALUE c.salary * 0.2 FROM c" }
// };
// foreach (ComputedProperty computedProperty in computedProperties)
// {
// containerProperties.ComputedProperties.Add(computedProperty);
// }
ContainerProperties propertiesAfterReplace = await container.ReplaceContainerAsync(containerProperties);
Assert.AreEqual(0, propertiesAfterReplace.IndexingPolicy.IncludedPaths.First().Indexes.Count);
Assert.AreEqual(1, propertiesAfterReplace.IndexingPolicy.CompositeIndexes.Count);
Collection<CompositePath> compositePaths = propertiesAfterReplace.IndexingPolicy.CompositeIndexes.First();
Assert.AreEqual(2, compositePaths.Count);
CompositePath compositePath0 = compositePaths.ElementAt(0);
CompositePath compositePath1 = compositePaths.ElementAt(1);
Assert.IsTrue(string.Equals(cPath0, compositePath0.Path) || string.Equals(cPath1, compositePath0.Path));
Assert.IsTrue(string.Equals(cPath0, compositePath1.Path) || string.Equals(cPath1, compositePath1.Path));
Assert.AreEqual(1, propertiesAfterReplace.IndexingPolicy.SpatialIndexes.Count);
Assert.AreEqual("/address/test/*", propertiesAfterReplace.IndexingPolicy.SpatialIndexes.First().Path);
ComputedPropertyComparer.AssertAreEqual(containerProperties.ComputedProperties, propertiesAfterReplace.ComputedProperties);
}
[TestMethod]
public async Task PartitionedCRUDTest()
{
string containerName = Guid.NewGuid().ToString();
string partitionKeyPath = "/users";
ContainerResponse containerResponse =
await this.database.DefineContainer(containerName, partitionKeyPath)
.WithIndexingPolicy()
.WithIndexingMode(IndexingMode.None)
.WithAutomaticIndexing(false)
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
Container container = containerResponse;
Assert.AreEqual(IndexingMode.None, containerResponse.Resource.IndexingPolicy.IndexingMode);
Assert.IsFalse(containerResponse.Resource.IndexingPolicy.Automatic);
containerResponse = await container.ReadContainerAsync();
Assert.AreEqual(HttpStatusCode.OK, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
Assert.AreEqual(IndexingMode.None, containerResponse.Resource.IndexingPolicy.IndexingMode);
Assert.IsFalse(containerResponse.Resource.IndexingPolicy.Automatic);
containerResponse = await containerResponse.Container.DeleteContainerAsync();
Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
}
[TestMethod]
public async Task WithUniqueKeys()
{
string containerName = Guid.NewGuid().ToString();
string partitionKeyPath = "/users";
ContainerResponse containerResponse =
await this.database.DefineContainer(containerName, partitionKeyPath)
.WithUniqueKey()
.Path("/attribute1")
.Path("/attribute2")
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
Container container = containerResponse;
Assert.AreEqual(1, containerResponse.Resource.UniqueKeyPolicy.UniqueKeys.Count);
Assert.AreEqual(2, containerResponse.Resource.UniqueKeyPolicy.UniqueKeys[0].Paths.Count);
Assert.AreEqual("/attribute1", containerResponse.Resource.UniqueKeyPolicy.UniqueKeys[0].Paths[0]);
Assert.AreEqual("/attribute2", containerResponse.Resource.UniqueKeyPolicy.UniqueKeys[0].Paths[1]);
containerResponse = await container.ReadContainerAsync();
Assert.AreEqual(HttpStatusCode.OK, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
Assert.AreEqual(1, containerResponse.Resource.UniqueKeyPolicy.UniqueKeys.Count);
Assert.AreEqual(2, containerResponse.Resource.UniqueKeyPolicy.UniqueKeys[0].Paths.Count);
Assert.AreEqual("/attribute1", containerResponse.Resource.UniqueKeyPolicy.UniqueKeys[0].Paths[0]);
Assert.AreEqual("/attribute2", containerResponse.Resource.UniqueKeyPolicy.UniqueKeys[0].Paths[1]);
containerResponse = await containerResponse.Container.DeleteContainerAsync();
Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
}
[TestMethod]
public async Task TestConflictResolutionPolicy()
{
Database databaseForConflicts = await this.GetClient().CreateDatabaseAsync("conflictResolutionContainerTest",
cancellationToken: this.cancellationToken);
try
{
string containerName = "conflictResolutionContainerTest";
string partitionKeyPath = "/users";
ContainerResponse containerResponse =
await databaseForConflicts.DefineContainer(containerName, partitionKeyPath)
.WithConflictResolution()
.WithLastWriterWinsResolution("/lww")
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
ContainerProperties containerSettings = containerResponse.Resource;
Assert.IsNotNull(containerSettings.ConflictResolutionPolicy);
Assert.AreEqual(ConflictResolutionMode.LastWriterWins, containerSettings.ConflictResolutionPolicy.Mode);
Assert.AreEqual("/lww", containerSettings.ConflictResolutionPolicy.ResolutionPath);
Assert.IsTrue(string.IsNullOrEmpty(containerSettings.ConflictResolutionPolicy.ResolutionProcedure));
// Delete container
await containerResponse.Container.DeleteContainerAsync();
// Re-create with custom policy
string sprocName = "customresolsproc";
containerResponse = await databaseForConflicts.DefineContainer(containerName, partitionKeyPath)
.WithConflictResolution()
.WithCustomStoredProcedureResolution(sprocName)
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
containerSettings = containerResponse.Resource;
Assert.IsNotNull(containerSettings.ConflictResolutionPolicy);
Assert.AreEqual(ConflictResolutionMode.Custom, containerSettings.ConflictResolutionPolicy.Mode);
Assert.AreEqual(UriFactory.CreateStoredProcedureUri(databaseForConflicts.Id, containerName, sprocName), containerSettings.ConflictResolutionPolicy.ResolutionProcedure);
Assert.IsTrue(string.IsNullOrEmpty(containerSettings.ConflictResolutionPolicy.ResolutionPath));
}
finally
{
await databaseForConflicts.DeleteAsync();
}
}
[TestMethod]
public async Task TestChangeFeedPolicy()
{
Database databaseForChangeFeed = await this.GetClient().CreateDatabaseAsync("changeFeedRetentionContainerTest",
cancellationToken: this.cancellationToken);
try
{
string containerName = "changeFeedRetentionContainerTest";
string partitionKeyPath = "/users";
TimeSpan retention = TimeSpan.FromMinutes(10);
ContainerResponse containerResponse =
await databaseForChangeFeed.DefineContainer(containerName, partitionKeyPath)
.WithChangeFeedPolicy(retention)
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
ContainerProperties containerSettings = containerResponse.Resource;
Assert.IsNotNull(containerSettings.ChangeFeedPolicy);
Assert.AreEqual(retention.TotalMinutes, containerSettings.ChangeFeedPolicy.FullFidelityRetention.TotalMinutes);
}
finally
{
await databaseForChangeFeed.DeleteAsync();
}
}
[TestMethod]
[Ignore("This test will be enabled once the vector similarity changes are made available into the public emulator.")]
public async Task TestVectorEmbeddingPolicy()
{
string vector1Path = "/vector1", vector2Path = "/vector2", vector3Path = "/vector3";
Database databaseForVectorEmbedding = await this.GetClient().CreateDatabaseAsync("vectorEmbeddingContainerTest",
cancellationToken: this.cancellationToken);
try
{
Collection<Embedding> embeddings = new Collection<Embedding>()
{
new Embedding()
{
Path = vector1Path,
DataType = VectorDataType.Int8,
DistanceFunction = DistanceFunction.DotProduct,
Dimensions = 1200,
},
new Embedding()
{
Path = vector2Path,
DataType = VectorDataType.Uint8,
DistanceFunction = DistanceFunction.Cosine,
Dimensions = 3,
},
new Embedding()
{
Path = vector3Path,
DataType = VectorDataType.Float32,
DistanceFunction = DistanceFunction.Euclidean,
Dimensions = 400,
},
};
string containerName = "vectorEmbeddingContainerTest";
string partitionKeyPath = "/users";
ContainerResponse containerResponse =
await databaseForVectorEmbedding.DefineContainer(containerName, partitionKeyPath)
.WithVectorEmbeddingPolicy(embeddings)
.Attach()
.WithIndexingPolicy()
.WithVectorIndex()
.Path(vector1Path, VectorIndexType.Flat)
.Attach()
.WithVectorIndex()
.Path(vector2Path, VectorIndexType.QuantizedFlat)
.WithQuantizationByteSize(3)
.WithVectorIndexShardKey(new string[] { "/Country" })
.Attach()
.WithVectorIndex()
.Path(vector3Path, VectorIndexType.DiskANN)
.WithQuantizationByteSize(2)
.WithIndexingSearchListSize(35)
.WithVectorIndexShardKey(new string[] { "/ZipCode" })
.Attach()
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
ContainerProperties containerSettings = containerResponse.Resource;
// Validate Vector Embeddings.
Assert.IsNotNull(containerSettings.VectorEmbeddingPolicy);
Assert.IsNotNull(containerSettings.VectorEmbeddingPolicy.Embeddings);
Assert.AreEqual(embeddings.Count, containerSettings.VectorEmbeddingPolicy.Embeddings.Count());
Assert.IsTrue(embeddings.OrderBy(x => x.Path).SequenceEqual(containerSettings.VectorEmbeddingPolicy.Embeddings.OrderBy(x => x.Path)));
// Validate Vector Indexes.
Assert.IsNotNull(containerSettings.IndexingPolicy.VectorIndexes);
Assert.AreEqual(embeddings.Count, containerSettings.IndexingPolicy.VectorIndexes.Count());
Assert.AreEqual(vector1Path, containerSettings.IndexingPolicy.VectorIndexes[0].Path);
Assert.AreEqual(VectorIndexType.Flat, containerSettings.IndexingPolicy.VectorIndexes[0].Type);
Assert.AreEqual(vector2Path, containerSettings.IndexingPolicy.VectorIndexes[1].Path);
Assert.AreEqual(VectorIndexType.QuantizedFlat, containerSettings.IndexingPolicy.VectorIndexes[1].Type);
Assert.AreEqual(3, containerSettings.IndexingPolicy.VectorIndexes[1].QuantizationByteSize);
CollectionAssert.AreEqual(new string[] { "/Country" }, containerSettings.IndexingPolicy.VectorIndexes[1].VectorIndexShardKey);
Assert.AreEqual(vector3Path, containerSettings.IndexingPolicy.VectorIndexes[2].Path);
Assert.AreEqual(VectorIndexType.DiskANN, containerSettings.IndexingPolicy.VectorIndexes[2].Type);
Assert.AreEqual(2, containerSettings.IndexingPolicy.VectorIndexes[2].QuantizationByteSize);
Assert.AreEqual(35, containerSettings.IndexingPolicy.VectorIndexes[2].IndexingSearchListSize);
CollectionAssert.AreEqual(new string[] { "/ZipCode" }, containerSettings.IndexingPolicy.VectorIndexes[2].VectorIndexShardKey);
}
finally
{
await databaseForVectorEmbedding.DeleteAsync();
}
}
[TestMethod]
public async Task WithIndexingPolicy()
{
string containerName = Guid.NewGuid().ToString();
string partitionKeyPath = "/users";
ContainerResponse containerResponse =
await this.database.DefineContainer(containerName, partitionKeyPath)
.WithIndexingPolicy()
.WithIncludedPaths()
.Path("/included1/*")
.Path("/included2/*")
.Attach()
.WithExcludedPaths()
.Path("/*")
.Attach()
.WithCompositeIndex()
.Path("/composite1")
.Path("/composite2", CompositePathSortOrder.Descending)
.Attach()
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
Container container = containerResponse;
Assert.AreEqual(2, containerResponse.Resource.IndexingPolicy.IncludedPaths.Count);
Assert.AreEqual("/included1/*", containerResponse.Resource.IndexingPolicy.IncludedPaths[0].Path);
Assert.AreEqual("/included2/*", containerResponse.Resource.IndexingPolicy.IncludedPaths[1].Path);
Assert.AreEqual("/*", containerResponse.Resource.IndexingPolicy.ExcludedPaths[0].Path);
Assert.AreEqual(1, containerResponse.Resource.IndexingPolicy.CompositeIndexes.Count);
Assert.AreEqual("/composite1", containerResponse.Resource.IndexingPolicy.CompositeIndexes[0][0].Path);
Assert.AreEqual("/composite2", containerResponse.Resource.IndexingPolicy.CompositeIndexes[0][1].Path);
Assert.AreEqual(CompositePathSortOrder.Descending, containerResponse.Resource.IndexingPolicy.CompositeIndexes[0][1].Order);
containerResponse = await container.ReadContainerAsync();
Assert.AreEqual(HttpStatusCode.OK, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
Assert.AreEqual(2, containerResponse.Resource.IndexingPolicy.IncludedPaths.Count);
Assert.AreEqual("/included1/*", containerResponse.Resource.IndexingPolicy.IncludedPaths[0].Path);
Assert.AreEqual("/included2/*", containerResponse.Resource.IndexingPolicy.IncludedPaths[1].Path);
Assert.AreEqual("/*", containerResponse.Resource.IndexingPolicy.ExcludedPaths[0].Path);
Assert.AreEqual(1, containerResponse.Resource.IndexingPolicy.CompositeIndexes.Count);
Assert.AreEqual("/composite1", containerResponse.Resource.IndexingPolicy.CompositeIndexes[0][0].Path);
Assert.AreEqual("/composite2", containerResponse.Resource.IndexingPolicy.CompositeIndexes[0][1].Path);
Assert.AreEqual(CompositePathSortOrder.Descending, containerResponse.Resource.IndexingPolicy.CompositeIndexes[0][1].Order);
containerResponse = await containerResponse.Container.DeleteContainerAsync();
Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
}
[TestMethod]
public async Task TestFullTextSearchPolicy()
{
string fullTextPath1 = "/fts1", fullTextPath2 = "/fts2", fullTextPath3 = "/fts3";
Database databaseForVectorEmbedding = await this.GetClient().CreateDatabaseAsync("fullTextSearchDB",
cancellationToken: this.cancellationToken);
try
{
Collection<FullTextPath> fullTextPaths = new Collection<FullTextPath>()
{
new FullTextPath()
{
Path = fullTextPath1,
Language = "en-US",
},
new FullTextPath()
{
Path = fullTextPath2,
Language = "en-US",
},
new FullTextPath()
{
Path = fullTextPath3,
Language = "en-US",
},
};
string containerName = "fullTextContainerTest";
string partitionKeyPath = "/pk";
ContainerResponse containerResponse =
await databaseForVectorEmbedding.DefineContainer(containerName, partitionKeyPath)
.WithFullTextPolicy(
defaultLanguage: "en-US",
fullTextPaths: fullTextPaths)
.Attach()
.WithIndexingPolicy()
.WithFullTextIndex()
.Path(fullTextPath1)
.Attach()
.WithFullTextIndex()
.Path(fullTextPath2)
.Attach()
.WithFullTextIndex()
.Path(fullTextPath3)
.Attach()
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
ContainerProperties containerSettings = containerResponse.Resource;
// Validate FullText Paths.
Assert.IsNotNull(containerSettings.FullTextPolicy);
Assert.IsNotNull(containerSettings.FullTextPolicy.FullTextPaths);
Assert.AreEqual(fullTextPaths.Count, containerSettings.FullTextPolicy.FullTextPaths.Count());
Assert.IsTrue(fullTextPaths.OrderBy(x => x.Path).SequenceEqual(containerSettings.FullTextPolicy.FullTextPaths.OrderBy(x => x.Path)));
// Validate Full Text Indexes.
Assert.IsNotNull(containerSettings.IndexingPolicy.FullTextIndexes);
Assert.AreEqual(fullTextPaths.Count, containerSettings.IndexingPolicy.FullTextIndexes.Count());
Assert.AreEqual(fullTextPath1, containerSettings.IndexingPolicy.FullTextIndexes[0].Path);
Assert.AreEqual(fullTextPath2, containerSettings.IndexingPolicy.FullTextIndexes[1].Path);
Assert.AreEqual(fullTextPath3, containerSettings.IndexingPolicy.FullTextIndexes[2].Path);
}
finally
{
await databaseForVectorEmbedding.DeleteAsync();
}
}
[TestMethod]
public async Task TestFullTextSearchPolicyWithDefaultLanguage()
{
string fullTextPath1 = "/fts1";
Database databaseForVectorEmbedding = await this.GetClient().CreateDatabaseAsync("fullTextSearchDB",
cancellationToken: this.cancellationToken);
try
{
string containerName = "fullTextContainerTest";
string partitionKeyPath = "/pk";
ContainerResponse containerResponse =
await databaseForVectorEmbedding.DefineContainer(containerName, partitionKeyPath)
.WithFullTextPolicy(
defaultLanguage: "en-US",
fullTextPaths: new Collection<FullTextPath>() { new FullTextPath()
{
Language = "en-US",
Path = fullTextPath1
}})
.Attach()
.WithIndexingPolicy()
.WithFullTextIndex()
.Path(fullTextPath1)
.Attach()
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
ContainerProperties containerSettings = containerResponse.Resource;
// Validate FullText Paths.
Assert.IsNotNull(containerSettings.FullTextPolicy);
Assert.IsNotNull(containerSettings.FullTextPolicy.FullTextPaths);
Assert.AreEqual(1, containerSettings.FullTextPolicy.FullTextPaths.Count());
// Validate Full Text Indexes.
Assert.IsNotNull(containerSettings.IndexingPolicy.FullTextIndexes);
Assert.AreEqual(1, containerSettings.IndexingPolicy.FullTextIndexes.Count());
Assert.AreEqual(fullTextPath1, containerSettings.IndexingPolicy.FullTextIndexes[0].Path);
}
finally
{
await databaseForVectorEmbedding.DeleteAsync();
}
}
[Ignore]
[TestMethod]
public async Task WithComputedProperties()
{
string containerName = Guid.NewGuid().ToString();
string partitionKeyPath = "/users";
var definitions = new[]
{
new { Name = "lowerName", Query = "SELECT VALUE LOWER(c.name) FROM c" },
new { Name = "estimatedTax", Query = "SELECT VALUE c.salary * 0.2 FROM c" }
};
ContainerResponse containerResponse =
await this.database.DefineContainer(containerName, partitionKeyPath)
.WithComputedProperties()
.WithComputedProperty(definitions[0].Name, definitions[0].Query)
.WithComputedProperty(definitions[1].Name, definitions[1].Query)
.Attach()
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
Assert.AreEqual(2, containerResponse.Resource.ComputedProperties.Count);
Assert.AreEqual(definitions[0].Name, containerResponse.Resource.ComputedProperties[0].Name);
Assert.AreEqual(definitions[0].Query, containerResponse.Resource.ComputedProperties[0].Query);
Assert.AreEqual(definitions[1].Name, containerResponse.Resource.ComputedProperties[1].Name);
Assert.AreEqual(definitions[1].Query, containerResponse.Resource.ComputedProperties[1].Query);
Container container = containerResponse;
containerResponse = await container.ReadContainerAsync();
Assert.AreEqual(HttpStatusCode.OK, containerResponse.StatusCode);
Assert.AreEqual(containerName, containerResponse.Resource.Id);
Assert.AreEqual(partitionKeyPath, containerResponse.Resource.PartitionKey.Paths.First());
Assert.AreEqual(2, containerResponse.Resource.ComputedProperties.Count);
Assert.AreEqual(definitions[0].Name, containerResponse.Resource.ComputedProperties[0].Name);
Assert.AreEqual(definitions[0].Query, containerResponse.Resource.ComputedProperties[0].Query);
Assert.AreEqual(definitions[1].Name, containerResponse.Resource.ComputedProperties[1].Name);
Assert.AreEqual(definitions[1].Query, containerResponse.Resource.ComputedProperties[1].Query);
containerResponse = await containerResponse.Container.DeleteContainerAsync();
Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
}
[TestMethod]
public async Task ThroughputTest()
{
int expectedThroughput = 2400;
string containerName = Guid.NewGuid().ToString();
string partitionKeyPath = "/users";
ContainerResponse containerResponse
= await this.database.DefineContainer(containerName, partitionKeyPath)
.CreateAsync(expectedThroughput);
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Container container = this.database.GetContainer(containerName);
int? readThroughput = await container.ReadThroughputAsync();
Assert.IsNotNull(readThroughput);
Assert.AreEqual(expectedThroughput, readThroughput);
containerResponse = await container.DeleteContainerAsync();
Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
}
[TestMethod]
public async Task ThroughputResponseTest()
{
int expectedThroughput = 2400;
string containerName = Guid.NewGuid().ToString();
string partitionKeyPath = "/users";
ContainerResponse containerResponse
= await this.database.DefineContainer(containerName, partitionKeyPath)
.CreateAsync(expectedThroughput);
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Container container = this.database.GetContainer(containerName);
ThroughputResponse readThroughput = await container.ReadThroughputAsync(new RequestOptions());
Assert.IsNotNull(readThroughput);
Assert.AreEqual(expectedThroughput, readThroughput.Resource.Throughput);
// Implicit conversion
ThroughputProperties throughputProperties = await container.ReadThroughputAsync(new RequestOptions());
Assert.IsNotNull(throughputProperties);
Assert.AreEqual(expectedThroughput, throughputProperties.Throughput);
// simple API
int? throughput = await container.ReadThroughputAsync();
Assert.IsNotNull(throughput);
Assert.AreEqual(expectedThroughput, throughput);
containerResponse = await container.DeleteContainerAsync();
Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
}
[TestMethod]
public async Task TimeToLiveTest()
{
string containerName = Guid.NewGuid().ToString();
string partitionKeyPath = "/users";
int timeToLiveInSeconds = 10;
ContainerResponse containerResponse = await this.database.DefineContainer(containerName, partitionKeyPath)
.WithDefaultTimeToLive(timeToLiveInSeconds)
.CreateAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Container container = containerResponse;
ContainerProperties responseSettings = containerResponse;
Assert.AreEqual(timeToLiveInSeconds, responseSettings.DefaultTimeToLive);
ContainerResponse readResponse = await container.ReadContainerAsync();
Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
Assert.AreEqual(timeToLiveInSeconds, readResponse.Resource.DefaultTimeToLive);
JObject itemTest = JObject.FromObject(new { id = Guid.NewGuid().ToString(), users = "testUser42" });
ItemResponse<JObject> createResponse = await container.CreateItemAsync<JObject>(item: itemTest);
JObject responseItem = createResponse;
Assert.IsNull(responseItem["ttl"]);
containerResponse = await container.DeleteContainerAsync();
Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
}
[TestMethod]
public async Task NoPartitionedCreateFail()
{
string containerName = Guid.NewGuid().ToString();
try
{
await this.database.DefineContainer(containerName, null)
.CreateAsync();
Assert.Fail("Create should throw null ref exception");
}
catch (ArgumentNullException ae)
{
Assert.IsNotNull(ae);
}
}
[TestMethod]
public async Task TimeToLivePropertyPath()
{
string containerName = Guid.NewGuid().ToString();
string partitionKeyPath = "/user";
int timeToLivetimeToLiveInSeconds = 10;
ContainerResponse containerResponse;
try
{
containerResponse = await this.database.DefineContainer(containerName, partitionKeyPath)
.WithTimeToLivePropertyPath("/creationDate")
.CreateAsync();
Assert.Fail("CreateCollection with TtlPropertyPath and with no DefaultTimeToLive should have failed.");
}
catch (CosmosException exeption)
{
// expected because DefaultTimeToLive was not specified
Assert.AreEqual(HttpStatusCode.BadRequest, exeption.StatusCode);
}
// Verify the container content.
containerResponse = await this.database.DefineContainer(containerName, partitionKeyPath)
.WithTimeToLivePropertyPath("/creationDate")
.WithDefaultTimeToLive(timeToLivetimeToLiveInSeconds)
.CreateAsync();
Container container = containerResponse;
Assert.AreEqual(timeToLivetimeToLiveInSeconds, containerResponse.Resource.DefaultTimeToLive);
#pragma warning disable 0612
Assert.AreEqual("/creationDate", containerResponse.Resource.TimeToLivePropertyPath);
#pragma warning restore 0612
//Creating an item and reading before expiration
var payload = new { id = "testId", user = "testUser", creationDate = ToEpoch(DateTime.UtcNow) };
ItemResponse<dynamic> createItemResponse = await container.CreateItemAsync<dynamic>(payload);
Assert.IsNotNull(createItemResponse.Resource);
Assert.AreEqual(createItemResponse.StatusCode, HttpStatusCode.Created);
ItemResponse<dynamic> readItemResponse = await container.ReadItemAsync<dynamic>(payload.id, new PartitionKey(payload.user));
Assert.IsNotNull(readItemResponse.Resource);
Assert.AreEqual(readItemResponse.StatusCode, HttpStatusCode.OK);
containerResponse = await container.DeleteContainerAsync();
Assert.AreEqual(HttpStatusCode.NoContent, containerResponse.StatusCode);
}
[TestMethod]
public async Task WithClientEncryptionPolicyTest()