private void RunMessageSizeLimitTests(
            IEnumerable <ReaderTestConfiguration> testConfigurations,
            EdmModel model,
            ODataPayloadElement payload,
            MessageSizeLimitTestCase[] testCases,
            Func <ReaderTestConfiguration, bool> skipTestConfigurationFunc = null)
        {
            var transformScope = this.Settings.PayloadTransformFactory.EmptyScope();

            using (transformScope.Apply())
            {
                this.CombinatorialEngineProvider.RunCombinations(
                    testCases,
                    testConfigurations,
                    (testCase, testConfiguration) =>
                {
                    int size = -1;
                    if (testConfiguration.Format == ODataFormat.Atom && testCase.AtomSizes != null)
                    {
                        size = testConfiguration.IsRequest ? testCase.AtomSizes.RequestSize : testCase.AtomSizes.ResponseSize;
                    }
                    else if (testConfiguration.Format == ODataFormat.Json && testCase.JsonLightSizes != null)
                    {
                        size = testConfiguration.IsRequest ? testCase.JsonLightSizes.RequestSize : testCase.JsonLightSizes.ResponseSize;
                    }
                    else if (testCase.RawSizes != null)
                    {
                        size = testConfiguration.IsRequest ? testCase.RawSizes.RequestSize : testCase.RawSizes.ResponseSize;
                    }

                    int maxSize = testCase.MaxMessageSize >= 0 ? testCase.MaxMessageSize : 1024 * 1024;
                    ExpectedException expectedException = size < 0
                            ? null
                            : ODataExpectedExceptions.ODataException("MessageStreamWrappingStream_ByteLimitExceeded", size.ToString(), maxSize.ToString());

                    var testDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadEdmModel             = model,
                        PayloadElement              = payload.DeepCopy(),
                        ExpectedException           = expectedException,
                        SkipTestConfiguration       = skipTestConfigurationFunc,
                        ApplyPayloadTransformations = false,
                    };

                    testDescriptor.ExpectedResultNormalizers.Add(
                        tc => (Func <ODataPayloadElement, ODataPayloadElement>)null);

                    if (testCase.MaxMessageSize > 0)
                    {
                        testConfiguration = new ReaderTestConfiguration(testConfiguration);
                        testConfiguration.MessageReaderSettings.MessageQuotas.MaxReceivedMessageSize = testCase.MaxMessageSize;
                    }

                    testDescriptor.RunTest(testConfiguration);
                });
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Runs each test descriptor with each ATOM reader test configuration and with ATOM metadata both enabled and disabled.
        /// </summary>
        /// <param name="testDescriptors">The test descriptors to run</param>
        /// <param name="runOnlyWithMetadataReadingOn">If true, then the test descriptors are only run with ATOM metadata reading enabled; false means run each descriptor with ATOM metadata reading both enabled and disabled.</param>
        protected void RunAtomMetadataReaderTests(IEnumerable <PayloadReaderTestDescriptor> testDescriptors, bool runOnlyWithMetadataReadingOn = false)
        {
            bool[] enableMetadataReadingOptions = runOnlyWithMetadataReadingOn
                ? new bool[] { true }
                : new bool[] { true, false };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                enableMetadataReadingOptions,
                (testDescriptor, testConfiguration, enableMetadataReading) =>
            {
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.EnableAtomMetadataReading = enableMetadataReading;

                testDescriptor = new PayloadReaderTestDescriptor(testDescriptor);

                // Normalize the payload elements so that if an ATOM metadata property is set, the corresponding ATOM metadata
                // annotation is created, and vice versa.
                testDescriptor.ExpectedResultNormalizers.Add(tc => ODataPayloadElementAtomMetadataNormalizer.GenerateNormalizer(tc));

                if (!enableMetadataReading)
                {
                    // If we are running with ATOM metadata reading turned off, strip off all ATOM metadata annotations and
                    // properties from the expected result.
                    testDescriptor.ExpectedResultNormalizers.Add(tc => RemoveAtomMetadataFromPayloadElementVisitor.Visit);

                    // Association links are only recognized in response and MPV >= V3
                    if (testConfiguration.IsRequest)
                    {
                        testDescriptor.ExpectedResultNormalizers.Add(tc =>
                                                                     (payloadElement => RemoveAssociationLinkPayloadElementNormalizer.Normalize(payloadElement)));
                    }

                    // Stream properties are only recognized in response and >=V3
                    if (testConfiguration.IsRequest)
                    {
                        testDescriptor.ExpectedResultNormalizers.Add(tc =>
                                                                     (payloadElement => RemoveStreamPropertyPayloadElementNormalizer.Normalize(payloadElement)));
                    }

                    // In this test class, expected exceptions apply only when ATOM metadata reading is on.
                    testDescriptor.ExpectedException = null;
                }
                else
                {
                    // In requests when metadata reading is enabled we have to turn stream properties and association links
                    // into Atom metadata (and XmlTree annotation instances)
                    testDescriptor.ExpectedResultNormalizers.Add(tc => (payloadElement) => ConvertAtomMetadataForConfigurationPayloadElementNormalizer.Normalize(payloadElement, tc));
                }

                testDescriptor.RunTest(testConfiguration);
            });
        }
