Esempio n. 1
0
        public void InitializeBatchExecutorForContainer_Null_WhenAllowBulk_False()
        {
            string databaseId = "db1234";
            string crId       = "cr42";

            CosmosClientContext context   = this.CreateMockClientContext();
            DatabaseInternal    db        = new DatabaseInlineCore(context, databaseId);
            ContainerInternal   container = new ContainerInlineCore(context, db, crId);

            Assert.IsNull(container.BatchExecutor);
        }
Esempio n. 2
0
        public async Task ShouldReturnNotModifiedOnSingleRange()
        {
            // Default mock is 1 range
            MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient();
            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.ClientOptions).Returns(MockCosmosUtil.GetDefaultConfiguration());
            mockContext.Setup(x => x.DocumentClient).Returns(new MockDocumentClient());
            mockContext.Setup(x => x.SerializerCore).Returns(MockCosmosUtil.Serializer);
            mockContext.Setup(x => x.Client).Returns(client);
            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns("/dbs/test/colls/test");

            ResponseMessage firstResponse = new ResponseMessage(HttpStatusCode.NotModified);

            firstResponse.Headers.ETag = "FirstContinuation";

            mockContext.SetupSequence(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                          It.IsAny <string>(),
                                          It.IsAny <Documents.ResourceType>(),
                                          It.IsAny <Documents.OperationType>(),
                                          It.IsAny <RequestOptions>(),
                                          It.IsAny <ContainerInternal>(),
                                          It.IsAny <PartitionKey?>(),
                                          It.IsAny <Stream>(),
                                          It.IsAny <Action <RequestMessage> >(),
                                          It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                          It.IsAny <CosmosDiagnosticsContext>(),
                                          It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(firstResponse));

            DatabaseInternal databaseCore = new DatabaseInlineCore(mockContext.Object, "mydb");

            StandByFeedIteratorCore iterator = new StandByFeedIteratorCore(
                mockContext.Object, new ContainerInlineCore(mockContext.Object, databaseCore, "myColl"), null, 10, new ChangeFeedRequestOptions());
            ResponseMessage firstRequest = await iterator.ReadNextAsync();

            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(firstResponse.Headers.ETag), "Response should contain the first continuation");
            Assert.AreEqual(HttpStatusCode.NotModified, firstRequest.StatusCode);

            mockContext.Verify(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                   It.IsAny <string>(),
                                   It.IsAny <Documents.ResourceType>(),
                                   It.IsAny <Documents.OperationType>(),
                                   It.IsAny <RequestOptions>(),
                                   It.IsAny <ContainerInternal>(),
                                   It.IsAny <PartitionKey?>(),
                                   It.IsAny <Stream>(),
                                   It.IsAny <Action <RequestMessage> >(),
                                   It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                   It.IsAny <CosmosDiagnosticsContext>(),
                                   It.IsAny <CancellationToken>()), Times.Once);
        }
        public void ValidateUriGenerationForResources()
        {
            string databaseId = "db1234";
            string crId       = "cr42";

            CosmosClientContext context = this.CreateMockClientContext();
            DatabaseInternal    db      = new DatabaseInlineCore(context, databaseId);

            Assert.AreEqual(db.LinkUri, "dbs/" + databaseId);

            ContainerInternal container = new ContainerInlineCore(context, db, crId);

            Assert.AreEqual(container.LinkUri, "dbs/" + databaseId + "/colls/" + crId);
        }
Esempio n. 4
0
        private (ContainerInternal, Mock <BatchAsyncContainerExecutor>) CreateMockBulkCosmosClientContext()
        {
            CosmosClientContext context = MockCosmosUtil.CreateMockCosmosClient(
                builder => builder.WithBulkExecution(true)).ClientContext;
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns <string, string, string>((x, y, z) => context.CreateLink(x, y, z));
            mockContext.Setup(x => x.ClientOptions).Returns(context.ClientOptions);
            mockContext.Setup(x => x.ResponseFactory).Returns(context.ResponseFactory);
            mockContext.Setup(x => x.SerializerCore).Returns(context.SerializerCore);
            mockContext.Setup(x => x.DocumentClient).Returns(context.DocumentClient);
            mockContext.Setup(x => x.ProcessResourceOperationStreamAsync(
                                  It.IsAny <Uri>(),
                                  It.IsAny <ResourceType>(),
                                  It.IsAny <OperationType>(),
                                  It.IsAny <RequestOptions>(),
                                  It.IsAny <ContainerInternal>(),
                                  It.IsAny <Cosmos.PartitionKey?>(),
                                  It.IsAny <string>(),
                                  It.IsAny <Stream>(),
                                  It.IsAny <Action <RequestMessage> >(),
                                  It.IsAny <CosmosDiagnosticsContext>(),
                                  It.IsAny <CancellationToken>())).Returns <Uri, ResourceType, OperationType, RequestOptions, ContainerInternal, Cosmos.PartitionKey, string, Stream, Action <RequestMessage>, CosmosDiagnosticsContext, CancellationToken>(
                (uri, resourceType, operationType, requestOptions, containerInternal, pk, itemId, stream, requestEnricher, diagnostics, cancellationToken) =>
                context.ProcessResourceOperationStreamAsync(
                    uri,
                    resourceType,
                    operationType,
                    requestOptions,
                    containerInternal,
                    pk,
                    itemId,
                    stream,
                    requestEnricher,
                    diagnostics,
                    cancellationToken));

            Mock <BatchAsyncContainerExecutor> mockedExecutor = this.GetMockedBatchExcecutor();

            mockContext.Setup(x => x.GetExecutorForContainer(It.IsAny <ContainerInternal>())).Returns(mockedExecutor.Object);

            DatabaseInternal  db        = new DatabaseInlineCore(mockContext.Object, "test");
            ContainerInternal container = new ContainerInlineCore(mockContext.Object, db, "test");

            return(container, mockedExecutor);
        }
        private static Container GetContainer(TestHandler testHandler = null)
        {
            CosmosClient client;

            if (testHandler != null)
            {
                client = MockCosmosUtil.CreateMockCosmosClient((builder) => builder.AddCustomHandlers(testHandler));
            }
            else
            {
                client = MockCosmosUtil.CreateMockCosmosClient();
            }

            DatabaseInternal  database  = new DatabaseInlineCore(client.ClientContext, BatchUnitTests.DatabaseId);
            ContainerInternal container = new ContainerInlineCore(client.ClientContext, database, BatchUnitTests.ContainerId);

            return(container);
        }
        private Container GetContainerWithMockSetup(EncryptionTestHandler encryptionTestHandler = null)
        {
            this.testHandler = encryptionTestHandler ?? new EncryptionTestHandler();

            this.mockEncryptor = new Mock <Encryptor>();

            this.mockEncryptor.Setup(m => m.EncryptAsync(It.IsAny <byte[]>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((byte[] plainText, string dekId, string algo, CancellationToken t) => EncryptionUnitTests.EncryptData(plainText));
            this.mockEncryptor.Setup(m => m.DecryptAsync(It.IsAny <byte[]>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((byte[] cipherText, string dekId, string algo, CancellationToken t) => EncryptionUnitTests.DecryptData(cipherText));
            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient((builder) => builder
                                                                        .AddCustomHandlers(this.testHandler)
                                                                        .WithEncryptor(this.mockEncryptor.Object));

            DatabaseInternal database = new DatabaseInlineCore(client.ClientContext, EncryptionUnitTests.DatabaseId);

            return(new ContainerInlineCore(client.ClientContext, database, EncryptionUnitTests.ContainerId));
        }
Esempio n. 7
0
        public async Task GetChangeFeedTokensAsyncReturnsOnePerPartitionKeyRange()
        {
            // Setting mock to have 3 ranges, to generate 3 tokens
            MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient();

            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.ClientOptions).Returns(MockCosmosUtil.GetDefaultConfiguration());
            mockContext.Setup(x => x.DocumentClient).Returns(documentClient);
            mockContext.Setup(x => x.SerializerCore).Returns(MockCosmosUtil.Serializer);
            mockContext.Setup(x => x.Client).Returns(client);
            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(UriFactory.CreateDocumentCollectionUri("test", "test").OriginalString);

            DatabaseInternal     db        = new DatabaseInlineCore(mockContext.Object, "test");
            ContainerInternal    container = new ContainerInlineCore(mockContext.Object, db, "test");
            IEnumerable <string> tokens    = await container.GetChangeFeedTokensAsync();

            Assert.AreEqual(3, tokens.Count());

            PartitionKeyRangeCache pkRangeCache = await documentClient.GetPartitionKeyRangeCacheAsync();

            foreach (string token in tokens)
            {
                // Validate that each token represents a StandByFeedContinuationToken with a single Range
                List <CompositeContinuationToken> deserialized = JsonConvert.DeserializeObject <List <CompositeContinuationToken> >(token);
                Assert.AreEqual(1, deserialized.Count);
                CompositeContinuationToken compositeToken = deserialized[0];

                IReadOnlyList <Documents.PartitionKeyRange> rangesForTheToken = await pkRangeCache.TryGetOverlappingRangesAsync("", compositeToken.Range);

                // Token represents one range
                Assert.AreEqual(1, rangesForTheToken.Count);
                Assert.AreEqual(rangesForTheToken[0].MinInclusive, compositeToken.Range.Min);
                Assert.AreEqual(rangesForTheToken[0].MaxExclusive, compositeToken.Range.Max);
            }
        }
Esempio n. 8
0
        public async Task ConcurrentGet_ReturnsSameExecutorInstance()
        {
            CosmosClientContext context = this.MockClientContext();

            DatabaseInternal db = new DatabaseInlineCore(context, "test");

            List <Task <ContainerInternal> > tasks = new List <Task <ContainerInternal> >();

            for (int i = 0; i < 20; i++)
            {
                tasks.Add(Task.Run(() => Task.FromResult((ContainerInternal) new ContainerInlineCore(context, db, "test"))));
            }

            await Task.WhenAll(tasks);

            BatchAsyncContainerExecutor firstExecutor = tasks[0].Result.BatchExecutor;

            Assert.IsNotNull(firstExecutor);
            for (int i = 1; i < 20; i++)
            {
                BatchAsyncContainerExecutor otherExecutor = tasks[i].Result.BatchExecutor;
                Assert.AreEqual(firstExecutor, otherExecutor);
            }
        }
Esempio n. 9
0
        private (ContainerInternal, Mock <BatchAsyncContainerExecutor>) CreateMockBulkCosmosClientContext()
        {
            CosmosClientContext context = MockCosmosUtil.CreateMockCosmosClient(
                builder => builder.WithBulkExecution(true)).ClientContext;
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns <string, string, string>((x, y, z) => context.CreateLink(x, y, z));
            mockContext.Setup(x => x.ClientOptions).Returns(context.ClientOptions);
            mockContext.Setup(x => x.ResponseFactory).Returns(context.ResponseFactory);
            mockContext.Setup(x => x.SerializerCore).Returns(context.SerializerCore);
            mockContext.Setup(x => x.DocumentClient).Returns(context.DocumentClient);

            mockContext.Setup(x => x.OperationHelperAsync <ResponseMessage>(
                                  It.IsAny <string>(),
                                  It.IsAny <RequestOptions>(),
                                  It.IsAny <Func <ITrace, Task <ResponseMessage> > >(),
                                  It.IsAny <TraceComponent>(),
                                  It.IsAny <TraceLevel>()))
            .Returns <string, RequestOptions, Func <ITrace, Task <ResponseMessage> >, TraceComponent, TraceLevel>(
                (operationName, requestOptions, func, comp, level) => func(NoOpTrace.Singleton));

            mockContext.Setup(x => x.OperationHelperAsync <ItemResponse <dynamic> >(
                                  It.IsAny <string>(),
                                  It.IsAny <RequestOptions>(),
                                  It.IsAny <Func <ITrace, Task <ItemResponse <dynamic> > > >(),
                                  It.IsAny <TraceComponent>(),
                                  It.IsAny <TraceLevel>()))
            .Returns <string, RequestOptions, Func <ITrace, Task <ItemResponse <dynamic> > >, TraceComponent, TraceLevel>(
                (operationName, requestOptions, func, comp, level) => func(NoOpTrace.Singleton));

            mockContext.Setup(x => x.ProcessResourceOperationStreamAsync(
                                  It.IsAny <string>(),
                                  It.IsAny <ResourceType>(),
                                  It.IsAny <OperationType>(),
                                  It.IsAny <RequestOptions>(),
                                  It.IsAny <ContainerInternal>(),
                                  It.IsAny <Cosmos.PartitionKey?>(),
                                  It.IsAny <string>(),
                                  It.IsAny <Stream>(),
                                  It.IsAny <Action <RequestMessage> >(),
                                  It.IsAny <ITrace>(),
                                  It.IsAny <CancellationToken>())).Returns <string, ResourceType, OperationType, RequestOptions, ContainerInternal, Cosmos.PartitionKey, string, Stream, Action <RequestMessage>, ITrace, CancellationToken>(
                (uri, resourceType, operationType, requestOptions, containerInternal, pk, itemId, stream, requestEnricher, trace, cancellationToken) =>
                context.ProcessResourceOperationStreamAsync(
                    uri,
                    resourceType,
                    operationType,
                    requestOptions,
                    containerInternal,
                    pk,
                    itemId,
                    stream,
                    requestEnricher,
                    trace,
                    cancellationToken));

            Mock <BatchAsyncContainerExecutor> mockedExecutor = this.GetMockedBatchExcecutor();

            mockContext.Setup(x => x.GetExecutorForContainer(It.IsAny <ContainerInternal>())).Returns(mockedExecutor.Object);

            DatabaseInternal  db        = new DatabaseInlineCore(mockContext.Object, "test");
            ContainerInternal container = new ContainerInlineCore(mockContext.Object, db, "test");

            return(container, mockedExecutor);
        }
Esempio n. 10
0
        public async Task ContinuationTokenIsNotUpdatedOnFails()
        {
            MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient();

            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.ClientOptions).Returns(MockCosmosUtil.GetDefaultConfiguration());
            mockContext.Setup(x => x.DocumentClient).Returns(documentClient);
            mockContext.Setup(x => x.SerializerCore).Returns(MockCosmosUtil.Serializer);
            mockContext.Setup(x => x.Client).Returns(client);
            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns("/dbs/test/colls/test");

            ResponseMessage firstResponse = new ResponseMessage(HttpStatusCode.NotModified);

            firstResponse.Headers.ETag = "FirstContinuation";
            ResponseMessage secondResponse = new ResponseMessage(
                statusCode: HttpStatusCode.NotFound,
                requestMessage: null,
                headers: new Headers()
            {
                ETag = "ShouldNotContainThis"
            },
                cosmosException: CosmosExceptionFactory.CreateNotFoundException("something"),
                diagnostics: new CosmosDiagnosticsContextCore());

            mockContext.SetupSequence(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                          It.IsAny <string>(),
                                          It.IsAny <Documents.ResourceType>(),
                                          It.IsAny <Documents.OperationType>(),
                                          It.IsAny <RequestOptions>(),
                                          It.IsAny <ContainerInternal>(),
                                          It.IsAny <Cosmos.FeedRange>(),
                                          It.IsAny <Stream>(),
                                          It.IsAny <Action <RequestMessage> >(),
                                          It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                          It.IsAny <CosmosDiagnosticsContext>(),
                                          It.IsAny <ITrace>(),
                                          It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(firstResponse))
            .Returns(Task.FromResult(secondResponse));

            DatabaseInternal databaseCore = new DatabaseInlineCore(mockContext.Object, "mydb");

            StandByFeedIteratorCore iterator = new StandByFeedIteratorCore(
                mockContext.Object, new ContainerInlineCore(mockContext.Object, databaseCore, "myColl"), null, 10, new StandByFeedIteratorRequestOptions());
            ResponseMessage firstRequest = await iterator.ReadNextAsync();

            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(firstResponse.Headers.ETag), "Response should contain the first continuation");
            Assert.IsTrue(!firstRequest.Headers.ContinuationToken.Contains(secondResponse.Headers.ETag), "Response should not contain the second continuation");
            Assert.AreEqual(HttpStatusCode.NotFound, firstRequest.StatusCode);

            mockContext.Verify(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                   It.IsAny <string>(),
                                   It.IsAny <Documents.ResourceType>(),
                                   It.IsAny <Documents.OperationType>(),
                                   It.IsAny <RequestOptions>(),
                                   It.IsAny <ContainerInternal>(),
                                   It.IsAny <Cosmos.FeedRange>(),
                                   It.IsAny <Stream>(),
                                   It.IsAny <Action <RequestMessage> >(),
                                   It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                   It.IsAny <CosmosDiagnosticsContext>(),
                                   It.IsAny <ITrace>(),
                                   It.IsAny <CancellationToken>()), Times.Exactly(2));
        }
