public void VerifyCosmosQueryResponseStream()
        {
            string contianerRid = "mockContainerRid";

            (QueryResponseCore response, IList <ToDoItem> items)factoryResponse = QueryResponseMessageFactory.Create(
                itemIdPrefix: $"TestPage",
                continuationToken: "SomeContinuationToken",
                collectionRid: contianerRid,
                itemCount: 100);

            QueryResponseCore responseCore = factoryResponse.response;

            QueryResponse queryResponse = QueryResponse.CreateSuccess(
                result: responseCore.CosmosElements,
                count: responseCore.CosmosElements.Count,
                responseLengthBytes: responseCore.ResponseLengthBytes,
                queryMetrics: responseCore.QueryMetrics,
                responseHeaders: new CosmosQueryResponseMessageHeaders(
                    responseCore.ContinuationToken,
                    responseCore.DisallowContinuationTokenMessage,
                    ResourceType.Document,
                    contianerRid)
            {
                RequestCharge = responseCore.RequestCharge,
                ActivityId    = responseCore.ActivityId
            });

            using (Stream stream = queryResponse.Content)
            {
                using (Stream innerStream = queryResponse.Content)
                {
                    Assert.IsTrue(object.ReferenceEquals(stream, innerStream), "Content should return the same stream");
                }
            }
        }
        public static List <ToDoItem> MockSinglePartitionKeyRangeContext(
            Mock <CosmosQueryClient> mockQueryContext,
            int[] responseMessagesPageSize,
            SqlQuerySpec sqlQuerySpec,
            PartitionKeyRange partitionKeyRange,
            string continuationToken,
            int maxPageSize,
            string collectionRid,
            Action executeCallback,
            CancellationToken cancellationToken)
        {
            // Setup a list of query responses. It generates a new continuation token for each response. This allows the mock to return the messages in the correct order.
            List <ToDoItem> allItems = new List <ToDoItem>();
            string          previousContinuationToken = continuationToken;

            for (int i = 0; i < responseMessagesPageSize.Length; i++)
            {
                string newContinuationToken = null;

                // The last response should have a null continuation token
                if (i + 1 != responseMessagesPageSize.Length)
                {
                    newContinuationToken = Guid.NewGuid().ToString();
                }

                (QueryResponseCore response, IList <ToDoItem> items)queryResponse = QueryResponseMessageFactory.Create(
                    itemIdPrefix: $"page{i}-pk{partitionKeyRange.Id}-",
                    continuationToken: newContinuationToken,
                    collectionRid: collectionRid,
                    itemCount: responseMessagesPageSize[i]);

                allItems.AddRange(queryResponse.items);

                mockQueryContext.Setup(x =>
                                       x.ExecuteItemQueryAsync(
                                           It.IsAny <string>(),
                                           ResourceType.Document,
                                           OperationType.Query,
                                           It.IsAny <Guid>(),
                                           It.IsAny <QueryRequestOptions>(),
                                           It.IsAny <Action <QueryPageDiagnostics> >(),
                                           It.Is <SqlQuerySpec>(specInput => IsSqlQuerySpecEqual(sqlQuerySpec, specInput)),
                                           previousContinuationToken,
                                           It.Is <PartitionKeyRangeIdentity>(rangeId => string.Equals(rangeId.PartitionKeyRangeId, partitionKeyRange.Id) && string.Equals(rangeId.CollectionRid, collectionRid)),
                                           It.IsAny <bool>(),
                                           maxPageSize,
                                           cancellationToken))
                .Callback(() => executeCallback?.Invoke())
                .Returns(Task.FromResult(queryResponse.response));


                if (responseMessagesPageSize[i] != QueryResponseMessageFactory.SPLIT)
                {
                    previousContinuationToken = newContinuationToken;
                }
            }

            return(allItems);
        }
        public static List <ToDoItem> MockSinglePartitionKeyRangeContext(
            Mock <CosmosQueryContext> mockQueryContext,
            int[] responseMessagesPageSize,
            SqlQuerySpec sqlQuerySpec,
            PartitionKeyRange partitionKeyRange,
            string continuationToken,
            int maxPageSize,
            string collectionRid,
            TimeSpan?responseDelay,
            CancellationToken cancellationToken)
        {
            // Setup a list of query responses. It generates a new continuation token for each response. This allows the mock to return the messages in the correct order.
            List <ToDoItem> allItems = new List <ToDoItem>();
            string          previousContinuationToken = continuationToken;

            for (int i = 0; i < responseMessagesPageSize.Length; i++)
            {
                string newContinuationToken = null;

                // The last response should have a null continuation token
                if (i + 1 != responseMessagesPageSize.Length)
                {
                    newContinuationToken = Guid.NewGuid().ToString();
                }

                (QueryResponse response, IList <ToDoItem> items)queryResponse = QueryResponseMessageFactory.Create(
                    itemIdPrefix: $"page{i}-pk{partitionKeyRange.Id}-",
                    continuationToken: newContinuationToken,
                    collectionRid: collectionRid,
                    itemCount: responseMessagesPageSize[i]);

                allItems.AddRange(queryResponse.items);

                mockQueryContext.Setup(x =>
                                       x.ExecuteQueryAsync(
                                           It.Is <SqlQuerySpec>(specInput => IsSqlQuerySpecEqual(sqlQuerySpec, specInput)),
                                           previousContinuationToken,
                                           It.Is <PartitionKeyRangeIdentity>(rangeId => string.Equals(rangeId.PartitionKeyRangeId, partitionKeyRange.Id) && string.Equals(rangeId.CollectionRid, collectionRid)),
                                           It.IsAny <bool>(),
                                           maxPageSize,
                                           cancellationToken))
                .Callback(() =>
                {
                    if (responseDelay.HasValue)
                    {
                        Thread.Sleep(responseDelay.Value);
                    }
                })
                .Returns(Task.FromResult(queryResponse.response));
                previousContinuationToken = newContinuationToken;
            }

            return(allItems);
        }
Esempio n. 4
0
        public void VerifyItemQueryResponseResult()
        {
            string contianerRid = "mockContainerRid";

            (QueryResponseCore response, IList <ToDoItem> items)factoryResponse = QueryResponseMessageFactory.Create(
                itemIdPrefix: $"TestPage",
                continuationToken: "SomeContinuationToken",
                collectionRid: contianerRid,
                itemCount: 100);

            QueryResponseCore    responseCore   = factoryResponse.response;
            List <CosmosElement> cosmosElements = new List <CosmosElement>(responseCore.CosmosElements);

            QueryResponse queryResponse = QueryResponse.CreateSuccess(
                result: cosmosElements,
                count: cosmosElements.Count,
                responseLengthBytes: responseCore.ResponseLengthBytes,
                serializationOptions: null,
                responseHeaders: new CosmosQueryResponseMessageHeaders(
                    responseCore.ContinuationToken,
                    responseCore.DisallowContinuationTokenMessage,
                    ResourceType.Document,
                    contianerRid)
            {
                RequestCharge = responseCore.RequestCharge,
                ActivityId    = responseCore.ActivityId
            },
                diagnostics: new CosmosDiagnosticsContextCore());

            QueryResponse <ToDoItem> itemQueryResponse = QueryResponseMessageFactory.CreateQueryResponse <ToDoItem>(queryResponse);
            List <ToDoItem>          resultItems       = new List <ToDoItem>(itemQueryResponse.Resource);
            ToDoItemComparer         comparer          = new ToDoItemComparer();

            Assert.AreEqual(factoryResponse.items.Count, resultItems.Count);
            for (int i = 0; i < factoryResponse.items.Count; i++)
            {
                Assert.AreNotSame(factoryResponse.items[i], resultItems[i]);
                Assert.AreEqual(0, comparer.Compare(factoryResponse.items[i], resultItems[i]));
            }
        }
Esempio n. 5
0
        private static IList <ToDoItem> GenerateAndMockResponseHelper(
            Mock <CosmosQueryClient> mockQueryClient,
            Mock <IRoutingMapProvider> mockRoutingMap,
            IList <ToDoItem> allItemsOrdered,
            bool isOrderByQuery,
            SqlQuerySpec sqlQuerySpec,
            string containerRid,
            string initContinuationToken,
            int maxPageSize,
            MockPartitionResponse[] mockResponseForSinglePartition,
            CancellationToken cancellationTokenForMocks)
        {
            if (mockResponseForSinglePartition == null)
            {
                throw new ArgumentNullException(nameof(mockResponseForSinglePartition));
            }

            // Loop through all the partitions
            foreach (MockPartitionResponse partitionAndMessages in mockResponseForSinglePartition)
            {
                PartitionKeyRange partitionKeyRange = partitionAndMessages.PartitionKeyRange;

                string previousContinuationToken = initContinuationToken;

                // Loop through each message inside the partition
                List <int[]> messages         = partitionAndMessages.MessagesWithItemIndex;
                int          messagesCount    = messages == null ? 0 : messages.Count;
                int          lastMessageIndex = messagesCount - 1;
                for (int i = 0; i < messagesCount; i++)
                {
                    int[] message = partitionAndMessages.MessagesWithItemIndex[i];

                    string newContinuationToken = null;

                    List <ToDoItem> currentPageItems = new List <ToDoItem>();
                    // Null represents an empty page
                    if (message != null)
                    {
                        foreach (int itemPosition in message)
                        {
                            currentPageItems.Add(allItemsOrdered[itemPosition]);
                        }
                    }

                    // Last message should have null continuation token
                    // Split means it's not the last message for this PK range
                    if (i != lastMessageIndex || partitionAndMessages.HasSplit)
                    {
                        newContinuationToken = Guid.NewGuid().ToString();
                    }

                    QueryResponse queryResponse = QueryResponseMessageFactory.CreateQueryResponse(
                        currentPageItems,
                        isOrderByQuery,
                        newContinuationToken,
                        containerRid);

                    mockQueryClient.Setup(x =>
                                          x.ExecuteItemQueryAsync(
                                              It.IsAny <Uri>(),
                                              ResourceType.Document,
                                              OperationType.Query,
                                              containerRid,
                                              It.IsAny <QueryRequestOptions>(),
                                              It.Is <SqlQuerySpec>(specInput => MockItemProducerFactory.IsSqlQuerySpecEqual(sqlQuerySpec, specInput)),
                                              previousContinuationToken,
                                              It.Is <PartitionKeyRangeIdentity>(rangeId => string.Equals(rangeId.PartitionKeyRangeId, partitionKeyRange.Id) && string.Equals(rangeId.CollectionRid, containerRid)),
                                              It.IsAny <bool>(),
                                              maxPageSize,
                                              cancellationTokenForMocks))
                    .Returns(Task.FromResult(queryResponse));

                    previousContinuationToken = newContinuationToken;
                }

                if (partitionAndMessages.HasSplit)
                {
                    QueryResponse querySplitResponse = QueryResponseMessageFactory.CreateSplitResponse(containerRid);

                    mockRoutingMap.Setup(x =>
                                         x.TryGetOverlappingRangesAsync(
                                             containerRid,
                                             It.Is <Documents.Routing.Range <string> >(inputRange => inputRange.Equals(partitionKeyRange.ToRange())),
                                             true)).Returns(Task.FromResult(partitionAndMessages.GetPartitionKeyRangeOfSplit()));

                    mockQueryClient.Setup(x =>
                                          x.ExecuteItemQueryAsync(
                                              It.IsAny <Uri>(),
                                              ResourceType.Document,
                                              OperationType.Query,
                                              containerRid,
                                              It.IsAny <QueryRequestOptions>(),
                                              It.Is <SqlQuerySpec>(specInput => MockItemProducerFactory.IsSqlQuerySpecEqual(sqlQuerySpec, specInput)),
                                              previousContinuationToken,
                                              It.Is <PartitionKeyRangeIdentity>(rangeId => string.Equals(rangeId.PartitionKeyRangeId, partitionKeyRange.Id) && string.Equals(rangeId.CollectionRid, containerRid)),
                                              It.IsAny <bool>(),
                                              maxPageSize,
                                              cancellationTokenForMocks))
                    .Returns(Task.FromResult(querySplitResponse));

                    GenerateAndMockResponseHelper(
                        mockQueryClient: mockQueryClient,
                        mockRoutingMap: mockRoutingMap,
                        allItemsOrdered: allItemsOrdered,
                        isOrderByQuery: isOrderByQuery,
                        sqlQuerySpec: sqlQuerySpec,
                        containerRid: containerRid,
                        initContinuationToken: previousContinuationToken,
                        maxPageSize: maxPageSize,
                        mockResponseForSinglePartition: partitionAndMessages.Split,
                        cancellationTokenForMocks: cancellationTokenForMocks);
                }
            }

            return(allItemsOrdered);
        }