Exemplo n.º 3
0
        public void InvalidXmlBaseUriHandlingTest()
        {
            string absoluteUri = "http://odata.org/relative";

            var testCases = new[]
            {
                new
                {
                    BaseUriString     = "relativeUri",
                    SettingsBaseUri   = (string)null,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomDeserializer_RelativeUriUsedWithoutBaseUriSpecified", "relativeUri")
                },
                new
                {
                    BaseUriString     = string.Empty,
                    SettingsBaseUri   = (string)null,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomDeserializer_RelativeUriUsedWithoutBaseUriSpecified", string.Empty)
                },
                new
                {
                    BaseUriString     = "http://invalid:uri:value",
                    SettingsBaseUri   = (string)null,
                    ExpectedException = new ExpectedException(typeof(UriFormatException))
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                new TestODataBehaviorKind[] { TestODataBehaviorKind.Default, TestODataBehaviorKind.WcfDataServicesServer },
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testCase, behaviorKind, testConfiguration) =>
            {
                var td = new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity().AsMediaLinkEntry().StreamSourceLink(absoluteUri)
                                     .XmlRepresentation("<entry xml:base='" + testCase.BaseUriString + "'><content src='" + absoluteUri + "'/></entry>"),
                    ExpectedException = testCase.ExpectedException
                };

                // [Astoria-ODataLib-Integration] Parsing of URLs on OData recognized places may fail, but Astoria server doesn't
                // In server mode we need to normalize payload to not expect information that the server does not read
                if (behaviorKind == TestODataBehaviorKind.WcfDataServicesServer)
                {
                    td.ExpectedResultNormalizers.Add((tc) => (payloadElement => WcfDsServerPayloadElementNormalizer.Normalize(payloadElement, tc.Format, (EdmModel)null)));
                }


                testConfiguration = testConfiguration.CloneAndApplyBehavior(behaviorKind);
                testConfiguration.MessageReaderSettings.BaseUri = testCase.SettingsBaseUri == null ? null : new Uri(testCase.SettingsBaseUri);

                td.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 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);
                });
        }
