Esempio n. 1
0
        public void ParameterReaderReadComplexParameterWithPrimitiveValueShouldThrow()
        {
            IEdmModel           model = TestModels.BuildModelWithFunctionImport();
            IEdmOperationImport functionImport_Complex = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Complex").First();

            var testConfigurations = this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(c => c.IsRequest);

            this.CombinatorialEngineProvider.RunCombinations(
                testConfigurations,
                (testConfiguration) =>
            {
                this.Assert.ExpectedException(
                    () =>
                {
                    ODataParameterReaderTestWrapper reader = CreateODataParameterReader(model, functionImport_Complex, testConfiguration, "{\"complex\":1}");
                    while (reader.Read())
                    {
                        if (reader.State == ODataParameterReaderState.Resource)
                        {
                            var complexReader = reader.CreateResourceReader();
                            while (complexReader.Read())
                            {
                                ;
                            }
                        }
                    }
                },
                    ODataExpectedExceptions.ODataException("ODataJsonLightReader_UnexpectedPrimitiveValueForODataResource"),
                    this.ExceptionVerifier);
            });
        }
        public void StreamPropertyTestWithRelativeLinkUris()
        {
            IEdmModel model = TestModels.BuildTestModel();

            var testCases = new[]
            {
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid edit link - non-URL",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"xxx yyy zzz\"",
                    ExpectedException = null,
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid read link - non-URL",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"xxx yyy zzz\"",
                    ExpectedException = null,
                    OnlyResponse      = true,
                },
            };

            this.RunStreamPropertyTest(model, testCases);
        }
Esempio n. 3
0
        public void ParameterReaderIgnoreMissingMultipleNullableParameterTest()
        {
            IEdmModel           model          = TestModels.BuildModelWithFunctionImport();
            IEdmOperationImport functionImport = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_MultipleNullableParameters").Single();

            var parameterValues = new[]
            {
                "\"p1\" : \"AAEC\"",
                "\"p2\" : true",
                "\"p3\" : 1",
                "\"p5\" : \"2012-05-25T09:00:42.5018138-07:00\"",
                "\"p6\" : 79228162514264337593543950335",
                "\"p7\" : \"INF\"",
                "\"p8\" : \"446806b7-7d7f-4e60-9e2b-bc28d9671a4f\"",
                "\"p9\" : \"32767\"",
                "\"p10\" : 2147483647",
                "\"p11\" : 0",
                "\"p12\" : \"1\"",
                "\"p13\" : \"0.01\"",
                "\"p14\" : { type: \"Point\", coordinates: [ -122.107711791992, 47.6472206115723 ], crs: { type: \"name\", properties: { name: \"EPSG:4326\" } } }",
                "\"p15\" : \"foo\"",
                "\"p16\" : { @odata.type: \"#TestModel.ComplexTypeWithNullableProperties\", IntegerProperty: 1 }",
                "\"p17\" : \"enumType1_value2\"", // supports reading enum values without validation
            };

            var multipleParameterTestCases = parameterValues.Combinations(false, new[] { 1, 2, 16 }).ToArray();

            this.CombinatorialEngineProvider.RunCombinations(
                multipleParameterTestCases,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(c => c.IsRequest == true),
                (testCase, testConfiguration) =>
            {
                string payload = "{" + string.Join(",", testCase) + "}";

                var reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, payload);
                foreach (var parameter in testCase)
                {
                    this.Assert.IsTrue(reader.Read(), "Read() should not fail for payload " + payload);
                    if (parameter.Contains("p16"))
                    {
                        var complexReader = reader.CreateResourceReader();
                        while (complexReader.Read())
                        {
                            ;
                        }
                        this.Assert.AreEqual(ODataParameterReaderState.Resource, reader.State, "State should be Value.");
                    }
                    else
                    {
                        this.Assert.AreEqual(ODataParameterReaderState.Value, reader.State, "State should be Value.");
                    }
                }

                this.Assert.IsFalse(reader.Read(), "Read() should fail after reading all parameters");
                this.Assert.AreEqual(ODataParameterReaderState.Completed, reader.State, "State should be Complete.");
            });
        }
        public void ConvertToUriLiteralNullTest()
        {
            List <ConvertToUriLiteralTestCase> testCases = new List <ConvertToUriLiteralTestCase>();
            IEdmModel edmModel = TestModels.BuildTestModel();

            testCases.Add(
                new ConvertToUriLiteralTestCase()
            {
                Parameter     = null,
                Model         = edmModel,
                ExpectedValue = "null",
            });


            this.RunTestCases(testCases);
        }
Esempio n. 5
0
        public void ParameterReaderAdditionalNullValueTest()
        {
            IEdmModel           model = TestModels.BuildModelWithFunctionImport();
            IEdmOperationImport functionImport_Complex             = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Complex").First();
            IEdmOperationImport functionImport_PrimitiveCollection = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_PrimitiveCollection").First();
            IEdmOperationImport functionImport_ComplexCollection   = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_ComplexCollection").First();

            var testConfigurations = this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(c => c.IsRequest);

            this.CombinatorialEngineProvider.RunCombinations(
                testConfigurations,
                (testConfiguration) =>
            {
                ODataParameterReader reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_PrimitiveCollection, testConfiguration, "{\"primitiveCollection\":null}");
                reader.Read();
                this.Assert.AreEqual("primitiveCollection", reader.Name, "Unexpected first parameter name.");
                this.Assert.IsNull(reader.Value, "Unexpected first parameter value.");
                this.Assert.AreEqual(ODataParameterReaderState.Value, reader.State, "Unexpected first parameter state.");

                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_PrimitiveCollection, testConfiguration, "{\"primitiveCollection\":123}");
                this.Assert.ExpectedException(
                    () => reader.Read(),
                    ODataExpectedExceptions.ODataException("ODataJsonLightParameterDeserializer_NullCollectionExpected", "PrimitiveValue", "123"),
                    this.ExceptionVerifier);
                this.Assert.AreEqual(ODataParameterReaderState.Exception, reader.State, "Unexpected first parameter state.");

                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_ComplexCollection, testConfiguration, "{\"complexCollection\":null}");
                reader.Read();
                this.Assert.AreEqual("complexCollection", reader.Name, "Unexpected first parameter name.");
                this.Assert.IsNull(reader.Value, "Unexpected first parameter value.");
                this.Assert.AreEqual(ODataParameterReaderState.Value, reader.State, "Unexpected first parameter state.");

                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_ComplexCollection, testConfiguration, "{\"complexCollection\":123}");
                this.Assert.ExpectedException(
                    () => reader.Read(),
                    ODataExpectedExceptions.ODataException("ODataJsonLightParameterDeserializer_NullCollectionExpected", "PrimitiveValue", "123"),
                    this.ExceptionVerifier);
                this.Assert.AreEqual(ODataParameterReaderState.Exception, reader.State, "Unexpected first parameter state.");

                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_Complex, testConfiguration, "{\"complex\":null}");
                reader.Read();
                this.Assert.AreEqual("complex", reader.Name, "Unexpected first parameter name.");
                this.Assert.IsNull(reader.Value, "Unexpected first parameter value.");
                this.Assert.AreEqual(ODataParameterReaderState.Resource, reader.State, "Unexpected first parameter state.");
            });
        }
Esempio n. 6
0
        public void ParameterReaderIgnoreMissingNullableParameterTest()
        {
            IEdmModel           model          = TestModels.BuildModelWithFunctionImport();
            IEdmOperationImport functionImport = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_NullablePrimitive").First();

            this.CombinatorialEngineProvider.RunCombinations(
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(c => c.IsRequest == true),
                (testConfiguration) =>
            {
                // Reading an empty payload should not fail
                ODataParameterReaderTestWrapper reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration);
                this.Assert.IsFalse(reader.Read(), "Read() should return false on an empty payload.");
                this.Assert.AreEqual(ODataParameterReaderState.Completed, reader.State, "State should be completed.");

                // Reading a parameter payload with no parameter should not fail
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, "{}");
                this.Assert.IsFalse(reader.Read(), "Read() should return false on a parameter payload with no parameter.");
                this.Assert.AreEqual(ODataParameterReaderState.Completed, reader.State, "State should be completed.");
            });
        }
