Esempio n. 1
0
        public void TestNumber()
        {
            {
                Number64 value = 32;
                ReadOnlyMemory <byte> result       = JsonSerializer.Serialize(value);
                CosmosNumber64        cosmosNumber = (CosmosNumber64)CosmosElement.CreateFromBuffer(result);
                Assert.AreEqual(expected: value, actual: cosmosNumber.Value);
            }

            {
                sbyte value = 32;
                ReadOnlyMemory <byte> result       = JsonSerializer.Serialize(value);
                CosmosInt8            cosmosNumber = (CosmosInt8)CosmosElement.CreateFromBuffer(result);
                Assert.AreEqual(expected: value, actual: cosmosNumber.Value);
            }

            {
                short value = 32;
                ReadOnlyMemory <byte> result       = JsonSerializer.Serialize(value);
                CosmosInt16           cosmosNumber = (CosmosInt16)CosmosElement.CreateFromBuffer(result);
                Assert.AreEqual(expected: value, actual: cosmosNumber.Value);
            }

            {
                int value = 32;
                ReadOnlyMemory <byte> result       = JsonSerializer.Serialize(value);
                CosmosInt32           cosmosNumber = (CosmosInt32)CosmosElement.CreateFromBuffer(result);
                Assert.AreEqual(expected: value, actual: cosmosNumber.Value);
            }

            {
                long value = 32;
                ReadOnlyMemory <byte> result       = JsonSerializer.Serialize(value);
                CosmosInt64           cosmosNumber = (CosmosInt64)CosmosElement.CreateFromBuffer(result);
                Assert.AreEqual(expected: value, actual: cosmosNumber.Value);
            }

            {
                uint value = 32;
                ReadOnlyMemory <byte> result       = JsonSerializer.Serialize(value);
                CosmosUInt32          cosmosNumber = (CosmosUInt32)CosmosElement.CreateFromBuffer(result);
                Assert.AreEqual(expected: value, actual: cosmosNumber.Value);
            }

            {
                float value = 32.1337f;
                ReadOnlyMemory <byte> result       = JsonSerializer.Serialize(value);
                CosmosFloat32         cosmosNumber = (CosmosFloat32)CosmosElement.CreateFromBuffer(result);
                Assert.AreEqual(expected: value, actual: cosmosNumber.Value);
            }

            {
                double value = 32.1337;
                ReadOnlyMemory <byte> result       = JsonSerializer.Serialize(value);
                CosmosFloat64         cosmosNumber = (CosmosFloat64)CosmosElement.CreateFromBuffer(result);
                Assert.AreEqual(expected: value, actual: cosmosNumber.Value);
            }
        }
            /// <summary>
            /// Reads a payload from a json reader.
            /// </summary>
            /// <param name="reader">The reader.</param>
            /// <param name="objectType">The object type.</param>
            /// <param name="existingValue">The existing value.</param>
            /// <param name="serializer">The serialized</param>
            /// <returns>The deserialized JSON.</returns>
            public override object ReadJson(
                JsonReader reader,
                Type objectType,
                object existingValue,
                JsonSerializer serializer)
            {
                JToken jToken = JToken.Load(reader);
                // TODO: In the future we can go from jToken to CosmosElement if we have the eager implemenation.
                CosmosElement cosmosElement = CosmosElement.CreateFromBuffer(Encoding.UTF8.GetBytes(jToken.ToString()));

                return(new OrderByItem(cosmosElement));
            }
        public void WriteToWriter()
        {
            CosmosArray lazilyDeserializedPeople = CosmosElement.CreateFromBuffer(LazyCosmosElementTests.bufferedSerializedPeople) as CosmosArray;
            IJsonWriter jsonWriter = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Text);

            lazilyDeserializedPeople.WriteTo(jsonWriter);
            byte[] bufferedResult = jsonWriter.GetResult().ToArray();

            string bufferedSerializedPeopleString = Encoding.UTF8.GetString(bufferedSerializedPeople);
            string bufferedResultString           = Encoding.UTF8.GetString(bufferedResult);

            Assert.AreEqual(bufferedSerializedPeopleString, bufferedResultString);
        }
Esempio n. 4
0
        public void TestList()
        {
            List <int> list = new List <int> {
                1, 2, 3
            };
            ReadOnlyMemory <byte> result = JsonSerializer.Serialize(list);

            CosmosArray cosmosArray = (CosmosArray)CosmosElement.CreateFromBuffer(result);

            Assert.AreEqual(list[0], (cosmosArray[0] as CosmosNumber).Value);
            Assert.AreEqual(list[1], (cosmosArray[1] as CosmosNumber).Value);
            Assert.AreEqual(list[2], (cosmosArray[2] as CosmosNumber).Value);
        }
Esempio n. 5
0
        public void TestBool()
        {
            {
                ReadOnlyMemory <byte> result        = JsonSerializer.Serialize(true);
                CosmosBoolean         cosmosBoolean = (CosmosBoolean)CosmosElement.CreateFromBuffer(result);
                Assert.IsTrue(cosmosBoolean.Value);
            }

            {
                ReadOnlyMemory <byte> result        = JsonSerializer.Serialize(false);
                CosmosBoolean         cosmosBoolean = (CosmosBoolean)CosmosElement.CreateFromBuffer(result);
                Assert.IsFalse(cosmosBoolean.Value);
            }
        }