Exemplo n.º 6
0
        public void TopLevelPropertyNamespaceTest()
        {
            var testCases = new[]
            {
                new
                {
                    // Support custom data namespace for compatibility with WCF DS client.
                    NamespaceUri      = TestAtomConstants.ODataMetadataNamespace + "/custom",
                    ExpectedException = new System.Func <TestODataBehaviorKind, ODataVersion, ExpectedException>((TestODataBehaviorKind behavior, ODataVersion odataVersion) =>
                    {
                        if (behavior == TestODataBehaviorKind.WcfDataServicesServer)
                        {
                            return(null);
                        }
                        else
                        {
                            return(ODataExpectedExceptions.ODataException("ODataAtomPropertyAndValueDeserializer_TopLevelPropertyElementWrongNamespace", TestAtomConstants.ODataMetadataNamespace + "/custom", TestAtomConstants.ODataMetadataNamespace));
                        }
                    })
                },
                new
                {
                    NamespaceUri      = TestAtomConstants.ODataMetadataNamespace,
                    ExpectedException = new System.Func <TestODataBehaviorKind, ODataVersion, ExpectedException>((TestODataBehaviorKind behavior, ODataVersion odataVersion) =>
                    {
                        return(null);
                    })
                },
                new
                {
                    NamespaceUri      = TestAtomConstants.ODataNamespace,
                    ExpectedException = new System.Func <TestODataBehaviorKind, ODataVersion, ExpectedException>((TestODataBehaviorKind behavior, ODataVersion odataVersion) =>
                    {
                        if (behavior == TestODataBehaviorKind.WcfDataServicesServer)
                        {
                            return(null);
                        }
                        else
                        {
                            return(ODataExpectedExceptions.ODataException("ODataAtomPropertyAndValueDeserializer_TopLevelPropertyElementWrongNamespace", TestAtomConstants.ODataNamespace, TestAtomConstants.ODataMetadataNamespace));
                        }
                    })
                },
                new
                {
                    NamespaceUri      = "http://odata.org/customUri",
                    ExpectedException = new System.Func <TestODataBehaviorKind, ODataVersion, ExpectedException>((TestODataBehaviorKind behavior, ODataVersion odataVersion) =>
                    {
                        if (behavior == TestODataBehaviorKind.WcfDataServicesServer)
                        {
                            return(null);
                        }
                        else
                        {
                            return(ODataExpectedExceptions.ODataException("ODataAtomPropertyAndValueDeserializer_TopLevelPropertyElementWrongNamespace", "http://odata.org/customUri", TestAtomConstants.ODataMetadataNamespace));
                        }
                    })
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                TestReaderUtils.ODataBehaviorKinds,
                new[] { ODataVersion.V4 },
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testCase, behavior, odataVersion, testConfiguration) =>
            {
                var td = new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty(null, string.Empty)
                                     .XmlRepresentation("<p:value xmlns:p='" + testCase.NamespaceUri + "'/>"),
                    ExpectedException = testCase.ExpectedException(behavior, odataVersion)
                };

                testConfiguration = testConfiguration.CloneAndApplyBehavior(behavior);

                td.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(),
                },
                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);
            });
        }
        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 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);
            });
        }
