public void DeferredLinkTest()
        {
            IEdmModel model    = Test.OData.Utils.Metadata.TestModels.BuildTestModel();
            var       cityType = model.FindType("TestModel.CityType");

            Debug.Assert(cityType != null, "cityType != null");

            // TODO: add test cases that use relative URIs

            // Few hand-crafted payloads
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                // Single deferred link
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).WithTypeAnnotation(cityType)
                                        .NavigationProperty("CityHall", "http://odata.org/CityHall"),
                    PayloadEdmModel = model
                },

                // Multiple deferred links
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).WithTypeAnnotation(cityType)
                                        .NavigationProperty("CityHall", "http://odata.org/CityHall")
                                        .NavigationProperty("DOL", "http://odata.org/DOL"),
                    PayloadEdmModel = model
                },

                // Multiple deferred links with primitive properties in between
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").WithTypeAnnotation(cityType)
                                        .Property("Id", PayloadBuilder.PrimitiveValue(1))
                                        .NavigationProperty("CityHall", "http://odata.org/CityHall")
                                        .Property("Name", PayloadBuilder.PrimitiveValue("Vienna"))
                                        .NavigationProperty("DOL", "http://odata.org/DOL"),
                    PayloadEdmModel = model
                },
            };

            // Add standard deferred link payloads
            testDescriptors = testDescriptors.Concat(PayloadReaderTestDescriptorGenerator.CreateDeferredNavigationLinkTestDescriptors(this.Settings, true));

            // Generate interesting payloads around the entry
            testDescriptors = testDescriptors.SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                // Deferred links are response only.
                // TODO: Reenable Json Light support
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => !tc.IsRequest && tc.Format == ODataFormat.Atom),
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 2
0
        public void EntryAtomMetadataCategoryTest()
        {
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = this.CreateCategoryTestDescriptors(PayloadBuilder.Entity(), "entry");

            // Add entry-specific category test case.
            testDescriptors = testDescriptors.Concat(
                new []
            {
                // Category which also conveys the entity type in OData.
                // If the category element is used to convey entity type it's stored separately.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity("TestModel.TypeName")
                                     .XmlRepresentation("<entry><category term='TestModel.TypeName' scheme='http://docs.oasis-open.org/odata/ns/scheme' label='someLabel' /></entry>")
                                     .AtomCategoryWithTypeName("TestModel.TypeName", "someLabel")
                },
                // Category with type name, with no term - null TypeName reported
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.Entity()
                                     .XmlRepresentation("<entry><category scheme='http://docs.oasis-open.org/odata/ns/scheme' label='someLabel' /></entry>")
                                     .AtomCategoryWithTypeName(null, "someLabel")
                },
            });

            this.RunAtomMetadataReaderTests(testDescriptors);
        }
Esempio n. 3
0
        /// <summary>
        /// Generates an open entity set containing entities with different amounts of primitive open properties.
        /// </summary>
        /// <param name="model">The entity model. The method will modify the model and call Fixup().</param>
        /// <param name="withTypeNames">True if the payloads should specify type names.</param>
        /// <param name="primitiveValueFilter">A function for excluding primitives which are unsupported for open properties.</param>
        /// <returns>The open entity set containing entities with primitive open properties.</returns>
        public static ODataPayloadElement CreateOpenEntitySetInstance(EdmModel model, bool withTypeNames, Func <PrimitiveValue, bool> primitiveValueFilter)
        {
            ExceptionUtilities.CheckArgumentNotNull(model, "model");
            ExceptionUtilities.CheckArgumentNotNull(primitiveValueFilter, "primitiveValueFilter");

            var edmEntityType = new EdmEntityType("TestModel", "OpenEntityType", baseType: null, isAbstract: false, isOpen: true);

            model.AddElement(edmEntityType);
            edmEntityType.AddStructuralProperty("Name", EdmPrimitiveTypeKind.String, true);

            var container = new EdmEntityContainer("TestModel", "DefaultContainer");

            container.AddEntitySet("OpenEntityTypes", edmEntityType);
            model.AddElement(container);

            var feed = PayloadBuilder.EntitySet().WithTypeAnnotation(edmEntityType);

            string entityTypeName = withTypeNames ? edmEntityType.FullName() : null;

            var primitiveValues = TestValues.CreatePrimitiveValuesWithMetadata(true).Where(p => primitiveValueFilter(p));

            int idx = 0;

            for (int i = 0; i <= primitiveValues.Count(); ++i)
            {
                var entityInstance = PayloadBuilder.Entity(entityTypeName).PrimitiveProperty("Name", Guid.NewGuid().ToString());
                foreach (var property in primitiveValues.Take(i))
                {
                    entityInstance.PrimitiveProperty("Property" + (idx++), property.ClrValue);
                }
                feed.Add(entityInstance);
            }
            return(feed);
        }
Esempio n. 4
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,
                });
            }
Esempio n. 5
0
        public void SingletonRelativeNavigationLinkInRequestTest()
        {
            IEnumerable <NavigationLinkTestCase> testCases = new[]
            {
                new NavigationLinkTestCase
                {
                    DebugDescription           = "Binding link with relative URI - no odata.context annotation in payload.",
                    Json                       = "\"" + JsonLightUtils.GetPropertyAnnotationName("PoliceStation", JsonLightConstants.ODataBindAnnotationName) + "\":\"yyy\"",
                    ExpectedEntity             = PayloadBuilder.Entity().NavigationProperty("PoliceStation", "yyy"),
                    ExpectedIsCollectionValues = new Dictionary <string, bool?> {
                        { "PoliceStation", false }
                    },
                },
            };

            this.RunNavigationLinkInRequestTest(testCases);

            testCases = new[]
            {
                new NavigationLinkTestCase
                {
                    DebugDescription           = "Binding link with relative URI - with odata.context annotation in payload.",
                    Json                       = "\"" + JsonLightUtils.GetPropertyAnnotationName("PoliceStation", JsonLightConstants.ODataBindAnnotationName) + "\":\"yyy\"",
                    ExpectedEntity             = PayloadBuilder.Entity().NavigationProperty("PoliceStation", "yyy"),
                    ExpectedException          = null,
                    ExpectedIsCollectionValues = new Dictionary <string, bool?> {
                        { "PoliceStation", false }
                    },
                },
            };

            this.RunNavigationLinkInRequestTest(testCases, withMetadataAnnotation: true);
        }
Esempio n. 6
0
        public void CollectionRelativeNavigationLinkInRequestTest()
        {
            IEnumerable <NavigationLinkTestCase> testCases = new[]
            {
                new NavigationLinkTestCase
                {
                    DebugDescription           = "Invalid binding item value - relative uri",
                    Json                       = "\"" + JsonLightUtils.GetPropertyAnnotationName("CityHall", JsonLightConstants.ODataBindAnnotationName) + "\":[\"yyy\"]",
                    ExpectedEntity             = PayloadBuilder.Entity().NavigationProperty("CityHall", "yyy"),
                    ExpectedException          = null,
                    ExpectedIsCollectionValues = new Dictionary <string, bool?> {
                        { "CityHall", true }
                    },
                },
            };

            this.RunNavigationLinkInRequestTest(testCases);

            testCases = new[]
            {
                new NavigationLinkTestCase
                {
                    DebugDescription           = "Invalid binding item value - relative uri",
                    Json                       = "\"" + JsonLightUtils.GetPropertyAnnotationName("CityHall", JsonLightConstants.ODataBindAnnotationName) + "\":[\"yyy\"]",
                    ExpectedEntity             = PayloadBuilder.Entity().NavigationProperty("CityHall", "yyy"),
                    ExpectedException          = null,
                    ExpectedIsCollectionValues = new Dictionary <string, bool?> {
                        { "CityHall", true }
                    },
                },
            };

            this.RunNavigationLinkInRequestTest(testCases, withMetadataAnnotation: true);
        }
        public void StreamPropertyTestWithRelativeLinkUris()
        {
            IEdmModel model = TestModels.BuildTestModel();

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

            this.RunStreamPropertyTest(model, testCases);
        }
            public PayloadReaderTestDescriptor ToTestDescriptor(PayloadReaderTestDescriptor.Settings settings, IEdmModel model, bool throwOnUndeclaredPropertyForNonOpenType)
            {
                var cityType = model.FindDeclaredType("TestModel.CityType").ToTypeReference();
                var cities = model.EntityContainer.FindEntitySet("Cities");
                EntityInstance entity = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1)
                    .ExpectedEntityType(cityType, cities)
                    .JsonRepresentation(
                        "{" +
                            "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.DefaultContainer.Cities()/$entity\"," +
                            "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.CityType\"," +
                            "\"Id\":1," +
                            this.Json +
                        "}");
                foreach (PropertyInstance property in this.ExpectedEntity.Properties)
                {
                    entity.Add(property.DeepCopy());
                }

                ExpectedException expectedException = this.ExpectedException;
                if (throwOnUndeclaredPropertyForNonOpenType)
                {
                    expectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "UndeclaredProperty", "TestModel.CityType");
                }

                return new PayloadReaderTestDescriptor(settings)
                {
                    DebugDescription = this.DebugDescription,
                    PayloadElement = entity,
                    PayloadEdmModel = model,
                    ExpectedException = expectedException
                };
            }