Esempio n. 11
0
        public async Task ShouldReturnNotModifiedAfterCyclingOnAllRanges()
        {
            // Setting mock to have 3 ranges, this test will get a 304 on all 3 ranges, do 3 backend requests, and return a 304
            MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient();

            using CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.ClientOptions).Returns(MockCosmosUtil.GetDefaultConfiguration());
            mockContext.Setup(x => x.DocumentClient).Returns(documentClient);
            mockContext.Setup(x => x.SerializerCore).Returns(MockCosmosUtil.Serializer);
            mockContext.Setup(x => x.Client).Returns(client);
            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns("/dbs/test/colls/test");

            ResponseMessage firstResponse = new ResponseMessage(HttpStatusCode.NotModified);

            firstResponse.Headers.ETag = "FirstContinuation";
            ResponseMessage secondResponse = new ResponseMessage(HttpStatusCode.NotModified);

            secondResponse.Headers.ETag = "SecondContinuation";
            ResponseMessage thirdResponse = new ResponseMessage(HttpStatusCode.NotModified);

            thirdResponse.Headers.ETag = "ThirdContinuation";

            mockContext.SetupSequence(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                          It.IsAny <string>(),
                                          It.IsAny <Documents.ResourceType>(),
                                          It.IsAny <Documents.OperationType>(),
                                          It.IsAny <RequestOptions>(),
                                          It.IsAny <ContainerInternal>(),
                                          It.IsAny <Cosmos.FeedRange>(),
                                          It.IsAny <Stream>(),
                                          It.IsAny <Action <RequestMessage> >(),
                                          It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                          It.IsAny <CosmosDiagnosticsContext>(),
                                          It.IsAny <ITrace>(),
                                          It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(firstResponse))
            .Returns(Task.FromResult(secondResponse))
            .Returns(Task.FromResult(thirdResponse));

            DatabaseInternal databaseCore = new DatabaseInlineCore(mockContext.Object, "mydb");

            StandByFeedIteratorCore iterator = new StandByFeedIteratorCore(
                mockContext.Object, new ContainerInlineCore(mockContext.Object, databaseCore, "myColl"), null, 10, new StandByFeedIteratorRequestOptions());
            ResponseMessage firstRequest = await iterator.ReadNextAsync();

            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(firstResponse.Headers.ETag), "Response should contain the first continuation");
            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(secondResponse.Headers.ETag), "Response should contain the second continuation");
            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(thirdResponse.Headers.ETag), "Response should contain the third continuation");
            Assert.AreEqual(HttpStatusCode.NotModified, firstRequest.StatusCode);

            mockContext.Verify(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                   It.IsAny <string>(),
                                   It.IsAny <Documents.ResourceType>(),
                                   It.IsAny <Documents.OperationType>(),
                                   It.IsAny <RequestOptions>(),
                                   It.IsAny <ContainerInternal>(),
                                   It.IsAny <Cosmos.FeedRange>(),
                                   It.IsAny <Stream>(),
                                   It.IsAny <Action <RequestMessage> >(),
                                   It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                   It.IsAny <CosmosDiagnosticsContext>(),
                                   It.IsAny <ITrace>(),
                                   It.IsAny <CancellationToken>()), Times.Exactly(3));
        }
