コード例 #1
0
        internal void GetDeserializedObjectsFromQueryResponseTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string vertex1Id             = "v_0";
            const string vertex2Id             = "v_1";
            const string vertex1Label          = "l_0";
            const string vertex2Label          = "l_1";
            const string vertex1PkValue        = "pk_0";
            const string vertex2PkValue        = "pk_1";
            const string property1Name         = "p_0";
            const string vertex1Property1Value = "v_0_p_0_v_0";
            const string vertex2Property1Value = "v_1_p_0_v_0";
            const string property2Name         = "p_1";
            const double vertex1Property2Value = 12.34;
            const long   vertex2Property2Value = 5678;

            // Compose two initial vertex documents using eager CosmosElements
            CosmosObject initialVertex1EagerObject = this.CreateVertexDocument(
                vertex1Id,
                vertex1Label,
                GremlinScenarioTests.PartitionKeyPropertyName,
                vertex1PkValue,
                new Tuple <string, IEnumerable <object> >[]
            {
                Tuple.Create <string, IEnumerable <object> >(property1Name, new object[] { vertex1Property1Value }),
                Tuple.Create <string, IEnumerable <object> >(property2Name, new object[] { vertex1Property2Value }),
            });
            CosmosObject initialVertex2EagerObject = this.CreateVertexDocument(
                vertex2Id,
                vertex2Label,
                GremlinScenarioTests.PartitionKeyPropertyName,
                vertex2PkValue,
                new Tuple <string, IEnumerable <object> >[]
            {
                Tuple.Create <string, IEnumerable <object> >(property1Name, new object[] { vertex2Property1Value }),
                Tuple.Create <string, IEnumerable <object> >(property2Name, new object[] { vertex2Property2Value }),
            });

            // Serialize the initial vertex object into a document using the specified serialization format
            IJsonWriter jsonWriter = JsonWriter.Create(jsonSerializationFormat);

            initialVertex1EagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> vertex1JsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(vertex1JsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            jsonWriter = JsonWriter.Create(jsonSerializationFormat);
            initialVertex2EagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> vertex2JsonWriterResult = jsonWriter.GetResult();

            Assert.IsTrue(vertex2JsonWriterResult.Length > 0, "IJsonWriter result data is empty.");

            // Navigate into the serialized vertex documents using lazy CosmosElements
            CosmosElement vertex1LazyObject = CosmosElement.CreateFromBuffer(vertex1JsonWriterResult);
            CosmosElement vertex2LazyObject = CosmosElement.CreateFromBuffer(vertex2JsonWriterResult);

            // Create a dynamically-typed QueryResponse backed by the vertex document CosmosElements
            CosmosArray vertexArray = CosmosArray.Create(
                new CosmosElement[]
            {
                vertex1LazyObject,
                vertex2LazyObject,
            });
            QueryResponse queryResponse = QueryResponse.CreateSuccess(
                vertexArray,
                count: 2,
                responseLengthBytes: vertex1JsonWriterResult.Length + vertex2JsonWriterResult.Length,
                serializationOptions: null,
                trace: NoOpTrace.Singleton,
                responseHeaders: CosmosQueryResponseMessageHeaders.ConvertToQueryHeaders(
                    sourceHeaders: null,
                    resourceType: ResourceType.Document,
                    containerRid: GremlinScenarioTests.CreateRandomString(10)));
            QueryResponse <dynamic> cosmosElementQueryResponse =
                QueryResponse <dynamic> .CreateResponse <dynamic>(
                    queryResponse,
                    MockCosmosUtil.Serializer);

            // Assert that other objects (anything besides the lazy CosmosElements that we created earlier) are deserialized
            // from the backing CosmosElement contents rather than being directly returned as CosmosElements
            List <dynamic> responseCosmosElements = new List <dynamic>(cosmosElementQueryResponse.Resource);

            Assert.AreEqual(vertexArray.Count, responseCosmosElements.Count);
            Assert.AreNotSame(vertex1LazyObject, responseCosmosElements[0]);
            Assert.AreNotSame(vertex2LazyObject, responseCosmosElements[1]);
        }