Esempio n. 9
0
        public void CollectionOfComplexInstanceTest()
        {
            EdmModel model       = new EdmModel();
            var      complexType = new EdmComplexType("TestModel", "ComplexType").Property("Name", EdmPrimitiveTypeKind.String, true);

            model.AddElement(complexType);
            var owningType = new EdmEntityType("TestModel", "OwningType");

            owningType.AddKeys(owningType.AddStructuralProperty("ID", EdmCoreModel.Instance.GetInt32(false)));
            owningType.AddStructuralProperty("PrimitiveCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)));
            owningType.AddStructuralProperty("ComplexCollection", EdmCoreModel.GetCollection(complexType.ToTypeReference()));
            model.AddElement(owningType);
            model.Fixup();

            var primitiveMultiValue = PayloadBuilder.PrimitiveMultiValue("Collection(Edm.Int32)").Item(42).Item(43);
            var complexMultiValue   = PayloadBuilder.EntitySet(new EntityInstance[]
            {
                PayloadBuilder.Entity("TestModel.ComplexType")
                .PrimitiveProperty("Name", "Value")
                .AddAnnotation(new SerializationTypeNameTestAnnotation()
                {
                    TypeName = null
                })
                .IsComplex(true)
            })
                                      .JsonRepresentation("[{\"Name\":\"Value\"}]")
                                      .AddAnnotation(new SerializationTypeNameTestAnnotation()
            {
                TypeName = null
            });

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Simple complex collection.",
                    PayloadEdmModel  = model,
                    PayloadElement   = PayloadBuilder.Property("ComplexCollection", complexMultiValue)
                                       .ExpectedProperty(owningType, "ComplexCollection"),
                    ExpectedResultPayloadElement = tc => tc.IsRequest
                        ? PayloadBuilder.Property(string.Empty, complexMultiValue)
                        : PayloadBuilder.Property("ComplexCollection", complexMultiValue)
                },
            };

            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. 10
0
 /// <summary>
 /// Constructs test descriptors which test entry ATOM metadata elements of type atomTextConstruct ("rights", "title", and "summary").
 /// </summary>
 /// <param name="elementName">The name of the ATOM metadata element to create test descriptors for.</param>
 /// <param name="addTextAtomMetadataAnnotation">A Func which takes an entity instance, the value of the text construct element,
 /// and the name of the text construct kind and produces the entity instance with the added text construct ATOM metadata.</param>
 /// <returns>A list of test descriptors.</returns>
 private IEnumerable <PayloadReaderTestDescriptor> CreateTextConstructEntryTestDescriptors(
     string elementName,
     Func <EntityInstance, string, string, EntityInstance> addTextAtomMetadataAnnotation)
 {
     return(this.CreateTextConstructTestDescriptors(
                PayloadBuilder.Entity(),
                "entry",
                elementName,
                addTextAtomMetadataAnnotation));
 }
        public void JsonLightTaupoSerializerFeedTest()
        {
            var testCases = new JsonLightSerializerTestCase[]
            {
                // Empty feed
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.EntitySet().WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson   = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          """ + JsonLightConstants.ODataValuePropertyName + @""":[]
                        }"
                },
                // Empty feed with count and next link
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.EntitySet()
                                     .InlineCount(42)
                                     .NextLink("http://odata.org/next")
                                     .WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataCountAnnotationName + @""":42,
                          """ + JsonLightConstants.ODataValuePropertyName + @""":[],
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataNextLinkAnnotationName + @""":""http://odata.org/next""
                        }"
                },
                // Feed with single entry
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.EntitySet()
                                     .Append(PayloadBuilder.Entity().PrimitiveProperty("ID", (long)42))
                                     .WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          """ + JsonLightConstants.ODataValuePropertyName + @""":[
                            { ""ID"":42 }
                          ]
                        }"
                },
            };

            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. 12
0
        public void FeedWithSubContextUriTest()
        {
            IEdmModel           model           = Test.OData.Utils.Metadata.TestModels.BuildTestModel();
            IEdmEntityContainer container       = model.FindEntityContainer("DefaultContainer");
            IEdmEntitySet       citiesEntitySet = container.FindEntitySet("Cities");
            IEdmType            cityType        = model.FindType("TestModel.CityType") as IEdmType;

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Feed containing entries with and without sub context uri",
                    PayloadElement   = PayloadBuilder
                                       .EntitySet(new EntityInstance[]
                    {
                        PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        }),
                        PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 2).AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        }),
                    })
                                       .XmlRepresentation(
                        "<feed m:context=\"http://odata.org/test/$metadata#Cities(Id)\">" +
                        "<entry m:context=\"http://odata.org/test/$metadata#Cities(Id)/$entity\">" +
                        "<content type=\"application/xml\">" +
                        "<m:properties>" +
                        "<d:Id>1</d:Id>" +
                        "</m:properties>" +
                        "</content>" +
                        "</entry>" +
                        "<entry>" +
                        "<content type=\"application/xml\">" +
                        "<m:properties>" +
                        "<d:Id>2</d:Id>" +
                        "</m:properties>" +
                        "</content>" +
                        "</entry>" +
                        "</feed>")
                                       .ExpectedEntityType(cityType, citiesEntitySet),
                    PayloadEdmModel = model
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
        private void RunStreamPropertyTest(IEdmModel model, IEnumerable <StreamPropertyTestCase> testCases)
        {
            var cityType = model.FindDeclaredType("TestModel.CityType").ToTypeReference();
            var cities   = model.EntityContainer.FindEntitySet("Cities");
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = testCases.Select(testCase =>
            {
                IEdmTypeReference entityType = testCase.OwningEntityType ?? cityType;
                EntityInstance entity        = PayloadBuilder.Entity(entityType.FullName()).PrimitiveProperty("Id", 1)
                                               .JsonRepresentation(
                    "{" +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.DefaultContainer.Cities/" + entityType.FullName() + "()/$entity\"," +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"" + entityType.FullName() + "\"," +
                    "\"Id\": 1," +
                    testCase.Json +
                    "}")
                                               .ExpectedEntityType(entityType, cities);
                foreach (NamedStreamInstance streamProperty in testCase.ExpectedEntity.Properties.OfType <NamedStreamInstance>())
                {
                    entity.Add(streamProperty.DeepCopy());
                }

                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = testCase.DebugDescription,
                    PayloadEdmModel = model,
                    PayloadElement = entity,
                    ExpectedException = testCase.ExpectedException,
                    SkipTestConfiguration = tc => testCase.OnlyResponse ? tc.IsRequest : false,
                    InvalidOnRequest = testCase.InvalidOnRequest
                });
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                if (testConfiguration.IsRequest && testDescriptor.InvalidOnRequest)
                {
                    testDescriptor = new PayloadReaderTestDescriptor(testDescriptor)
                    {
                        ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightResourceDeserializer_StreamPropertyInRequest")
                    };
                }

                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                var testConfigClone = new ReaderTestConfiguration(testConfiguration);
                testConfigClone.MessageReaderSettings.BaseUri = null;

                testDescriptor.RunTest(testConfigClone);
            });
        }