Esempio n. 12
0
        public async Task WithClientEncryptionPolicyTest()
        {
            // create ClientEncryptionKeys
            DatabaseInlineCore databaseInlineCore = (DatabaseInlineCore)this.database;
            await TestCommon.CreateClientEncryptionKey("dekId1", databaseInlineCore);

            await TestCommon.CreateClientEncryptionKey("dekId2", databaseInlineCore);

            string containerName               = Guid.NewGuid().ToString();
            string partitionKeyPath            = "/users";
            ClientEncryptionIncludedPath path1 = new ClientEncryptionIncludedPath()
            {
                Path = "/path1",
                ClientEncryptionKeyId = "dekId1",
                EncryptionType        = "Randomized",
                EncryptionAlgorithm   = "AEAD_AES_256_CBC_HMAC_SHA256"
            };

            ClientEncryptionIncludedPath path2 = new ClientEncryptionIncludedPath()
            {
                Path = "/path2",
                ClientEncryptionKeyId = "dekId2",
                EncryptionType        = "Randomized",
                EncryptionAlgorithm   = "AEAD_AES_256_CBC_HMAC_SHA256",
            };

            ContainerResponse containerResponse = await this.database.DefineContainer(containerName, partitionKeyPath)
                                                  .WithClientEncryptionPolicy()
                                                  .WithIncludedPath(path1)
                                                  .WithIncludedPath(path2)
                                                  .Attach()
                                                  .CreateAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Container           container        = containerResponse;
            ContainerProperties responseSettings = containerResponse;

            Assert.IsNotNull(responseSettings.ClientEncryptionPolicy);
            Assert.AreEqual(2, responseSettings.ClientEncryptionPolicy.IncludedPaths.Count());
            ClientEncryptionIncludedPath clientEncryptionIncludedPath = responseSettings.ClientEncryptionPolicy.IncludedPaths.First();

            Assert.IsTrue(this.VerifyClientEncryptionIncludedPath(path1, clientEncryptionIncludedPath));
            clientEncryptionIncludedPath = responseSettings.ClientEncryptionPolicy.IncludedPaths.Last();
            Assert.IsTrue(this.VerifyClientEncryptionIncludedPath(path2, clientEncryptionIncludedPath));

            ContainerResponse readResponse = await container.ReadContainerAsync();

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);
            Assert.IsNotNull(readResponse.Resource.ClientEncryptionPolicy);

            // update CEP and replace container
            readResponse.Resource.ClientEncryptionPolicy = null;
            try
            {
                await container.ReplaceContainerAsync(readResponse.Resource);

                Assert.Fail("ReplaceCollection with update to ClientEncryptionPolicy should have failed.");
            }
            catch (CosmosException ex)
            {
                Assert.AreEqual(HttpStatusCode.BadRequest, ex.StatusCode);
                Assert.IsTrue(ex.Message.Contains("'clientEncryptionPolicy' cannot be changed as part of collection replace operation."));
            }
        }
