public async Task BatchServerResponseTooLargeAsync()
        {
            Container container          = BatchTestBase.JsonContainer;
            const int operationCount     = 10;
            int       appxDocSizeInBytes = 1 * 1024 * 1024;

            TestDoc doc = await BatchTestBase.CreateJsonTestDocAsync(container, this.PartitionKey1, appxDocSizeInBytes);

            TransactionalBatch batch = new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1));

            for (int i = 0; i < operationCount; i++)
            {
                batch.ReadItem(doc.Id);
            }

            TransactionalBatchResponse batchResponse = await batch.ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(
                batchResponse,
                numberOfOperations: operationCount,
                expectedStatusCode: HttpStatusCode.RequestEntityTooLarge);

            Assert.AreEqual((int)StatusCodes.FailedDependency, (int)batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.RequestEntityTooLarge, batchResponse[operationCount - 1].StatusCode);
        }
        public async Task BatchOrderedAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            TestDoc firstDoc = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TestDoc replaceDoc = this.GetTestDocCopy(firstDoc);

            replaceDoc.Cost += 20;

            TransactionalBatchResponse batchResponse = await new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                       .CreateItem(firstDoc)
                                                       .ReplaceItem(replaceDoc.Id, replaceDoc)
                                                       .ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);

            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

            // Ensure that the replace overwrote the doc from the first operation
            await BatchTestBase.VerifyByReadAsync(container, replaceDoc);
        }
        private async Task <Container> RunWithErrorAsync(
            Container container,
            Action <TransactionalBatch> appendOperation,
            HttpStatusCode expectedFailedOperationStatusCode)
        {
            TestDoc testDocToCreate        = BatchTestBase.PopulateTestDoc(this.PartitionKey1);
            TestDoc anotherTestDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TransactionalBatch batch = new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                       .CreateItem(testDocToCreate);

            appendOperation(batch);

            TransactionalBatchResponse batchResponse = await batch
                                                       .CreateItem(anotherTestDocToCreate)
                                                       .ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(
                batchResponse,
                numberOfOperations: 3,
                expectedStatusCode: expectedFailedOperationStatusCode);

            Assert.AreEqual((HttpStatusCode)StatusCodes.FailedDependency, batchResponse[0].StatusCode);
            Assert.AreEqual(expectedFailedOperationStatusCode, batchResponse[1].StatusCode);
            Assert.AreEqual((HttpStatusCode)StatusCodes.FailedDependency, batchResponse[2].StatusCode);

            await BatchTestBase.VerifyNotFoundAsync(container, testDocToCreate);

            await BatchTestBase.VerifyNotFoundAsync(container, anotherTestDocToCreate);

            return(container);
        }
        private static bool PopulateRequestOptions(RequestOptions requestOptions, TestDoc doc, bool isSchematized, bool useEpk, int?ttlInSeconds)
        {
            Dictionary <string, object> properties = new Dictionary <string, object>();

            requestOptions.Properties = properties;
            if (isSchematized)
            {
                properties.Add(WFConstants.BackendHeaders.BinaryId, Encoding.UTF8.GetBytes(doc.Id));

                if (ttlInSeconds.HasValue)
                {
                    properties.Add(WFConstants.BackendHeaders.TimeToLiveInSeconds, ttlInSeconds.Value.ToString());
                }

                if (useEpk)
                {
                    string epk = new Microsoft.Azure.Documents.PartitionKey(doc.Status)
                                 .InternalKey
                                 .GetEffectivePartitionKeyString(BatchTestBase.PartitionKeyDefinition);

                    properties.Add(WFConstants.BackendHeaders.EffectivePartitionKeyString, epk);
                    properties.Add(WFConstants.BackendHeaders.EffectivePartitionKey, BatchTestBase.HexStringToBytes(epk));
                    requestOptions.IsEffectivePartitionKeyRouting = true;
                }

                return(true);
            }

            return(false);
        }
        public async Task BatchItemETagAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            {
                TestDoc testDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

                TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingA);
                testDocToReplace.Cost++;

                ItemResponse <TestDoc> readResponse = await BatchTestBase.JsonContainer.ReadItemAsync <TestDoc>(
                    this.TestDocPk1ExistingA.Id,
                    BatchTestBase.GetPartitionKey(this.PartitionKey1));

                TransactionalBatchItemRequestOptions firstReplaceOptions = new TransactionalBatchItemRequestOptions()
                {
                    IfMatchEtag = readResponse.ETag
                };

                TransactionalBatchResponse batchResponse = await new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                           .CreateItem(testDocToCreate)
                                                           .ReplaceItem(testDocToReplace.Id, testDocToReplace, requestOptions: firstReplaceOptions)
                                                           .ExecuteAsync();

                BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);

                Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
                Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

                await BatchTestBase.VerifyByReadAsync(container, testDocToCreate, eTag : batchResponse[0].ETag);

                await BatchTestBase.VerifyByReadAsync(container, testDocToReplace, eTag : batchResponse[1].ETag);
            }

            {
                TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingB);
                testDocToReplace.Cost++;

                TransactionalBatchItemRequestOptions replaceOptions = new TransactionalBatchItemRequestOptions()
                {
                    IfMatchEtag = BatchTestBase.Random.Next().ToString()
                };

                TransactionalBatchResponse batchResponse = await new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                           .ReplaceItem(testDocToReplace.Id, testDocToReplace, requestOptions: replaceOptions)
                                                           .ExecuteAsync();

                BatchSinglePartitionKeyTests.VerifyBatchProcessed(
                    batchResponse,
                    numberOfOperations: 1,
                    expectedStatusCode: HttpStatusCode.PreconditionFailed);

                Assert.AreEqual(HttpStatusCode.PreconditionFailed, batchResponse[0].StatusCode);

                // ensure the document was not updated
                await BatchTestBase.VerifyByReadAsync(container, this.TestDocPk1ExistingB);
            }
        }