Exemplo n.º 11
0
        public void ComplexValueIgnorePropertyNullValuesTest()
        {
            var versions = new Version[] {
                null,
                new Version(4, 0),
            };

            EdmModel        edmModel          = new EdmModel();
            IEdmComplexType countryRegionType = edmModel.ComplexType("CountryRegion")
                                                .Property("Name", EdmPrimitiveTypeKind.String)
                                                .Property("CountryRegionCode", EdmPrimitiveTypeKind.String);
            IEdmComplexType countryRegionNullType = edmModel.ComplexType("CountryRegionNull")
                                                    .Property("Name", EdmPrimitiveTypeKind.String)
                                                    .Property("CountryRegionCode", EdmPrimitiveTypeKind.String);
            IEdmComplexType addressType = edmModel.ComplexType("Address")
                                          .Property("Street", EdmPrimitiveTypeKind.String)
                                          .Property("StreetNull", EdmCoreModel.Instance.GetString(true) as EdmTypeReference)
                                          .Property("Numbers", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)) as EdmTypeReference)
                                          .Property("CountryRegion", new EdmComplexTypeReference(countryRegionType, false))
                                          .Property("CountryRegionNull", new EdmComplexTypeReference(countryRegionNullType, true));

            edmModel.EntityType("Customer")
            .KeyProperty("ID", EdmCoreModel.Instance.GetInt32(false) as EdmTypeReference)
            .Property("Address", new EdmComplexTypeReference(addressType, false));
            edmModel.Fixup();

            this.CombinatorialEngineProvider.RunCombinations(
                new ODataNullValueBehaviorKind[] { ODataNullValueBehaviorKind.Default, ODataNullValueBehaviorKind.DisableValidation, ODataNullValueBehaviorKind.IgnoreValue },
                versions,
                versions,
                TestReaderUtils.ODataBehaviorKinds,
                (nullPropertyValueReaderBehavior, dataServiceVersion, edmVersion, behaviorKind) =>
            {
                edmModel.SetEdmVersion(edmVersion);

                // Now we set the 'IgnoreNullValues' annotation on all properties
                IEdmComplexType edmAddressType = (IEdmComplexType)edmModel.FindType("TestModel.Address");
                foreach (IEdmStructuralProperty edmProperty in edmAddressType.StructuralProperties())
                {
                    edmModel.SetNullValueReaderBehavior(edmProperty, nullPropertyValueReaderBehavior);
                }

                EntityInstance customerPayload = PayloadBuilder.Entity("TestModel.Customer")
                                                 .PrimitiveProperty("ID", 1)
                                                 .Property("Address", PayloadBuilder.ComplexValue("TestModel.Address")
                                                           .PrimitiveProperty("Street", "One Microsoft Way")
                                                           .PrimitiveProperty("StreetNull", "One Microsoft Way")
                                                           .Property("Numbers", PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)").Item(1).Item(2))
                                                           .Property("CountryRegion", PayloadBuilder.ComplexValue("TestModel.CountryRegion")
                                                                     .PrimitiveProperty("Name", "Austria")
                                                                     .PrimitiveProperty("CountryRegionCode", "AUT"))
                                                           .Property("CountryRegionNull", PayloadBuilder.ComplexValue("TestModel.CountryRegionNull")
                                                                     .PrimitiveProperty("Name", "Austria")
                                                                     .PrimitiveProperty("CountryRegionCode", "AUT")));

                var testCases = new[]
                {
                    // Complex types that are not nullable should not allow null values.
                    // Null primitive property in the payload and non-nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "Street",
                        ExpectedResponseException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "Street", "Edm.String"),
                    },
                    // Null complex property in the payload and non-nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "CountryRegion",
                        ExpectedResponseException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "CountryRegion", "TestModel.CountryRegion"),
                    },
                    // Null collection property in the payload and non-nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "Numbers",
                        ExpectedResponseException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullNamedValueForNonNullableType", "Numbers", "Collection(Edm.Int32)"),
                    },
                    // Complex types that are nullable should allow null values.
                    // Null primitive property in the payload and nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "StreetNull",
                    },
                    // Null complex property in the payload and nullable property in the model
                    new IgnoreNullValueTestCase
                    {
                        PropertyName = "CountryRegionNull",
                    },
                };

                Func <IgnoreNullValueTestCase, ReaderTestConfiguration, PayloadReaderTestDescriptor> createTestDescriptor =
                    (testCase, testConfig) =>
                {
                    EntityInstance payloadValue         = customerPayload.DeepCopy();
                    ComplexInstance payloadAddressValue = ((ComplexProperty)payloadValue.GetProperty("Address")).Value;
                    SetToNull(payloadAddressValue, testCase.PropertyName);

                    ComplexInstance resultValue = payloadValue;
                    if (testConfig.IsRequest && nullPropertyValueReaderBehavior == ODataNullValueBehaviorKind.IgnoreValue)
                    {
                        resultValue = customerPayload.DeepCopy();
                        ComplexInstance resultAddressValue = ((ComplexProperty)resultValue.GetProperty("Address")).Value;
                        resultAddressValue.Remove(resultAddressValue.GetProperty(testCase.PropertyName));
                    }

                    return(new PayloadReaderTestDescriptor(this.Settings)
                    {
                        PayloadElement = payloadValue,
                        PayloadEdmModel = edmModel,
                        ExpectedResultPayloadElement =
                            tc =>
                        {
                            if (tc.Format == ODataFormat.Json)
                            {
                                // under the client knob ODL will compute edit links, ids, etc
                                // so we need to update the expected payload
                                if (tc.RunBehaviorKind == TestODataBehaviorKind.WcfDataServicesClient)
                                {
                                    var entity = resultValue as EntityInstance;
                                    if (entity != null)
                                    {
                                        if (!tc.IsRequest)
                                        {
                                            entity.Id = "http://odata.org/test/Customer(1)";
                                            entity.EditLink = "http://odata.org/test/Customer(1)";
                                            entity.WithSelfLink("http://odata.org/test/Customer(1)");
                                        }
                                    }
                                }

                                var tempDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                                {
                                    PayloadElement = resultValue,
                                    PayloadEdmModel = edmModel,
                                };

                                JsonLightPayloadElementFixup.Fixup(tempDescriptor);
                                return tempDescriptor.PayloadElement;
                            }

                            return resultValue;
                        },
                        ExpectedException = (testConfig.IsRequest && nullPropertyValueReaderBehavior != ODataNullValueBehaviorKind.Default) ? null : testCase.ExpectedResponseException
                    });
                };

                this.CombinatorialEngineProvider.RunCombinations(
                    testCases,
                    this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                    (testCase, testConfiguration) =>
                {
                    testConfiguration = testConfiguration.CloneAndApplyBehavior(behaviorKind);
                    testConfiguration.MessageReaderSettings.BaseUri = null;

                    PayloadReaderTestDescriptor testDescriptor = createTestDescriptor(testCase, testConfiguration);
                    testDescriptor.RunTest(testConfiguration);
                });
            });
        }