Esempio n. 7
0
        public void SpatialPropertyWithDisabledPrimitiveTypeConversionTest()
        {
            IEdmModel testModel = TestModels.BuildTestModel();

            var testValues = new object[]
            {
                GeographyFactory.Point(10, 20).Build(),
                GeometryFactory.Point(10, 20).Build()
            };

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors =
                TestValues.PrimitiveTypes.SelectMany(primitiveTypes => testValues.Select(testValue =>
            {
                PrimitiveDataType targetType       = EntityModelUtils.GetPrimitiveEdmType(primitiveTypes);
                ODataPayloadElement payloadElement = PayloadBuilder
                                                     .Property(null, PayloadBuilder.PrimitiveValue(testValue))
                                                     .ExpectedPropertyType(targetType);
                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                    PayloadEdmModel = testModel
                });
            }));

            // TODO: Task 1429690:Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                new bool[] { false, true },
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                (testDescriptor, disableStrictValidation, testConfig) =>
            {
                testConfig = new ReaderTestConfiguration(testConfig);
                testConfig.MessageReaderSettings.EnablePrimitiveTypeConversion = false;
                if (disableStrictValidation)
                {
                    testConfig = testConfig.CloneAndApplyBehavior(TestODataBehaviorKind.WcfDataServicesServer);
                }
                testDescriptor.RunTest(testConfig);
            });
        }
Esempio n. 8
0
        public void ParameterReaderVersioningTest()
        {
            IEdmModel           model = TestModels.BuildModelWithFunctionImport();
            IEdmOperationImport functionImport_Complex = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Complex").First();

            var testConfigurations = this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(c => c.IsRequest);

            this.CombinatorialEngineProvider.RunCombinations(
                testConfigurations,
                (testConfiguration) =>
            {
                this.Assert.ExpectedException(
                    () =>
                {
                    ODataParameterReaderTestWrapper reader = CreateODataParameterReader(model, functionImport_Complex, testConfiguration, "{\"complex\":null}");
                    while (reader.Read())
                    {
                        ;
                    }
                },
                    null,
                    this.ExceptionVerifier);
            });
        }
        public void StreamPropertyTest()
        {
            IEdmModel model = TestModels.BuildTestModel();

            var testCases = new[]
            {
                new StreamPropertyTestCase
                {
                    DebugDescription = "Just edit link",
                    InvalidOnRequest = true,
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/test/Cities(1)/Skyline", "http://odata.org/streamproperty/editlink", null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"",
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Just read link",
                    InvalidOnRequest = true,
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/streamproperty/readlink", "http://odata.org/test/Cities(1)/Skyline", null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/streamproperty/readlink\""
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Just content type",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, "streamproperty:contenttype", null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"streamproperty:contenttype\""
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Just ETag",
                    InvalidOnRequest = true,
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/test/Cities(1)/Skyline", "http://odata.org/test/Cities(1)/Skyline", null, "streamproperty:etag"),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"streamproperty:etag\""
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Everything",
                    InvalidOnRequest = true,
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/streamproperty/readlink", "http://odata.org/streamproperty/editlink", "streamproperty:contenttype", "streamproperty:etag"),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/streamproperty/readlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"streamproperty:contenttype\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"streamproperty:etag\""
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Just custom annotation - should report empty stream property",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", "custom.value") + "\":\"value\""
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Everything with custom annotation - custom annotations should be ignored",
                    InvalidOnRequest = true,
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/streamproperty/readlink", "http://odata.org/streamproperty/editlink", "streamproperty:contenttype", "streamproperty:etag"),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", "custom.value") + "\":\"value\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/streamproperty/readlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"streamproperty:contenttype\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"streamproperty:etag\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", "custom.type") + "\":42"
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "With odata.type annotation - should fail",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataTypeAnnotationName) + "\":\"Edm.Stream\"",
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Everything with navigation link URL annotation - should fail",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", "http://odata.org/streamproperty/readlink", "http://odata.org/streamproperty/editlink", "streamproperty:contenttype", "streamproperty:etag"),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/streamproperty/readlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/streamproperty/navlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"streamproperty:contenttype\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"streamproperty:etag\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_UnexpectedStreamPropertyAnnotation", "Skyline", JsonLightConstants.ODataNavigationLinkUrlAnnotationName)
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid edit link - wrong primitive",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":42",
                    ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_CannotReadPropertyValueAsString", "42", JsonLightConstants.ODataMediaEditLinkAnnotationName),
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid edit link - null",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":null",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightReaderUtils_AnnotationWithNullValue", JsonLightConstants.ODataMediaEditLinkAnnotationName),
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid read link - wrong primitive",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":true",
                    ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_CannotReadPropertyValueAsString", "True", JsonLightConstants.ODataMediaReadLinkAnnotationName),
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid read link - null",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":null",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightReaderUtils_AnnotationWithNullValue", JsonLightConstants.ODataMediaReadLinkAnnotationName),
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid ETag - non primitive",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":[]",
                    ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "PrimitiveValue", "StartArray"),
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid ETag - null",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaETagAnnotationName) + "\":null",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightReaderUtils_AnnotationWithNullValue", JsonLightConstants.ODataMediaETagAnnotationName),
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid content type - non primitive",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":{}",
                    ExpectedException = ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "PrimitiveValue", "StartObject"),
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Invalid content type - null",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, null, null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":null",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightReaderUtils_AnnotationWithNullValue", JsonLightConstants.ODataMediaContentTypeAnnotationName),
                    OnlyResponse      = true,
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Open stream property",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("OpenSkyline", null, "http://odata.org/streamproperty/editlink", null, null),
                    OwningEntityType = model.FindDeclaredType("TestModel.CityOpenType").ToTypeReference(),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("OpenSkyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"",
                    OnlyResponse = true
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Undeclared stream property (disallowed by default)",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("NewSkyline", null, "http://odata.org/streamproperty/editlink", null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("NewSkyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "NewSkyline", "TestModel.CityType"),
                    OnlyResponse      = true
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Stream property declared with non-stream type",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Name", null, "http://odata.org/streamproperty/editlink", null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Name", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_PropertyWithoutValueWithWrongType", "Name", "Edm.String"),
                    OnlyResponse      = true
                },
                new StreamPropertyTestCase
                {
                    DebugDescription = "Stream property with value",
                    ExpectedEntity   = PayloadBuilder.Entity().StreamProperty("Skyline", null, "http://odata.org/streamproperty/editlink", null, null),
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("Skyline", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/streamproperty/editlink\"," +
                        "\"Skyline\":\"value\"",
                    OnlyResponse = true
                },
            };

            this.RunStreamPropertyTest(model, testCases);
        }