Esempio n. 14
0
        public void InvalidXmlBaseUriHandlingTest()
        {
            string absoluteUri = "http://odata.org/relative";

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

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

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


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

                td.RunTest(testConfiguration);
            });
        }
Esempio n. 15
0
        public void DataServiceVersionHeaderTest()
        {
            EdmModel model = (EdmModel)Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            var entry = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1)
                        .ExpandedNavigationProperty("CityHall", PayloadBuilder.EntitySet());

            DataServiceVersionTestDescriptor[] testDescriptors = new DataServiceVersionTestDescriptor[]
            {
                // valid entry with DSV 4.0
                new DataServiceVersionTestDescriptor(this.Settings)
                {
                    PayloadElement        = entry,
                    PayloadEdmModel       = model,
                    DataServiceVersion    = ODataVersion.V4.ToText(),
                    SkipTestConfiguration = tc => tc.Version != ODataVersion.V4,
                },
                // invalid DSV (negative number)
                new DataServiceVersionTestDescriptor(this.Settings)
                {
                    PayloadElement     = entry,
                    PayloadEdmModel    = model,
                    DataServiceVersion = "-1.0",
                    ExpectedException  = ODataExpectedExceptions.ODataException("ODataUtils_UnsupportedVersionHeader", "-1.0"),
                },
                // invalid DSV (unsupported positive number)
                new DataServiceVersionTestDescriptor(this.Settings)
                {
                    PayloadElement     = entry,
                    PayloadEdmModel    = model,
                    DataServiceVersion = "12345.0",
                    ExpectedException  = ODataExpectedExceptions.ODataException("ODataUtils_UnsupportedVersionHeader", "12345.0"),
                },
                // invalid DSV (NaN)
                new DataServiceVersionTestDescriptor(this.Settings)
                {
                    PayloadElement     = entry,
                    PayloadEdmModel    = model,
                    DataServiceVersion = "foo",
                    ExpectedException  = ODataExpectedExceptions.ODataException("ODataUtils_UnsupportedVersionHeader", "foo"),
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 16
0
        public void FeedWithEntriesTest()
        {
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                // Single empty entry (empty element)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.EntitySet().Append(PayloadBuilder.Entity())
                                     .XmlRepresentation("<feed><entry/></feed>")
                },
                // Single empty entry (full end element)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.EntitySet().Append(PayloadBuilder.Entity())
                                     .XmlRepresentation("<feed><entry></entry></feed>")
                },
                // Two entries (first empty element)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.EntitySet().Append(PayloadBuilder.Entity().ETag("etag1"), PayloadBuilder.Entity().ETag("etag2"))
                                     .XmlRepresentation("<feed><entry m:etag='etag1'/><entry m:etag='etag2'></entry></feed>")
                },
                // Two entries (first full end element)
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.EntitySet().Append(PayloadBuilder.Entity().ETag("etag1"), PayloadBuilder.Entity().ETag("etag2"))
                                     .XmlRepresentation("<feed><entry m:etag='etag1'></entry><entry m:etag='etag2'/></feed>")
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = PayloadBuilder.EntitySet().InlineCount(42).NextLink("http://odata.org/next").AtomId("urn:id")
                                     .Append(PayloadBuilder.Entity(), PayloadBuilder.Entity().ETag("second")),
                    SkipTestConfiguration = tc => tc.IsRequest
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 17
0
        /// <summary>
        /// Generates various payloads with different link properties set to the specified cross reference value.
        /// </summary>
        /// <param name="crossReferenceLink">The cross reference link values to set on each payload.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        /// <returns>The payloads.</returns>
        private static IEnumerable <ODataPayloadElement> GeneratePayloadElementsWithCrossReferenceLinks(string crossReferenceLink, ReaderTestConfiguration testConfiguration)
        {
            List <ODataPayloadElement> payloadElements = new List <ODataPayloadElement>();

            // Entry with edit link
            payloadElements.Add(PayloadBuilder.Entity("TestModel.Address").PrimitiveProperty("Zip", 12345).WithEditLink(crossReferenceLink));

            // Entry with self link
            payloadElements.Add(PayloadBuilder.Entity("TestModel.Address").PrimitiveProperty("Zip", 98765).WithSelfLink(crossReferenceLink));

            // Entry with deferred navprop
            payloadElements.Add(PayloadBuilder.Entity("TestModel.CityType").DeferredNavigationProperty("CityHall", PayloadBuilder.DeferredLink(crossReferenceLink)));

            // Entry with expanded navprop
            payloadElements.Add(PayloadBuilder.Entity("TestModel.CityType").ExpandedNavigationProperty("PoliceStation", PayloadBuilder.Entity("TestModel.OfficeType").PrimitiveProperty("Id", 0), crossReferenceLink));

            if (!testConfiguration.IsRequest)
            {
                // Entry with deferred navprop with association link
                payloadElements.Add(PayloadBuilder.Entity("TestModel.CityType").DeferredNavigationProperty("DOL", PayloadBuilder.DeferredLink("http://odata.org"), PayloadBuilder.DeferredLink(crossReferenceLink)));

                // Entry with expanded navprop with association link
                payloadElements.Add(PayloadBuilder.Entity("TestModel.CityType").NavigationProperty(
                                        PayloadBuilder.ExpandedNavigationProperty("PoliceStation", PayloadBuilder.Entity("TestModel.OfficeType").PrimitiveProperty("Id", 0), "http://odata.org", crossReferenceLink)));

                // Entry with stream property with read link
                payloadElements.Add(PayloadBuilder.Entity("TestModel.CityType").StreamProperty("Skyline", crossReferenceLink));

                // Entry with stream property with edit link
                payloadElements.Add(PayloadBuilder.Entity("TestModel.CityType").StreamProperty("Skyline", null, crossReferenceLink));

                // Feed with multiple entries referencing same link
                payloadElements.Add(PayloadBuilder.EntitySet(
                                        new[]
                {
                    PayloadBuilder.Entity("TestModel.CityType").DeferredNavigationProperty("CityHall", PayloadBuilder.DeferredLink(crossReferenceLink)),
                    PayloadBuilder.Entity("TestModel.CityType").DeferredNavigationProperty("CityHall", PayloadBuilder.DeferredLink(crossReferenceLink)),
                }));
            }

            return(payloadElements);
        }
Esempio n. 18
0
        private static IEnumerable <PayloadReaderTestDescriptor> CreateUndeclaredPropertyBehaviorKindStreamPropertyTestDescriptors(bool throwOnUndeclaredPropertyForNonOpenType, PayloadReaderTestDescriptor.Settings settings)
        {
            IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                // Undeclared stream property with read-link only.
                new PayloadReaderTestDescriptor(settings)
                {
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).StreamProperty("UndeclaredProperty", "http://odata.org/readlink"),
                    PayloadEdmModel   = model,
                    ExpectedException = throwOnUndeclaredPropertyForNonOpenType
                                            ? ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "UndeclaredProperty", "TestModel.CityType")
                                            : null
                },
                // Undeclared stream property with edit-link only.
                new PayloadReaderTestDescriptor(settings)
                {
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).StreamProperty("UndeclaredProperty", null, "http://odata.org/editlink"),
                    PayloadEdmModel   = model,
                    ExpectedException = throwOnUndeclaredPropertyForNonOpenType
                                            ? ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "UndeclaredProperty", "TestModel.CityType")
                                            : null
                },
                // Undeclared stream property with all properties.
                new PayloadReaderTestDescriptor(settings)
                {
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).StreamProperty("UndeclaredProperty", "http://odata.org/readlink", "http://odata.org/editlink", "stream/content", "stream:etag"),
                    PayloadEdmModel   = model,
                    ExpectedException = throwOnUndeclaredPropertyForNonOpenType
                                            ? ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "UndeclaredProperty", "TestModel.CityType")
                                            : null
                },
            };

            return(testDescriptors);
        }
        public void EntityReferenceLinkTest()
        {
            IEdmModel model    = Test.OData.Utils.Metadata.TestModels.BuildTestModel();
            var       cityType = model.FindType("TestModel.CityType");

            Debug.Assert(cityType != null, "cityType != null");

            // TODO: add test cases that use relative URIs

            // Few hand-crafted payloads
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                // Single entity reference link for a singleton
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").WithTypeAnnotation(cityType)
                                        .Property(PayloadBuilder.NavigationProperty("PoliceStation", "http://odata.org/PoliceStation").IsCollection(false)),
                    PayloadEdmModel = model
                },
                // Single entity reference link for a collection
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").WithTypeAnnotation(cityType)
                                        .Property(PayloadBuilder.NavigationProperty("CityHall", "http://odata.org/CityHall").IsCollection(true)),
                    PayloadEdmModel = model
                },

                // Multiple entity reference links
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").WithTypeAnnotation(cityType)
                                        .Property(PayloadBuilder.NavigationProperty("CityHall", "http://odata.org/CityHall").IsCollection(true))
                                        .Property(PayloadBuilder.NavigationProperty("PoliceStation", "http://odata.org/PoliceStation").IsCollection(false)),
                    PayloadEdmModel = model
                },

                // Multiple entity reference links with primitive properties in between
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType").WithTypeAnnotation(cityType)
                                        .Property("Id", PayloadBuilder.PrimitiveValue(1))
                                        .Property(PayloadBuilder.NavigationProperty("CityHall", "http://odata.org/CityHall").IsCollection(true))
                                        .Property("Name", PayloadBuilder.PrimitiveValue("Vienna"))
                                        .Property(PayloadBuilder.NavigationProperty("DOL", "http://odata.org/DOL").IsCollection(true)),
                    PayloadEdmModel = model
                },
            };

            // Generate interesting payloads around the entry
            testDescriptors = testDescriptors.SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                // Entity reference links are request only.
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void UndeclaredStreamPropertyTests()
        {
            IEdmModel model = TestModels.BuildTestModel();

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

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

                    // These descriptors are already tailored specifically for Json Light and
                    // do not require normalization.
                    testDescriptor.TestDescriptorNormalizers.Clear();
                    testDescriptor.RunTest(testConfiguration);
                });
        }