Exemplo n.º 12
0
        /// <summary>
        /// Helper method to run a single iteration of the URI reading tests in a specified configuration.
        /// </summary>
        /// <typeparam name="T">The type of the payload to read.</typeparam>
        /// <param name="payloadElement">The payload to read.</param>
        /// <param name="setExpectedUriAction">An action to set the URI in question on the payload.</param>
        /// <param name="model">The metadata model.</param>
        /// <param name="baseUriValue">The base URI value for the current iteration.</param>
        /// <param name="testConfiguration">The reader test configuration.</param>
        private void RunNullUriReadingTest <T>(
            T payloadElement,
            NullUriValueTestCase <T> testCase,
            IEdmModel model,
            BaseUriValue baseUriValue,
            ReaderTestConfiguration testConfiguration) where T : ODataPayloadElement
        {
            this.Assert.IsNotNull(testCase.SetNullUriAction, "SetNullUriAction must not be null.");
            this.Assert.IsNull(testConfiguration.MessageReaderSettings.BaseUri, "No base URI expected on reader settings.");

            ExpectedException expectedException = null;
            Uri settingsBaseUri = baseUriValue.ReaderSettingBaseUri;

            // Set the base URI on the message reader settings if specified
            if (settingsBaseUri != null)
            {
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.BaseUri = settingsBaseUri;
            }

            // Create the payload element
            T clonedPayloadElement = payloadElement.DeepCopy();

            // modify the payload to represent the 'null' URI
            testCase.SetNullUriAction(clonedPayloadElement, /*uri*/ null, testConfiguration);

            var setExpectedUriAction = testCase.SetExpectedUriAction ?? testCase.SetNullUriAction;

            if (testConfiguration.Format == ODataFormat.Atom)
            {
                XElement xmlRepresentation = this.PayloadElementToXmlConverter.ConvertToXml(clonedPayloadElement);

                // add an xml:base attribute if specified
                Uri xmlBaseUri = baseUriValue.XmlBaseUri;
                if (xmlBaseUri != null)
                {
                    xmlRepresentation.Add(new XAttribute(XNamespace.Xml.GetName("base"), xmlBaseUri.OriginalString));
                }

                clonedPayloadElement.XmlRepresentation(xmlRepresentation);

                // First check all error conditions that are independent of a potential base URI
                if (payloadElement.ElementType == ODataPayloadElementType.ServiceDocumentInstance)
                {
                    // Resource collections must have a URL
                    expectedException = ODataExpectedExceptions.ODataException("ValidationUtils_ServiceDocumentElementUrlMustNotBeNull");
                }
                else
                {
                    if (xmlBaseUri != null)
                    {
                        setExpectedUriAction(clonedPayloadElement, xmlBaseUri, testConfiguration);
                    }
                    else if (settingsBaseUri != null)
                    {
                        setExpectedUriAction(clonedPayloadElement, settingsBaseUri, testConfiguration);
                    }
                    else
                    {
                        // fail for relative URIs without base URI
                        if (payloadElement.ElementType == ODataPayloadElementType.DeferredLink ||
                            payloadElement.ElementType == ODataPayloadElementType.LinkCollection)
                        {
                            expectedException = ODataExpectedExceptions.ODataException("ODataAtomDeserializer_RelativeUriUsedWithoutBaseUriSpecified", string.Empty);
                        }
                    }

                    // NOTE: ATOM properly detects MLEs even without read or edit link
                }
            }
            else
            {
                throw new NotSupportedException("Unsupported configuration format: " + testConfiguration.Format.ToString());
            }

            PayloadReaderTestDescriptor testDescriptor = new PayloadReaderTestDescriptor(this.Settings)
            {
                PayloadElement        = clonedPayloadElement,
                PayloadEdmModel       = model,
                ExpectedException     = expectedException,
                SkipTestConfiguration = tc => ODataPayloadElementConfigurationValidator.GetSkipTestConfiguration(payloadElement, ODataPayloadElementConfigurationValidator.AllValidators)(tc),
            };

            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);
            });
        }