Esempio n. 10
0
        public void PrimitiveTopLevelValueWithDisabledTypeConversionTest()
        {
            IEdmModel testModel = TestModels.BuildTestModel();

            IEnumerable <ReaderContentTypeTestDescriptor> testDescriptors = primitiveValueConversionTestCases
                                                                            .SelectMany(testCase => TestValues.PrimitiveTypes
                                                                                        .SelectMany(nonNullableTargetType => new bool[] { true, false }
                                                                                                    .SelectMany(includeNullableType => new bool[] { true, false }
                                                                                                                .Select(useExpectedType =>
            {
                PrimitiveDataType targetType = EntityModelUtils.GetPrimitiveEdmType(nonNullableTargetType);
                if (includeNullableType)
                {
                    targetType = targetType.Nullable();
                }

                ODataPayloadElement resultValue;
                if (nonNullableTargetType == typeof(byte[]))
                {
                    resultValue = testCase.ConversionValues.Where(cv => cv.ClrValue.GetType() == typeof(byte[])).Single().DeepCopy();
                }
                else
                {
                    resultValue = testCase.ConversionValues.Where(cv => cv.ClrValue.GetType() == typeof(string)).Single().DeepCopy();
                }

                ODataPayloadElement payloadElement;
                if (useExpectedType)
                {
                    payloadElement = PayloadBuilder.PrimitiveValue(testCase.SourceString).ExpectedPrimitiveValueType(targetType);
                }
                else
                {
                    payloadElement = PayloadBuilder.PrimitiveValue(testCase.SourceString);
                }

                return(new ReaderContentTypeTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                    ExpectedResultPayloadElement = (testConfig) => resultValue,
                    ContentType = ComputeContentType(nonNullableTargetType),
                    ExpectedFormat = ODataFormat.RawValue,
                });
            }))));

            // add variants that use a metadata provider
            testDescriptors = testDescriptors.Concat(testDescriptors.Select(td => new ReaderContentTypeTestDescriptor(td)
            {
                PayloadEdmModel = testModel
            }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                // restricting the set of default format configurations to limiti runtime of the tests
                this.ReaderTestConfigurationProvider.DefaultFormatConfigurations.Where(tc => tc.MessageReaderSettings.EnableMessageStreamDisposal && !tc.IsRequest),
                (testDescriptor, testConfig) =>
            {
                testConfig = new ReaderTestConfiguration(testConfig);
                testConfig.MessageReaderSettings.EnablePrimitiveTypeConversion = false;

                testDescriptor.RunTest(testConfig);
            });
        }
        public void UndeclaredValuePropertyTests()
        {
            IEdmModel model = TestModels.BuildTestModel();

            IEnumerable <UndeclaredPropertyTestCase> testCases = new[]
            {
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Number without type",
                    Json             = "\"UndeclaredProperty\":42",
                    IsValue          = true,
                    ExpectedEntity   = PayloadBuilder.Entity(),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "String without type",
                    Json             = "\"UndeclaredProperty\":\"value\"",
                    IsValue          = true,
                    ExpectedEntity   = PayloadBuilder.Entity(),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "null without type",
                    Json             = "\"UndeclaredProperty\":null",
                    IsValue          = true,
                    ExpectedEntity   = PayloadBuilder.Entity(),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Boolean without type",
                    Json             = "\"UndeclaredProperty\":false",
                    IsValue          = true,
                    ExpectedEntity   = PayloadBuilder.Entity(),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Number with type",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataTypeAnnotationName) + "\":\"Edm.Int16\"," +
                        "\"UndeclaredProperty\":42",
                    IsValue        = true,
                    ExpectedEntity = PayloadBuilder.Entity(),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Number with invalid type - should work, the type is ignored",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataTypeAnnotationName) + "\":\"TestModel.Unknown\"," +
                        "\"UndeclaredProperty\":42",
                    IsValue        = true,
                    ExpectedEntity = PayloadBuilder.Entity(),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Number with another odata annotation - should fail",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataBindAnnotationName) + "\":\"http://odata.org/reference\"," +
                        "\"UndeclaredProperty\":42",
                    IsValue           = true,
                    ExpectedEntity    = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_UnexpectedDataPropertyAnnotation", "UndeclaredProperty", JsonLightConstants.ODataBindAnnotationName)
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Property without value and with no recognized annotations - should fail",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", "custom.annotation") + "\":\"value\"",
                    ExpectedEntity    = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_PropertyWithoutValueWithUnknownType", "UndeclaredProperty")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Property without value and with known annotation - should fail",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataBindAnnotationName) + "\":\"http://odata.org/reference\"",
                    ExpectedEntity    = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_PropertyWithoutValueWithUnknownType", "UndeclaredProperty")
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                TestReaderUtils.ODataUndeclaredPropertyBehaviorKindsCombinations,
                // Undeclared properties are only allowed in responses
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => !tc.IsRequest),
                (testCase, undeclaredPropertyBehaviorKinds, testConfiguration) =>
            {
                PayloadReaderTestDescriptor testDescriptor = testCase.ToTestDescriptor(this.Settings, model, undeclaredPropertyBehaviorKinds);
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.UndeclaredPropertyBehaviorKinds = undeclaredPropertyBehaviorKinds;

                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 12
0
        public void ReadAssociationLinkTest()
        {
            IEdmModel model = TestModels.BuildTestModel();

            // TODO: add a payload with a relative association Uri

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                // Association link with nav. link
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder
                                     .NavigationProperty("NavPropWithAssociationUri", "http://odata.org/NavProp", "http://odata.org/NavPropWithAssociationUri")
                                     .IsCollection(true),
                    PayloadEdmModel = model
                },

                // No need to add expanded nav links since those will be generated for us by the payload generator below.
            }.SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            // Association links with nav. link
            IEnumerable <PayloadReaderTestDescriptor> associationLinkTestDescriptors = new PayloadReaderTestDescriptor[]
            {
                // Association links without a nav. link
                // Association link for a singleton nav. property.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1),
                    PayloadEdmModel = model
                },
                // Association link for a collection nav. property.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1),
                    PayloadEdmModel = model
                },
                // Association link which is not declared
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).Property(
                        PayloadBuilder.NavigationProperty("Nonexistant", null, "http://odata.org/CityHallLink").IsCollection(true)),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "Nonexistant", "TestModel.CityType")
                },
                // Association link which is not declared on an open type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity("TestModel.CityOpenType")
                                     .PrimitiveProperty("Id", 1)
                                     .Property(
                        PayloadBuilder.NavigationProperty("Nonexistant", null, "http://odata.org/CityHallLink").IsCollection(true)),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback =
                        (tc) => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = null
                    },
                },
                // Association link which is declared but of wrong kind
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).Property(
                        PayloadBuilder.NavigationProperty("Name", null, "http://odata.org/CityHallLink").IsCollection(true)),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback =
                        (tc) => new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException =
                            (tc.Format == ODataFormat.Json)
                                        ? ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_PropertyWithoutValueWithWrongType", "Name", "Edm.String")
                                        : ODataExpectedExceptions.ODataException("ValidationUtils_NavigationPropertyExpected", "Name", "TestModel.CityType", "Structural"),
                    },
                },
            };

            // Generate interesting payloads around the navigation property - this will skip failure cases like request payloads or wrong versions.
            testDescriptors = testDescriptors.Concat(associationLinkTestDescriptors.SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td)));

            // Add the same cases again, but without skipping interesting configurations.
            testDescriptors = testDescriptors.Concat(associationLinkTestDescriptors.Select(td =>
            {
                PayloadReaderTestDescriptor result = new PayloadReaderTestDescriptor(td);
                var originalResultCallback         = result.ExpectedResultCallback;
                result.ExpectedResultCallback      = tc =>
                                                     new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                {
                    ExpectedException = tc.IsRequest
                                ? null
                                : originalResultCallback == null ? result.ExpectedException : originalResultCallback(tc).ExpectedException,
                    ExpectedPayloadElement = tc.IsRequest
                                ? RemoveAssociationLinkPayloadElementNormalizer.Normalize(result.PayloadElement.DeepCopy())
                                : result.PayloadElement
                };

                // Setting the ExpectedResultCallback prevents normalizers from being run.
                result.SkipTestConfiguration = tc => tc.Format == ODataFormat.Json;

                return(result);
            }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                ODataVersionUtils.AllSupportedVersions,
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, maxProtocolVersion, testConfiguration) =>
            {
                if (maxProtocolVersion < testConfiguration.Version)
                {
                    return;
                }

                testDescriptor.RunTest(testConfiguration.CloneAndApplyMaxProtocolVersion(maxProtocolVersion));
            });
        }