Esempio n. 21
0
        public void InStreamErrorInEntriesTest()
        {
            EdmModel edmModel = new EdmModel();

            EdmEntityContainer defaultContainer = new EdmEntityContainer("TestModel", "DefaultContainer");

            edmModel.AddElement(defaultContainer);

            var dummyType = new EdmEntityType("TestModel", "DummyEntryType");

            dummyType.AddKeys(dummyType.AddStructuralProperty("Id", EdmCoreModel.Instance.GetInt32(/*isNullable*/ false)));
            edmModel.AddElement(dummyType);

            var dummySet = defaultContainer.AddEntitySet("DummySet", dummyType);

            var errorCases = new []
            {
                new
                {
                    Json = "{{ \"{0}\": {{ \"code\": \"my-error-code\" }} }}",
                    ExpectedException = ODataExpectedExceptions.ODataErrorException(new ODataError {
                        ErrorCode = "my-error-code"
                    })
                },
                new
                {
                    Json = "{{ \"{0}\": {{ \"message\": \"my-error-message\" }} }}",
                    ExpectedException = ODataExpectedExceptions.ODataErrorException(new ODataError {
                        Message = "my-error-message"
                    })
                },
                new
                {
                    Json = "{{ \"{0}\": {{ \"code\": \"my-error-code\", \"message\": \"my-error-message\" }} }}",
                    ExpectedException = ODataExpectedExceptions.ODataErrorException(new ODataError {
                        ErrorCode = "my-error-code", Message = "my-error-message"
                    })
                },
                new
                {
                    Json = "{{ \"{0}\": {{ \"code\": \"my-error-code\", \"innererror\": {{ \"message\": \"my-inner-error\" }} }} }}",
                    ExpectedException = ODataExpectedExceptions.ODataErrorException(new ODataError {
                        ErrorCode = "my-error-code", InnerError = new ODataInnerError {
                            Message = "my-inner-error"
                        }
                    })
                },
                new
                {
                    Json = "{{ \"{0}\": {{ \"innererror\": {{ \"message\": \"my-inner-error\" }} }} }}",
                    ExpectedException = ODataExpectedExceptions.ODataErrorException(new ODataError {
                        InnerError = new ODataInnerError {
                            Message = "my-inner-error"
                        }
                    })
                },
                new
                {
                    Json = "{{ \"{0}\": {{ \"message\":  \"my-error-message\", \"innererror\": {{ \"message\": \"my-inner-error\" }} }} }}",
                    ExpectedException = ODataExpectedExceptions.ODataErrorException(new ODataError {
                        Message = "my-error-message", InnerError = new ODataInnerError {
                            Message = "my-inner-error"
                        }
                    })
                },
                new
                {
                    Json = "{{ \"{0}\": {{ \"code\": \"my-error-code\", \"message\": \"my-error-message\", \"innererror\": {{ \"message\": \"my-inner-error\" }} }} }}",
                    ExpectedException = ODataExpectedExceptions.ODataErrorException(new ODataError {
                        ErrorCode = "my-error-code", Message = "my-error-message", InnerError = new ODataInnerError {
                            Message = "my-inner-error"
                        }
                    })
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                errorCases,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (errorCase, testConfiguration) =>
            {
                string errorElementName = JsonLightConstants.ODataErrorPropertyName;

                var testCase = new JsonPayloadErrorTestCase
                {
                    Json = PayloadBuilder.Entity("TestModel.DummyEntryType")
                           .JsonRepresentation(string.Format(errorCase.Json, errorElementName))
                           .ExpectedEntityType(dummyType, dummySet),
                    EdmModel = edmModel,
                    ExpectedExceptionFunc = (tCase, tConfig) => errorCase.ExpectedException,
                };

                var descriptor = testCase.ToEdmPayloadReaderTestDescriptor(this.PayloadTestDescriptorSettings, this.PayloadExpectedResultSettings);

                // NOTE: payload generation is not supported for JSON Light yet
                var descriptors = testConfiguration.Format == ODataFormat.Json
                        ? new PayloadReaderTestDescriptor[] { descriptor }
                        : this.PayloadGenerator.GenerateReaderPayloads(descriptor);

                this.CombinatorialEngineProvider.RunCombinations(
                    descriptors,
                    testDescriptor => testDescriptor.RunTest(testConfiguration));
            });
        }
        public void StreamPropertyTest()
        {
            IEdmModel model = TestModels.BuildTestModel();

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

            this.RunStreamPropertyTest(model, testCases);
        }
        public void UndeclaredValuePropertyTests()
        {
            IEdmModel model = TestModels.BuildTestModel();

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

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

                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 24
0
        public void ReadODataOperationErrorTest()
        {
            IEdmModel           model     = Test.OData.Utils.Metadata.TestModels.BuildTestModel();
            IEdmEntityContainer container = model.FindEntityContainer("DefaultContainer");
            IEdmEntitySet       cities    = container.FindEntitySet("Cities");
            IEdmType            cityType  = model.FindType("TestModel.CityType");

            var testCases = new[]
            {
                new
                {
                    DebugDescription  = "Metadata reference property not supported in request.",
                    Json              = "\"#operationMetadata\":{}",
                    SkipForRequest    = false,
                    SkipForResponse   = true,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_MetadataReferencePropertyInRequest"),
                },
                new
                {
                    DebugDescription  = "Duplicated metadata reference property names.",
                    Json              = "\"#TestModel.PrimitiveResultOperation\":{}, \"#TestModel.PrimitiveResultOperation\":{}",
                    SkipForRequest    = true,
                    SkipForResponse   = false,
                    ExpectedException = ODataExpectedExceptions.ODataException("DuplicatePropertyNamesChecker_DuplicatePropertyNamesNotAllowed", "#TestModel.PrimitiveResultOperation"),
                },
                new
                {
                    DebugDescription  = "Operation value must start with start array or start object.",
                    Json              = "\"#TestModel.PrimitiveResultOperation\":null",
                    SkipForRequest    = true,
                    SkipForResponse   = false,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonOperationsDeserializerUtils_OperationsPropertyMustHaveObjectValue", "#TestModel.PrimitiveResultOperation", "PrimitiveValue"),
                },
                new
                {
                    DebugDescription  = "Operation value can only have at most 1 title.",
                    Json              = "\"#TestModel.PrimitiveResultOperation\":{\"title\":\"PrimitiveResultOperation\",\"title\":\"PrimitiveResultOperation\"}",
                    SkipForRequest    = true,
                    SkipForResponse   = false,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_MultipleOptionalPropertiesInOperation", "title", "#TestModel.PrimitiveResultOperation"),
                },
                new
                {
                    DebugDescription  = "Operation value can only have at most 1 target.",
                    Json              = "\"#TestModel.PrimitiveResultOperation\":{\"target\":\"http://www.example.com/foo\",\"target\":\"http://www.example.com/foo\"}",
                    SkipForRequest    = true,
                    SkipForResponse   = false,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_MultipleOptionalPropertiesInOperation", "target", "#TestModel.PrimitiveResultOperation"),
                },
                new
                {
                    DebugDescription  = "Operation values inside an array must have target.",
                    Json              = "\"#TestModel.PrimitiveResultOperation\":[{},{}]",
                    SkipForRequest    = true,
                    SkipForResponse   = false,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataJsonLightEntryAndFeedDeserializer_OperationMissingTargetProperty", "#TestModel.PrimitiveResultOperation"),
                },
            };

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = testCases.Select(
                t => new PayloadReaderTestDescriptor(this.Settings)
            {
                IgnorePropertyOrder = true,
                DebugDescription    = t.DebugDescription,
                PayloadEdmModel     = model,
                PayloadElement      = PayloadBuilder.Entity("TestModel.CityType")
                                      .JsonRepresentation(
                    "{" +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#DefaultContainer.Cities/$entity\"," +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.CityType\"," +
                    "\"Id\":1," +
                    t.Json +
                    "}")
                                      .ExpectedEntityType(cityType, cities),
                ExpectedException     = t.ExpectedException,
                SkipTestConfiguration = tc => tc.IsRequest ? t.SkipForRequest : t.SkipForResponse
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                if (testConfiguration.IsRequest)
                {
                    testDescriptor = new PayloadReaderTestDescriptor(testDescriptor);
                    testDescriptor.ExpectedResultNormalizers.Add(tc => RemoveOperationsNormalizer.Normalize);
                }

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

                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 25
0
        public void ReadBindableODataOperationTest()
        {
            EdmModel           model            = Test.OData.Utils.Metadata.TestModels.BuildTestModel() as EdmModel;
            EdmEntityContainer defaultContainer = model.FindEntityContainer("DefaultContainer") as EdmEntityContainer;
            IEdmEntitySet      cities           = defaultContainer.FindEntitySet("Cities");
            IEdmEntityType     cityType         = (IEdmEntityType)model.FindDeclaredType("TestModel.CityType");

            var addressInCity1BindableFunctionWithOverload = defaultContainer.AddActionAndActionImport(model, "AddressInCity", EdmCoreModel.Instance.GetBoolean(isNullable: true), null, true);
            var addressInCity1Action = addressInCity1BindableFunctionWithOverload.Action.AsEdmAction();

            addressInCity1Action.AddParameter("city", new EdmEntityTypeReference(cityType, isNullable: true));
            addressInCity1Action.AddParameter("address", EdmCoreModel.Instance.GetString(isNullable: true));

            var funcWithOneParamImport = defaultContainer.AddFunctionAndFunctionImport(model, "BindableFunctionWithOverload", EdmCoreModel.Instance.GetInt32(true), null, false, true);
            var funcWithOneParam       = funcWithOneParamImport.Function.AsEdmFunction();

            funcWithOneParam.AddParameter("p1", new EdmEntityTypeReference(cityType, isNullable: true));

            var funcWithTwoParamImport = defaultContainer.AddFunctionAndFunctionImport(model, "BindableFunctionWithOverload", EdmCoreModel.Instance.GetInt32(true), null, false, true);
            var funcWithTwoParam       = funcWithTwoParamImport.Function.AsEdmFunction();

            funcWithTwoParam.AddParameter("p1", new EdmEntityTypeReference(cityType, isNullable: true));
            funcWithTwoParam.AddParameter("p2", EdmCoreModel.Instance.GetString(isNullable: true));

            var testCases = new[]
            {
                new
                {
                    DebugDescription = "No always bindable operations in payload",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.AddressInCity", Title = "TestModel.AddressInCity", Target = "http://odata.org/test/Cities(1)/TestModel.AddressInCity"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("()"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("(p2)"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload(p2=@p2)"
                        },
                    }
                },
                new
                {
                    DebugDescription = "Always bindable operations from default container and always bindable function group in payload",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{},\"#TestModel.AddressInCity\":{},\"#TestModel.BindableFunctionWithOverload\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.AddressInCity", Title = "TestModel.AddressInCity", Target = "http://odata.org/test/Cities(1)/TestModel.AddressInCity"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload", Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload"
                        },
                    }
                },
                new
                {
                    DebugDescription = "Always bindable operations and function group with namespace from default container in payload",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{},\"#TestModel.AddressInCity\":{},\"#TestModel.BindableFunctionWithOverload\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.AddressInCity", Title = "TestModel.AddressInCity", Target = "http://odata.org/test/Cities(1)/TestModel.AddressInCity"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload", Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload"
                        },
                    }
                },
                new
                {
                    DebugDescription = "Always bindable operations from non-default container and function overload with 1 param in payload",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{},\"#TestModel.AddressInCity\":{},\"#TestModel.BindableFunctionWithOverload(p1)\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.AddressInCity", Title = "TestModel.AddressInCity", Target = "http://odata.org/test/Cities(1)/TestModel.AddressInCity"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("()"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("(p2)"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload(p2=@p2)"
                        },
                    }
                },
                new
                {
                    DebugDescription = "Always bindable operations and function overload with 2 params, with namespace from non-default container in payload",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{},\"#TestModel.AddressInCity\":{},\"#TestModel.BindableFunctionWithOverload(p1)\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.AddressInCity", Title = "TestModel.AddressInCity", Target = "http://odata.org/test/Cities(1)/TestModel.AddressInCity"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("()"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("(p2)"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload(p2=@p2)"
                        },
                    }
                },
                new
                {
                    DebugDescription = "All of the always bindable operations in payload",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{},\"#TestModel.AddressInCity\":{}," +
                                       "\"#TestModel.BindableFunctionWithOverload(p1)\":{},\"#TestModel.BindableFunctionWithOverload(p1,p2)\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.AddressInCity", Title = "TestModel.AddressInCity", Target = "http://odata.org/test/Cities(1)/TestModel.AddressInCity"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("()"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("(p2)"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload(p2=@p2)"
                        },
                    }
                },
                new
                {
                    DebugDescription = "All of the always bindable operations with namespace in payload",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{},\"#TestModel.AddressInCity\":{}," +
                                       "\"#TestModel.BindableFunctionWithOverload(p1)\":{},\"#TestModel.BindableFunctionWithOverload(p1,p2)\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.AddressInCity", Title = "TestModel.AddressInCity", Target = "http://odata.org/test/Cities(1)/TestModel.AddressInCity"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("()"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload"
                        },
                        new ServiceOperationDescriptor {
                            IsFunction = true, Metadata = "http://odata.org/test/$metadata#TestModel.BindableFunctionWithOverload" + Uri.EscapeDataString("(p2)"), Title = "TestModel.BindableFunctionWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.BindableFunctionWithOverload(p2=@p2)"
                        },
                    }
                },
            };

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = testCases.Select(
                t => new PayloadReaderTestDescriptor(this.Settings)
            {
                DebugDescription = t.DebugDescription,
                PayloadEdmModel  = model,
                PayloadElement   = PayloadBuilder.Entity("TestModel.CityType")
                                   .JsonRepresentation(
                    "{" +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#DefaultContainer.Cities/$entity\"," +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.CityType\"," +
                    "\"Id\":1," +
                    "\"Name\":\"New York\"," +
                    t.Json +
                    "}")
                                   .ExpectedEntityType(cityType, cities),
                ExpectedResultPayloadElement = (tc) =>
                {
                    var entityInstance = PayloadBuilder.Entity("TestModel.CityType").
                                         PrimitiveProperty("Id", 1).
                                         PrimitiveProperty("Name", "New York").
                                         StreamProperty("Skyline", "http://odata.org/test/Cities(1)/Skyline", "http://odata.org/test/Cities(1)/Skyline").
                                         NavigationProperty("CityHall", "http://odata.org/test/Cities(1)/CityHall").
                                         NavigationProperty("DOL", "http://odata.org/test/Cities(1)/DOL").
                                         NavigationProperty("PoliceStation", "http://odata.org/test/Cities(1)/PoliceStation");
                    foreach (var op in t.ExpectedServiceOperationDescriptor)
                    {
                        entityInstance.OperationDescriptor(op);
                    }
                    return(entityInstance);
                },
                SkipTestConfiguration = tc => tc.IsRequest
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                if (testConfiguration.IsRequest)
                {
                    testDescriptor = new PayloadReaderTestDescriptor(testDescriptor);
                    testDescriptor.ExpectedResultNormalizers.Add(tc => RemoveOperationsNormalizer.Normalize);
                }

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

                testDescriptor.RunTest(testConfiguration);
            });
        }
