Example #1
0
        public async Task SharedThroughputTests()
        {
            string           databaseId     = Guid.NewGuid().ToString();
            int              throughput     = 10000;
            DatabaseResponse createResponse = await this.CreateDatabaseHelper(databaseId, databaseExists : false, throughput : throughput);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            Cosmos.Database cosmosDatabase = createResponse;
            int?            readThroughput = await cosmosDatabase.ReadThroughputAsync();

            Assert.AreEqual(throughput, readThroughput);

            string            containerId       = Guid.NewGuid().ToString();
            string            partitionPath     = "/users";
            ContainerResponse containerResponse = await cosmosDatabase.CreateContainerAsync(containerId, partitionPath);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);

            Container container = containerResponse;

            try
            {
                readThroughput = await((ContainerCore)container).ReadThroughputAsync();
                Assert.Fail("Should through not found exception as throughput is not configured");
            } catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            await container.DeleteContainerAsync();

            await cosmosDatabase.DeleteAsync();
        }
        public async Task ValidateCurrentWriteQuorumAndReplicaSetHeader()
        {
            CosmosClient client = TestCommon.CreateCosmosClient(false);

            Cosmos.Database db = null;
            try
            {
                db = await client.CreateDatabaseAsync(Guid.NewGuid().ToString());

                PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition {
                    Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/id" }), Kind = PartitionKind.Hash
                };
                ContainerProperties containerSetting = new ContainerProperties()
                {
                    Id           = Guid.NewGuid().ToString(),
                    PartitionKey = partitionKeyDefinition
                };
                Container coll = await db.CreateContainerAsync(containerSetting);

                Document documentDefinition = new Document {
                    Id = Guid.NewGuid().ToString()
                };
                ItemResponse <Document> docResult = await coll.CreateItemAsync <Document>(documentDefinition);

                Assert.IsTrue(int.Parse(docResult.Headers[WFConstants.BackendHeaders.CurrentWriteQuorum], CultureInfo.InvariantCulture) > 0);
                Assert.IsTrue(int.Parse(docResult.Headers[WFConstants.BackendHeaders.CurrentReplicaSetSize], CultureInfo.InvariantCulture) > 0);
            }
            finally
            {
                await db.DeleteAsync();
            }
        }
Example #3
0
        public async Task ValidateUserAgentHeaderWithMacOs(bool useMacOs)
        {
            const string suffix = " UserApplicationName/1.0";

            CosmosClientOptions clientOptions = this.SetEnvironmentInformation(useMacOs);

            clientOptions.ApplicationName = suffix;

            using (CosmosClient client = TestCommon.CreateCosmosClient(clientOptions))
            {
                Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy(client.ClientId).UserAgentContainer;

                string userAgentString = userAgentContainer.UserAgent;
                Assert.IsTrue(userAgentString.Contains(suffix));
                if (useMacOs)
                {
                    Assert.IsTrue(userAgentString.Contains("Darwin 18.0.0"));
                }

                Cosmos.Database db = await client.CreateDatabaseIfNotExistsAsync(Guid.NewGuid().ToString());

                Assert.IsNotNull(db);
                await db.DeleteAsync();
            }
        }
        public async Task SharedThroughputTests()
        {
            string           databaseId     = Guid.NewGuid().ToString();
            int              throughput     = 10000;
            DatabaseResponse createResponse = await this.CreateDatabaseHelper(databaseId, databaseExists : false, throughput : throughput);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            Cosmos.Database cosmosDatabase = createResponse;
            int?            readThroughput = await((DatabaseCore)cosmosDatabase).ReadProvisionedThroughputAsync();

            Assert.AreEqual(throughput, readThroughput);

            string            containerId       = Guid.NewGuid().ToString();
            string            partitionPath     = "/users";
            ContainerResponse containerResponse = await cosmosDatabase.CreateContainerAsync(containerId, partitionPath);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);

            Container container = containerResponse;

            readThroughput = await((ContainerCore)container).ReadProvisionedThroughputAsync();
            Assert.IsNull(readThroughput);

            await container.DeleteContainerAsync();

            await cosmosDatabase.DeleteAsync();
        }
        public async Task VerifyUserAgentWithFeatures(bool useMacOs)
        {
            this.SetEnvironmentInformation(useMacOs);

            const string suffix = " UserApplicationName/1.0";

            string features = Convert.ToString((int)CosmosClientOptionsFeatures.AllowBulkExecution, 2).PadLeft(8, '0');

            using (CosmosClient client = TestCommon.CreateCosmosClient(builder => builder.WithApplicationName(suffix).WithBulkExecution(true)))
            {
                Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy().UserAgentContainer;

                string userAgentString = userAgentContainer.UserAgent;
                Assert.IsTrue(userAgentString.Contains(suffix));
                Assert.IsTrue(userAgentString.Contains($"|F {features}"));
                if (useMacOs)
                {
                    Assert.IsTrue(userAgentString.Contains("Darwin 18.0.0"));
                }

                Cosmos.Database db = await client.CreateDatabaseIfNotExistsAsync(Guid.NewGuid().ToString());

                Assert.IsNotNull(db);
                await db.DeleteAsync();
            }

            using (CosmosClient client = TestCommon.CreateCosmosClient(builder => builder.WithApplicationName(suffix).WithBulkExecution(false)))
            {
                Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy().UserAgentContainer;

                string userAgentString = userAgentContainer.UserAgent;
                Assert.IsTrue(userAgentString.Contains(suffix));
                Assert.IsFalse(userAgentString.Contains($"|F {features}"));
            }
        }
        public async Task ImplicitConversion()
        {
            string databaseName = Guid.NewGuid().ToString();

            DatabaseResponse cosmosDatabaseResponse = await this.cosmosClient.GetDatabase(databaseName).ReadAsync(cancellationToken: this.cancellationToken);

            Cosmos.Database    cosmosDatabase         = cosmosDatabaseResponse;
            DatabaseProperties cosmosDatabaseSettings = cosmosDatabaseResponse;

            Assert.IsNotNull(cosmosDatabase);
            Assert.IsNull(cosmosDatabaseSettings);

            cosmosDatabaseResponse = await this.CreateDatabaseHelper();

            cosmosDatabase         = cosmosDatabaseResponse;
            cosmosDatabaseSettings = cosmosDatabaseResponse;
            Assert.IsNotNull(cosmosDatabase);
            Assert.IsNotNull(cosmosDatabaseSettings);

            cosmosDatabaseResponse = await cosmosDatabase.DeleteAsync(cancellationToken : this.cancellationToken);

            cosmosDatabase         = cosmosDatabaseResponse;
            cosmosDatabaseSettings = cosmosDatabaseResponse;
            Assert.IsNotNull(cosmosDatabase);
            Assert.IsNull(cosmosDatabaseSettings);
        }
Example #7
0
 public static void CleanUp()
 {
     if (testDb != null)
     {
         testDb.DeleteAsync().Wait();
     }
 }
Example #8
0
        public async Task ReadReplaceThroughputResponseTests()
        {
            string           databaseId     = Guid.NewGuid().ToString();
            int              throughput     = 10000;
            DatabaseResponse createResponse = await this.CreateDatabaseHelper(databaseId, databaseExists : false, throughput : throughput);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            Cosmos.Database    cosmosDatabase         = createResponse;
            ThroughputResponse readThroughputResponse = await cosmosDatabase.ReadThroughputAsync(new RequestOptions());

            Assert.IsNotNull(readThroughputResponse);
            Assert.IsNotNull(readThroughputResponse.Resource);
            Assert.IsNotNull(readThroughputResponse.MinThroughput);
            Assert.IsNotNull(readThroughputResponse.Resource.Throughput);
            Assert.AreEqual(throughput, readThroughputResponse.Resource.Throughput.Value);

            // Implicit
            ThroughputProperties throughputProperties = await cosmosDatabase.ReadThroughputAsync(new RequestOptions());

            Assert.IsNotNull(throughputProperties);
            Assert.AreEqual(throughput, throughputProperties.Throughput);

            // Simple API
            int?readThroughput = await cosmosDatabase.ReadThroughputAsync();

            Assert.AreEqual(throughput, readThroughput);

            string            containerId       = Guid.NewGuid().ToString();
            string            partitionPath     = "/users";
            ContainerResponse containerResponse = await cosmosDatabase.CreateContainerAsync(containerId, partitionPath);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);

            ThroughputResponse replaceThroughputResponse = await cosmosDatabase.ReplaceThroughputAsync(readThroughputResponse.Resource.Throughput.Value + 1000);

            Assert.IsNotNull(replaceThroughputResponse);
            Assert.IsNotNull(replaceThroughputResponse.Resource);
            Assert.AreEqual(readThroughputResponse.Resource.Throughput.Value + 1000, replaceThroughputResponse.Resource.Throughput.Value);

            Container container = containerResponse;

            try
            {
                readThroughputResponse = await container.ReadThroughputAsync(new RequestOptions());

                Assert.Fail("Should through not found exception as throughput is not configured");
            }
            catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            await container.DeleteContainerAsync();

            await cosmosDatabase.DeleteAsync();
        }
        public async Task NoThroughputTests()
        {
            string           databaseId     = Guid.NewGuid().ToString();
            DatabaseResponse createResponse = await this.CreateDatabaseHelper(databaseId, databaseExists : false);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            Cosmos.Database cosmosDatabase = createResponse;
            int?            readThroughput = await((DatabaseCore)cosmosDatabase).ReadProvisionedThroughputAsync();

            Assert.IsNull(readThroughput);

            await cosmosDatabase.DeleteAsync();
        }
Example #10
0
        public async Task HttpClientConnectionLimitTest()
        {
            int gatewayConnectionLimit = 1;

            IReadOnlyList <string> excludeConnections = GetActiveConnections();
            CosmosClient           cosmosClient       = new CosmosClient(
                ConfigurationManager.AppSettings["GatewayEndpoint"],
                ConfigurationManager.AppSettings["MasterKey"],
                new CosmosClientOptions
            {
                ApplicationName = "test",
                GatewayModeMaxConnectionLimit = gatewayConnectionLimit,
                ConnectionMode     = ConnectionMode.Gateway,
                ConnectionProtocol = Protocol.Https
            }
                );

            FieldInfo         httpClient        = cosmosClient.DocumentClient.GetType().GetField("httpClient", BindingFlags.NonPublic | BindingFlags.Instance);
            CosmosHttpClient  cosmosHttpClient  = (CosmosHttpClient)httpClient.GetValue(cosmosClient.DocumentClient);
            HttpClientHandler httpClientHandler = (HttpClientHandler)cosmosHttpClient.HttpMessageHandler;

            Assert.AreEqual(gatewayConnectionLimit, httpClientHandler.MaxConnectionsPerServer);

            Cosmos.Database database = await cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString());

            Container container = await database.CreateContainerAsync(
                "TestConnections",
                "/pk",
                throughput : 20000);

            List <Task> creates = new List <Task>();

            for (int i = 0; i < 100; i++)
            {
                creates.Add(container.CreateItemAsync <dynamic>(new { id = Guid.NewGuid().ToString(), pk = Guid.NewGuid().ToString() }));
            }

            await Task.WhenAll(creates);

            // Verify the handler still exists after client warm up
            //Assert.AreEqual(gatewayConnectionLimit, httpClientHandler.MaxConnectionsPerServer);
            IReadOnlyList <string> afterConnections = GetActiveConnections();

            // Clean up the database and container
            await database.DeleteAsync();

            int connectionDiff = afterConnections.Count - excludeConnections.Count;

            Assert.IsTrue(connectionDiff <= gatewayConnectionLimit, $"Connection before : {excludeConnections.Count}, after {afterConnections.Count}");
        }
        public async Task HttpClientConnectionLimitTest()
        {
            int gatewayConnectionLimit = 1;

            IReadOnlyList <string> excludeConnections = GetActiveConnections();

            using (CosmosClient cosmosClient = new CosmosClient(
                       ConfigurationManager.AppSettings["GatewayEndpoint"],
                       ConfigurationManager.AppSettings["MasterKey"],
                       new CosmosClientOptions
            {
                ApplicationName = "test",
                GatewayModeMaxConnectionLimit = gatewayConnectionLimit,
                ConnectionMode = ConnectionMode.Gateway,
                ConnectionProtocol = Protocol.Https
            }
                       ))
            {
                CosmosHttpClient  cosmosHttpClient  = cosmosClient.DocumentClient.httpClient;
                HttpClientHandler httpClientHandler = (HttpClientHandler)cosmosHttpClient.HttpMessageHandler;
                Assert.AreEqual(gatewayConnectionLimit, httpClientHandler.MaxConnectionsPerServer);

                Cosmos.Database database = await cosmosClient.CreateDatabaseAsync(Guid.NewGuid().ToString());

                Container container = await database.CreateContainerAsync(
                    "TestConnections",
                    "/pk",
                    throughput : 20000);

                List <Task> creates = new List <Task>();
                for (int i = 0; i < 100; i++)
                {
                    creates.Add(container.CreateItemAsync <dynamic>(new { id = Guid.NewGuid().ToString(), pk = Guid.NewGuid().ToString() }));
                }

                await Task.WhenAll(creates);

                // Clean up the database and container
                await database.DeleteAsync();
            }


            IReadOnlyList <string> afterConnections = GetActiveConnections();

            int connectionDiff = afterConnections.Count - excludeConnections.Count;

            Assert.IsTrue(connectionDiff <= gatewayConnectionLimit, $"Connection before : {excludeConnections.Count}, after {afterConnections.Count};" +
                          $"Before connections: {JsonConvert.SerializeObject(excludeConnections)}; After connections: {JsonConvert.SerializeObject(afterConnections)}");
        }
Example #12
0
        public async Task ImplicitConversion()
        {
            DatabaseResponse cosmosDatabaseResponse = await this.CreateDatabaseHelper();

            Cosmos.Database    cosmosDatabase         = cosmosDatabaseResponse;
            DatabaseProperties cosmosDatabaseSettings = cosmosDatabaseResponse;

            Assert.IsNotNull(cosmosDatabase);
            Assert.IsNotNull(cosmosDatabaseSettings);

            cosmosDatabaseResponse = await cosmosDatabase.DeleteAsync(cancellationToken : this.cancellationToken);

            cosmosDatabase         = cosmosDatabaseResponse;
            cosmosDatabaseSettings = cosmosDatabaseResponse;
            Assert.IsNotNull(cosmosDatabase);
            Assert.IsNull(cosmosDatabaseSettings);
        }
Example #13
0
        public async Task HttpClientFactorySmokeTest()
        {
            HttpClient client = new HttpClient();
            Mock <Func <HttpClient> > factory = new Mock <Func <HttpClient> >();

            factory.Setup(f => f()).Returns(client);
            CosmosClient cosmosClient = new CosmosClient(
                ConfigurationManager.AppSettings["GatewayEndpoint"],
                ConfigurationManager.AppSettings["MasterKey"],
                new CosmosClientOptions
            {
                ApplicationName    = "test",
                ConnectionMode     = ConnectionMode.Gateway,
                ConnectionProtocol = Protocol.Https,
                HttpClientFactory  = factory.Object
            }
                );

            string someId = Guid.NewGuid().ToString();

            Cosmos.Database database = null;
            try
            {
                database = await cosmosClient.CreateDatabaseAsync(someId);

                Cosmos.Container container = await database.CreateContainerAsync(Guid.NewGuid().ToString(), "/id");

                await container.CreateItemAsync <dynamic>(new { id = someId });

                await container.ReadItemAsync <dynamic>(someId, new Cosmos.PartitionKey(someId));

                await container.DeleteItemAsync <dynamic>(someId, new Cosmos.PartitionKey(someId));

                await container.DeleteContainerAsync();

                Mock.Get(factory.Object).Verify(f => f(), Times.Once);
            }
            finally
            {
                if (database != null)
                {
                    await database.DeleteAsync();
                }
            }
        }
Example #14
0
        public async Task NoThroughputTests()
        {
            string           databaseId     = Guid.NewGuid().ToString();
            DatabaseResponse createResponse = await this.CreateDatabaseHelper(databaseId, databaseExists : false);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            Cosmos.Database cosmosDatabase = createResponse;
            try
            {
                int?readThroughput = await((DatabaseCore)cosmosDatabase).ReadThroughputAsync();
                Assert.Fail("Should through not found exception as throughput is not configured");
            }
            catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            await cosmosDatabase.DeleteAsync();
        }
        public async Task ReadReplaceThroughputResponseTests()
        {
            string           databaseId     = Guid.NewGuid().ToString();
            int              throughput     = 10000;
            DatabaseResponse createResponse = await this.CreateDatabaseHelper(databaseId, databaseExists : false, throughput : throughput);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            Cosmos.Database    cosmosDatabase         = createResponse;
            ThroughputResponse readThroughputResponse = await cosmosDatabase.ReadThroughputAsync();

            Assert.IsNotNull(readThroughputResponse);
            Assert.IsNotNull(readThroughputResponse.Resource);
            Assert.IsNotNull(readThroughputResponse.MinThroughput);
            Assert.IsNotNull(readThroughputResponse.Resource.Throughput);
            Assert.AreEqual(throughput, readThroughputResponse.Resource.Throughput.Value);

            string            containerId       = Guid.NewGuid().ToString();
            string            partitionPath     = "/users";
            ContainerResponse containerResponse = await cosmosDatabase.CreateContainerAsync(containerId, partitionPath);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);

            ThroughputResponse replaceThroughputResponse = await cosmosDatabase.ReplaceThroughputAsync(readThroughputResponse.Resource.Throughput.Value + 1000);

            Assert.IsNotNull(replaceThroughputResponse);
            Assert.IsNotNull(replaceThroughputResponse.Resource);
            Assert.AreEqual(readThroughputResponse.Resource.Throughput.Value + 1000, replaceThroughputResponse.Resource.Throughput.Value);

            Container container = containerResponse;

            readThroughputResponse = await container.ReadThroughputAsync();

            Assert.IsNull(readThroughputResponse.Resource);

            await container.DeleteContainerAsync();

            await cosmosDatabase.DeleteAsync();
        }
        public async Task ReadReplaceThroughputResponseTests()
        {
            int toStreamCount   = 0;
            int fromStreamCount = 0;

            CosmosSerializerHelper mockJsonSerializer = new CosmosSerializerHelper(
                null,
                (x) => fromStreamCount++,
                (x) => toStreamCount++);

            //Create a new cosmos client with the mocked cosmos json serializer
            CosmosClient client = TestCommon.CreateCosmosClient(
                (cosmosClientBuilder) => cosmosClientBuilder.WithCustomSerializer(mockJsonSerializer));

            int databaseThroughput = 10000;

            Cosmos.Database databaseNoThroughput = await client.CreateDatabaseAsync(Guid.NewGuid().ToString(), null);

            Cosmos.Database databaseWithThroughput = await client.CreateDatabaseAsync(Guid.NewGuid().ToString(), databaseThroughput, null);


            string    containerId           = Guid.NewGuid().ToString();
            string    partitionPath         = "/users";
            Container containerNoThroughput = await databaseWithThroughput.CreateContainerAsync(containerId, partitionPath, throughput : null);

            try
            {
                await containerNoThroughput.ReadThroughputAsync(new RequestOptions());

                Assert.Fail("Should through not found exception as throughput is not configured");
            }
            catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            try
            {
                await containerNoThroughput.ReplaceThroughputAsync(2000, new RequestOptions());

                Assert.Fail("Should through not found exception as throughput is not configured");
            }
            catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            int       containerThroughput = 1000;
            Container container           = await databaseNoThroughput.CreateContainerAsync(Guid.NewGuid().ToString(), "/id", throughput : containerThroughput);

            int?containerResponseThroughput = await container.ReadThroughputAsync();

            Assert.AreEqual(containerThroughput, containerResponseThroughput);

            ThroughputResponse containerThroughputResponse = await container.ReadThroughputAsync(new RequestOptions());

            Assert.IsNotNull(containerThroughputResponse);
            Assert.IsNotNull(containerThroughputResponse.Resource);
            Assert.IsNotNull(containerThroughputResponse.MinThroughput);
            Assert.IsNotNull(containerThroughputResponse.Resource.Throughput);
            Assert.AreEqual(containerThroughput, containerThroughputResponse.Resource.Throughput.Value);

            containerThroughput        += 500;
            containerThroughputResponse = await container.ReplaceThroughputAsync(containerThroughput, new RequestOptions());

            Assert.IsNotNull(containerThroughputResponse);
            Assert.IsNotNull(containerThroughputResponse.Resource);
            Assert.IsNotNull(containerThroughputResponse.Resource.Throughput);
            Assert.AreEqual(containerThroughput, containerThroughputResponse.Resource.Throughput.Value);

            Assert.AreEqual(0, toStreamCount, "Custom serializer to stream should not be used for offer operations");
            Assert.AreEqual(0, fromStreamCount, "Custom serializer from stream should not be used for offer operations");
            await databaseNoThroughput.DeleteAsync();
        }
        public async Task VerifyUserAgentWithFeatures(bool setApplicationName, bool useMacOs)
        {
            this.SetEnvironmentInformation(useMacOs);

            const string suffix = " UserApplicationName/1.0";
            CosmosClientOptionsFeatures featuresFlags = CosmosClientOptionsFeatures.NoFeatures;

            featuresFlags |= CosmosClientOptionsFeatures.AllowBulkExecution;
            featuresFlags |= CosmosClientOptionsFeatures.HttpClientFactory;

            string features = Convert.ToString((int)featuresFlags, 2).PadLeft(8, '0');

            Action <Fluent.CosmosClientBuilder> applicationNameBuilder = (builder) =>
            {
                if (setApplicationName)
                {
                    builder.WithApplicationName(suffix);
                }
            };

            using (CosmosClient client = TestCommon.CreateCosmosClient(builder => applicationNameBuilder(builder.WithBulkExecution(true).WithHttpClientFactory(() => new HttpClient()))))
            {
                Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy().UserAgentContainer;

                string userAgentString = userAgentContainer.UserAgent;
                if (setApplicationName)
                {
                    Assert.IsTrue(userAgentString.Contains(suffix));
                }
                else
                {
                    Assert.IsFalse(userAgentString.Contains(suffix));
                }

                Assert.IsTrue(userAgentString.Contains($"|F {features}"));
                if (useMacOs)
                {
                    Assert.IsTrue(userAgentString.Contains("Darwin 18.0.0"));
                }

                Cosmos.Database db = await client.CreateDatabaseIfNotExistsAsync(Guid.NewGuid().ToString());

                Assert.IsNotNull(db);
                await db.DeleteAsync();
            }

            using (CosmosClient client = TestCommon.CreateCosmosClient(builder => applicationNameBuilder(builder)))
            {
                Cosmos.UserAgentContainer userAgentContainer = client.ClientOptions.GetConnectionPolicy().UserAgentContainer;

                string userAgentString = userAgentContainer.UserAgent;
                if (setApplicationName)
                {
                    Assert.IsTrue(userAgentString.Contains(suffix));
                }
                else
                {
                    Assert.IsFalse(userAgentString.Contains(suffix));
                }

                Assert.IsFalse(userAgentString.Contains($"|F {features}"));
            }
        }
        private async Task ValidateCollectionIndexProgressHeaders(CosmosClient client)
        {
            Cosmos.Database db = await client.CreateDatabaseAsync(Guid.NewGuid().ToString());

            try
            {
                PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition {
                    Paths = new System.Collections.ObjectModel.Collection <string>(new[] { "/id" }), Kind = PartitionKind.Hash
                };
                var lazyCollection = new ContainerProperties()
                {
                    Id = Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition
                };
                lazyCollection.IndexingPolicy.IndexingMode = Cosmos.IndexingMode.Lazy;
                Container lazyContainer = await db.CreateContainerAsync(lazyCollection);

                var consistentCollection = new ContainerProperties()
                {
                    Id = Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition
                };
                consistentCollection.IndexingPolicy.IndexingMode = Cosmos.IndexingMode.Consistent;
                Container consistentContainer = await db.CreateContainerAsync(consistentCollection);

                var noneIndexCollection = new ContainerProperties()
                {
                    Id = Guid.NewGuid().ToString(), PartitionKey = partitionKeyDefinition
                };
                noneIndexCollection.IndexingPolicy.Automatic    = false;
                noneIndexCollection.IndexingPolicy.IndexingMode = Cosmos.IndexingMode.None;
                Container noneIndexContainer = await db.CreateContainerAsync(noneIndexCollection);

                var doc = new Document()
                {
                    Id = Guid.NewGuid().ToString()
                };
                await lazyContainer.CreateItemAsync <Document>(doc);

                await consistentContainer.CreateItemAsync <Document>(doc);

                await noneIndexContainer.CreateItemAsync <Document>(doc);


                // Lazy-indexing collection.
                {
                    ContainerResponse collectionResponse = await lazyContainer.ReadContainerAsync(requestOptions : new ContainerRequestOptions {
                        PopulateQuotaInfo = true
                    });

                    Assert.IsTrue(int.Parse(collectionResponse.Headers[HttpConstants.HttpHeaders.CollectionLazyIndexingProgress], CultureInfo.InvariantCulture) >= 0,
                                  "Expect lazy indexer progress when reading lazy collection.");
                    Assert.AreEqual(100, int.Parse(collectionResponse.Headers[HttpConstants.HttpHeaders.CollectionIndexTransformationProgress], CultureInfo.InvariantCulture),
                                    "Expect reindexer progress when reading lazy collection.");
                }

                // Consistent-indexing collection.
                {
                    ContainerResponse collectionResponse = await consistentContainer.ReadContainerAsync(requestOptions : new ContainerRequestOptions {
                        PopulateQuotaInfo = true
                    });

                    Assert.IsFalse(collectionResponse.Headers.AllKeys().Contains(HttpConstants.HttpHeaders.CollectionLazyIndexingProgress),
                                   "No lazy indexer progress when reading consistent collection.");
                    Assert.AreEqual(100, int.Parse(collectionResponse.Headers[HttpConstants.HttpHeaders.CollectionIndexTransformationProgress], CultureInfo.InvariantCulture),
                                    "Expect reindexer progress when reading consistent collection.");
                }

                // None-indexing collection.
                {
                    ContainerResponse collectionResponse = await noneIndexContainer.ReadContainerAsync(requestOptions : new ContainerRequestOptions {
                        PopulateQuotaInfo = true
                    });

                    Assert.IsFalse(collectionResponse.Headers.AllKeys().Contains(HttpConstants.HttpHeaders.CollectionLazyIndexingProgress),
                                   "No lazy indexer progress when reading none-index collection.");
                    Assert.AreEqual(100, int.Parse(collectionResponse.Headers[HttpConstants.HttpHeaders.CollectionIndexTransformationProgress], CultureInfo.InvariantCulture),
                                    "Expect reindexer progress when reading none-index collection.");
                }
            }
            finally
            {
                await db.DeleteAsync();
            }
        }
Example #19
0
        public async Task ReadReplaceThroughputResponseTests()
        {
            int toStreamCount   = 0;
            int fromStreamCount = 0;

            CosmosSerializerHelper mockJsonSerializer = new CosmosSerializerHelper(
                null,
                (x) => fromStreamCount++,
                (x) => toStreamCount++);

            //Create a new cosmos client with the mocked cosmos json serializer
            CosmosClient client = TestCommon.CreateCosmosClient(
                (cosmosClientBuilder) => cosmosClientBuilder.WithCustomSerializer(mockJsonSerializer));

            string           databaseId     = Guid.NewGuid().ToString();
            int              throughput     = 10000;
            DatabaseResponse createResponse = await client.CreateDatabaseAsync(databaseId, throughput, null);

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);

            Cosmos.Database    cosmosDatabase         = createResponse;
            ThroughputResponse readThroughputResponse = await cosmosDatabase.ReadThroughputAsync(new RequestOptions());

            Assert.IsNotNull(readThroughputResponse);
            Assert.IsNotNull(readThroughputResponse.Resource);
            Assert.IsNotNull(readThroughputResponse.MinThroughput);
            Assert.IsNotNull(readThroughputResponse.Resource.Throughput);
            Assert.AreEqual(throughput, readThroughputResponse.Resource.Throughput.Value);

            // Implicit
            ThroughputProperties throughputProperties = await cosmosDatabase.ReadThroughputAsync(new RequestOptions());

            Assert.IsNotNull(throughputProperties);
            Assert.AreEqual(throughput, throughputProperties.Throughput);

            // Simple API
            int?readThroughput = await cosmosDatabase.ReadThroughputAsync();

            Assert.AreEqual(throughput, readThroughput);

            // Database must have a container before it can be scaled
            string            containerId       = Guid.NewGuid().ToString();
            string            partitionPath     = "/users";
            ContainerResponse containerResponse = await cosmosDatabase.CreateContainerAsync(containerId, partitionPath, throughput : null);

            Assert.AreEqual(HttpStatusCode.Created, containerResponse.StatusCode);

            ThroughputResponse replaceThroughputResponse = await cosmosDatabase.ReplaceThroughputAsync(readThroughputResponse.Resource.Throughput.Value + 1000);

            Assert.IsNotNull(replaceThroughputResponse);
            Assert.IsNotNull(replaceThroughputResponse.Resource);
            Assert.AreEqual(readThroughputResponse.Resource.Throughput.Value + 1000, replaceThroughputResponse.Resource.Throughput.Value);

            await cosmosDatabase.DeleteAsync();

            Database databaseNoThroughput = await client.CreateDatabaseAsync(Guid.NewGuid().ToString(), throughput : null);

            try
            {
                ThroughputResponse throughputResponse = await databaseNoThroughput.ReadThroughputAsync(new RequestOptions());

                Assert.Fail("Should through not found exception as throughput is not configured");
            }
            catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            try
            {
                ThroughputResponse throughputResponse = await databaseNoThroughput.ReplaceThroughputAsync(2000, new RequestOptions());

                Assert.Fail("Should through not found exception as throughput is not configured");
            }
            catch (CosmosException exception)
            {
                Assert.AreEqual(HttpStatusCode.NotFound, exception.StatusCode);
            }

            int?dbThroughput = await databaseNoThroughput.ReadThroughputAsync();

            Assert.IsNull(dbThroughput);

            Assert.AreEqual(0, toStreamCount, "Custom serializer to stream should not be used for offer operations");
            Assert.AreEqual(0, fromStreamCount, "Custom serializer from stream should not be used for offer operations");
            await databaseNoThroughput.DeleteAsync();
        }