Esempio n. 13
0
        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
                            }
                        }
                    }
                },
                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 <= 1);
            ClientEncryptionIncludedPath clientEncryptionIncludedPath = responseProperties.ClientEncryptionPolicy.IncludedPaths.First();

            Assert.IsTrue(this.VerifyClientEncryptionIncludedPath(clientEncryptionIncludedPath1, clientEncryptionIncludedPath));
        }
Esempio n. 14
0
        public async Task ShouldContinueUntilResponseOk()
        {
            // Setting 3 ranges, first one returns a 304, second returns Ok
            MultiRangeMockDocumentClient documentClient = new MultiRangeMockDocumentClient();
            CosmosClient client = MockCosmosUtil.CreateMockCosmosClient();
            Mock <CosmosClientContext> mockContext = new Mock <CosmosClientContext>();

            mockContext.Setup(x => x.ClientOptions).Returns(MockCosmosUtil.GetDefaultConfiguration());
            mockContext.Setup(x => x.DocumentClient).Returns(documentClient);
            mockContext.Setup(x => x.SerializerCore).Returns(MockCosmosUtil.Serializer);
            mockContext.Setup(x => x.Client).Returns(client);
            mockContext.Setup(x => x.CreateLink(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())).Returns(new Uri("/dbs/test/colls/test", UriKind.Relative));

            ResponseMessage firstResponse = new ResponseMessage(HttpStatusCode.NotModified);

            firstResponse.Headers.ETag = "FirstContinuation";
            ResponseMessage secondResponse = new ResponseMessage(HttpStatusCode.OK);

            secondResponse.Headers.ETag = "SecondContinuation";

            mockContext.SetupSequence(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                          It.IsAny <Uri>(),
                                          It.IsAny <Documents.ResourceType>(),
                                          It.IsAny <Documents.OperationType>(),
                                          It.IsAny <RequestOptions>(),
                                          It.IsAny <ContainerInternal>(),
                                          It.IsAny <PartitionKey?>(),
                                          It.IsAny <Stream>(),
                                          It.IsAny <Action <RequestMessage> >(),
                                          It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                          It.IsAny <CosmosDiagnosticsContext>(),
                                          It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(firstResponse))
            .Returns(Task.FromResult(secondResponse));

            DatabaseInternal databaseCore = new DatabaseInlineCore(mockContext.Object, "mydb");

            StandByFeedIteratorCore iterator = new StandByFeedIteratorCore(
                mockContext.Object,
                new ContainerInlineCore(mockContext.Object, databaseCore, "myColl"),
                new ChangeFeedRequestOptions()
            {
                MaxItemCount = 10,
                From         = ChangeFeedRequestOptions.StartFrom.CreateFromBeginning(),
            });
            ResponseMessage firstRequest = await iterator.ReadNextAsync();

            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(firstResponse.Headers.ETag), "Response should contain the first continuation");
            Assert.IsTrue(firstRequest.Headers.ContinuationToken.Contains(secondResponse.Headers.ETag), "Response should contain the second continuation");
            Assert.AreEqual(HttpStatusCode.OK, firstRequest.StatusCode);

            mockContext.Verify(x => x.ProcessResourceOperationAsync <ResponseMessage>(
                                   It.IsAny <Uri>(),
                                   It.IsAny <Documents.ResourceType>(),
                                   It.IsAny <Documents.OperationType>(),
                                   It.IsAny <RequestOptions>(),
                                   It.IsAny <ContainerInternal>(),
                                   It.IsAny <PartitionKey?>(),
                                   It.IsAny <Stream>(),
                                   It.IsAny <Action <RequestMessage> >(),
                                   It.IsAny <Func <ResponseMessage, ResponseMessage> >(),
                                   It.IsAny <CosmosDiagnosticsContext>(),
                                   It.IsAny <CancellationToken>()), Times.Exactly(2));
        }