Esempio n. 26
0
        public void ReadODataOperationTest()
        {
            IEdmModel           model     = Test.OData.Utils.Metadata.TestModels.BuildTestModel();
            IEdmEntityContainer container = model.FindEntityContainer("DefaultContainer");
            IEdmEntitySet       cities    = container.FindEntitySet("Cities");
            IEdmType            cityType  = model.FindType("TestModel.CityType");

            var testCases = new[]
            {
                new
                {
                    DebugDescription = "Single operation without title and target",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{}",
                    ExpectedServiceOperationDescriptor = new[] { new ServiceOperationDescriptor {
                                                                     IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                                                                 } }
                },
                new
                {
                    DebugDescription = "Single operation with title",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{\"title\":\"PrimitiveResultOperation\"}",
                    ExpectedServiceOperationDescriptor = new[] { new ServiceOperationDescriptor {
                                                                     IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                                                                 } }
                },
                new
                {
                    DebugDescription = "Single operation with target",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{\"target\":\"http://odata.org/test/PrimitiveResultOperation\"}",
                    ExpectedServiceOperationDescriptor = new[] { new ServiceOperationDescriptor {
                                                                     IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/PrimitiveResultOperation"
                                                                 } }
                },
                new
                {
                    DebugDescription = "Single operation with title and target",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{\"title\":\"PrimitiveResultOperation\", \"target\":\"http://odata.org/test/PrimitiveResultOperation\"}",
                    ExpectedServiceOperationDescriptor = new[] { new ServiceOperationDescriptor {
                                                                     IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "PrimitiveResultOperation", Target = "http://odata.org/test/PrimitiveResultOperation"
                                                                 } }
                },
                new
                {
                    DebugDescription = "Single operation with 2 targets",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":[{\"target\":\"http://odata.org/test/PrimitiveResultOperation1\"},{\"target\":\"http://odata.org/test/PrimitiveResultOperation2\"}]",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/PrimitiveResultOperation1"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/PrimitiveResultOperation2"
                        }
                    }
                },
                new
                {
                    DebugDescription = "Single operation with 2 targets and 2 titles",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":[{\"title\":\"title1\",\"target\":\"http://odata.org/test/PrimitiveResultOperation1\"},{\"title\":\"title2\",\"target\":\"http://odata.org/test/PrimitiveResultOperation2\"}]",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "title1", Target = "http://odata.org/test/PrimitiveResultOperation1"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "title2", Target = "http://odata.org/test/PrimitiveResultOperation2"
                        }
                    }
                },
                new
                {
                    DebugDescription = "Two operations, one without target or title, the other with with 2 targets",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":[{\"target\":\"http://odata.org/test/PrimitiveResultOperation1\"},{\"target\":\"http://odata.org/test/PrimitiveResultOperation2\"}]," +
                                       "\"#TestModel.ComplexResultOperation\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/PrimitiveResultOperation1"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/PrimitiveResultOperation2"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.ComplexResultOperation", Title = "TestModel.ComplexResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.ComplexResultOperation"
                        },
                    }
                },
                new
                {
                    DebugDescription = "Two operations, one with target and title, the other with 2 targets and 1 title",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":[{\"title\":\"PrimitiveResultOperation\",\"target\":\"http://odata.org/test/PrimitiveResultOperation1\"},{\"target\":\"http://odata.org/test/PrimitiveResultOperation2\"}]," +
                                       "\"#TestModel.ComplexResultOperation\":{\"title\":\"ComplexResultOperation\",\"target\":\"http://odata.org/test/ComplexResultOperation\"}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "PrimitiveResultOperation", Target = "http://odata.org/test/PrimitiveResultOperation1"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "TestModel.PrimitiveResultOperation", Target = "http://odata.org/test/PrimitiveResultOperation2"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.ComplexResultOperation", Title = "ComplexResultOperation", Target = "http://odata.org/test/ComplexResultOperation"
                        }
                    }
                },
                new
                {
                    DebugDescription = "function group with overloads",
                    Json             = "\"#TestModel.FunctionImportWithOverload\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload", Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.FunctionImportWithOverload"
                        },
                    }
                },
                new
                {
                    DebugDescription = "function group with overloads and the overload with 0 parameter",
                    Json             = "\"#TestModel.FunctionImportWithOverload\":{}," +
                                       "\"#TestModel.FunctionImportWithOverload()\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload", Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.FunctionImportWithOverload"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload" + Uri.EscapeDataString("()"), Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.FunctionImportWithOverload"
                        },
                    }
                },
                new
                {
                    DebugDescription = "function group with overloads and the overload with 1 parameter",
                    Json             = "\"#TestModel.FunctionImportWithOverload\":{}," +
                                       "\"#TestModel.FunctionImportWithOverload(p1)\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload", Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.FunctionImportWithOverload"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload" + Uri.EscapeDataString("(p1)"), Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.FunctionImportWithOverload(p1=@p1)"
                        },
                    }
                },
                new
                {
                    DebugDescription = "three overloads of an operation, with 0, 1 and 2 parameters",
                    Json             = "\"#TestModel.FunctionImportWithOverload()\":{}," +
                                       "\"#TestModel.FunctionImportWithOverload(p1)\":{}," +
                                       "\"#TestModel.FunctionImportWithOverload(p1,p2)\":{}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload" + Uri.EscapeDataString("()"), Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.FunctionImportWithOverload"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload" + Uri.EscapeDataString("(p1)"), Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.FunctionImportWithOverload(p1=@p1)"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload" + Uri.EscapeDataString("(p1,p2)"), Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/Cities(1)/TestModel.FunctionImportWithOverload(p1=@p1,p2=@p2)"
                        },
                    }
                },
                new
                {
                    DebugDescription = "Two overloads of an operation, one with target and title, the other with 2 targets and 1 title",
                    Json             = "\"#TestModel.FunctionImportWithOverload()\":[{\"title\":\"FunctionImportWithOverload\",\"target\":\"http://odata.org/test/FunctionImportWithOverload/Target1\"},{\"target\":\"http://odata.org/test/FunctionImportWithOverload/Target2\"}]," +
                                       "\"#TestModel.FunctionImportWithOverload(p1)\":{\"title\":\"FunctionImportWithOverload(p1)\",\"target\":\"http://odata.org/test/FunctionImportWithOverload(p1=@p1)\"}",
                    ExpectedServiceOperationDescriptor = new[]
                    {
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload" + Uri.EscapeDataString("()"), Title = "FunctionImportWithOverload", Target = "http://odata.org/test/FunctionImportWithOverload/Target1"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload" + Uri.EscapeDataString("()"), Title = "TestModel.FunctionImportWithOverload", Target = "http://odata.org/test/FunctionImportWithOverload/Target2"
                        },
                        new ServiceOperationDescriptor {
                            IsAction = false, Metadata = "http://odata.org/test/$metadata#TestModel.FunctionImportWithOverload" + Uri.EscapeDataString("(p1)"), Title = "FunctionImportWithOverload(p1)", Target = "http://odata.org/test/FunctionImportWithOverload(p1=@p1)"
                        }
                    }
                },
                new
                {
                    DebugDescription = "The operation that is not in model",
                    Json             = "\"#TestModel.UnknownOperation()\":[{\"title\":\"FunctionImportWithOverload\",\"target\":\"http://odata.org/test/FunctionImportWithOverload/Target1\"}]",
                    ExpectedServiceOperationDescriptor = new ServiceOperationDescriptor[] {},
                },
                new
                {
                    DebugDescription = "Single operation with title and a operation that is not in model",
                    Json             = "\"#TestModel.PrimitiveResultOperation\":{\"title\":\"PrimitiveResultOperation\"}," +
                                       "\"#TestModel.UnknownOperation\":{\"title\":\"UnknownOperation\"}",
                    ExpectedServiceOperationDescriptor = new[] { new ServiceOperationDescriptor {
                                                                     IsAction = true, Metadata = "http://odata.org/test/$metadata#TestModel.PrimitiveResultOperation", Title = "PrimitiveResultOperation", Target = "http://odata.org/test/Cities(1)/TestModel.PrimitiveResultOperation"
                                                                 } }
                },
            };

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = testCases.Select(
                t => new PayloadReaderTestDescriptor(this.Settings)
            {
                DebugDescription = t.DebugDescription,
                PayloadEdmModel  = model,
                PayloadElement   = PayloadBuilder.Entity("TestModel.CityType")
                                   .JsonRepresentation(
                    "{" +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#DefaultContainer.Cities/$entity\"," +
                    "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataTypeAnnotationName + "\":\"TestModel.CityType\"," +
                    "\"Id\":1," +
                    "\"Name\":\"cityTypeName\"," +
                    t.Json +
                    "}")
                                   .ExpectedEntityType(cityType, cities),
                ExpectedResultPayloadElement = (tc) =>
                {
                    var entityInstance = PayloadBuilder.Entity("TestModel.CityType").
                                         PrimitiveProperty("Id", 1).
                                         PrimitiveProperty("Name", "cityTypeName").
                                         StreamProperty("Skyline", "http://odata.org/test/Cities(1)/Skyline", "http://odata.org/test/Cities(1)/Skyline").
                                         NavigationProperty("CityHall", "http://odata.org/test/Cities(1)/CityHall").
                                         NavigationProperty("DOL", "http://odata.org/test/Cities(1)/DOL").
                                         NavigationProperty("PoliceStation", "http://odata.org/test/Cities(1)/PoliceStation");
                    foreach (var op in t.ExpectedServiceOperationDescriptor)
                    {
                        entityInstance.OperationDescriptor(op);
                    }
                    return(entityInstance);
                },
                SkipTestConfiguration = tc => tc.IsRequest
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                if (testConfiguration.IsRequest)
                {
                    testDescriptor = new PayloadReaderTestDescriptor(testDescriptor);
                    testDescriptor.ExpectedResultNormalizers.Add(tc => RemoveOperationsNormalizer.Normalize);
                }

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

                testDescriptor.RunTest(testConfiguration);
            });
        }
        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);
            });
        }
        public void UndeclaredNavigationLinkTests()
        {
            IEdmModel model = TestModels.BuildTestModel();

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

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

                    // These descriptors are already tailored specifically for Json Light and
                    // do not require normalization.
                    testDescriptor.TestDescriptorNormalizers.Clear();
                    testDescriptor.RunTest(testConfiguration);
                });
        }
Esempio n. 29
0
        public void FeedReaderWithSubContextUriTest()
        {
            IEdmModel           model            = Test.OData.Utils.Metadata.TestModels.BuildTestModel();
            IEdmEntityContainer container        = model.FindEntityContainer("DefaultContainer");
            IEdmEntitySet       citiesEntitySet  = container.FindEntitySet("Cities");
            IEdmType            cityType         = model.FindType("TestModel.CityType") as IEdmType;
            IEdmEntitySet       personsEntitySet = container.FindEntitySet("Persons");
            IEdmType            personType       = model.FindType("TestModel.Person") as IEdmType;

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new[]
            {
                #region Test cases
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Feed containing entries with and without sub context uri",
                    PayloadElement   = PayloadBuilder
                                       .EntitySet(new EntityInstance[]
                    {
                        PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        }),
                        PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 2).AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        }),
                    })
                                       .JsonRepresentation(
                        "{" +
                        "\"@odata.context\":\"http://odata.org/test/$metadata#Cities(Id)\"," +
                        "\"value\":[" +
                        "{" +
                        "\"@odata.context\":\"http://odata.org/test/$metadata#Cities/$entity\"," +
                        "\"Id\":1" +
                        "}," +
                        "{" +
                        "\"Id\":2" +
                        "}," +
                        "]" +
                        "}")
                                       .ExpectedEntityType(cityType, citiesEntitySet),
                    PayloadEdmModel = model
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Feed containing entries with expanded navigation properties with sub context uri",
                    PayloadElement   = PayloadBuilder
                                       .EntitySet(new EntityInstance[] {
                        PayloadBuilder
                        .Entity("TestModel.CityType")
                        .PrimitiveProperty("Id", 1)
                        .ExpandedNavigationProperty(
                            "CityHall",
                            PayloadBuilder.EntitySet(new EntityInstance[]
                        {
                            PayloadBuilder.Entity("TestModel.OfficeType").PrimitiveProperty("Id", 1).AddAnnotation(new SerializationTypeNameTestAnnotation()
                            {
                                TypeName = null
                            }),
                        }))
                        .AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        })
                    })
                                       .JsonRepresentation(
                        "{" +
                        "\"@odata.context\":\"http://odata.org/test/$metadata#Cities(Id)\"," +
                        "\"value\":[" +
                        "{" +
                        "\"@odata.context\":\"http://odata.org/test/$metadata#Cities(Id,CityHall(Id))/$entity\"," +
                        "\"Id\":1," +
                        "\"CityHall\":[" +
                        "{" +
                        "\"@odata.context\":\"http://odata.org/test/$metadata#Offices/$entity\"," +
                        "\"Id\":1" +
                        "}" +
                        "]" +
                        "}" +
                        "]" +
                        "}")
                                       .ExpectedEntityType(cityType, citiesEntitySet),
                    PayloadEdmModel = model
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Feed containg entries with mismatch sub context uri",
                    PayloadElement   = PayloadBuilder
                                       .EntitySet(new EntityInstance[]
                    {
                        PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 1).AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        }),
                    })
                                       .JsonRepresentation(
                        "{" +
                        "\"@odata.context\":\"http://odata.org/test/$metadata#Cities(Id)\"," +
                        "\"value\":[" +
                        "{" +
                        "\"@odata.context\":\"http://odata.org/test/$metadata#Offices/$entity\"," +
                        "\"Id\":1" +
                        "}," +
                        "]" +
                        "}")
                                       .ExpectedEntityType(cityType, citiesEntitySet),
                    PayloadEdmModel   = model,
                    ExpectedException = ODataExpectedExceptions.ODataException(
                        "ReaderValidationUtils_ContextUriValidationInvalidExpectedEntitySet",
                        "http://odata.org/test/$metadata#Offices/$entity",
                        "Offices",
                        "Cities")
                },

                /* TODO: Enable this case after updating SelectedPropertiesNode class to adapt to V4
                 * new PayloadReaderTestDescriptor(this.Settings)
                 * {
                 *  DebugDescription = "Empty feed without next link or inline count.",
                 *  PayloadElement = PayloadBuilder.EntitySet( new EntityInstance[]
                 *  {
                 *      PayloadBuilder.Entity("TestModel.CityType")
                 *          .PrimitiveProperty("Id", 1)
                 *          .NavigationProperty(new NavigationPropertyInstance("PoliceStation",null))
                 *          .AddAnnotation(new SerializationTypeNameTestAnnotation() { TypeName = null }),
                 *      PayloadBuilder.Entity("TestModel.CityType").PrimitiveProperty("Id", 2).AddAnnotation(new SerializationTypeNameTestAnnotation() { TypeName = null }),
                 *  })
                 *      .JsonRepresentation(
                 *          "{" +
                 *              "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#Collection(TestModel.CityType)\"," +
                 *              "\"" + JsonLightConstants.ODataValuePropertyName + "\":[" +
                 *                  "{" +
                 *                      "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.DefaultContainer.Cities/$entity\"," +
                 *                      "\"Id\":1" +
                 *                  "}," +
                 *                  "{" +
                 *                      "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#TestModel.DefaultContainer.Cities/$entity\"," +
                 *                      "\"Id\":2" +
                 *                  "}," +
                 *              "]" +
                 *          "}")
                 *      .ExpectedEntityType(cityType, citiesEntitySet),
                 *  PayloadEdmModel = model
                 * },
                 */
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    DebugDescription = "Empty feed without next link or inline count.",
                    PayloadElement   = PayloadBuilder.EntitySet(new EntityInstance[]
                    {
                        PayloadBuilder.Entity("TestModel.Person")
                        .PrimitiveProperty("Id", 1)
                        .ExpandedNavigationProperty(
                            "Friend",
                            PayloadBuilder.EntitySet(new EntityInstance[] {}))
                        .AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        }),
                        PayloadBuilder.Entity("TestModel.Person")
                        .PrimitiveProperty("Id", 2)
                        .ExpandedNavigationProperty(
                            "Friend",
                            PayloadBuilder.EntitySet(new EntityInstance[] {}))
                        .AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        }),
                        PayloadBuilder.Entity("TestModel.Person")
                        .PrimitiveProperty("Id", 3)
                        .ExpandedNavigationProperty(
                            "Friend",
                            PayloadBuilder.EntitySet(new EntityInstance[] {}))
                        .AddAnnotation(new SerializationTypeNameTestAnnotation()
                        {
                            TypeName = null
                        }),
                    })
                                       .JsonRepresentation(
                        "{" +
                        "\"@odata.context\":\"http://odata.org/test/$metadata#Collection(TestModel.Person)\"," +
                        "\"value\":[" +
                        "{" +
                        "\"@odata.context\":\"$metadata#TestModel.DefaultContainer.Persons/$entity\"," +
                        "\"Id\":1," +
                        "\"Friend\":[]" +
                        "}," +
                        "{" +
                        "\"@odata.context\":\"#Persons/$entity\"," +
                        "\"Id\":2," +
                        "\"Friend\":[]" +
                        "}," +
                        "{" +
                        "\"@odata.context\":\"#TestModel.Person\"," +
                        "\"Id\":3," +
                        "\"Friend\":[]" +
                        "}," +
                        "]" +
                        "}")
                                       .ExpectedEntityType(personType, personsEntitySet),
                    PayloadEdmModel = model
                },
                #endregion Test cases
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                if (testConfiguration.IsRequest && testDescriptor.ExpectedException != null)
                {
                    return;
                }

                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void ExpandedLinkTest()
        {
            IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            // TODO: add test cases that use relative URIs

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = PayloadReaderTestDescriptorGenerator.CreateDeferredNavigationLinkTestDescriptors(this.Settings, true);

            // Generate interesting payloads around the navigation property
            // Note that this will actually expand the deferred nav links as well.
            testDescriptors = testDescriptors.SelectMany(td => this.PayloadGenerator.GenerateReaderPayloads(td));

            IEnumerable <PayloadReaderTestDescriptor> customTestDescriptors = new PayloadReaderTestDescriptor[]
            {
                // Expanded null entry
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadEdmModel   = model,
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType")
                                        .PrimitiveProperty("Id", 1)
                                        .ExpandedNavigationProperty("PoliceStation", PayloadBuilder.NullEntity()),
                },
                // Expanded null entry after another expanded collection link
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadEdmModel   = model,
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType")
                                        .PrimitiveProperty("Id", 1)
                                        .ExpandedNavigationProperty("CityHall", PayloadBuilder.EntitySet())
                                        .ExpandedNavigationProperty("PoliceStation", PayloadBuilder.NullEntity()),
                },
                // incorrect type at related end
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadEdmModel   = model,
                    PayloadElement    = PayloadBuilder.Entity("TestModel.CityType")
                                        .PrimitiveProperty("Id", 1)
                                        .ExpandedNavigationProperty("PoliceStation", PayloadBuilder.Entity("TestModel.CityType")),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_EntryTypeNotAssignableToExpectedType", "TestModel.CityType", "TestModel.OfficeType"),
                },
                // Nested entry of depth 4 should fail because we set MaxNestingDepth = 3 below
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadEdmModel   = model,
                    PayloadElement    = PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 1),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_MaxDepthOfNestedEntriesExceeded", "3"),
                }.InEntryWithExpandedLink(true /* isSingleton */)
                .InEntryWithExpandedLink(true)
                .InEntryWithExpandedLink(true),

                // Nested entry of depth 4 within expanded feeds should fail
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadEdmModel   = model,
                    PayloadElement    = PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 1),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_MaxDepthOfNestedEntriesExceeded", "3"),
                }.InFeed()
                .InEntryWithExpandedLink(false /* isSingleton */)
                .InFeed()
                .InEntryWithExpandedLink(false)
                .InFeed()
                .InEntryWithExpandedLink(false),

                // Nested entry of depth 3 should succeed
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadEdmModel   = model,
                    PayloadElement    = PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 1)
                }.InEntryWithExpandedLink(true /* isSingleton */)
                .InEntryWithExpandedLink(true),

                // Nested entry of depth 3 within expanded feeds should succeed
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadEdmModel   = model,
                    PayloadElement    = PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 1)
                }.InFeed()
                .InEntryWithExpandedLink(false /* isSingleton */)
                .InFeed()
                .InEntryWithExpandedLink(false),

                // Expanded feed with a number of child entries greater than recursive depth limit should succeed.
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadDescriptor = new PayloadTestDescriptor(),
                    PayloadEdmModel   = model,
                    PayloadElement    = PayloadBuilder.EntitySet().Append(
                        PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 1),
                        PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 2),
                        PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 3),
                        PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 4),
                        PayloadBuilder.Entity("TestModel.Person").PrimitiveProperty("Id", 5)),
                }.InEntryWithExpandedLink(false /* isSingleton */)
                .InEntryWithExpandedLink(true),
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.Concat(customTestDescriptors),
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.MessageQuotas.MaxNestingDepth = 3;

                testDescriptor.RunTest(testConfiguration);
            });
        }