Esempio n. 13
0
        public void ParameterReaderErrorTests()
        {
            IEdmModel           model                 = TestModels.BuildModelWithFunctionImport();
            IEdmOperationImport functionImport        = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Primitive").First();
            IEdmOperationImport functionImport_Stream = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Stream").First();
            IEdmOperationImport functionImport_Entry  = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Entry").First();
            IEdmOperationImport functionImport_Feed   = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Feed").First();

            var testConfigurations = this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(c => c.IsRequest);

            this.CombinatorialEngineProvider.RunCombinations(
                testConfigurations,
                (testConfiguration) =>
            {
                // Reading an empty payload should fail.
                ODataParameterReaderTestWrapper reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration);
                this.RunParameterReaderErrorTest(reader,
                                                 ODataExpectedExceptions.ODataException("ODataParameterReaderCore_ParametersMissingInPayload", "FunctionImport_Primitive", "primitive"));

                // Calling Read/ReadAsync in 'Exception' state should fail.
                this.RunParameterReaderErrorTest(reader,
                                                 ODataExpectedExceptions.ODataException("ODataParameterReaderCore_ReadOrReadAsyncCalledInInvalidState", "Exception"));

                // Reading a parameter payload with no parameter should fail because of the missing parameter
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, "{}");
                this.RunParameterReaderErrorTest(reader,
                                                 ODataExpectedExceptions.ODataException("ODataParameterReaderCore_ParametersMissingInPayload", "FunctionImport_Primitive", "primitive"));

                // Duplicated parameter name in the payload should fail.
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, "{ primitive: \"foo\", primitive: \"bar\" }");
                if (reader != null)
                {
                    this.RunParameterReaderErrorTest(reader, null, ODataParameterReaderState.Value);
                    this.Assert.AreEqual(ODataParameterReaderState.Value, reader.State, "Reader should be in Value state.");
                    this.Assert.AreEqual("primitive", reader.Name, "Parameter name should be 'primitive'.");
                    this.Assert.AreEqual("foo", reader.Value, "Parameter value should be 'foo'.");
                    this.RunParameterReaderErrorTest(reader,
                                                     ODataExpectedExceptions.ODataException("ODataParameterReaderCore_DuplicateParametersInPayload", "primitive"));
                }

                // Read until we are in Completed state.
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, "{ primitive: \"foo\" }");
                if (reader != null)
                {
                    this.RunParameterReaderErrorTest(reader, null, ODataParameterReaderState.Value);
                    this.Assert.AreEqual("primitive", reader.Name, "Parameter name should be 'primitive'.");
                    this.Assert.AreEqual("foo", reader.Value, "Parameter value should be 'foo'.");
                    this.RunParameterReaderErrorTest(reader, null, ODataParameterReaderState.Completed);
                }

                // Calling Read/ReadAsync in 'Completed' state should fail.
                this.RunParameterReaderErrorTest(reader,
                                                 ODataExpectedExceptions.ODataException("ODataParameterReaderCore_ReadOrReadAsyncCalledInInvalidState", "Completed"),
                                                 ODataParameterReaderState.Completed);

                // Calling Read in async reader or ReadAsync in sync reader should fail.
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration);
                if (reader != null)
                {
                    if (testConfiguration.Synchronous)
                    {
                        this.Assert.ExpectedException(
                            () => ((ODataParameterReaderTestWrapper)reader).ParameterReader.ReadAsync(),
                            ODataExpectedExceptions.ODataException("ODataParameterReaderCore_AsyncCallOnSyncReader"), this.ExceptionVerifier);
                        this.Assert.AreEqual(ODataParameterReaderState.Start, reader.State, "Reader should be in 'Start' state.");
                    }
                    else
                    {
                        this.Assert.ExpectedException(
                            () => ((ODataParameterReaderTestWrapper)reader).ParameterReader.Read(),
                            ODataExpectedExceptions.ODataException("ODataParameterReaderCore_SyncCallOnAsyncReader"), this.ExceptionVerifier);
                        this.Assert.AreEqual(ODataParameterReaderState.Start, reader.State, "Reader should be in 'Start' state.");
                    }
                }

                // Reading payload with parameter not in metadata should fail.
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, "{ p1 : \"foo\" }");
                this.RunParameterReaderErrorTest(reader,
                                                 ODataExpectedExceptions.ODataException("ODataParameterReaderCore_ParameterNameNotInMetadata", "p1", "FunctionImport_Primitive"));

                // Reading payload with first parameter not in metadata should fail.
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, "{ p2 : \"foo\", primitive : \"bar\"  }");
                this.RunParameterReaderErrorTest(reader,
                                                 ODataExpectedExceptions.ODataException("ODataParameterReaderCore_ParameterNameNotInMetadata", "p2", "FunctionImport_Primitive"));

                // Reading payload with additional parameter not in metadata should fail.
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, "{ primitive : \"foo\", p2 : \"bar\"  }");
                if (reader != null)
                {
                    reader.Read();
                    this.RunParameterReaderErrorTest(reader,
                                                     ODataExpectedExceptions.ODataException("ODataParameterReaderCore_ParameterNameNotInMetadata", "p2", "FunctionImport_Primitive"));
                }

                // Reading a parameter of stream primitive type should fail.
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_Stream, testConfiguration, "{ stream : \"foo\" }");
                this.RunParameterReaderErrorTest(reader,
                                                 ODataExpectedExceptions.ODataException("ODataJsonLightParameterDeserializer_UnsupportedPrimitiveParameterType", "stream", "Stream"));
            });
        }
        public void OpenTopLevelPropertiesTest()
        {
            IEdmModel model = TestModels.BuildTestModel();

            var testCases = new OpenPropertyTestCase[]
            {
                new OpenPropertyTestCase
                {
                    DebugDescription = "Integer open property.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", 42),
                    ExpectedPropertyWhenTypeUnavailable = PayloadBuilder.PrimitiveProperty("OpenProperty", 42),
                    ExpectedPropertyType = EdmCoreModel.Instance.GetInt32(false),
                    JsonTypeInformation  = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.Int32\",",
                    Json = "{0}{1}\"" + JsonLightConstants.ODataValuePropertyName + "\":42",
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "Null open property.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", null),
                    ExpectedPropertyWhenTypeUnavailable = PayloadBuilder.PrimitiveProperty("OpenProperty", null),
                    ExpectedPropertyType = EdmCoreModel.Instance.GetString(true),
                    JsonTypeInformation  = string.Empty,
                    Json = "{0}{1}\"value\":null",
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "String open property.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", "value"),
                    ExpectedPropertyWhenTypeUnavailable = PayloadBuilder.PrimitiveProperty("OpenProperty", "value"),
                    ExpectedPropertyType = EdmCoreModel.Instance.GetString(true),
                    JsonTypeInformation  = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.String\",",
                    Json = "{0}{1}\"" + JsonLightConstants.ODataValuePropertyName + "\":\"" + JsonLightConstants.ODataValuePropertyName + "\"",
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "DateTimeOffset open property with type information.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", new DateTimeOffset(2012, 4, 13, 2, 43, 10, 215, TimeSpan.Zero)),
                    ExpectedPropertyWhenTypeUnavailable = PayloadBuilder.PrimitiveProperty("OpenProperty", "2012-04-13T02:43:10.215Z"),
                    ExpectedPropertyType = EdmCoreModel.Instance.GetDateTimeOffset(false),
                    JsonTypeInformation  = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.DateTimeOffset\",",
                    Json = "{0}{1}\"" + JsonLightConstants.ODataValuePropertyName + "\":\"2012-04-13T02:43:10.215Z\"",
                },
            };

            bool[] withExpectedTypes = new bool[] { true, false };
            bool[] withPayloadTypes  = new bool[] { true, false };
            bool[] includeContextUri = new bool[] { true, false };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                withExpectedTypes,
                withPayloadTypes,
                includeContextUri,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testCase, withExpectedType, withPayloadType, withContextUri, testConfiguration) =>
            {
                if (withContextUri && testConfiguration.IsRequest)
                {
                    return;
                }

                string expectedTypeName = testCase.ExpectedPropertyType is IEdmCollectionTypeReference ? "Collection(" + ((IEdmCollectionType)testCase.ExpectedPropertyType.Definition).ElementType.FullName() + ")" : testCase.ExpectedPropertyType.TestFullName();
                string contextUri       = withContextUri ? "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + string.Format("\":\"http://odata.org/test/$metadata#{0}\",", expectedTypeName) : string.Empty;
                string json             = string.Format(
                    CultureInfo.InvariantCulture,
                    testCase.Json,
                    contextUri,
                    withPayloadType ? testCase.JsonTypeInformation : string.Empty);

                bool typeGiven = withExpectedType || withPayloadType || withContextUri;

                if (!typeGiven && testCase.ExpectedPropertyWhenTypeUnavailable == null)
                {
                    testCase.ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_ValueWithoutType");
                }

                PropertyInstance property = typeGiven || testCase.ExpectedPropertyWhenTypeUnavailable == null ? testCase.ExpectedProperty : testCase.ExpectedPropertyWhenTypeUnavailable;
                property = property.DeepCopy();

                if (withExpectedType)
                {
                    property = property.ExpectedPropertyType(testCase.ExpectedPropertyType);
                }

                if (!withPayloadType)
                {
                    ComplexProperty complexProperty = property as ComplexProperty;
                    if (complexProperty != null)
                    {
                        complexProperty.Value.AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        });
                    }
                    else
                    {
                        PrimitiveMultiValueProperty primitiveCollectionProperty = property as PrimitiveMultiValueProperty;
                        if (primitiveCollectionProperty != null)
                        {
                            primitiveCollectionProperty.Value.AddAnnotation(new SerializationTypeNameTestAnnotation()
                            {
                                TypeName = null
                            });
                        }
                        else
                        {
                            ComplexMultiValueProperty complexCollectionProperty = property as ComplexMultiValueProperty;
                            if (complexCollectionProperty != null)
                            {
                                complexCollectionProperty.Value.AddAnnotation(new SerializationTypeNameTestAnnotation()
                                {
                                    TypeName = null
                                });
                            }
                        }
                    }
                }

                ExpectedException expectedException = testCase.ExpectedException;
                if (!withContextUri && !testConfiguration.IsRequest)
                {
                    expectedException = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty");
                }

                PayloadReaderTestDescriptor testDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = testCase.DebugDescription + "[Expected type: " + withExpectedType + ", payload type: " + withPayloadType + "]",
                    PayloadElement   = property
                                       .JsonRepresentation("{" + json + "}"),
                    PayloadEdmModel   = model,
                    ExpectedException = expectedException,
                };

                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void UndeclaredStreamPropertyTests()
        {
            IEdmModel model = TestModels.BuildTestModel();

            IEnumerable<UndeclaredPropertyTestCase> testCases = new[]
            {
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Just edit link",
                    Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/mediaeditlink\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().StreamProperty("UndeclaredProperty", null, "http://odata.org/mediaeditlink", null, null)
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Just read link",
                    Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/mediareadlink\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().StreamProperty("UndeclaredProperty", "http://odata.org/mediareadlink", null, null, null)
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Just content type",
                    Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"media/contenttype\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().StreamProperty("UndeclaredProperty", null, null, "media/contenttype", null)
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Just ETag",
                    Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"etag\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().StreamProperty("UndeclaredProperty", null, null, null, "etag")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Everything",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/mediaeditlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/mediareadlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"media/contenttype\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"etag\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().StreamProperty("UndeclaredProperty", "http://odata.org/mediareadlink", "http://odata.org/mediaeditlink", "media/contenttype", "etag")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Everything with custom annotations",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/mediaeditlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"http://odata.org/mediareadlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", "custom.annotation") + "\":\"value\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"media/contenttype\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"etag\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", "custom.annotation2") + "\":42",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().StreamProperty("UndeclaredProperty", "http://odata.org/mediareadlink", "http://odata.org/mediaeditlink", "media/contenttype", "etag")
                },
                //new UndeclaredPropertyTestCase
                //{
                //    DebugDescription = "Stream property with odata.type annotation",
                //    Json =
                //        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/mediaeditlink\"," +
                //        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataTypeAnnotationName) + "\":\"#Stream\"",
                //    IsLink = true,
                //    ExpectedEntity = PayloadBuilder.Entity(),
                //    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_UnexpectedStreamPropertyAnnotation", "UndeclaredProperty", JsonLightConstants.ODataTypeAnnotationName)
                //},
                //new UndeclaredPropertyTestCase
                //{
                //    DebugDescription = "Stream property with a value",
                //    Json =
                //        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/mediaeditlink\"," +
                //        "\"UndeclaredProperty\":null",
                //    IsLink = true,
                //    ExpectedEntity = PayloadBuilder.Entity(),
                //    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_StreamPropertyWithValue", "UndeclaredProperty")
                //},
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                new[] { false, true },
                // Undeclared properties are only allowed in responses
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => !tc.IsRequest),
                (testCase, throwOnUndeclaredPropertyForNonOpenType, testConfiguration) =>
                {
                    var settings = testConfiguration.Format == ODataFormat.Json ? this.JsonLightSettings : this.Settings;
                    PayloadReaderTestDescriptor testDescriptor = testCase.ToTestDescriptor(settings, model, throwOnUndeclaredPropertyForNonOpenType);
                    testConfiguration = new ReaderTestConfiguration(testConfiguration);
                    if (!throwOnUndeclaredPropertyForNonOpenType)
                    {
                        testConfiguration.MessageReaderSettings.Validations &= ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;
                    }

                    // These descriptors are already tailored specifically for Json Light and
                    // do not require normalization.
                    testDescriptor.TestDescriptorNormalizers.Clear();
                    testDescriptor.RunTest(testConfiguration);
                });
        }