Пример #6
0
        protected static async Task VerifyByReadAsync(Container container, TestDoc doc, bool isStream = false, bool isSchematized = false, bool useEpk = false, string eTag = null)
        {
            Cosmos.PartitionKey partitionKey = BatchTestBase.GetPartitionKey(doc.Status);

            if (isStream)
            {
                string             id             = BatchTestBase.GetId(doc, isSchematized);
                ItemRequestOptions requestOptions = BatchTestBase.GetItemRequestOptions(doc, isSchematized, useEpk);
                ResponseMessage    response       = await container.ReadItemStreamAsync(id, partitionKey, requestOptions);

                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.AreEqual(doc, BatchTestBase.StreamToTestDoc(response.Content, isSchematized));

                if (eTag != null)
                {
                    Assert.AreEqual(eTag, response.Headers.ETag);
                }
            }
            else
            {
                ItemResponse <TestDoc> response = await container.ReadItemAsync <TestDoc>(doc.Id, partitionKey);

                Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
                Assert.AreEqual(doc, response.Resource);

                if (eTag != null)
                {
                    Assert.AreEqual(eTag, response.Headers.ETag);
                }
            }
        }
        public async Task BatchItemSessionTokenAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            TestDoc testDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingA);

            testDocToReplace.Cost++;

            ItemResponse <TestDoc> readResponse = await BatchTestBase.JsonContainer.ReadItemAsync <TestDoc>(
                this.TestDocPk1ExistingA.Id,
                BatchTestBase.GetPartitionKey(this.PartitionKey1));

            ISessionToken beforeRequestSessionToken = BatchTestBase.GetSessionToken(readResponse.Headers.Session);

            TransactionalBatchResponse batchResponse = await new BatchCore((ContainerInlineCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                       .CreateItem(testDocToCreate)
                                                       .ReplaceItem(testDocToReplace.Id, testDocToReplace)
                                                       .ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);
            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

            ISessionToken afterRequestSessionToken = BatchTestBase.GetSessionToken(batchResponse.Headers.Session);

            Assert.IsTrue(afterRequestSessionToken.LSN > beforeRequestSessionToken.LSN, "Response session token should be more than request session token");
        }
        public async Task BatchItemTimeToLiveAsync()
        {
            // Verify with schematized containers where we are allowed to send TTL as a header
            const bool isSchematized = true;
            const bool isStream      = true;
            Container  container     = BatchTestBase.SchematizedContainer;

            await this.CreateSchematizedTestDocsAsync(container);

            {
                TestDoc testDocToCreate        = BatchTestBase.PopulateTestDoc(this.PartitionKey1);
                TestDoc anotherTestDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

                TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingA);
                testDocToReplace.Cost++;

                const int ttlInSeconds = 3;
                const int infiniteTtl  = -1;

                TestDoc testDocToUpsert = await BatchTestBase.CreateSchematizedTestDocAsync(container, this.PartitionKey1, ttlInSeconds : ttlInSeconds);

                testDocToUpsert.Cost++;

                BatchCore batch = (BatchCore)(new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                              .CreateItemStream(
                                                  BatchTestBase.TestDocToStream(testDocToCreate, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToCreate, isSchematized, ttlInSeconds: ttlInSeconds))
                                              .CreateItemStream(
                                                  BatchTestBase.TestDocToStream(anotherTestDocToCreate, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(anotherTestDocToCreate, isSchematized))
                                              .ReplaceItemStream(
                                                  BatchTestBase.GetId(testDocToReplace, isSchematized),
                                                  BatchTestBase.TestDocToStream(testDocToReplace, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToReplace, isSchematized, ttlInSeconds: ttlInSeconds))
                                              .UpsertItemStream(
                                                  BatchTestBase.TestDocToStream(testDocToUpsert, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToUpsert, isSchematized, ttlInSeconds: infiniteTtl)));

                TransactionalBatchResponse batchResponse = await batch.ExecuteAsync(BatchTestBase.GetUpdatedBatchRequestOptions(isSchematized: true));

                BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 4);

                Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
                Assert.AreEqual(HttpStatusCode.Created, batchResponse[1].StatusCode);
                Assert.AreEqual(HttpStatusCode.OK, batchResponse[2].StatusCode);
                Assert.AreEqual(HttpStatusCode.OK, batchResponse[3].StatusCode);

                // wait for TTL to expire
                await Task.Delay(TimeSpan.FromSeconds(ttlInSeconds + 1));

                await BatchTestBase.VerifyNotFoundAsync(container, testDocToCreate, isSchematized);

                await BatchTestBase.VerifyByReadAsync(container, anotherTestDocToCreate, isStream, isSchematized);

                await BatchTestBase.VerifyNotFoundAsync(container, testDocToReplace, isSchematized);

                await BatchTestBase.VerifyByReadAsync(container, testDocToUpsert, isStream, isSchematized);
            }
        }
Пример #9
0
        protected static async Task <TestDoc> CreateJsonTestDocAsync(Container container, object partitionKey, int minDesiredSize = 20)
        {
            TestDoc doc = BatchTestBase.PopulateTestDoc(partitionKey, minDesiredSize);
            ItemResponse <TestDoc> createResponse = await container.CreateItemAsync(doc, BatchTestBase.GetPartitionKey(partitionKey));

            Assert.AreEqual(HttpStatusCode.Created, createResponse.StatusCode);
            return(doc);
        }
Пример #10
0
        internal static string GetDifferentLSNToken(string token, long lsnIncrement)
        {
            string[]      tokenParts            = token.Split(':');
            ISessionToken sessionToken          = SessionTokenHelper.Parse(tokenParts[1]);
            ISessionToken differentSessionToken = BatchTestBase.CreateSessionToken(sessionToken, sessionToken.LSN + lsnIncrement);

            return(string.Format(CultureInfo.InvariantCulture, "{0}:{1}", tokenParts[0], differentSessionToken.ConvertToString()));
        }
        public async Task BatchWithInvalidCreateAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            // partition key mismatch between doc and and value passed in to the operation
            await this.RunWithErrorAsync(
                container,
                batch => batch.CreateItem(BatchTestBase.PopulateTestDoc(partitionKey: Guid.NewGuid().ToString())),
                HttpStatusCode.BadRequest);
        }
Пример #12
0
        protected virtual async Task CreateSchematizedTestDocsAsync(Container container)
        {
            this.TestDocPk1ExistingA = await BatchTestBase.CreateSchematizedTestDocAsync(container, this.PartitionKey1);

            this.TestDocPk1ExistingB = await BatchTestBase.CreateSchematizedTestDocAsync(container, this.PartitionKey1);

            this.TestDocPk1ExistingC = await BatchTestBase.CreateSchematizedTestDocAsync(container, this.PartitionKey1);

            this.TestDocPk1ExistingD = await BatchTestBase.CreateSchematizedTestDocAsync(container, this.PartitionKey1);
        }
Пример #13
0
        protected static async Task VerifyNotFoundAsync(Container container, TestDoc doc, bool isSchematized = false, bool useEpk = false)
        {
            string id = BatchTestBase.GetId(doc, isSchematized);

            Cosmos.PartitionKey partitionKey   = BatchTestBase.GetPartitionKey(doc.Status);
            ItemRequestOptions  requestOptions = BatchTestBase.GetItemRequestOptions(doc, isSchematized, useEpk);

            ResponseMessage response = await container.ReadItemStreamAsync(id, partitionKey, requestOptions);

            Assert.AreEqual(HttpStatusCode.NotFound, response.StatusCode);
        }
Пример #14
0
        protected static async Task <TestDoc> CreateSchematizedTestDocAsync(Container container, object partitionKey, int?ttlInSeconds = null)
        {
            TestDoc         doc            = BatchTestBase.PopulateTestDoc(partitionKey);
            ResponseMessage createResponse = await container.CreateItemStreamAsync(
                doc.ToHybridRowStream(),
                BatchTestBase.GetPartitionKey(partitionKey),
                BatchTestBase.GetItemRequestOptions(doc, isSchematized: true, ttlInSeconds: ttlInSeconds));

            Assert.AreEqual(
                HttpStatusCode.Created,
                createResponse.StatusCode);
            return(doc);
        }
        public async Task BatchCustomSerializerUsedForPatchAsync()
        {
            CosmosClientOptions clientOptions = new CosmosClientOptions()
            {
                Serializer = new CosmosJsonDotNetSerializer(
                    new JsonSerializerSettings()
                {
                    DateFormatString = "yyyy--MM--dd hh:mm"
                })
            };

            CosmosClient customSerializationClient    = TestCommon.CreateCosmosClient(clientOptions);
            Container    customSerializationContainer = customSerializationClient.GetContainer(BatchTestBase.Database.Id, BatchTestBase.JsonContainer.Id);

            TestDoc testDoc = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            DateTime patchDate = new DateTime(2020, 07, 01, 01, 02, 03);
            List <PatchOperation> patchOperations = new List <PatchOperation>()
            {
                PatchOperation.CreateAddOperation("/date", patchDate)
            };

            BatchCore batch = (BatchCore) new BatchCore((ContainerInlineCore)customSerializationContainer, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                              .CreateItem(testDoc);

            batch = (BatchCore)batch.PatchItem(testDoc.Id, patchOperations);

            TransactionalBatchResponse batchResponse = await batch.ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);

            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);

            JsonSerializerSettings jsonSettings = new JsonSerializerSettings();

            jsonSettings.DateFormatString = "yyyy--MM--dd hh:mm";
            string dateJson = JsonConvert.SerializeObject(patchDate, jsonSettings);

            // regular container
            ItemResponse <dynamic> response = await BatchTestBase.JsonContainer.ReadItemAsync <dynamic>(
                testDoc.Id,
                BatchTestBase.GetPartitionKey(this.PartitionKey1));

            Assert.AreEqual(HttpStatusCode.OK, response.StatusCode);
            Assert.IsNotNull(response.Resource);
            Assert.IsTrue(dateJson.Contains(response.Resource["date"].ToString()));
        }
        private async Task RunBatchWithCreateConflictAsync(Container container)
        {
            await this.CreateJsonTestDocsAsync(container);

            // try to create a doc with id that already exists (should return a Conflict)
            TestDoc conflictingTestDocToCreate = this.GetTestDocCopy(this.TestDocPk1ExistingA);

            conflictingTestDocToCreate.Cost++;

            await this.RunWithErrorAsync(
                container,
                batch => batch.CreateItem(conflictingTestDocToCreate),
                HttpStatusCode.Conflict);

            // make sure the conflicted doc hasn't changed
            await BatchTestBase.VerifyByReadAsync(container, this.TestDocPk1ExistingA);
        }