コード例 #2
0
        public async Task TestItemProducerTreeWithFailure()
        {
            int callBackCount = 0;
            Mock <CosmosQueryContext> mockQueryContext = new Mock <CosmosQueryContext>();

            SqlQuerySpec      sqlQuerySpec      = new SqlQuerySpec("Select * from t");
            PartitionKeyRange partitionKeyRange = new PartitionKeyRange {
                Id = "0", MinInclusive = "A", MaxExclusive = "B"
            };
            Action <ItemProducerTree, int, double, QueryMetrics, long, CancellationToken> produceAsyncCompleteCallback = (
                ItemProducerTree producer,
                int itemsBuffered,
                double resourceUnitUsage,
                QueryMetrics queryMetrics,
                long responseLengthBytes,
                CancellationToken token) => { callBackCount++; };

            Mock <IComparer <ItemProducerTree> >      comparer = new Mock <IComparer <ItemProducerTree> >();
            Mock <IEqualityComparer <CosmosElement> > cosmosElementComparer = new Mock <IEqualityComparer <CosmosElement> >();
            CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();

            IEnumerable <CosmosElement> cosmosElements = new List <CosmosElement>()
            {
                new Mock <CosmosElement>(CosmosElementType.Object).Object
            };

            CosmosQueryResponseMessageHeaders headers = new CosmosQueryResponseMessageHeaders("TestToken", null, ResourceType.Document, "ContainerRid")
            {
                ActivityId    = "AA470D71-6DEF-4D61-9A08-272D8C9ABCFE",
                RequestCharge = 42
            };

            mockQueryContext.Setup(x => x.ExecuteQueryAsync(sqlQuerySpec, cancellationTokenSource.Token, It.IsAny <Action <CosmosRequestMessage> >())).Returns(
                Task.FromResult(QueryResponse.CreateSuccess(cosmosElements, 1, 500, headers)));

            ItemProducerTree itemProducerTree = new ItemProducerTree(
                queryContext: mockQueryContext.Object,
                querySpecForInit: sqlQuerySpec,
                partitionKeyRange: partitionKeyRange,
                produceAsyncCompleteCallback: produceAsyncCompleteCallback,
                itemProducerTreeComparer: comparer.Object,
                equalityComparer: cosmosElementComparer.Object,
                deferFirstPage: false,
                collectionRid: "collectionRid",
                initialContinuationToken: null,
                initialPageSize: 50);

            // Buffer to success responses
            await itemProducerTree.BufferMoreDocumentsAsync(cancellationTokenSource.Token);

            await itemProducerTree.BufferMoreDocumentsAsync(cancellationTokenSource.Token);

            // Buffer a failure
            mockQueryContext.Setup(x => x.ExecuteQueryAsync(sqlQuerySpec, cancellationTokenSource.Token, It.IsAny <Action <CosmosRequestMessage> >())).Returns(
                Task.FromResult(QueryResponse.CreateFailure(headers, HttpStatusCode.InternalServerError, null, "Error message", null)));

            await itemProducerTree.BufferMoreDocumentsAsync(cancellationTokenSource.Token);

            // First item should be a success
            var result = await itemProducerTree.MoveNextAsync(cancellationTokenSource.Token);

            Assert.IsTrue(result.successfullyMovedNext);
            Assert.IsNull(result.failureResponse);
            Assert.IsTrue(itemProducerTree.HasMoreResults);

            // Second item should be a success
            result = await itemProducerTree.MoveNextAsync(cancellationTokenSource.Token);

            Assert.IsTrue(result.successfullyMovedNext);
            Assert.IsNull(result.failureResponse);
            Assert.IsTrue(itemProducerTree.HasMoreResults);

            // Third item should be a failure
            result = await itemProducerTree.MoveNextAsync(cancellationTokenSource.Token);

            Assert.IsFalse(result.successfullyMovedNext);
            Assert.IsNotNull(result.failureResponse);
            Assert.IsFalse(itemProducerTree.HasMoreResults);

            // Try to buffer after failure. It should return the previous cached failure and not try to buffer again.
            mockQueryContext.Setup(x => x.ExecuteQueryAsync(sqlQuerySpec, cancellationTokenSource.Token, It.IsAny <Action <CosmosRequestMessage> >())).
            Throws(new Exception("Previous buffer failed. Operation should return original failure and not try again"));

            await itemProducerTree.BufferMoreDocumentsAsync(cancellationTokenSource.Token);

            Assert.IsFalse(result.successfullyMovedNext);
            Assert.IsNotNull(result.failureResponse);
            Assert.IsFalse(itemProducerTree.HasMoreResults);
        }