Esempio n. 6
0
        public void TestPoco()
        {
            Person person = Person.GetRandomPerson();
            ReadOnlyMemory <byte> result = JsonSerializer.Serialize(person);

            CosmosObject cosmosObject = (CosmosObject)CosmosElement.CreateFromBuffer(result);

            Assert.IsTrue(cosmosObject.TryGetValue("Name", out CosmosString personName));
            Assert.AreEqual(person.Name, personName.Value.ToString());

            Assert.IsTrue(cosmosObject.TryGetValue("Age", out CosmosNumber personAge));
            Assert.AreEqual(person.Age, personAge.Value);

            Assert.IsTrue(cosmosObject.TryGetValue("Children", out CosmosArray personChildren));
            Assert.AreEqual(person.Children.Count, personChildren.Count);
        }
        private static void TestCosmosElementVisitabilityFromJson(string json)
        {
            ReadOnlyMemory <byte> payload = LazyCosmosElementTests.ConvertStringToBinary(json);

            CosmosElement cosmosElement = CosmosElement.CreateFromBuffer(payload);

            IJsonWriter jsonWriterIndexer    = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Binary);
            IJsonWriter jsonWriterEnumerable = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Binary);

            LazyCosmosElementTests.VisitCosmosElementIndexer(cosmosElement, jsonWriterIndexer);
            LazyCosmosElementTests.VisitCosmosElementEnumerable(cosmosElement, jsonWriterEnumerable);

            CosmosElement cosmosElementFromIndexer    = CosmosElement.CreateFromBuffer(jsonWriterIndexer.GetResult());
            CosmosElement cosmosElementFromEnumerable = CosmosElement.CreateFromBuffer(jsonWriterEnumerable.GetResult());

            Assert.AreEqual(cosmosElement, cosmosElementFromIndexer);
            Assert.AreEqual(cosmosElement, cosmosElementFromEnumerable);
        }
        private static void TestCosmosElementVisitability(string filename)
        {
            ReadOnlyMemory <byte> payload = LazyCosmosElementTests.GetPayload(filename);

            CosmosElement cosmosElement = CosmosElement.CreateFromBuffer(payload);

            IJsonWriter jsonWriterIndexer    = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Binary);
            IJsonWriter jsonWriterEnumerable = Microsoft.Azure.Cosmos.Json.JsonWriter.Create(JsonSerializationFormat.Binary);

            LazyCosmosElementTests.VisitCosmosElementIndexer(cosmosElement, jsonWriterIndexer);
            LazyCosmosElementTests.VisitCosmosElementEnumerable(cosmosElement, jsonWriterEnumerable);

            ReadOnlySpan <byte> payloadIndexer    = jsonWriterIndexer.GetResult().Span;
            ReadOnlySpan <byte> payloadEnumerable = jsonWriterEnumerable.GetResult().Span;

            Assert.IsTrue(payload.Span.SequenceEqual(payloadIndexer));
            Assert.IsTrue(payload.Span.SequenceEqual(payloadEnumerable));
        }
        public void TestCaching()
        {
            CosmosArray lazilyDeserializedPeople = CosmosElement.CreateFromBuffer(LazyCosmosElementTests.bufferedSerializedPeople) as CosmosArray;

            Assert.IsTrue(
                object.ReferenceEquals(lazilyDeserializedPeople[0], lazilyDeserializedPeople[0]),
                "Array did not return the item from the cache.");

            CosmosObject lazilyDeserializedPerson = lazilyDeserializedPeople[0] as CosmosObject;

            Assert.IsTrue(
                object.ReferenceEquals(lazilyDeserializedPerson[nameof(Person.Age)], lazilyDeserializedPerson[nameof(Person.Age)]),
                "Object did not return the property from the cache.");

            CosmosString personName = lazilyDeserializedPerson[nameof(Person.Name)] as CosmosString;

            Assert.IsTrue(
                object.ReferenceEquals(personName.Value, personName.Value),
                "Did not return the string from the cache.");

            // Numbers is a value type so we don't need to test for the cache.
            // Booleans are multitons so we don't need to test for the cache.
            // Nulls are singletons so we don't need to test for the cache.
        }
Esempio n. 10
0
            public static TryCatch <DistinctMap> TryCreate(string continuationToken)
            {
                HashSet <Number64> numbers             = new HashSet <Number64>();
                HashSet <uint>     stringsLength4      = new HashSet <uint>();
                HashSet <ulong>    stringsLength8      = new HashSet <ulong>();
                HashSet <UInt128>  stringsLength16     = new HashSet <UInt128>();
                HashSet <UInt128>  stringsLength16Plus = new HashSet <UInt128>();
                HashSet <UInt128>  arrays       = new HashSet <UInt128>();
                HashSet <UInt128>  objects      = new HashSet <UInt128>();
                SimpleValues       simpleValues = SimpleValues.None;

                if (continuationToken != null)
                {
                    byte[]        binaryBuffer  = Convert.FromBase64String(continuationToken);
                    CosmosElement cosmosElement = CosmosElement.CreateFromBuffer(binaryBuffer);
                    if (!(cosmosElement is CosmosObject hashDictionary))
                    {
                        return(TryCatch <DistinctMap> .FromException(
                                   new MalformedContinuationTokenException(
                                       $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                    }

                    // Numbers
                    if (!hashDictionary.TryGetValue(UnorderdDistinctMap.NumbersName, out CosmosArray numbersArray))
                    {
                        return(TryCatch <DistinctMap> .FromException(
                                   new MalformedContinuationTokenException(
                                       $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                    }

                    foreach (CosmosElement rawNumber in numbersArray)
                    {
                        if (!(rawNumber is CosmosNumber64 number))
                        {
                            return(TryCatch <DistinctMap> .FromException(
                                       new MalformedContinuationTokenException(
                                           $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                        }

                        numbers.Add(number.GetValue());
                    }

                    // Strings Length 4
                    if (!hashDictionary.TryGetValue(UnorderdDistinctMap.StringsLength4Name, out CosmosArray stringsLength4Array))
                    {
                        return(TryCatch <DistinctMap> .FromException(
                                   new MalformedContinuationTokenException(
                                       $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                    }

                    foreach (CosmosElement rawStringLength4 in stringsLength4Array)
                    {
                        if (!(rawStringLength4 is CosmosUInt32 stringlength4))
                        {
                            return(TryCatch <DistinctMap> .FromException(
                                       new MalformedContinuationTokenException(
                                           $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                        }

                        stringsLength4.Add(stringlength4.GetValue());
                    }

                    // Strings Length 8
                    if (!hashDictionary.TryGetValue(UnorderdDistinctMap.StringsLength8Name, out CosmosArray stringsLength8Array))
                    {
                        return(TryCatch <DistinctMap> .FromException(
                                   new MalformedContinuationTokenException(
                                       $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                    }

                    foreach (CosmosElement rawStringLength8 in stringsLength8Array)
                    {
                        if (!(rawStringLength8 is CosmosInt64 stringlength8))
                        {
                            return(TryCatch <DistinctMap> .FromException(
                                       new MalformedContinuationTokenException(
                                           $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                        }

                        stringsLength8.Add((ulong)stringlength8.GetValue());
                    }

                    // Strings Length 16
                    stringsLength16 = Parse128BitHashes(hashDictionary, UnorderdDistinctMap.StringsLength16Name);

                    // Strings Length 24
                    stringsLength16Plus = Parse128BitHashes(hashDictionary, UnorderdDistinctMap.StringsLength16PlusName);

                    // Array
                    arrays = Parse128BitHashes(hashDictionary, UnorderdDistinctMap.ArraysName);

                    // Object
                    objects = Parse128BitHashes(hashDictionary, UnorderdDistinctMap.ObjectName);

                    // Simple Values
                    CosmosElement rawSimpleValues = hashDictionary[UnorderdDistinctMap.SimpleValuesName];
                    if (!(rawSimpleValues is CosmosString simpleValuesString))
                    {
                        return(TryCatch <DistinctMap> .FromException(
                                   new MalformedContinuationTokenException(
                                       $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                    }

                    if (!Enum.TryParse <SimpleValues>(simpleValuesString.Value, out simpleValues))
                    {
                        return(TryCatch <DistinctMap> .FromException(
                                   new MalformedContinuationTokenException(
                                       $"{nameof(UnorderdDistinctMap)} continuation token was malformed.")));
                    }
                }

                return(TryCatch <DistinctMap> .FromResult(new UnorderdDistinctMap(
                                                              numbers,
                                                              stringsLength4,
                                                              stringsLength8,
                                                              stringsLength16,
                                                              stringsLength16Plus,
                                                              arrays,
                                                              objects,
                                                              simpleValues)));
            }
Esempio n. 11
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,
                responseHeaders: CosmosQueryResponseMessageHeaders.ConvertToQueryHeaders(
                    sourceHeaders: null,
                    resourceType: ResourceType.Document,
                    containerRid: GremlinScenarioTests.CreateRandomString(10)),
                diagnostics: null);
            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]);
        }
Esempio n. 12
0
        internal void DeserializeModifyAndSerializeVertexDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName            = "id";
            const string idValue           = "v_0";
            const string pkValue           = "pk_0";
            const string labelName         = "label";
            const string labelValue        = "l_0";
            const string property1Name     = "p_0";
            const string property1Value1Id = "3648bdcc-5113-43f8-86dd-c19fe793a2f8";
            const string property1Value1   = "p_0_v_0";
            const string property1Value2Id = "7546f541-a003-4e69-a25c-608372ed1321";
            const long   property1Value2   = 1234;
            const string property2Name     = "p_1";
            const string property2Value1Id = "b119c62a-82a2-48b2-b293-9963fa99fbe2";
            const double property2Value1   = 34.56;
            const string property3Name     = "p_2";
            const string property3Value1Id = "98d27280-70ee-4edd-8461-7633a328539a";
            const bool   property3Value1   = true;
            const string property4Name     = "p_3";
            const string property4Value1Id = "f9bfcc22-221a-4c92-b5b9-be53cdedb092";
            const string property4Value1   = "p_3_v_0";

            // Compose the initial vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> initialVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value1Id), CosmosString.Create(property1Value1)),
                    }
                        )
                },
                {
                    property2Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property2Value1Id), CosmosNumber64.Create(property2Value1)),
                    }
                        )
                },
                {
                    property3Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property3Value1Id), CosmosBoolean.Create(property3Value1)),
                    }
                        )
                },
            };

            CosmosObject initialVertexEagerObject = CosmosObject.Create(initialVertexDocumentProperties);

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

            initialVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> initialJsonWriterResult = jsonWriter.GetResult();

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

            // Navigate into the serialized vertex document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(initialJsonWriterResult);

            // Root vertex document object
            CosmosObject vertexLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(vertexLazyObject, $"Vertex document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(initialVertexDocumentProperties.Count, vertexLazyObject.Count);

            CosmosString idLazyString    = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, idName);
            CosmosString pkLazyString    = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);
            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, labelName);
            CosmosArray  property2Array  = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, property2Name);

            // Compose a new vertex document using a combination of lazy and eager CosmosElements
            Dictionary <string, CosmosElement> modifiedVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, idLazyString },
                { GremlinScenarioTests.PartitionKeyPropertyName, pkLazyString },
                { labelName, labelLazyString },

                // Property 1 is modified with a new value
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value2Id), CosmosNumber64.Create(property1Value2)),
                    }
                        )
                },

                // Property 2 is unmodified
                { property2Name, property2Array },

                // Property 3 is deleted

                // Property 4 is newly added
                {
                    property4Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property4Value1Id), CosmosString.Create(property4Value1)),
                    }
                        )
                },
            };

            CosmosObject modifiedVertexEagerObject = CosmosObject.Create(modifiedVertexDocumentProperties);

            // Serialize the modified vertex object into a document using the specified serialization format
            jsonWriter = JsonWriter.Create(jsonSerializationFormat);
            modifiedVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> modifiedJsonWriterResult = jsonWriter.GetResult();

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

            // Compose an expected vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> expectedVertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    property1Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property1Value2Id), CosmosNumber64.Create(property1Value2)),
                    }
                        )
                },
                {
                    property2Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property2Value1Id), CosmosNumber64.Create(property2Value1)),
                    }
                        )
                },
                {
                    property4Name,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(property4Value1Id), CosmosString.Create(property4Value1)),
                    }
                        )
                },
            };

            CosmosObject expectedVertexEagerObject = CosmosObject.Create(expectedVertexDocumentProperties);

            // Serialize the initial vertex object into a document using the specified serialization format
            jsonWriter = JsonWriter.Create(jsonSerializationFormat);
            expectedVertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> expectedJsonWriterResult = jsonWriter.GetResult();

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

            // Verify that the modified serialized document matches the expected serialized document
            Assert.IsTrue(modifiedJsonWriterResult.Span.SequenceEqual(expectedJsonWriterResult.Span));
        }
Esempio n. 13
0
        internal void SerializeAndDeserializeVertexDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName             = "id";
            const string idValue            = "v_0";
            const string pkValue            = "pk_0";
            const string labelName          = "label";
            const string labelValue         = "l_0";
            const string boolName           = "myBool";
            const string boolId             = "3648bdcc-5113-43f8-86dd-c19fe793a2f8";
            const bool   boolValue          = true;
            const string intName            = "myInteger";
            const string intId              = "7546f541-a003-4e69-a25c-608372ed1321";
            const int    intValue           = 12345;
            const string longId             = "b119c62a-82a2-48b2-b293-9963fa99fbe2";
            const long   longValue          = 67890L;
            const string floatName          = "myFloatingPoint";
            const string floatId            = "98d27280-70ee-4edd-8461-7633a328539a";
            const float  floatValue         = 123.4f;
            const string doubleId           = "f9bfcc22-221a-4c92-b5b9-be53cdedb092";
            const double doubleValue        = 56.78;
            const string stringName         = "myString";
            const string stringId           = "6bb8ae5b-19ca-450e-b369-922a34c02729";
            const string stringValue        = "str_0";
            const string metaProperty0Name  = "myMetaProperty0";
            const string metaProperty0Value = "m_0";
            const string metaProperty1Name  = "myMetaProperty1";
            const int    metaProperty1Value = 123;

            // Compose the vertex document using eager CosmosElements
            Dictionary <string, CosmosElement> vertexDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                {
                    boolName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(boolId), CosmosBoolean.Create(boolValue)),
                    }
                        )
                },
                {
                    intName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(intId), CosmosNumber64.Create(intValue)),
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(longId), CosmosNumber64.Create(longValue)),
                    }
                        )
                },
                {
                    floatName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(floatId), CosmosNumber64.Create(floatValue)),
                        this.CreateVertexPropertySingleComplexValue(CosmosString.Create(doubleId), CosmosNumber64.Create(doubleValue)),
                    }
                        )
                },
                {
                    stringName,
                    CosmosArray.Create(
                        new CosmosElement[]
                    {
                        this.CreateVertexPropertySingleComplexValue(
                            CosmosString.Create(stringId),
                            CosmosString.Create(stringValue),
                            Tuple.Create <string, CosmosElement>(metaProperty0Name, CosmosString.Create(metaProperty0Value)),
                            Tuple.Create <string, CosmosElement>(metaProperty1Name, CosmosNumber64.Create(metaProperty1Value))),
                    }
                        )
                },
            };

            CosmosObject vertexEagerObject = CosmosObject.Create(vertexDocumentProperties);

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

            vertexEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> jsonResult = jsonWriter.GetResult();

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

            // Navigate into the serialized vertex document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(jsonResult);

            // Validate the expected vertex document structure/values

            // Root vertex document object
            CosmosObject vertexLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(vertexLazyObject, $"Vertex document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(vertexDocumentProperties.Count, vertexLazyObject.Count);

            // Vertex system document properties
            CosmosString idLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, idName);

            Assert.AreEqual(idValue, idLazyString.Value);

            CosmosString pkLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);

            Assert.AreEqual(pkValue, pkLazyString.Value);

            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(vertexLazyObject, labelName);

            Assert.AreEqual(labelValue, labelLazyString.Value);

            // Vertex user properties
            CosmosArray boolLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, boolName);

            Assert.AreEqual(1, boolLazyArray.Count);

            // Bool value(s)
            CosmosObject boolValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(boolLazyArray, 0);
            CosmosString boolValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(boolValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(boolId, boolValue0IdLazyString.Value);
            CosmosBoolean boolValue0ValueLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(boolValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(boolValue, boolValue0ValueLazyBool.Value);

            CosmosArray intLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, intName);

            Assert.AreEqual(2, intLazyArray.Count);

            // Integer value(s)
            CosmosObject intValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(intLazyArray, 0);
            CosmosString intValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(intValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(intId, intValue0IdLazyString.Value);
            CosmosNumber intValue0ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(intValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(CosmosNumberType.Number64, intValue0ValueLazyNumber.NumberType);
            Assert.IsTrue(intValue0ValueLazyNumber.IsInteger);
            Assert.AreEqual((long)intValue, intValue0ValueLazyNumber.AsInteger().Value);

            CosmosObject intValue1LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(intLazyArray, 1);
            CosmosString intValue1IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(intValue1LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(longId, intValue1IdLazyString.Value);
            CosmosNumber intValue1ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(intValue1LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(CosmosNumberType.Number64, intValue1ValueLazyNumber.NumberType);
            Assert.IsTrue(intValue1ValueLazyNumber.IsInteger);
            Assert.AreEqual(longValue, intValue1ValueLazyNumber.AsInteger().Value);

            // Floating point value(s)
            CosmosArray floatLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, floatName);

            Assert.AreEqual(2, floatLazyArray.Count);

            CosmosObject floatValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(floatLazyArray, 0);
            CosmosString floatValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(floatValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(floatId, floatValue0IdLazyString.Value);
            CosmosNumber floatValue0ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(floatValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(CosmosNumberType.Number64, floatValue0ValueLazyNumber.NumberType);
            Assert.IsTrue(floatValue0ValueLazyNumber.IsFloatingPoint);
            Assert.AreEqual((double)floatValue, floatValue0ValueLazyNumber.AsFloatingPoint().Value);

            CosmosObject floatValue1LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(floatLazyArray, 1);
            CosmosString floatValue1IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(floatValue1LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(doubleId, floatValue1IdLazyString.Value);
            CosmosNumber floatValue1ValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(floatValue1LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(CosmosNumberType.Number64, floatValue1ValueLazyNumber.NumberType);
            Assert.IsTrue(floatValue1ValueLazyNumber.IsFloatingPoint);
            Assert.AreEqual(doubleValue, floatValue1ValueLazyNumber.AsFloatingPoint().Value);

            // String value(s)
            CosmosArray stringLazyArray = this.GetAndAssertObjectProperty <CosmosArray>(vertexLazyObject, stringName);

            Assert.AreEqual(1, stringLazyArray.Count);

            CosmosObject stringValue0LazyObject   = this.GetAndAssertArrayValue <CosmosObject>(stringLazyArray, 0);
            CosmosString stringValue0IdLazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_ID);

            Assert.AreEqual(stringId, stringValue0IdLazyString.Value);
            CosmosString stringValue0ValueLazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_VALUE);

            Assert.AreEqual(stringValue, stringValue0ValueLazyString.Value);

            // String value meta-properties
            CosmosObject stringValue0MetaLazyObject = this.GetAndAssertObjectProperty <CosmosObject>(stringValue0LazyObject, GremlinKeywords.KW_PROPERTY_META);

            Assert.AreEqual(2, stringValue0MetaLazyObject.Count);

            CosmosString stringValue0MetaValue0LazyString = this.GetAndAssertObjectProperty <CosmosString>(stringValue0MetaLazyObject, metaProperty0Name);

            Assert.AreEqual(metaProperty0Value, stringValue0MetaValue0LazyString.Value);

            CosmosNumber stringValue0MetaValue1LazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(stringValue0MetaLazyObject, metaProperty1Name);

            Assert.AreEqual(CosmosNumberType.Number64, stringValue0MetaValue1LazyNumber.NumberType);
            Assert.IsTrue(stringValue0MetaValue1LazyNumber.IsInteger);
            Assert.AreEqual((long)metaProperty1Value, stringValue0MetaValue1LazyNumber.AsInteger().Value);
        }
        public void TestCaching()
        {
            CosmosArray lazilyDeserializedPeople = CosmosElement.CreateFromBuffer <CosmosArray>(LazyCosmosElementTests.bufferedSerializedPeople);

            Assert.IsTrue(
                object.ReferenceEquals(lazilyDeserializedPeople[0], lazilyDeserializedPeople[0]),
                "Array did not return the item from the cache.");

            CosmosObject lazilyDeserializedPerson = lazilyDeserializedPeople[0] as CosmosObject;

            foreach (string key in lazilyDeserializedPerson.Keys)
            {
                Assert.IsTrue(
                    object.ReferenceEquals(lazilyDeserializedPerson[key], lazilyDeserializedPerson[key]),
                    "Object property was not served from the cache");
            }

            foreach ((string key1, string key2) in lazilyDeserializedPerson.Keys.Zip(lazilyDeserializedPerson.Keys, (first, second) => (first, second)))
            {
                Assert.IsTrue(
                    object.ReferenceEquals(key1, key2),
                    "Object keys are not served from the cache.");
            }

            foreach ((CosmosElement value1, CosmosElement value2) in lazilyDeserializedPerson.Values.Zip(lazilyDeserializedPerson.Values, (first, second) => (first, second)))
            {
                Assert.IsTrue(
                    object.ReferenceEquals(value1, value2),
                    "Object values are not served from the cache.");
            }

            int countFromCount      = lazilyDeserializedPerson.Count;
            int countFromEnumerator = 0;

            foreach (KeyValuePair <string, CosmosElement> kvp in lazilyDeserializedPerson)
            {
                countFromEnumerator++;
            }

            Assert.AreEqual(countFromCount, countFromEnumerator);

            CosmosString personName = lazilyDeserializedPerson[nameof(Person.Name)] as CosmosString;

            Assert.IsTrue(
                object.ReferenceEquals(personName.Value, personName.Value),
                "Did not return the string from the cache.");

            int i = 0;

            foreach (CosmosElement arrayItem in lazilyDeserializedPeople)
            {
                Assert.IsTrue(
                    object.ReferenceEquals(arrayItem, lazilyDeserializedPeople[i++]));
            }

            Assert.AreEqual(i, lazilyDeserializedPeople.Count);

            int count = lazilyDeserializedPeople.Count;

            for (i = 0; i < count; i++)
            {
                Assert.IsTrue(
                    object.ReferenceEquals(lazilyDeserializedPeople[i], lazilyDeserializedPeople[i]));
            }

            // Numbers is a value type so we don't need to test for the cache.
            // Booleans are multitons so we don't need to test for the cache.
            // Nulls are singletons so we don't need to test for the cache.
        }
Esempio n. 15
0
 public void TestNull()
 {
     ReadOnlyMemory <byte> result     = JsonSerializer.Serialize((object)null);
     CosmosNull            cosmosNull = (CosmosNull)CosmosElement.CreateFromBuffer(result);
 }
Esempio n. 16
0
        internal void SerializeAndDeserializeEdgeDocumentTest(JsonSerializationFormat jsonSerializationFormat)
        {
            // Constants to use for vertex document property key/values
            const string idName                = "id";
            const string idValue               = "e_0";
            const string pkValue               = "pk_0";
            const string labelName             = "label";
            const string labelValue            = "l_0";
            const string vertexIdValue         = "v_0";
            const string vertexLabelValue      = "l_1";
            const string sinkIdValue           = "v_1";
            const string sinkLabelValue        = "l_2";
            const string sinkPartitionValue    = "pk_1";
            const bool   isEdgeValue           = true;
            const bool   isPkEdgePropertyValue = true;
            const string boolName              = "myBool";
            const bool   boolValue             = true;
            const string intName               = "myInteger";
            const int    intValue              = 12345;
            const string longName              = "myLong";
            const long   longValue             = 67890L;
            const string floatName             = "myFloatingPoint";
            const float  floatValue            = 123.4f;
            const string doubleName            = "myDouble";
            const double doubleValue           = 56.78;
            const string stringName            = "myString";
            const string stringValue           = "str_0";

            Dictionary <string, CosmosElement> edgeDocumentProperties = new Dictionary <string, CosmosElement>()
            {
                { idName, CosmosString.Create(idValue) },
                { GremlinScenarioTests.PartitionKeyPropertyName, CosmosString.Create(pkValue) },
                { labelName, CosmosString.Create(labelValue) },
                { GremlinKeywords.KW_EDGEDOC_VERTEXID, CosmosString.Create(vertexIdValue) },
                { GremlinKeywords.KW_EDGEDOC_VERTEXLABEL, CosmosString.Create(vertexLabelValue) },
                { GremlinKeywords.KW_EDGE_SINKV, CosmosString.Create(sinkIdValue) },
                { GremlinKeywords.KW_EDGE_SINKV_LABEL, CosmosString.Create(sinkLabelValue) },
                { GremlinKeywords.KW_EDGE_SINKV_PARTITION, CosmosString.Create(sinkPartitionValue) },
                { GremlinKeywords.KW_EDGEDOC_IDENTIFIER, CosmosBoolean.Create(isEdgeValue) },
                { GremlinKeywords.KW_EDGEDOC_ISPKPROPERTY, CosmosBoolean.Create(isPkEdgePropertyValue) },
                { boolName, CosmosBoolean.Create(boolValue) },
                { intName, CosmosNumber64.Create(intValue) },
                { longName, CosmosNumber64.Create(longValue) },
                { floatName, CosmosNumber64.Create(floatValue) },
                { doubleName, CosmosNumber64.Create(doubleValue) },
                { stringName, CosmosString.Create(stringValue) },
            };

            CosmosObject edgeEagerObject = CosmosObject.Create(edgeDocumentProperties);

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

            edgeEagerObject.WriteTo(jsonWriter);
            ReadOnlyMemory <byte> jsonResult = jsonWriter.GetResult();

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

            // Navigate into the serialized edge document using lazy CosmosElements
            CosmosElement rootLazyElement = CosmosElement.CreateFromBuffer(jsonResult);

            // Validate the expected edge document structure/values

            // Root edge document object
            CosmosObject edgeLazyObject = rootLazyElement as CosmosObject;

            Assert.IsNotNull(edgeLazyObject, $"Edge document root is not {nameof(CosmosObject)}.");
            Assert.AreEqual(edgeDocumentProperties.Count, edgeLazyObject.Count);

            // Edge system document properties
            CosmosString idLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, idName);

            Assert.AreEqual(idValue, idLazyString.Value);

            CosmosString pkLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinScenarioTests.PartitionKeyPropertyName);

            Assert.AreEqual(pkValue, pkLazyString.Value);

            CosmosString labelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, labelName);

            Assert.AreEqual(labelValue, labelLazyString.Value);

            CosmosString vertexIdLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_VERTEXID);

            Assert.AreEqual(vertexIdValue, vertexIdLazyString.Value);

            CosmosString vertexLabelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_VERTEXLABEL);

            Assert.AreEqual(vertexLabelValue, vertexLabelLazyString.Value);

            CosmosString sinkIdLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV);

            Assert.AreEqual(sinkIdValue, sinkIdLazyString.Value);

            CosmosString sinkLabelLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV_LABEL);

            Assert.AreEqual(sinkLabelValue, sinkLabelLazyString.Value);

            CosmosString sinkPartitionLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, GremlinKeywords.KW_EDGE_SINKV_PARTITION);

            Assert.AreEqual(sinkPartitionValue, sinkPartitionLazyString.Value);

            CosmosBoolean isEdgeLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_IDENTIFIER);

            Assert.AreEqual(isEdgeValue, isEdgeLazyBool.Value);

            CosmosBoolean isPkEdgePropertyLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, GremlinKeywords.KW_EDGEDOC_ISPKPROPERTY);

            Assert.AreEqual(isPkEdgePropertyValue, isPkEdgePropertyLazyBool.Value);

            // Edge user properties

            CosmosBoolean boolValueLazyBool = this.GetAndAssertObjectProperty <CosmosBoolean>(edgeLazyObject, boolName);

            Assert.AreEqual(boolValue, boolValueLazyBool.Value);

            CosmosNumber intValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, intName);

            Assert.AreEqual(CosmosNumberType.Number64, intValueLazyNumber.NumberType);
            Assert.IsTrue(intValueLazyNumber.IsInteger);
            Assert.AreEqual((long)intValue, intValueLazyNumber.AsInteger().Value);

            CosmosNumber longValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, longName);

            Assert.AreEqual(CosmosNumberType.Number64, intValueLazyNumber.NumberType);
            Assert.IsTrue(intValueLazyNumber.IsInteger);
            Assert.AreEqual(longValue, longValueLazyNumber.AsInteger().Value);

            CosmosNumber floatValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, floatName);

            Assert.AreEqual(CosmosNumberType.Number64, floatValueLazyNumber.NumberType);
            Assert.IsTrue(floatValueLazyNumber.IsFloatingPoint);
            Assert.AreEqual((double)floatValue, floatValueLazyNumber.AsFloatingPoint().Value);

            CosmosNumber doubleValueLazyNumber = this.GetAndAssertObjectProperty <CosmosNumber>(edgeLazyObject, doubleName);

            Assert.AreEqual(CosmosNumberType.Number64, doubleValueLazyNumber.NumberType);
            Assert.IsTrue(doubleValueLazyNumber.IsFloatingPoint);
            Assert.AreEqual((double)doubleValue, doubleValueLazyNumber.AsFloatingPoint().Value);

            CosmosString stringValueLazyString = this.GetAndAssertObjectProperty <CosmosString>(edgeLazyObject, stringName);

            Assert.AreEqual(stringValue, stringValueLazyString.Value);
        }
Esempio n. 17
0
        public async Task TestCosmosOrderByQueryExecutionContextWithEmptyPagesAndSplitAsync(bool createInitialContinuationToken)
        {
            int maxPageSize = 5;

            List <MockPartitionResponse[]> mockResponsesScenario = MockQueryFactory.GetSplitScenarios();

            Mock <CosmosQueryClient> mockQueryClient = new Mock <CosmosQueryClient>();

            foreach (MockPartitionResponse[] mockResponse in mockResponsesScenario)
            {
                string initialContinuationToken = null;
                string fullContinuationToken    = null;
                if (createInitialContinuationToken)
                {
                    ToDoItem itemToRepresentPreviousQuery = ToDoItem.CreateItems(
                        1,
                        "itemToRepresentPreviousQuery",
                        MockQueryFactory.DefaultCollectionRid).First();

                    initialContinuationToken = $" - RID:{itemToRepresentPreviousQuery._rid} ==#RT:1#TRC:1";
                    CompositeContinuationToken compositeContinuation = new CompositeContinuationToken()
                    {
                        Range = new Documents.Routing.Range <string>(
                            min: MockQueryFactory.DefaultPartitionKeyRange.MinInclusive,
                            max: MockQueryFactory.DefaultPartitionKeyRange.MaxExclusive,
                            isMaxInclusive: false,
                            isMinInclusive: true),
                        Token = initialContinuationToken
                    };

                    List <OrderByItem> orderByItems = new List <OrderByItem>()
                    {
                        new OrderByItem(CosmosElement.CreateFromBuffer(Encoding.UTF8.GetBytes("{\"item\":\"2c4ce711-13c3-4c93-817c-49287b71b6c3\"}")))
                    };

                    OrderByContinuationToken orderByContinuationToken = new OrderByContinuationToken(
                        compositeContinuationToken: compositeContinuation,
                        orderByItems: orderByItems,
                        rid: itemToRepresentPreviousQuery._rid,
                        skipCount: 0,
                        filter: null);

                    fullContinuationToken = CosmosArray.Create(
                        new List <CosmosElement>()
                    {
                        OrderByContinuationToken.ToCosmosElement(orderByContinuationToken)
                    }).ToString();
                }


                IList <ToDoItem> allItems = MockQueryFactory.GenerateAndMockResponse(
                    mockQueryClient,
                    isOrderByQuery: true,
                    sqlQuerySpec: MockQueryFactory.DefaultQuerySpec,
                    containerRid: MockQueryFactory.DefaultCollectionRid,
                    initContinuationToken: initialContinuationToken,
                    maxPageSize: maxPageSize,
                    mockResponseForSinglePartition: mockResponse,
                    cancellationTokenForMocks: this.cancellationToken);

                // Order by drains the partitions until it finds an item
                // If there are no items then it's not possible to have a continuation token
                if (allItems.Count == 0 && createInitialContinuationToken)
                {
                    continue;
                }

                CosmosQueryContext context = MockQueryFactory.CreateContext(
                    mockQueryClient.Object);

                QueryInfo queryInfo = new QueryInfo()
                {
                    OrderBy            = new SortOrder[] { SortOrder.Ascending },
                    OrderByExpressions = new string[] { "id" }
                };

                CosmosCrossPartitionQueryExecutionContext.CrossPartitionInitParams initParams = new CosmosCrossPartitionQueryExecutionContext.CrossPartitionInitParams(
                    sqlQuerySpec: MockQueryFactory.DefaultQuerySpec,
                    collectionRid: MockQueryFactory.DefaultCollectionRid,
                    partitionedQueryExecutionInfo: new PartitionedQueryExecutionInfo()
                {
                    QueryInfo = queryInfo
                },
                    partitionKeyRanges: new List <PartitionKeyRange>()
                {
                    MockQueryFactory.DefaultPartitionKeyRange
                },
                    initialPageSize: maxPageSize,
                    maxConcurrency: null,
                    maxItemCount: maxPageSize,
                    maxBufferedItemCount: null,
                    returnResultsInDeterministicOrder: true,
                    testSettings: new TestInjections(simulate429s: false, simulateEmptyPages: false));

                IDocumentQueryExecutionComponent executionContext = (await CosmosOrderByItemQueryExecutionContext.TryCreateAsync(
                                                                         context,
                                                                         initParams,
                                                                         fullContinuationToken != null ? CosmosElement.Parse(fullContinuationToken) : null,
                                                                         this.cancellationToken)).Result;

                // For order by it will drain all the pages till it gets a value.
                if (allItems.Count == 0)
                {
                    Assert.IsTrue(executionContext.IsDone);
                    continue;
                }

                Assert.IsTrue(!executionContext.IsDone);

                // Read all the pages from both splits
                List <ToDoItem> itemsRead = new List <ToDoItem>();
                while (!executionContext.IsDone)
                {
                    QueryResponseCore queryResponse = await executionContext.DrainAsync(
                        maxPageSize,
                        this.cancellationToken);

                    string responseContinuationToken = queryResponse.ContinuationToken;
                    foreach (CosmosElement element in queryResponse.CosmosElements)
                    {
                        string   jsonValue = element.ToString();
                        ToDoItem item      = JsonConvert.DeserializeObject <ToDoItem>(jsonValue);
                        itemsRead.Add(item);
                    }
                }

                Assert.AreEqual(allItems.Count, itemsRead.Count);

                CollectionAssert.AreEqual(allItems.ToList(), itemsRead, new ToDoItemComparer());
            }
        }