Пример #17
0
        protected static ItemRequestOptions GetItemRequestOptions(TestDoc doc, bool isSchematized, bool useEpk = false, int?ttlInSeconds = null)
        {
            ItemRequestOptions requestOptions = new ItemRequestOptions();
            bool wasPopulated = BatchTestBase.PopulateRequestOptions(requestOptions, doc, isSchematized, useEpk, ttlInSeconds);

            if (isSchematized)
            {
                Dictionary <string, object> properties = requestOptions.Properties as Dictionary <string, object>;
                properties.Add(WFConstants.BackendHeaders.BinaryPassthroughRequest, bool.TrueString);
                wasPopulated = true;
            }

            if (wasPopulated)
            {
                return(requestOptions);
            }

            return(null);
        }
Пример #18
0
        protected static RequestOptions GetUpdatedBatchRequestOptions(
            RequestOptions batchOptions = null,
            bool isSchematized          = false,
            bool useEpk         = false,
            object partitionKey = null)
        {
            if (isSchematized)
            {
                if (batchOptions == null)
                {
                    batchOptions = new RequestOptions();
                }

                Dictionary <string, object> properties = new Dictionary <string, object>()
                {
                    { WFConstants.BackendHeaders.BinaryPassthroughRequest, bool.TrueString }
                };

                if (batchOptions.Properties != null)
                {
                    foreach (KeyValuePair <string, object> entry in batchOptions.Properties)
                    {
                        properties.Add(entry.Key, entry.Value);
                    }
                }

                if (useEpk)
                {
                    string epk = new Microsoft.Azure.Documents.PartitionKey(partitionKey)
                                 .InternalKey
                                 .GetEffectivePartitionKeyString(BatchTestBase.PartitionKeyDefinition);

                    properties.Add(WFConstants.BackendHeaders.EffectivePartitionKeyString, epk);
                    properties.Add(WFConstants.BackendHeaders.EffectivePartitionKey, BatchTestBase.HexStringToBytes(epk));
                    batchOptions.IsEffectivePartitionKeyRouting = true;
                }

                batchOptions.Properties = properties;
            }

            return(batchOptions);
        }
        private async Task <TransactionalBatchResponse[]> RunTwoLargeBatchesAsync(Container container)
        {
            TransactionalBatch batch1 = new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1));
            TransactionalBatch batch2 = new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1));

            for (int i = 0; i < Constants.MaxOperationsInDirectModeBatchRequest; i++)
            {
                batch1.CreateItem(BatchSinglePartitionKeyTests.PopulateTestDoc(this.PartitionKey1));
                batch2.CreateItem(BatchSinglePartitionKeyTests.PopulateTestDoc(this.PartitionKey1));
            }

            Task <TransactionalBatchResponse> batch1Task = batch1.ExecuteAsync();
            await Task.Delay(50);

            Task <TransactionalBatchResponse> batch2Task = batch2.ExecuteAsync();

            TransactionalBatchResponse[] batchResponses = await Task.WhenAll(batch1Task, batch2Task);

            return(batchResponses);
        }
        public async Task BatchLargerThanServerRequestAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            const int operationCount = 20;
            int       appxDocSize    = Constants.MaxDirectModeBatchRequestBodySizeInBytes / operationCount;

            // Increase the doc size by a bit so all docs won't fit in one server request.
            appxDocSize = (int)(appxDocSize * 1.05);
            TransactionalBatch batch = new BatchCore((ContainerCore)container, new Cosmos.PartitionKey(this.PartitionKey1));

            for (int i = 0; i < operationCount; i++)
            {
                TestDoc doc = BatchTestBase.PopulateTestDoc(this.PartitionKey1, minDesiredSize: appxDocSize);
                batch.CreateItem(doc);
            }

            TransactionalBatchResponse batchResponse = await batch.ExecuteAsync();

            Assert.AreEqual(HttpStatusCode.RequestEntityTooLarge, batchResponse.StatusCode);
        }
        public async Task BatchCreateAndPatchAsync()
        {
            TestDoc testDoc = BatchTestBase.PopulateTestDoc(this.PartitionKey1);
            List <PatchOperation> patchOperations = new List <PatchOperation>()
            {
                PatchOperation.CreateReplaceOperation("/Cost", testDoc.Cost + 1)
            };

            BatchCore batch = (BatchCore) new BatchCore((ContainerInlineCore)BatchTestBase.JsonContainer, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                              .CreateItem(testDoc);

            batch = (BatchCore)batch.PatchItem(testDoc.Id, patchOperations);

            TransactionalBatchResponse batchResponse = await batch.ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 2);

            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);
            testDoc.Cost = testDoc.Cost + 1;
            await BatchTestBase.VerifyByReadAsync(BatchTestBase.JsonContainer, testDoc, isStream : false, isSchematized : false, useEpk : false);
        }
        public async Task BatchWithReplaceOfStaleEntityAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            TestDoc staleTestDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingA);

            staleTestDocToReplace.Cost++;
            TransactionalBatchItemRequestOptions staleReplaceOptions = new TransactionalBatchItemRequestOptions()
            {
                IfMatchEtag = Guid.NewGuid().ToString()
            };

            await this.RunWithErrorAsync(
                container,
                batch => batch.ReplaceItem(staleTestDocToReplace.Id, staleTestDocToReplace, staleReplaceOptions),
                HttpStatusCode.PreconditionFailed);

            // make sure the stale doc hasn't changed
            await BatchTestBase.VerifyByReadAsync(container, this.TestDocPk1ExistingA);
        }
 public static void ClassInitialize(TestContext context)
 {
     BatchTestBase.ClassInit(context);
 }
 public static void ClassCleanup()
 {
     BatchTestBase.ClassClean();
 }
        public async Task BatchReadsOnlyAsync()
        {
            Container container = BatchTestBase.JsonContainer;

            await this.CreateJsonTestDocsAsync(container);

            TransactionalBatchResponse batchResponse = await new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                                       .ReadItem(this.TestDocPk1ExistingA.Id)
                                                       .ReadItem(this.TestDocPk1ExistingB.Id)
                                                       .ReadItem(this.TestDocPk1ExistingC.Id)
                                                       .ExecuteAsync();

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 3);

            Assert.AreEqual(HttpStatusCode.OK, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[2].StatusCode);

            Assert.AreEqual(this.TestDocPk1ExistingA, batchResponse.GetOperationResultAtIndex <TestDoc>(0).Resource);
            Assert.AreEqual(this.TestDocPk1ExistingB, batchResponse.GetOperationResultAtIndex <TestDoc>(1).Resource);
            Assert.AreEqual(this.TestDocPk1ExistingC, batchResponse.GetOperationResultAtIndex <TestDoc>(2).Resource);
        }
        private async Task <TransactionalBatchResponse> RunCrudAsync(bool isStream, bool isSchematized, bool useEpk, Container container)
        {
            RequestOptions batchOptions = null;

            if (isSchematized)
            {
                await this.CreateSchematizedTestDocsAsync(container);

                batchOptions = BatchTestBase.GetUpdatedBatchRequestOptions(batchOptions, isSchematized, useEpk, this.PartitionKey1);
            }
            else
            {
                await this.CreateJsonTestDocsAsync(container);
            }

            TestDoc testDocToCreate = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TestDoc testDocToUpsert = BatchTestBase.PopulateTestDoc(this.PartitionKey1);

            TestDoc anotherTestDocToUpsert = this.GetTestDocCopy(this.TestDocPk1ExistingA);

            anotherTestDocToUpsert.Cost++;

            TestDoc testDocToReplace = this.GetTestDocCopy(this.TestDocPk1ExistingB);

            testDocToReplace.Cost++;

            // We run CRUD operations where all are expected to return HTTP 2xx.
            TransactionalBatchResponse batchResponse;

            if (!isStream)
            {
                batchResponse = await new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                .CreateItem(testDocToCreate)
                                .ReadItem(this.TestDocPk1ExistingC.Id)
                                .ReplaceItem(testDocToReplace.Id, testDocToReplace)
                                .UpsertItem(testDocToUpsert)
                                .UpsertItem(anotherTestDocToUpsert)
                                .DeleteItem(this.TestDocPk1ExistingD.Id)
                                .ExecuteAsync();
            }
            else
            {
                BatchCore batch = (BatchCore)(new BatchCore((ContainerCore)container, BatchTestBase.GetPartitionKey(this.PartitionKey1))
                                              .CreateItemStream(
                                                  BatchTestBase.TestDocToStream(testDocToCreate, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToCreate, isSchematized))
                                              .ReadItem(
                                                  BatchTestBase.GetId(this.TestDocPk1ExistingC, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(this.TestDocPk1ExistingC, isSchematized))
                                              .ReplaceItemStream(
                                                  BatchTestBase.GetId(testDocToReplace, isSchematized),
                                                  BatchTestBase.TestDocToStream(testDocToReplace, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToReplace, isSchematized))
                                              .UpsertItemStream(
                                                  BatchTestBase.TestDocToStream(testDocToUpsert, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(testDocToUpsert, isSchematized))
                                              .UpsertItemStream(
                                                  BatchTestBase.TestDocToStream(anotherTestDocToUpsert, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(anotherTestDocToUpsert, isSchematized))
                                              .DeleteItem(
                                                  BatchTestBase.GetId(this.TestDocPk1ExistingD, isSchematized),
                                                  BatchTestBase.GetBatchItemRequestOptions(this.TestDocPk1ExistingD, isSchematized)));

                batchResponse = await batch.ExecuteAsync(batchOptions);
            }

            BatchSinglePartitionKeyTests.VerifyBatchProcessed(batchResponse, numberOfOperations: 6);

            Assert.AreEqual(HttpStatusCode.Created, batchResponse[0].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[1].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[2].StatusCode);
            Assert.AreEqual(HttpStatusCode.Created, batchResponse[3].StatusCode);
            Assert.AreEqual(HttpStatusCode.OK, batchResponse[4].StatusCode);
            Assert.AreEqual(HttpStatusCode.NoContent, batchResponse[5].StatusCode);

            if (!isStream)
            {
                Assert.AreEqual(this.TestDocPk1ExistingC, batchResponse.GetOperationResultAtIndex <TestDoc>(1).Resource);
            }
            else
            {
                Assert.AreEqual(this.TestDocPk1ExistingC, BatchTestBase.StreamToTestDoc(batchResponse[1].ResourceStream, isSchematized));
            }

            await BatchTestBase.VerifyByReadAsync(container, testDocToCreate, isStream, isSchematized, useEpk);

            await BatchTestBase.VerifyByReadAsync(container, testDocToReplace, isStream, isSchematized, useEpk);

            await BatchTestBase.VerifyByReadAsync(container, testDocToUpsert, isStream, isSchematized, useEpk);

            await BatchTestBase.VerifyByReadAsync(container, anotherTestDocToUpsert, isStream, isSchematized, useEpk);

            await BatchTestBase.VerifyNotFoundAsync(container, this.TestDocPk1ExistingD, isSchematized, useEpk);

            return(batchResponse);
        }