Esempio n. 16
0
        public void ParameterReaderCreateReaderStateMachineTests()
        {
            IEdmModel           model = TestModels.BuildModelWithFunctionImport();
            IEdmOperationImport functionImport_Primitive           = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Primitive").First();
            IEdmOperationImport functionImport_PrimitiveCollection = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_PrimitiveCollection").First();
            IEdmOperationImport functionImport_Complex             = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Complex").First();
            IEdmOperationImport functionImport_ComplexCollection   = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_ComplexCollection").First();
            IEdmOperationImport functionImport_Entry = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Entry").First();
            IEdmOperationImport functionImport_Feed  = model.FindEntityContainer("TestContainer").FindOperationImports("FunctionImport_Feed").First();

            CreateReaderMethods[] createReaderMethods = new CreateReaderMethods[]
            {
                CreateReaderMethods.CreateCollectionReader,
            };

            var testConfigurations = this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(c => c.IsRequest);

            this.CombinatorialEngineProvider.RunCombinations(
                testConfigurations,
                createReaderMethods,
                (testConfiguration, createReaderMethod) =>
            {
                // Calling Create*Reader in Start state should fail.
                ODataParameterReader reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_Complex, testConfiguration, "{ complex : { PrimitiveProperty : \"456\" } }");
                this.Assert.ExpectedException(
                    () => CreateSubReader(reader, createReaderMethod),
                    ODataExpectedExceptions.ODataException("ODataParameterReaderCore_InvalidCreateReaderMethodCalledForState", createReaderMethod.ToString(), ODataParameterReaderState.Start.ToString()), this.ExceptionVerifier);
                this.Assert.AreEqual(ODataParameterReaderState.Start, reader.State, "Unexpected parameter reader state.");

                // Calling Create*Reader in Value state should fail.
                reader.Read();
                this.Assert.AreEqual(ODataParameterReaderState.Resource, reader.State, "Unexpected parameter reader state.");
                this.Assert.ExpectedException(
                    () => CreateSubReader(reader, createReaderMethod),
                    ODataExpectedExceptions.ODataException("ODataParameterReaderCore_InvalidCreateReaderMethodCalledForState", createReaderMethod.ToString(), ODataParameterReaderState.Resource.ToString()), this.ExceptionVerifier);
                this.Assert.AreEqual(ODataParameterReaderState.Resource, reader.State, "Unexpected parameter reader state.");

                if (createReaderMethod != CreateReaderMethods.CreateResourceReader)
                {
                    // Calling Create*Reader in Entry state should fail.
                    reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_Entry, testConfiguration, "{ entry : {} }");
                    reader.Read();
                    this.Assert.AreEqual(ODataParameterReaderState.Resource, reader.State, "Unexpected parameter reader state.");
                    this.Assert.ExpectedException(
                        () => CreateSubReader(reader, createReaderMethod),
                        ODataExpectedExceptions.ODataException("ODataParameterReaderCore_InvalidCreateReaderMethodCalledForState", createReaderMethod.ToString(), ODataParameterReaderState.Resource.ToString()), this.ExceptionVerifier);
                    this.Assert.AreEqual(ODataParameterReaderState.Resource, reader.State, "Unexpected parameter reader state.");
                }

                if (createReaderMethod != CreateReaderMethods.CreateResourceSetReader)
                {
                    // Calling Create*Reader in Feed state should fail.
                    reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_Feed, testConfiguration, "{ feed : [] }");
                    reader.Read();
                    this.Assert.AreEqual(ODataParameterReaderState.ResourceSet, reader.State, "Unexpected parameter reader state.");
                    this.Assert.ExpectedException(
                        () => CreateSubReader(reader, createReaderMethod),
                        ODataExpectedExceptions.ODataException("ODataParameterReaderCore_InvalidCreateReaderMethodCalledForState", createReaderMethod.ToString(), ODataParameterReaderState.ResourceSet.ToString()), this.ExceptionVerifier);
                    this.Assert.AreEqual(ODataParameterReaderState.ResourceSet, reader.State, "Unexpected parameter reader state.");
                }

                if (createReaderMethod != CreateReaderMethods.CreateCollectionReader)
                {
                    // Calling Create*Reader in Collection state should fail.
                    reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport_ComplexCollection, testConfiguration, "{ complexCollection : [] }");
                    reader.Read();
                    this.Assert.AreEqual(ODataParameterReaderState.Collection, reader.State, "Unexpected parameter reader state.");
                    this.Assert.ExpectedException(
                        () => CreateSubReader(reader, createReaderMethod),
                        ODataExpectedExceptions.ODataException("ODataParameterReaderCore_InvalidCreateReaderMethodCalledForState", createReaderMethod.ToString(), ODataParameterReaderState.Collection.ToString()), this.ExceptionVerifier);
                    this.Assert.AreEqual(ODataParameterReaderState.Collection, reader.State, "Unexpected parameter reader state.");
                }

                // Calling Read() in Entry/Feed/Collection state without calling Create***Reader should fail.
                IEdmOperationImport functionImport = createReaderMethod == CreateReaderMethods.CreateResourceReader ? functionImport_Entry : (createReaderMethod == CreateReaderMethods.CreateResourceSetReader ? functionImport_Feed : functionImport_ComplexCollection);
                string payload = createReaderMethod == CreateReaderMethods.CreateResourceReader ? "{ entry : {} }" : (createReaderMethod == CreateReaderMethods.CreateResourceSetReader ? "{ feed : [] }" : "{ complexCollection : [] }");
                ODataParameterReaderState expectedParameterState = createReaderMethod == CreateReaderMethods.CreateResourceReader ? ODataParameterReaderState.Resource : ODataParameterReaderState.ResourceSet;
                var expectedReaderMethod = createReaderMethod == CreateReaderMethods.CreateCollectionReader ? CreateReaderMethods.CreateResourceSetReader.ToString() : createReaderMethod.ToString();
                reader = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, payload);
                reader.Read();
                this.Assert.AreEqual(expectedParameterState, reader.State, "Unexpected parameter reader state.");
                this.Assert.ExpectedException(
                    () => reader.Read(),
                    ODataExpectedExceptions.ODataException("ODataParameterReaderCore_SubReaderMustBeCreatedAndReadToCompletionBeforeTheNextReadOrReadAsyncCall", expectedParameterState.ToString(), expectedReaderMethod), this.ExceptionVerifier);
                this.Assert.AreEqual(expectedParameterState, reader.State, "Unexpected parameter reader state.");

                // Calling Read() in Entry/Feed/Collection state after Create***Reader() is called but before the created reader finishes should fail.
                var subReaderMethod = createReaderMethod == CreateReaderMethods.CreateCollectionReader
                        ? CreateReaderMethods.CreateResourceSetReader : createReaderMethod;
                object subReader = CreateSubReader(reader,
                                                   subReaderMethod);
                this.Assert.ExpectedException(
                    () => reader.Read(),
                    ODataExpectedExceptions.ODataException("ODataParameterReaderCore_SubReaderMustBeInCompletedStateBeforeTheNextReadOrReadAsyncCall", expectedParameterState.ToString(), expectedReaderMethod), this.ExceptionVerifier);
                this.Assert.AreEqual(expectedParameterState, reader.State, "Unexpected parameter reader state.");

                // Calling Create*Reader() before the sub-reader is completed should fail.
                string parameterName = createReaderMethod == CreateReaderMethods.CreateResourceReader ? "entry" : (createReaderMethod == CreateReaderMethods.CreateResourceSetReader ? "feed" : "complexCollection");
                subReader.GetType().GetMethod("Read").Invoke(subReader, null);
                this.Assert.ExpectedException(
                    () => CreateSubReader(reader, subReaderMethod),
                    ODataExpectedExceptions.ODataException("ODataParameterReaderCore_CreateReaderAlreadyCalled", expectedReaderMethod, parameterName), this.ExceptionVerifier);
                this.Assert.AreEqual(expectedParameterState, reader.State, "Unexpected parameter reader state.");

                // Calling Create*Reader() after sub-reader is completed should fail.
                while ((bool)subReader.GetType().GetMethod("Read").Invoke(subReader, null))
                {
                    ;
                }
                this.Assert.AreEqual("Completed", subReader.GetType().GetProperty("State").GetValue(subReader, null).ToString(), "Unexpected sub-reader state.");
                this.Assert.ExpectedException(
                    () => CreateSubReader(reader, subReaderMethod),
                    ODataExpectedExceptions.ODataException("ODataParameterReaderCore_CreateReaderAlreadyCalled", expectedReaderMethod, parameterName), this.ExceptionVerifier);
                this.Assert.AreEqual(expectedParameterState, reader.State, "Unexpected parameter reader state.");

                // Finish reading...
                reader.Read();
                this.Assert.AreEqual(ODataParameterReaderState.Completed, reader.State, "Unexpected parameter reader state.");

                // Calling Create*Reader in Completed state should fail.
                this.Assert.ExpectedException(
                    () => CreateSubReader(reader, subReaderMethod),
                    ODataExpectedExceptions.ODataException("ODataParameterReaderCore_InvalidCreateReaderMethodCalledForState", expectedReaderMethod, ODataParameterReaderState.Completed.ToString()), this.ExceptionVerifier);
                this.Assert.AreEqual(ODataParameterReaderState.Completed, reader.State, "Unexpected parameter reader state.");

                // Exception in subReader should put parent reader in Exception state.
                payload = createReaderMethod == CreateReaderMethods.CreateResourceReader ? "{ entry : \"foo\" }" : (createReaderMethod == CreateReaderMethods.CreateResourceSetReader ? "{ feed : { \"foo\" : \"bar\" } }" : "{ complexCollection : { \"foo\" : \"bar\" } }");
                reader  = this.CreateParameterReaderForRequestOrResponse(model, functionImport, testConfiguration, payload);
                reader.Read();
                this.Assert.AreEqual(expectedParameterState, reader.State, "Unexpected parameter reader state.");
                subReader = CreateSubReader(reader, subReaderMethod);
                this.Assert.IsNotNull(TestExceptionUtils.RunCatching(() => { while ((bool)subReader.GetType().GetMethod("Read").Invoke(subReader, null))
                                                                             {
                                                                             }
                                                                     }), "Expecting sub-reader.Read() to fail.");
                this.Assert.AreEqual("Exception", subReader.GetType().GetProperty("State").GetValue(subReader, null).ToString(), "Unexpected sub-reader state.");
                this.Assert.AreEqual(ODataParameterReaderState.Exception, reader.State, "Unexpected parameter reader state.");

                // Calling Create*Reader in Exception state should fail.
                this.Assert.ExpectedException(
                    () => CreateSubReader(reader, subReaderMethod),
                    ODataExpectedExceptions.ODataException("ODataParameterReaderCore_InvalidCreateReaderMethodCalledForState", expectedReaderMethod, ODataParameterReaderState.Exception.ToString()), this.ExceptionVerifier);
                this.Assert.AreEqual(ODataParameterReaderState.Exception, reader.State, "Unexpected parameter reader state.");
            });
        }
        public void OpenTopLevelPropertiesErrorTest()
        {
            IEdmModel model = TestModels.BuildTestModel();

            var testCases = new OpenPropertyTestCase[]
            {
                new OpenPropertyTestCase
                {
                    DebugDescription = "String open property with property annotation type information - should fail.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", "value").ExpectedPropertyType(EdmCoreModel.Instance.GetString(true)),
                    Json             =
                        "{0}" +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName(JsonLightConstants.ODataValuePropertyName, JsonLightConstants.ODataTypeAnnotationName) + "\":\"Edm.String\"," +
                        "\"" + JsonLightConstants.ODataValuePropertyName + "\":\"" + JsonLightConstants.ODataValuePropertyName + "\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_UnexpectedODataPropertyAnnotation", JsonLightConstants.ODataTypeAnnotationName)
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "String open property with complex type information - should fail.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", "value").ExpectedPropertyType(EdmCoreModel.Instance.GetString(true)),
                    Json             =
                        "{0}" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.Address\"," +
                        "\"" + JsonLightConstants.ODataValuePropertyName + "\":\"" + JsonLightConstants.ODataValuePropertyName + "\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "TestModel.Address", "Primitive", "Complex")
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "Type property after the data property - should fail.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", "value").ExpectedPropertyType(EdmCoreModel.Instance.GetString(true)),
                    Json             =
                        "{0}" +
                        "\"" + JsonLightConstants.ODataValuePropertyName + "\":\"" + JsonLightConstants.ODataValuePropertyName + "\"," +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.String\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_TypePropertyAfterValueProperty", JsonLightConstants.ODataTypeAnnotationName, JsonLightConstants.ODataValuePropertyName)
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "Duplicate data property - should fail.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", "value").ExpectedPropertyType(EdmCoreModel.Instance.GetString(true)),
                    Json             =
                        "{0}" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.String\"," +
                        "\"" + JsonLightConstants.ODataValuePropertyName + "\":\"" + JsonLightConstants.ODataValuePropertyName + "\"," +
                        "\"" + JsonLightConstants.ODataValuePropertyName + "\":\"" + JsonLightConstants.ODataValuePropertyName + "\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesNotAllowed", JsonLightConstants.ODataValuePropertyName)
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "Duplicate odata.type property - should fail.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", "value").ExpectedPropertyType(EdmCoreModel.Instance.GetString(true)),
                    Json             =
                        "{0}" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.String\"," +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.String\"," +
                        "\"" + JsonLightConstants.ODataValuePropertyName + "\":\"" + JsonLightConstants.ODataValuePropertyName + "\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicateAnnotationNotAllowed", JsonLightConstants.ODataTypeAnnotationName)
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "No data property - should fail.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", "value").ExpectedPropertyType(EdmCoreModel.Instance.GetString(true)),
                    Json             =
                        "{0}" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.String\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_InvalidTopLevelPropertyPayload")
                },
                new OpenPropertyTestCase
                {
                    DebugDescription = "No data property (only type property) - should fail.",
                    ExpectedProperty = PayloadBuilder.PrimitiveProperty("OpenProperty", "value").ExpectedPropertyType(EdmCoreModel.Instance.GetString(true)),
                    Json             =
                        "{0}" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"Edm.String\"",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_InvalidTopLevelPropertyPayload")
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testCase, testConfiguration) =>
            {
                string json = string.Format(
                    CultureInfo.InvariantCulture,
                    testCase.Json,
                    testConfiguration.IsRequest
                            ? string.Empty
                            : "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.String\",");

                PayloadReaderTestDescriptor testDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = testCase.DebugDescription,
                    PayloadElement   = testCase.ExpectedProperty
                                       .JsonRepresentation("{" + json + "}"),
                    PayloadEdmModel   = model,
                    ExpectedException = testCase.ExpectedException,
                };

                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void OpenComplexTopLevelPropertiesTest()
        {
            IEdmModel model = TestModels.BuildTestModel();

            var addressType = model.FindDeclaredType("TestModel.Address");

            var testCases = new OpenPropertyTestCase[]
            {
                new OpenPropertyTestCase
                {
                    DebugDescription     = "Empty complex open property with type information.",
                    ExpectedProperty     = PayloadBuilder.Property("OpenProperty", PayloadBuilder.ComplexValue("TestModel.Address")),
                    ExpectedPropertyType = addressType.ToTypeReference(),
                    JsonTypeInformation  = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.Address\"",
                    Json = "{0}{1}",
                },
                new OpenPropertyTestCase
                {
                    DebugDescription     = "Complex property with data.",
                    ExpectedProperty     = PayloadBuilder.Property("OpenProperty", PayloadBuilder.ComplexValue("TestModel.Address").PrimitiveProperty("Street", "First")),
                    ExpectedPropertyType = addressType.ToTypeReference(),
                    JsonTypeInformation  = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.Address\",",
                    Json = "{0}{1}\"Street\":\"First\"",
                },

                new OpenPropertyTestCase
                {
                    DebugDescription     = "Complex property with data.",
                    ExpectedProperty     = PayloadBuilder.Property("OpenProperty", PayloadBuilder.ComplexValue("TestModel.Address").PrimitiveProperty("Street", "First")),
                    ExpectedPropertyType = addressType.ToTypeReference(),
                    JsonTypeInformation  = "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.Address\",",
                    Json = "{0}{1}\"Street\":\"First\"",
                },
            };

            bool[] withExpectedTypes = new bool[] { true, false };
            bool[] withPayloadTypes  = new bool[] { true, false };
            bool[] includeContextUri = new bool[] { true, false };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                withExpectedTypes,
                withPayloadTypes,
                includeContextUri,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testCase, withExpectedType, withPayloadType, withContextUri, testConfiguration) =>
            {
                if (withContextUri && testConfiguration.IsRequest)
                {
                    return;
                }

                PropertyInstance property       = testCase.ExpectedProperty.DeepCopy();
                ComplexProperty complexProperty = (ComplexProperty)property;
                ComplexInstance complexValue    = complexProperty.Value;
                bool isEmpty = !complexValue.Properties.Any();

                string contextUri = withContextUri ? "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.Address\"," : string.Empty;
                string json       = string.Format(
                    CultureInfo.InvariantCulture,
                    testCase.Json,
                    contextUri,
                    withPayloadType ? testCase.JsonTypeInformation : string.Empty);

                if (isEmpty && json.EndsWith(","))
                {
                    json = json.Substring(0, json.Length - 1);
                }

                if (withExpectedType)
                {
                    property = property.ExpectedPropertyType(testCase.ExpectedPropertyType);
                }

                if (!withPayloadType)
                {
                    complexProperty.Value.AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    });
                }

                ExpectedException expectedException = testCase.ExpectedException;
                if (!withContextUri && !testConfiguration.IsRequest)
                {
                    expectedException = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty");
                }
                else if (!withExpectedType && !withPayloadType && !withContextUri)
                {
                    string firstPropertyName = isEmpty ? null : complexValue.Properties.First().Name;

                    // An open property without expected and payload type cannot be read; expect an exception.
                    expectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_ResourceWithoutType");
                }

                PayloadReaderTestDescriptor testDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = testCase.DebugDescription + "[Expected type: " + withExpectedType + ", payload type: " + withPayloadType + "]",
                    PayloadElement   = property
                                       .JsonRepresentation("{" + json + "}"),
                    PayloadEdmModel   = model,
                    ExpectedException = expectedException,
                };

                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();

                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void UndeclaredNavigationLinkTests()
        {
            IEdmModel model = TestModels.BuildTestModel();

            IEnumerable<UndeclaredPropertyTestCase> testCases = new[]
            {
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Just navigation link",
                    Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navigationlink\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().NavigationProperty("UndeclaredProperty", "http://odata.org/navigationlink")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Just association link",
                    Json = "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataAssociationLinkUrlAnnotationName) + "\":\"http://odata.org/associationlink\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().NavigationProperty("UndeclaredProperty", null, "http://odata.org/associationlink")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Navigation and association link",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navigationlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataAssociationLinkUrlAnnotationName) + "\":\"http://odata.org/associationlink\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().NavigationProperty("UndeclaredProperty", "http://odata.org/navigationlink", "http://odata.org/associationlink")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Navigation and association link with custom annotation",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navigationlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", "custom.annotation") + "\":null," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataAssociationLinkUrlAnnotationName) + "\":\"http://odata.org/associationlink\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().NavigationProperty("UndeclaredProperty", "http://odata.org/navigationlink", "http://odata.org/associationlink")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Navigation link with odata.type annotation",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataTypeAnnotationName) + "\":\"TestModel.OfficeType\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navigationlink\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity().NavigationProperty("UndeclaredProperty", "http://odata.org/navigationlink")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Association link with another odata.mediaEditLink annotation - should fail",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"http://odata.org/mediaeditlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataAssociationLinkUrlAnnotationName) + "\":\"http://odata.org/associationlink\"",
                    IsLink = true,
                    ExpectedEntity = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_UnexpectedStreamPropertyAnnotation", "UndeclaredProperty", JsonLightConstants.ODataAssociationLinkUrlAnnotationName)
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Expanded feed navigation link",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navigationlink\"," +
                        "\"UndeclaredProperty\":[]",
                    IsLink = true,
                    IsValue = true,
                    ExpectedEntity = PayloadBuilder.Entity().NavigationProperty("UndeclaredProperty", "http://odata.org/navigationlink"),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Expanded entry navigation link",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataAssociationLinkUrlAnnotationName) + "\":\"http://odata.org/associationlink\"," +
                        "\"UndeclaredProperty\":{}",
                    IsLink = true,
                    IsValue = true,
                    ExpectedEntity = PayloadBuilder.Entity().NavigationProperty("UndeclaredProperty", null, "http://odata.org/associationlink"),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Expanded null entry navigation link",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navigationlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataAssociationLinkUrlAnnotationName) + "\":\"http://odata.org/associationlink\"," +
                        "\"UndeclaredProperty\":null",
                    IsLink = true,
                    IsValue = true,
                    ExpectedEntity = PayloadBuilder.Entity().NavigationProperty("UndeclaredProperty", "http://odata.org/navigationlink", "http://odata.org/associationlink"),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Expanded navigation link with wrong value",
                    Json =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navigationlink\"," +
                        "\"UndeclaredProperty\":42",
                    IsLink = true,
                    IsValue = true,
                    ExpectedEntity = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_CannotReadNestedResource", "UndeclaredProperty")
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                new[] { false, true },
                // Undeclared properties are only allowed in responses
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => !tc.IsRequest),
                (testCase, throwOnUndeclaredPropertyForNonOpenType, testConfiguration) =>
                {
                    PayloadReaderTestDescriptor testDescriptor = testCase.ToTestDescriptor(this.Settings, model, throwOnUndeclaredPropertyForNonOpenType);
                    testConfiguration = new ReaderTestConfiguration(testConfiguration);
                    if (!throwOnUndeclaredPropertyForNonOpenType)
                    {
                        testConfiguration.MessageReaderSettings.Validations &= ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;
                    }

                    // These descriptors are already tailored specifically for Json Light and
                    // do not require normalization.
                    testDescriptor.TestDescriptorNormalizers.Clear();
                    testDescriptor.RunTest(testConfiguration);
                });
        }
        public void UndeclaredValuePropertyTests()
        {
            IEdmModel model = TestModels.BuildTestModel();

            IEnumerable <UndeclaredPropertyTestCase> testCases = new[]
            {
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Number without type",
                    Json             = "\"UndeclaredProperty\":42",
                    IsValue          = true,
                    ExpectedEntity   = PayloadBuilder.Entity().PrimitiveProperty("UndeclaredProperty", 42),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "String without type",
                    Json             = "\"UndeclaredProperty\":\"value\"",
                    IsValue          = true,
                    ExpectedEntity   = PayloadBuilder.Entity().PrimitiveProperty("UndeclaredProperty", "value"),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "null without type",
                    Json             = "\"UndeclaredProperty\":null",
                    IsValue          = true,
                    ExpectedEntity   = PayloadBuilder.Entity().PrimitiveProperty("UndeclaredProperty", null),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Boolean without type",
                    Json             = "\"UndeclaredProperty\":false",
                    IsValue          = true,
                    ExpectedEntity   = PayloadBuilder.Entity().PrimitiveProperty("UndeclaredProperty", false),
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Number with type",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataTypeAnnotationName) + "\":\"Edm.Int16\"," +
                        "\"UndeclaredProperty\":42",
                    IsValue        = true,
                    ExpectedEntity = PayloadBuilder.Entity().PrimitiveProperty("UndeclaredProperty", (short)42),
                },

                // TODO read: Microsoft.OData.ODataException: A type named 'TestModel.Unknown' could not be resolved by the model. When a model is available, each type name must resolve to a valid type.
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Number with invalid type - should work, the type is ignored",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataTypeAnnotationName) + "\":\"TestModel.Unknown\"," +
                        "\"UndeclaredProperty\":42",
                    IsValue           = true,
                    ExpectedEntity    = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "TestModel.Unknown")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Number with another odata annotation - should fail",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataBindAnnotationName) + "\":\"http://odata.org/reference\"," +
                        "\"UndeclaredProperty\":42",
                    IsValue           = true,
                    ExpectedEntity    = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_UnexpectedDataPropertyAnnotation", "UndeclaredProperty", JsonLightConstants.ODataBindAnnotationName)
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Property without value and with no recognized annotations - should fail",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", "custom.annotation") + "\":\"value\"",
                    ExpectedEntity    = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_PropertyWithoutValueWithUnknownType", "UndeclaredProperty")
                },
                new UndeclaredPropertyTestCase
                {
                    DebugDescription = "Property without value and with known annotation - should fail",
                    Json             =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("UndeclaredProperty", JsonLightConstants.ODataBindAnnotationName) + "\":\"http://odata.org/reference\"",
                    ExpectedEntity    = PayloadBuilder.Entity(),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_PropertyWithoutValueWithUnknownType", "UndeclaredProperty")
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                new[] { false, true },
                // Undeclared properties are only allowed in responses
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => !tc.IsRequest),
                (testCase, throwOnUndeclaredPropertyForNonOpenType, testConfiguration) =>
            {
                PayloadReaderTestDescriptor testDescriptor = testCase.ToTestDescriptor(this.Settings, model, throwOnUndeclaredPropertyForNonOpenType);
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                if (!throwOnUndeclaredPropertyForNonOpenType)
                {
                    testConfiguration.MessageReaderSettings.Validations &= ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;
                }

                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }