Esempio n. 1
0
            public PayloadReaderTestDescriptor ToTestDescriptor(PayloadReaderTestDescriptor.Settings settings, IEdmModel model, bool withMetadataAnnotation = false)
            {
                IEdmEntityContainer container       = model.FindEntityContainer("DefaultContainer");
                IEdmEntitySet       citiesEntitySet = container.FindEntitySet("Cities");
                IEdmType            cityType        = model.FindType("TestModel.CityType");

                EntityInstance entity = PayloadBuilder.Entity("TestModel.CityType")
                                        .ExpectedEntityType(cityType, citiesEntitySet)
                                        .JsonRepresentation(
                    "{" +
                    (withMetadataAnnotation ? ("\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://http://odata.org/test/$metadata#DefaultContainer.Cities/$entity\",") : string.Empty) +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.CityType\"," +
                    this.Json +
                    ",\"Id\":1" +
                    "}");

                foreach (PropertyInstance property in this.ExpectedEntity.Properties)
                {
                    entity.Add(property.DeepCopy());
                }

                entity.Add(PayloadBuilder.PrimitiveProperty("Id", 1));

                return(new NavigationLinkTestCaseDescriptor(settings)
                {
                    DebugDescription = this.DebugDescription,
                    PayloadElement = entity,
                    PayloadEdmModel = model,
                    ExpectedException = this.ExpectedException,
                    ExpectedIsCollectionValues = this.ExpectedIsCollectionValues,
                });
            }
        public void TopLevelPropertyTest()
        {
            var testDescriptors = new PayloadReaderTestDescriptor[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty(null, "foo")
                                     .XmlRepresentation("<value xmlns=''>42</value>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomPropertyAndValueDeserializer_TopLevelPropertyElementWrongNamespace", string.Empty, TestAtomConstants.ODataMetadataNamespace),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty("propertyName", "foo")
                                     .XmlRepresentation("<d:value>42</d:value>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomPropertyAndValueDeserializer_TopLevelPropertyElementWrongNamespace", TestAtomConstants.ODataNamespace, TestAtomConstants.ODataMetadataNamespace),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty(null, "")
                                     .XmlRepresentation("<m:value m:type='Edm.String'/>"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty(null, "")
                                     .XmlRepresentation("<!--s-->  <?value?><m:value m:type='Edm.String'/><?value?><!-- -->"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty(null, GeographyFactory.Point(50, 70).Build())
                                     .XmlRepresentation(
                        "<m:value>" +
                        "<gml:Point gml:srsName=\"http://www.opengis.net/def/crs/EPSG/0/4326\" xmlns:gml=\"http://www.opengis.net/gml\">" +
                        "<gml:pos>50 70</gml:pos>" +
                        "</gml:Point>" +
                        "</m:value>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty(null, GeographyFactory.Point(50, 70).Build())
                                     .XmlRepresentation(
                        "<m:value m:type='Edm.GeographyPoint'>" +
                        "<gml:Point gml:srsName=\"http://www.opengis.net/def/crs/EPSG/0/4326\" xmlns:gml=\"http://www.opengis.net/gml\">" +
                        "<gml:pos>50 70</gml:pos>" +
                        "</gml:Point>" +
                        "</m:value>"),
                    SkipTestConfiguration = tc => tc.Version < ODataVersion.V4
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void JsonLightTaupoSerializerPropertyTest()
        {
            var testCases = new JsonLightSerializerTestCase[]
            {
                // Null property
                // TODO: Change the payload of null top-level properties #645
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty("Prop", null).WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson   = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          ""value"":null
                        }"
                },
                // Primitive property
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty("Prop", "" + JsonLightConstants.ODataValuePropertyName + @"").WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson   = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          """ + JsonLightConstants.ODataValuePropertyName + @""":""" + JsonLightConstants.ODataValuePropertyName + @"""
                        }"
                },
                // Complex property
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.Property("Prop",
                                                             PayloadBuilder.ComplexValue("TestModel.City")
                                                             .PrimitiveProperty("City", "Vienna"))
                                     .WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + @""":""TestModel.City"", ""City"":""Vienna""
                        }"
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                (testCase) =>
            {
                JsonValue actualValue   = this.JsonLightSerializer.ConvertToJsonLightValue(testCase.PayloadElement);
                JsonValue expectedValue = JsonTextPreservingParser.ParseValue(new StringReader(testCase.ExpectedJson));

                this.JsonValueComparer.Compare(expectedValue, actualValue);
            });
        }
Esempio n. 4
0
        public void EncodingPropertyTest()
        {
            // NOTE: the XmlReader (when created via XmlReader.Create) will use the Xml declaration and/or scan
            //       ahead to detect the encoding from the payload. Only if both fail, do we have the opportunity
            //       to make a difference by specifying the encoding in the content type.
            //
            // Create an non-standard character in the iso-8859-9 (Turkish) encoding
            Encoding iso88599Encoding = Encoding.GetEncoding("iso-8859-9");

            char[] chars        = iso88599Encoding.GetChars(new byte[] { 250 });
            string payloadValue = new string(chars);

            var testCases = new[]
            {
                new
                {
                    ContentType       = "application/xml",
                    ResultString      = payloadValue,
                    ExpectedException = new ExpectedException(typeof(XmlException)),
                },
                new
                {
                    ContentType       = "application/xml;charset=iso-8859-9",
                    ResultString      = payloadValue,
                    ExpectedException = (ExpectedException)null,
                },
            };

            var testDescriptors = testCases.Select(testCase =>
                                                   new ReaderEncodingTestDescriptor(this.Settings, testCase.ContentType)
            {
                PayloadElement = PayloadBuilder.PrimitiveProperty(null, payloadValue)
                                 .SerializationEncoding("iso-8859-9", /*omitDeclaration*/ true),
                ExpectedResultPayloadElement = tc => PayloadBuilder.PrimitiveProperty(null, testCase.ResultString),
                ExpectedException            = testCase.ExpectedException,
            }
                                                   );

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.DisableMessageStreamDisposal = true;

                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void TopLevelNullPropertyWithInvalidTypeNameTest()
        {
            EdmModel model = new EdmModel().Fixup();

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveProperty(null, null)
                                     .XmlRepresentation("<m:value m:null='true' m:type='UnknownType' />"),
                    PayloadEdmModel = model,
                },
            };

            var expectedTypes = new DataType[]
            {
                null,
                EdmDataTypes.Int32.NotNullable(),
                EdmDataTypes.Int32.Nullable(),
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                new bool[] { true, false },
                expectedTypes,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, disablePrimitiveTypeConversion, expectedType, testConfiguration) =>
            {
                if (disablePrimitiveTypeConversion)
                {
                    testConfiguration = new ReaderTestConfiguration(testConfiguration);
                    testConfiguration.MessageReaderSettings.DisablePrimitiveTypeConversion = true;
                }

                if (expectedType != null)
                {
                    testDescriptor = new PayloadReaderTestDescriptor(testDescriptor);
                    ((PropertyInstance)testDescriptor.PayloadElement).ExpectedPropertyType(expectedType);

                    if (!disablePrimitiveTypeConversion && !expectedType.IsNullable)
                    {
                        testDescriptor.ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullValueForNonNullableType", "Edm.Int32");
                    }
                }

                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 6
0
        // TODO: Change the payload of null top-level properties #645
        public void NullValuePropertyTests()
        {
            EdmModel model = new EdmModel();

            var testCases = new []
            {
                new
                {
                    Payload = "{{\"@odata.context\":\"http://odata.org/test/$metadata#Edm.String\",\"value\":null{0}}}",
                    SkipTestConfiguration = (Func <ReaderTestConfiguration, bool>)(tc => false)
                },
                new
                {
                    Payload = "{{\"value\":null{0}}}",
                    SkipTestConfiguration = (Func <ReaderTestConfiguration, bool>)(tc => tc.IsRequest == false)
                },
            };

            var testDescriptors = testCases.SelectMany(testCase =>
                                                       new[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription      = "null property value - should pass.",
                    PayloadEdmModel       = model,
                    PayloadElement        = PayloadBuilder.PrimitiveProperty(null, null).JsonRepresentation(string.Format(testCase.Payload, string.Empty)),
                    SkipTestConfiguration = testCase.SkipTestConfiguration
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription      = "null property value with custom annotation - should pass.",
                    PayloadEdmModel       = model,
                    PayloadElement        = PayloadBuilder.PrimitiveProperty(null, null).JsonRepresentation(string.Format(testCase.Payload, ",\"@Custom.Annotation\":\"foo\"")),
                    SkipTestConfiguration = testCase.SkipTestConfiguration
                },
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 7
0
        /// <summary>
        /// Generates interesting properties element payloads with ordering of properties for ATOM reader.
        /// </summary>
        /// <typeparam name="T">The type of the payload element to use.</typeparam>
        /// <param name="sourceTestDescriptor">The source descriptor to use.
        /// This should have the PayloadElement be the instance to which to add properties, the PayloadModel should be filled if necessary
        /// with model which defines two properties stringProperty (Edm.String) and numberProperty (Edm.Int32) and nullProperty (Edm.String nullable).</param>
        /// <param name="applyXmlValue">Func which will apply the generated XML value to the payload element.</param>
        /// <returns>Enumeration of interesting test descriptors.</returns>
        public static IEnumerable <PayloadReaderTestDescriptor> CreatePropertiesElementOrderingPayloads <T>(
            PayloadReaderTestDescriptor sourceTestDescriptor,
            Func <T, IEnumerable <XNode>, T> applyXmlValue,
            string odataNamespace = TestAtomConstants.ODataNamespace) where T : ComplexInstance
        {
            XNamespace odataXNamespace = XNamespace.Get(odataNamespace);
            var        properties      = new[]
            {
                new
                {
                    PropertyXml     = new XElement(odataXNamespace + "stringProperty", "some"),
                    PropertyElement = PayloadBuilder.PrimitiveProperty("stringProperty", "some")
                },
                new
                {
                    PropertyXml = new XElement(odataXNamespace + "numberProperty",
                                               new XAttribute(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.AtomTypeAttributeName, "Edm.Int32"),
                                               "42"),
                    PropertyElement = PayloadBuilder.PrimitiveProperty("numberProperty", 42)
                },
                new
                {
                    PropertyXml = new XElement(odataXNamespace + "nullProperty",
                                               new XAttribute(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataNullAttributeName, TestAtomConstants.AtomTrueLiteral)),
                    PropertyElement = PayloadBuilder.PrimitiveProperty("nullProperty", null)
                },
            };

            return(properties.Permutations().Select(props =>
            {
                var payloadElement = (T)sourceTestDescriptor.PayloadElement.DeepCopy();
                List <XNode> xmlNodes = new List <XNode>();
                for (int i = 0; i < properties.Length; i++)
                {
                    xmlNodes.Add(props[i].PropertyXml);
                    payloadElement.Add(props[i].PropertyElement);
                }

                return new PayloadReaderTestDescriptor(sourceTestDescriptor)
                {
                    PayloadElement = applyXmlValue(payloadElement, xmlNodes)
                };
            }));
        }
        public void PropertyMessageSizeLimitReadTest()
        {
            EdmModel model = Test.OData.Utils.Metadata.TestModels.BuildTestModel() as EdmModel;

            ODataPayloadElement propertyPayload = PayloadBuilder.PrimitiveProperty("LongName", "This is a name with a lot of characters so that we can test some security limits.");

            var testCases = new MessageSizeLimitTestCase[]
            {
                // Single byte size should fail
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = 1,
                    AtomSizes      = new RequestResponseSizes {
                        RequestSize = 328, ResponseSize = 328
                    },
                    JsonLightSizes = new RequestResponseSizes {
                        RequestSize = 162, ResponseSize = 162
                    },
                },
                // Small number should fail
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = 40,
                    AtomSizes      = new RequestResponseSizes {
                        RequestSize = 328, ResponseSize = 328
                    },
                    JsonLightSizes = new RequestResponseSizes {
                        RequestSize = 162, ResponseSize = 162
                    },
                },
                // ATOM & JSON-L fails, Verbose JSON works
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = 120,
                    AtomSizes      = new RequestResponseSizes {
                        RequestSize = 328, ResponseSize = 328
                    },
                    JsonLightSizes = new RequestResponseSizes {
                        RequestSize = 162, ResponseSize = 162
                    },
                },
                // Large number should work
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = 10000,
                },
                // Default should work
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = -1,
                },
            };

            this.RunAtomJsonMessageSizeLimitTests(model, propertyPayload, testCases);

            // Another tests with a payload that is too large for the default max message size
            ODataPayloadElement propertyPayload2 = PayloadBuilder.PrimitiveProperty("LongName2", new string('a', 1024 * 1024 + 1));

            testCases = new MessageSizeLimitTestCase[]
            {
                // Default should fail
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = -1,
                    AtomSizes      = new RequestResponseSizes {
                        RequestSize = 1048839, ResponseSize = 1048839
                    },
                    JsonLightSizes = new RequestResponseSizes {
                        RequestSize = 1048658, ResponseSize = 1048658
                    },
                },
            };

            this.RunAtomJsonMessageSizeLimitTests(model, propertyPayload2, testCases);
        }
Esempio n. 9
0
        /// <summary>
        /// Generates interesting properties element payloads with paddings for ATOM reader.
        /// </summary>
        /// <typeparam name="T">The type of the payload element to use.</typeparam>
        /// <param name="sourceTestDescriptor">The source descriptor to use.
        /// This should have the PayloadElement be the instance to which to add properties, the PayloadModel should be filled if necessary
        /// with model which defines two properties stringProperty (Edm.String) and numberProperty (Edm.Int32).</param>
        /// <param name="applyXmlValue">Func which will apply the generated XML value to the payload element.</param>
        /// <returns>Enumeration of interesting test descriptors.</returns>
        public static IEnumerable <PayloadReaderTestDescriptor> CreatePropertiesElementPaddingPayloads <T>(
            PayloadReaderTestDescriptor sourceTestDescriptor,
            Func <T, string, T> applyXmlValue) where T : ComplexInstance
        {
            var payloadWithPadding = new[]
            {
                // Element with insignificant content is a valid complex value
                new
                {
                    XmlValue   = "{0}",
                    Properties = new PropertyInstance[] { }
                },
                // Simple empty string property - padding before
                new
                {
                    XmlValue   = "{0}<d:stringProperty/>",
                    Properties = new PropertyInstance[] { PayloadBuilder.PrimitiveProperty("stringProperty", string.Empty) }
                },
                // Simple empty string property - padding after
                new
                {
                    XmlValue   = "<d:stringProperty/>{0}",
                    Properties = new PropertyInstance[] { PayloadBuilder.PrimitiveProperty("stringProperty", string.Empty) }
                },
                // Two simple properties - padding between
                new
                {
                    XmlValue   = "<d:stringProperty/>{0}<d:numberProperty m:type='Edm.Int32'>42</d:numberProperty>",
                    Properties = new PropertyInstance[] {
                        PayloadBuilder.PrimitiveProperty("stringProperty", string.Empty),
                        PayloadBuilder.PrimitiveProperty("numberProperty", 42)
                    }
                },
                // Two simple properties - padding after
                new
                {
                    XmlValue   = "<d:stringProperty/><d:numberProperty m:type='Edm.Int32'>42</d:numberProperty>{0}",
                    Properties = new PropertyInstance[] {
                        PayloadBuilder.PrimitiveProperty("stringProperty", string.Empty),
                        PayloadBuilder.PrimitiveProperty("numberProperty", 42)
                    }
                },
            };

            string[] xmlPaddingToIgnore = new string[]
            {
                string.Empty,                                           // Nothing
                "  \r\n\t",                                             // Whitespace only
                "<!--s--> <?value?>",                                   // Insignificant nodes
                "some text <![CDATA[cdata]]>",                          // Significant nodes to be ignored
                "<foo xmlns=''/>",                                      // Element in no namespace
                "<c:foo xmlns:c='uri' attr='1'><c:child/>text</c:foo>", // Element in custom namespace
                "<m:properties/>",                                      // Element in metadata namespace (should be ignored as well)
                "<entry/>",                                             // Element in atom namespace (should also be ignored)
            };

            return(payloadWithPadding.SelectMany(payload =>
                                                 xmlPaddingToIgnore.Select(xmlPadding =>
            {
                var payloadElement = (T)sourceTestDescriptor.PayloadElement.DeepCopy();
                foreach (var prop in payload.Properties)
                {
                    payloadElement.Add(prop);
                }

                payloadElement = applyXmlValue(payloadElement, string.Format(CultureInfo.InvariantCulture, payload.XmlValue, xmlPadding));

                return new PayloadReaderTestDescriptor(sourceTestDescriptor)
                {
                    PayloadElement = payloadElement
                };
            })));
        }
        public void TopLevelPropertiesWithMetadataTest()
        {
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = PayloadReaderTestDescriptorGenerator.CreatePrimitiveValueTestDescriptors(this.Settings);

            testDescriptors = testDescriptors.Concat(PayloadReaderTestDescriptorGenerator.CreateComplexValueTestDescriptors(this.Settings, true));
            testDescriptors = testDescriptors.Concat(PayloadReaderTestDescriptorGenerator.CreateCollectionTestDescriptors(this.Settings, true));

            testDescriptors = testDescriptors.Select(collectionTestDescriptor => collectionTestDescriptor.InProperty("propertyName"));
            testDescriptors = testDescriptors.SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            // Limit to only top-level property payloads
            testDescriptors = testDescriptors.Where(td => td.PayloadElement is PropertyInstance);

            // Add a couple of invalid cases which use a standard model
            EdmModel model = new EdmModel();

            model.ComplexType("UnusedComplexType");

            EdmEntityType unusedEntityType = model.EntityType("UnusedEntityType");

            unusedEntityType.AddKeys(unusedEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, isNullable: false));
            unusedEntityType.Property("Name", EdmPrimitiveTypeKind.String, isNullable: false);

            EdmEntityType streamPropertyEntityType = model.EntityType("EntityTypeWithStreamProperty");

            streamPropertyEntityType.AddKeys(streamPropertyEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, isNullable: false));
            streamPropertyEntityType.AddStructuralProperty("Video", EdmPrimitiveTypeKind.Stream, isNullable: false);
            streamPropertyEntityType.Property("NonStreamProperty", EdmPrimitiveTypeKind.Boolean, isNullable: false);

            EdmEntityType navigationPropertyEntityType = model.EntityType("EntityTypeWithNavigationProperty");

            navigationPropertyEntityType.AddKeys(navigationPropertyEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, isNullable: false));
            navigationPropertyEntityType.NavigationProperty("Navigation", streamPropertyEntityType);

            model.Fixup();

            EdmEntityContainer container = model.EntityContainer as EdmEntityContainer;

            EdmFunction nameFunction = new EdmFunction(container.Namespace, "NameFunctionImport", EdmCoreModel.Instance.GetInt32(false), false /*isBound*/, null, false /*isComposable*/);

            model.AddElement(nameFunction);
            container.AddFunctionImport("NameFunctionImport", nameFunction);
            model.Fixup();

            var videoPropertyType = model.GetEntityType("TestModel.EntityTypeWithStreamProperty").Properties().Single(p => p.Name == "Video").Type;

            var explicitTestDescriptors = new[]
            {
                // Non existant type name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.Property("propertyName", PayloadBuilder.ComplexValue("TestModel.NonExistantType")),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "TestModel.NonExistantType"),
                    // This test has different meaning in JSON-L (no expected type + non-existent typename)
                    SkipTestConfiguration = (tc) => tc.Format == ODataFormat.Json,
                },
                // Existing type name without namespace
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.Property("propertyName", PayloadBuilder.ComplexValue("UnusedComplexType")),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "UnusedComplexType"),
                    // This test has different meaning in JSON-L (no expected type + non-existent typename)
                    SkipTestConfiguration = (tc) => tc.Format == ODataFormat.Json,
                },
                // Existing type of wrong kind
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.Property("propertyName", PayloadBuilder.ComplexValue("TestModel.UnusedEntityType")),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectValueTypeKind", "TestModel.UnusedEntityType", "Entity"),
                    // This test has different meaning in JSON-L
                    SkipTestConfiguration = (tc) => tc.Format == ODataFormat.Json,
                },
                // A stream is not allowed in a property with a non-stream property kind.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.Entity("TestModel.EntityTypeWithStreamProperty").StreamProperty("NonStreamProperty", "http://readlink", "http://editlink"),
                    PayloadEdmModel        = model,
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = tc.Format == ODataFormat.Json
                                        ? ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_PropertyWithoutValueWithWrongType", "NonStreamProperty", "Edm.Boolean")
                                        : ODataExpectedExceptions.ODataException("JsonReaderExtensions_UnexpectedNodeDetected", "PrimitiveValue", "StartObject")
                    },
                },
                // Top-level property of stream type is not allowed
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.PrimitiveProperty("Video", 42).ExpectedPropertyType(videoPropertyType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ArgumentException("ODataMessageReader_ExpectedPropertyTypeStream"),
                },
                // Top-level deferred navigation property is not allowed
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.PrimitiveProperty("Video", 42).ExpectedPropertyType(streamPropertyEntityType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ArgumentException("ODataMessageReader_ExpectedPropertyTypeEntityKind"),
                },
                // Top-level expanded navigation property is not allowed
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.PrimitiveProperty("Video", 42).ExpectedPropertyType(streamPropertyEntityType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ArgumentException("ODataMessageReader_ExpectedPropertyTypeEntityKind"),
                },
            };

            testDescriptors = testDescriptors.Concat(explicitTestDescriptors);

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                var property = testDescriptor.PayloadElement as PropertyInstance;
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 11
0
        public void NullValuePropertyTests()
        {
            EdmModel model = new EdmModel();

            var testCases = new []
            {
                new
                {
                    Payload = "{{\"@odata.context\":\"http://odata.org/test/$metadata#Edm.Null\",\"@odata.null\":true{0}}}",
                    SkipTestConfiguration = (Func <ReaderTestConfiguration, bool>)(tc => false)
                },
                new
                {
                    Payload = "{{\"@odata.context\":\"http://odata.org/test/$metadata#Edm.Null\"{0}}}",
                    SkipTestConfiguration = (Func <ReaderTestConfiguration, bool>)(tc => tc.IsRequest)
                },
                new
                {
                    Payload = "{{\"@odata.context\":\"http://odata.org/test/$metadata#Edm.String\",\"@odata.null\":true{0}}}",
                    SkipTestConfiguration = (Func <ReaderTestConfiguration, bool>)(tc => false)
                },
                new
                {
                    Payload = "{{\"@odata.null\":true{0}}}",
                    SkipTestConfiguration = (Func <ReaderTestConfiguration, bool>)(tc => tc.IsRequest == false)
                },
            };

            var testDescriptors = testCases.SelectMany(testCase =>
                                                       new[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription      = "null property value - should pass.",
                    PayloadEdmModel       = model,
                    PayloadElement        = PayloadBuilder.PrimitiveProperty(null, null).JsonRepresentation(string.Format(testCase.Payload, string.Empty)),
                    SkipTestConfiguration = testCase.SkipTestConfiguration
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription      = "null property value with custom annotation - should pass.",
                    PayloadEdmModel       = model,
                    PayloadElement        = PayloadBuilder.PrimitiveProperty(null, null).JsonRepresentation(string.Format(testCase.Payload, ",\"@Custom.Annotation\":\"foo\"")),
                    SkipTestConfiguration = testCase.SkipTestConfiguration
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription      = "null property value with sub-property - should fail.",
                    PayloadEdmModel       = model,
                    PayloadElement        = PayloadBuilder.PrimitiveProperty(null, null).JsonRepresentation(string.Format(testCase.Payload, ",\"p1\":1")),
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_NoPropertyAndAnnotationAllowedInNullPayload", "p1"),
                    SkipTestConfiguration = testCase.SkipTestConfiguration
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription      = "null property value with custom annotation and sub-property - should fail.",
                    PayloadEdmModel       = model,
                    PayloadElement        = PayloadBuilder.PrimitiveProperty(null, null).JsonRepresentation(string.Format(testCase.Payload, ",\"@Custom.Annotation\":\"foo\",\"p1\":1")),
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_NoPropertyAndAnnotationAllowedInNullPayload", "p1"),
                    SkipTestConfiguration = testCase.SkipTestConfiguration
                },
            });

            testDescriptors = testDescriptors.Concat(new[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "null property context URI with custom annotation followed by odata.null - should fail.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.PrimitiveProperty(null, null)
                                       .JsonRepresentation(
                        "{" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Null\"," +
                        "\"@Custom.Annotation\":\"foo\"," +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataNullAnnotationName + "\":true" +
                        "}"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_UnexpectedAnnotationProperties", "odata.null")
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "null property context URI with property followed by odata.null - should fail.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.PrimitiveProperty(null, null)
                                       .JsonRepresentation(
                        "{" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Null\"," +
                        "\"foo\":\"bar\"," +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataNullAnnotationName + "\":true" +
                        "}"),
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightPropertyAndValueDeserializer_NoPropertyAndAnnotationAllowedInNullPayload", "foo"),
                    SkipTestConfiguration = (Func <ReaderTestConfiguration, bool>)(tc => tc.IsRequest)
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "null property context URI on non-nullable type - should fail.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.PrimitiveProperty(null, null).AddExpectedTypeAnnotation(new ExpectedTypeODataPayloadElementAnnotation {
                        ExpectedType = EdmDataTypes.Int32
                    })
                                       .JsonRepresentation(
                        "{" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Null\"" +
                        "}"),
                    ExpectedException     = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullValueForNonNullableType", "Edm.Int32"),
                    SkipTestConfiguration = (Func <ReaderTestConfiguration, bool>)(tc => tc.IsRequest)
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "null property context URI on non-nullable type - should fail.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.PrimitiveProperty(null, null).AddExpectedTypeAnnotation(new ExpectedTypeODataPayloadElementAnnotation {
                        ExpectedType = EdmDataTypes.Int32
                    })
                                       .JsonRepresentation(
                        "{" +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Edm.Int32\"," +
                        "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataNullAnnotationName + "\":true" +
                        "}"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ReaderValidationUtils_NullValueForNonNullableType", "Edm.Int32")
                },
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 12
0
        private static ODataPayloadElement CreatePayloadElement(IEdmModel model, ODataPayloadKind payloadKind, ReaderTestConfiguration testConfig)
        {
            IEdmEntitySet          citySet              = model.EntityContainer.FindEntitySet("Cities");
            IEdmEntityType         cityType             = model.EntityTypes().Single(e => e.Name == "CityType");
            IEdmProperty           cityNameProperty     = cityType.Properties().Single(e => e.Name == "Name");
            IEdmNavigationProperty policeStationNavProp = cityType.NavigationProperties().Single(e => e.Name == "PoliceStation");
            IEdmOperationImport    primitiveCollectionResultOperation = model.EntityContainer.FindOperationImports("PrimitiveCollectionResultOperation").Single();
            IEdmOperationImport    serviceOp1 = model.EntityContainer.FindOperationImports("ServiceOperation1").Single();

            bool isRequest          = testConfig.IsRequest;
            bool isJsonLightRequest = isRequest && testConfig.Format == ODataFormat.Json;

            switch (payloadKind)
            {
            case ODataPayloadKind.Feed:
            {
                return(PayloadBuilder.EntitySet().WithTypeAnnotation(cityType).ExpectedEntityType(cityType, citySet));
            }

            case ODataPayloadKind.Entry:
            {
                return(PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).WithTypeAnnotation(cityType).ExpectedEntityType(cityType, citySet));
            }

            case ODataPayloadKind.Property:
                return(PayloadBuilder.PrimitiveProperty(isJsonLightRequest ? string.Empty : null, "SomeCityValue").ExpectedProperty(cityType, "Name"));

            case ODataPayloadKind.EntityReferenceLink:
                return(PayloadBuilder.DeferredLink("http://odata.org/entityreferencelink").ExpectedNavigationProperty(citySet, cityType, "PoliceStation"));

            case ODataPayloadKind.EntityReferenceLinks:
                return(PayloadBuilder.LinkCollection().Item(PayloadBuilder.DeferredLink("http://odata.org/entityreferencelink")).ExpectedNavigationProperty((EdmEntitySet)citySet, (EdmEntityType)cityType, "CityHall"));

            case ODataPayloadKind.Value:
                return(PayloadBuilder.PrimitiveValue("PrimitiveValue"));

            case ODataPayloadKind.BinaryValue:
                return(PayloadBuilder.PrimitiveValue(new byte[] { 0, 0, 1, 1 }));

            case ODataPayloadKind.Collection:
                return(PayloadBuilder.PrimitiveCollection().CollectionName(null).ExpectedFunctionImport((EdmOperationImport)primitiveCollectionResultOperation));

            case ODataPayloadKind.ServiceDocument:
                Debug.Assert(!isRequest, "Not supported in requests.");
                return(new ServiceDocumentInstance().Workspace(PayloadBuilder.Workspace()));

            case ODataPayloadKind.MetadataDocument:
                Debug.Assert(!isRequest, "Not supported in requests.");
                throw new NotImplementedException();

            case ODataPayloadKind.Error:
                Debug.Assert(!isRequest, "Not supported in requests.");
                return(PayloadBuilder.Error("ErrorCode"));

            case ODataPayloadKind.Parameter:
                // build parameter payload based on model definition
                var parameterPayload           = new ComplexInstance(null, false);
                ODataPayloadElement a          = PayloadBuilder.PrimitiveValue(123).WithTypeAnnotation(EdmCoreModel.Instance.GetInt32(false));
                ODataPayloadElement b          = PayloadBuilder.PrimitiveValue("stringvalue").WithTypeAnnotation(EdmCoreModel.Instance.GetString(false));
                PrimitiveProperty   parametera = new PrimitiveProperty("a", "Edm.Integer", ((PrimitiveValue)a).ClrValue);
                PrimitiveProperty   parameterb = new PrimitiveProperty("b", "Edm.String", ((PrimitiveValue)b).ClrValue);
                parameterPayload.Add(parametera);
                parameterPayload.Add(parameterb);
                parameterPayload.ExpectedFunctionImport((EdmOperationImport)serviceOp1);
                return(parameterPayload);

            case ODataPayloadKind.Unsupported:      // fall through
            default:
                throw new NotSupportedException();
            }
        }
Esempio n. 13
0
        public void ElementValueTest()
        {
            // TODO: Add test cases for ATOM metadata once it's implemented
            // Note that we don't test EPM here which we could do as well, although if we test ATOM metadata, then EPM uses almost the same code path.
            var targetsForEmptyString = new ElementValueTestTarget[]
            {
                // Property value
                new ElementValueTestTarget
                {
                    PayloadElement = (value, xmlValueCreator) =>
                                     PayloadBuilder.PrimitiveProperty(null, value).XmlRepresentation(xmlValueCreator("<m:value>{0}</m:value>", value))
                },
                // Error code
                new ElementValueTestTarget
                {
                    PayloadElement = (value, xmlValueCreator) =>
                                     PayloadBuilder.Error().Code(value).XmlRepresentation(xmlValueCreator("<m:error><m:code>{0}</m:code></m:error>", value))
                },
                // Error message
                new ElementValueTestTarget
                {
                    PayloadElement = (value, xmlValueCreator) =>
                                     PayloadBuilder.Error().Code("code").Message(value).XmlRepresentation(xmlValueCreator("<m:error><m:code>code</m:code><m:message>{0}</m:message></m:error>", value))
                },
                // Inner error message
                new ElementValueTestTarget
                {
                    PayloadElement = (value, xmlValueCreator) =>
                                     PayloadBuilder.Error().InnerError(PayloadBuilder.InnerError().Message(value)).XmlRepresentation(xmlValueCreator("<m:error><m:innererror><m:message>{0}</m:message></m:innererror></m:error>", value))
                },
                // Inner error type name
                new ElementValueTestTarget
                {
                    PayloadElement = (value, xmlValueCreator) =>
                                     PayloadBuilder.Error().InnerError(PayloadBuilder.InnerError().TypeName(value)).XmlRepresentation(xmlValueCreator("<m:error><m:innererror><m:type>{0}</m:type></m:innererror></m:error>", value))
                },
                // Inner error stacktrace
                new ElementValueTestTarget
                {
                    PayloadElement = (value, xmlValueCreator) =>
                                     PayloadBuilder.Error().InnerError(PayloadBuilder.InnerError().StackTrace(value)).XmlRepresentation(xmlValueCreator("<m:error><m:innererror><m:stacktrace>{0}</m:stacktrace></m:innererror></m:error>", value))
                },
            };

            var targetsForNonEmptyString = new ElementValueTestTarget[]
            {
                // Entity ID
                new ElementValueTestTarget
                {
                    PayloadElement = (value, xmlValueCreator) =>
                                     PayloadBuilder.Entity().Id(value).XmlRepresentation(xmlValueCreator("<entry><id>{0}</id></entry>", value))
                },
                // Feed ID
                new ElementValueTestTarget
                {
                    PayloadElement = (value, xmlValueCreator) =>
                                     PayloadBuilder.EntitySet().AtomId(value).XmlRepresentation(xmlValueCreator("<feed><id>{0}</id></feed>", value))
                }
            };

            var targets =
                SetValueForTarget(
                    new string[]
            {
                string.Empty
            },
                    targetsForEmptyString)
                .Concat(SetValueForTarget(
                            new string[]
            {
                "urn:id"
            },
                            targetsForNonEmptyString.Concat(targetsForEmptyString)));

            var values = new ElementValueTestValue[]
            {
                // Just a simple string with no xml:space
                new ElementValueTestValue
                {
                    XmlValueCreator = (template, value) => string.Format(CultureInfo.InvariantCulture, template, value)
                },
                // Comments and PIS before and after with no xml:space
                new ElementValueTestValue
                {
                    XmlValueCreator = (template, value) => string.Format(CultureInfo.InvariantCulture, template,
                                                                         "<!--before-->" + value + "<!--after-->")
                },
                // Insignificant whitespace before and after
                new ElementValueTestValue
                {
                    XmlValueCreator = (template, value) => string.Format(CultureInfo.InvariantCulture, template,
                                                                         "   <?before?>" + value + "<!--after-->\n\t")
                },
                // Comments, PI and whitespace in the middle
                new ElementValueTestValue
                {
                    XmlValueCreator = (template, value) =>
                    {
                        if (value.Length < 2)
                        {
                            return(string.Format(CultureInfo.InvariantCulture, template, value));
                        }
                        int    splitIndex = value.Length / 2;
                        string firstPart  = value.Substring(0, splitIndex);
                        string secondPart = value.Substring(splitIndex);
                        return(string.Format(CultureInfo.InvariantCulture, template,
                                             firstPart + "<!--middle-->  \n\t<?middle?>" + secondPart));
                    }
                },
                // Element before causes a failure
                new ElementValueTestValue
                {
                    XmlValueCreator = (template, value) => string.Format(CultureInfo.InvariantCulture, template,
                                                                         "<some/>" + value),
                    ExpectedException = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element")
                },
                // Element after causes a failure
                new ElementValueTestValue
                {
                    XmlValueCreator = (template, value) => string.Format(CultureInfo.InvariantCulture, template,
                                                                         value + "<some/>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element")
                }
            };

            var testDescriptors = targets.SelectMany(target => values.Select(value =>
            {
                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = target.PayloadElement(value.XmlValueCreator),
                    ExpectedException = value.ExpectedException
                });
            }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 14
0
        public void DuplicatePropertyNamesTest()
        {
            PropertyInstance primitiveProperty = PayloadBuilder.PrimitiveProperty("DuplicateProperty", 42);
            PropertyInstance complexProperty   = PayloadBuilder.Property("DuplicateProperty",
                                                                         PayloadBuilder.ComplexValue("TestModel.DuplicateComplexType").PrimitiveProperty("Name", "foo"));
            PropertyInstance collectionProperty = PayloadBuilder.Property("DuplicateProperty",
                                                                          PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.String")).WithTypeAnnotation(EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetString(false))));

            PropertyInstance[] allProperties = new[] { primitiveProperty, complexProperty, collectionProperty };
            PropertyInstance[] propertiesWithPossibleDuplication = new[] { primitiveProperty, complexProperty };
            PropertyInstance[] propertiesWithNoDuplication       = new[] { collectionProperty };

            IEnumerable <DuplicatePropertySet> duplicatePropertySets;

            // Those which may allow duplication
            duplicatePropertySets = propertiesWithPossibleDuplication
                                    .Variations(2).Select(properties => new DuplicatePropertySet {
                Properties = properties, DuplicationPotentiallyAllowed = true
            });

            // Then for each in those which don't allow duplication try it against all the others
            duplicatePropertySets = duplicatePropertySets.Concat(propertiesWithNoDuplication.SelectMany(
                                                                     propertyWithNoDuplication => allProperties.SelectMany(otherProperty =>
                                                                                                                           new[]
            {
                new DuplicatePropertySet {
                    Properties = new [] { propertyWithNoDuplication, otherProperty }, DuplicationPotentiallyAllowed = false
                },
                new DuplicatePropertySet {
                    Properties = new [] { otherProperty, propertyWithNoDuplication }, DuplicationPotentiallyAllowed = false
                },
            })));

            this.CombinatorialEngineProvider.RunCombinations(
                duplicatePropertySets,
                new bool[] { false, true },
                new bool[] { true, false },
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (duplicatePropertySet, allowDuplicateProperties, useMetadata, testConfiguration) =>
            {
                EdmModel model  = new EdmModel();
                var complexType = model.ComplexType("DuplicateComplexType");
                complexType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String);
                model.Fixup();

                PropertyInstance firstProperty  = duplicatePropertySet.Properties.ElementAt(0);
                PropertyInstance secondProperty = duplicatePropertySet.Properties.ElementAt(1);

                // Non-metadata reading is not possible in JSON
                if (!useMetadata && (testConfiguration.Format == ODataFormat.Json))
                {
                    return;
                }

                // If we will have metadata then we can only allow combinations of the same kind
                if (useMetadata)
                {
                    if (firstProperty.ElementType != secondProperty.ElementType)
                    {
                        return;
                    }
                }

                // Copy the test config
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                if (allowDuplicateProperties)
                {
                    testConfiguration.MessageReaderSettings.EnableODataServerBehavior();
                }

                // Create a descriptor with the first property
                PayloadReaderTestDescriptor testDescriptor = new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = firstProperty,
                    PayloadEdmModel = useMetadata ? model : null
                };

                // Now generate entity around it
                testDescriptor = testDescriptor.InComplexValue(5, 5);

                // Now add the second property to it
                ((ComplexInstance)testDescriptor.PayloadElement).Add(secondProperty);

                // [Astoria-ODataLib-Integration] Parsing of URLs on OData recognized places may fail, but Astoria server doesn't
                // Server does not read named stream links for Atom payload therefore the expected payload needs to be normalized
                if (testConfiguration.Format == ODataFormat.Atom)
                {
                    testDescriptor.ExpectedResultNormalizers.Add(config => (payloadElement => WcfDsServerPayloadElementNormalizer.Normalize(payloadElement, ODataFormat.Atom, testDescriptor.PayloadEdmModel as EdmModel)));
                }

                // We expect failure only if we don't allow duplicates or if the property kind doesn't allow duplicates ever
                if ((!duplicatePropertySet.DuplicationPotentiallyAllowed || !allowDuplicateProperties))
                {
                    testDescriptor.ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed", "DuplicateProperty");
                }

                IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
                {
                    testDescriptor.InProperty("TopLevelProperty"),
                    testDescriptor.InProperty("ComplexProperty").InEntity(2, 2),
                    testDescriptor.InCollection(5, 5).InProperty("TopLevelCollection"),
                };

                this.CombinatorialEngineProvider.RunCombinations(
                    testDescriptors,
                    td =>
                {
                    var property = td.PayloadElement as PropertyInstance;
                    if (property != null && testConfiguration.Format == ODataFormat.Atom)
                    {
                        property.Name = null;
                    }
                    td.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 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);
            });
        }
Esempio n. 17
0
        public void ComplexValueWithMetadataTest()
        {
            // Use some standard complex value payloads first
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = PayloadReaderTestDescriptorGenerator.CreateComplexValueTestDescriptors(this.Settings, true);

            // Add metadata validation tests
            EdmModel model            = new EdmModel();
            var      innerComplexType = model.ComplexType("InnerComplexType");

            innerComplexType.AddStructuralProperty("name", EdmCoreModel.Instance.GetString(true));

            var complexType = model.ComplexType("ComplexType");

            complexType.AddStructuralProperty("number", EdmPrimitiveTypeKind.Int32);
            complexType.AddStructuralProperty("string", EdmCoreModel.Instance.GetString(true));
            complexType.AddStructuralProperty("complex", MetadataUtils.ToTypeReference(innerComplexType, true));

            var entityType = model.EntityType("EntityType");

            entityType.KeyProperty("Id", EdmCoreModel.Instance.GetInt32(false));
            model.Fixup();

            // Test that different types of properties not present in the metadata all fail
            IEnumerable <PropertyInstance> undeclaredPropertyTestCases = new PropertyInstance[]
            {
                PayloadBuilder.PrimitiveProperty("undeclared", 42),
                PayloadBuilder.Property("undeclared", PayloadBuilder.ComplexValue(innerComplexType.FullName())),
                PayloadBuilder.Property("undeclared", PayloadBuilder.PrimitiveMultiValue(EntityModelUtils.GetCollectionTypeName("Edm.Int32"))),
                PayloadBuilder.Property("undeclared", PayloadBuilder.ComplexMultiValue(EntityModelUtils.GetCollectionTypeName("TestModel.InnerComplexType"))),
            };

            testDescriptors = testDescriptors.Concat(
                undeclaredPropertyTestCases.Select(tc =>
            {
                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue(complexType.FullName()).WithTypeAnnotation(complexType)
                                     .Property(tc),
                    PayloadEdmModel = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "undeclared", "TestModel.ComplexType"),
                });
            }));

            testDescriptors = testDescriptors.Concat(new[]
            {
                // Property which should take typename not from value but from the parent metadata
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue(complexType.FullName()).WithTypeAnnotation(complexType)
                                     .Property("complex", PayloadBuilder.ComplexValue(innerComplexType.FullName()).PrimitiveProperty("name", null)
                                               .JsonRepresentation("{ \"name\" : null }").XmlRepresentation("<d:name m:null=\"true\" />")
                                               .AddAnnotation(new SerializationTypeNameTestAnnotation()
                    {
                        TypeName = null
                    })),
                    PayloadEdmModel = model,
                },
                // Property which is declared in the metadata but with a different type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue(complexType.FullName()).WithTypeAnnotation(complexType)
                                     .Property("complex", PayloadBuilder.ComplexValue(complexType.FullName())),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncompatibleType", "TestModel.ComplexType", "TestModel.InnerComplexType"),
                },
                // Property which is declared in the metadata but with a wrong kind
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.ComplexValue(complexType.FullName()).WithTypeAnnotation(complexType)
                                     .Property("complex", PayloadBuilder.ComplexValue(entityType.FullName())),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_IncorrectTypeKind", "TestModel.EntityType", "Complex", "Entity"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.ComplexValue("").WithTypeAnnotation(complexType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", string.Empty)
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.ComplexValue("TestModel.NonExistant").WithTypeAnnotation(complexType),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_UnrecognizedTypeName", "TestModel.NonExistant"),
                },
            });

            // Wrap the complex type in a property
            testDescriptors = testDescriptors
                              .Select((td, index) => new PayloadReaderTestDescriptor(td)
            {
                PayloadDescriptor = td.PayloadDescriptor.InProperty("propertyName" + index)
            })
                              .SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            // Handcrafted cases
            testDescriptors = testDescriptors.Concat(new[]
            {
                // Top-level complex property without expected type
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = PayloadBuilder.Property("property", PayloadBuilder.ComplexValue(complexType.FullName()).PrimitiveProperty("number", 42)),
                    PayloadEdmModel = model
                },
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                var property = testDescriptor.PayloadElement as PropertyInstance;
                if (property != null && testConfiguration.Format == ODataFormat.Atom)
                {
                    property.Name = null;
                }
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 18
0
        private static void SetToNull(ComplexInstance complexInstance, string propertyName)
        {
            PropertyInstance nullProperty = PayloadBuilder.PrimitiveProperty(propertyName, null);

            complexInstance.Properties = complexInstance.Properties.ToList().Select(p => p.Name == propertyName ? nullProperty : p);
        }
Esempio n. 19
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 NoMetadataTest()
        {
            EdmModel model     = new EdmModel();
            var      container = new EdmEntityContainer("TestModel", "DefaultContainer");

            model.AddElement(container);

            var testDescriptors = new[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.EntitySet(),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.EntitySet(),
                    SkipTestConfiguration = tc => tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.EntitySet(),
                    PayloadEdmModel       = model,
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_NoEntitySetForRequest"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.Entity(),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.Entity(),
                    SkipTestConfiguration = tc => tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.Entity(),
                    PayloadEdmModel       = model,
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_NoEntitySetForRequest"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.PrimitiveProperty("propertyName", 42),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.Property("propertyName", PayloadBuilder.ComplexValue()),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.Property("propertyName", PayloadBuilder.PrimitiveMultiValue()),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.PrimitiveCollection(),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.PrimitiveCollection(),
                    SkipTestConfiguration = tc => tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.PrimitiveCollection(),
                    //PayloadModel = model,
                    PayloadEdmModel       = model,
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ItemTypeRequiredForCollectionReaderInRequests"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.ComplexCollection(),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.ComplexCollection(),
                    SkipTestConfiguration = tc => tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.ComplexCollection(),
                    PayloadEdmModel       = model,
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ItemTypeRequiredForCollectionReaderInRequests"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.ServiceDocument().Workspace(PayloadBuilder.Workspace()),
                    SkipTestConfiguration = tc => tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.DeferredLink("http://odata.org/deferred"),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.DeferredLink("http://odata.org/deferred"),
                    SkipTestConfiguration = tc => tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.LinkCollection(),
                    SkipTestConfiguration = tc => tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightDeserializer_ContextLinkNotFoundAsFirstProperty"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.ComplexValue(),
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataJsonLightInputContext_ModelRequiredForReading"),
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement        = PayloadBuilder.ComplexValue(),
                    PayloadEdmModel       = model,
                    SkipTestConfiguration = tc => !tc.IsRequest,
                    ExpectedException     = ODataExpectedExceptions.ArgumentNullException("ODataJsonLightInputContext_OperationCannotBeNullForCreateParameterReader", "operation")
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }