/// <summary>
        /// Creates a set of interesting entity reference link instances.
        /// </summary>
        /// <param name="settings">The test descriptor settings to use.</param>
        /// <returns>List of test descriptors with interesting entity reference link instances as payload.</returns>
        internal static IEnumerable <LinkCollection> CreateEntityReferenceLinksValues()
        {
            DeferredLink link1 = PayloadBuilder.DeferredLink("http://odata.org/deferred1");
            DeferredLink link2 = PayloadBuilder.DeferredLink("http://odata.org/deferred2");
            DeferredLink link3 = PayloadBuilder.DeferredLink("http://odata.org/deferred3");

            yield return(PayloadBuilder.LinkCollection());

            yield return(PayloadBuilder.LinkCollection().Item(link1));

            yield return(PayloadBuilder.LinkCollection().Item(link1).Item(link2).Item(link3));

            yield return(PayloadBuilder.LinkCollection().Item(link1).InlineCount(1));

            yield return(PayloadBuilder.LinkCollection().Item(link1).InlineCount(-1));

            yield return(PayloadBuilder.LinkCollection().Item(link1).NextLink("http://odata.org/nextlink"));

            yield return(PayloadBuilder.LinkCollection().Item(link1).InlineCount(1).NextLink("http://odata.org/nextlink"));

            yield return(PayloadBuilder.LinkCollection().Item(link1).Item(link2).Item(link3).InlineCount(1));

            yield return(PayloadBuilder.LinkCollection().Item(link1).Item(link2).Item(link3).InlineCount(-1));

            yield return(PayloadBuilder.LinkCollection().Item(link1).Item(link2).Item(link3).NextLink("http://odata.org/nextlink"));

            yield return(PayloadBuilder.LinkCollection().Item(link1).Item(link2).Item(link3).InlineCount(1).NextLink("http://odata.org/nextlink"));
        }
Esempio n. 2
0
        public void EntityReferenceLinksReadingBaseUriTest()
        {
            EdmModel model = (EdmModel)Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            model.Fixup();

            LinkCollection linkCollection = PayloadBuilder.LinkCollection();

            linkCollection.Add(PayloadBuilder.DeferredLink("http://odata.org/dummy"));
            linkCollection.Add(PayloadBuilder.DeferredLink("http://odata.org/dummy"));
            linkCollection.Add(PayloadBuilder.DeferredLink("http://odata.org/dummy"));

            this.CombinatorialEngineProvider.RunCombinations(
                payloadUris,
                baseUriValues,
                resolvers,
                new bool[] { false, true },
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (payloadUri, baseUriValue, resolver, runInBatch, testConfiguration) =>
            {
                Action <LinkCollection, Uri, ReaderTestConfiguration> setLinkAction =
                    (links, uri, testConfig) => links[1].UriString = UriToString(uri);
                this.RunBaseUriReadingTest(linkCollection, setLinkAction, model, payloadUri, baseUriValue, resolver, testConfiguration, runInBatch);
            });
        }
Esempio n. 3
0
        private static LinkCollection GetLinkCollection()
        {
            var collection = PayloadBuilder.LinkCollection();

            collection.Add(PayloadBuilder.DeferredLink("http://www.odata.org"));
            collection.Add(PayloadBuilder.DeferredLink("http://www.bubbles.org"));
            collection.Add(PayloadBuilder.DeferredLink("http://www.snowflakes.org"));
            return(collection);
        }
        public void EntityReferenceLinksMessageSizeLimitReadTest()
        {
            EdmModel model = Test.OData.Utils.Metadata.TestModels.BuildTestModel() as EdmModel;

            EdmEntityType cityType = model.FindDeclaredType("TestModel.CityType") as EdmEntityType;
            EdmEntitySet  citySet  = model.EntityContainersAcrossModels().Single().FindEntitySet("Cities") as EdmEntitySet;

            ODataPayloadElement payload = PayloadBuilder.LinkCollection()
                                          .Item(PayloadBuilder.DeferredLink("http://odata.org/erl1"))
                                          .Item(PayloadBuilder.DeferredLink("http://odata.org/erl2"))
                                          .Item(PayloadBuilder.DeferredLink("http://odata.org/erl3"))
                                          .ExpectedNavigationProperty(citySet, cityType, "CityHall");

            var testCases = new MessageSizeLimitTestCase[]
            {
                // Single byte size should fail
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = 1,
                    AtomSizes      = new RequestResponseSizes {
                        RequestSize = -1, ResponseSize = 337
                    },
                    JsonLightSizes = new RequestResponseSizes {
                        RequestSize = -1, ResponseSize = 216
                    },
                },
                // Small number should fail
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = 20,
                    AtomSizes      = new RequestResponseSizes {
                        RequestSize = -1, ResponseSize = 337
                    },
                    JsonLightSizes = new RequestResponseSizes {
                        RequestSize = -1, ResponseSize = 216
                    },
                },
                // Large number should work
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = 10000,
                },
                // Default should work
                new MessageSizeLimitTestCase
                {
                    MaxMessageSize = -1,
                },
            };

            this.RunAtomJsonMessageSizeLimitTests(model, payload, testCases, tc => tc.IsRequest);
        }
Esempio n. 5
0
        public void EntityReferenceLinksReadingNullUriTest()
        {
            EdmModel model = (EdmModel)Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            model.Fixup();

            LinkCollection linkCollection = PayloadBuilder.LinkCollection();

            linkCollection.Add(PayloadBuilder.DeferredLink(/*uri*/ null));
            linkCollection.Add(PayloadBuilder.DeferredLink(/*uri*/ null));
            linkCollection.Add(PayloadBuilder.DeferredLink(/*uri*/ null));

            this.CombinatorialEngineProvider.RunCombinations(
                baseUriValues,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (baseUriValue, testConfiguration) =>
            {
                // NOTE: In JSON, the value of the 'uri' property will be 'null' which is not allowed (and we expect an error)
                //       In ATOM, the HREF of an entity reference link is stored as element content and will thus be read as
                //       string.Empty even if the source link was null
                NullUriValueTestCase <LinkCollection> testCase = new NullUriValueTestCase <LinkCollection>
                {
                    SetNullUriAction =
                        (links, uri, testConfig) =>
                    {
                        links[0].UriString = null;
                        links[1].UriString = null;
                        links[2].UriString = null;
                    },
                    SetExpectedUriAction =
                        (links, uri, testConfig) =>
                    {
                        links[0].UriString = UriToString(uri);
                        links[1].UriString = UriToString(uri);
                        links[2].UriString = UriToString(uri);
                    }
                };

                this.RunNullUriReadingTest(linkCollection, testCase, model, baseUriValue, testConfiguration);
            });
        }
Esempio n. 6
0
            /// <summary>
            /// Visits an entity reference link collection.
            /// </summary>
            /// <param name="entityReferenceLinks">The entity reference link collection to visit.</param>
            protected override ODataPayloadElement VisitEntityReferenceLinks(ODataEntityReferenceLinks entityReferenceLinks)
            {
                ExceptionUtilities.CheckArgumentNotNull(entityReferenceLinks, "entityReferenceLinks");

                LinkCollection linkCollection = PayloadBuilder.LinkCollection()
                                                .InlineCount(entityReferenceLinks.Count)
                                                .NextLink(entityReferenceLinks.NextPageLink == null ? null : entityReferenceLinks.NextPageLink.OriginalString);

                IEnumerable <ODataEntityReferenceLink> links = entityReferenceLinks.Links;

                if (links != null)
                {
                    foreach (ODataEntityReferenceLink link in links)
                    {
                        DeferredLink deferredLink = (DeferredLink)this.Visit(link);
                        linkCollection.Add(deferredLink);
                    }
                }

                return(linkCollection);
            }
        public void NoMetadataTest()
        {
            EdmModel model     = new EdmModel();
            var      container = new EdmEntityContainer("TestModel", "DefaultContainer");

            model.AddElement(container);

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

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.JsonLightFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                // These descriptors are already tailored specifically for Json Light and
                // do not require normalization.
                testDescriptor.TestDescriptorNormalizers.Clear();
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void JsonLightTaupoSerializerEntityReferenceLinkTest()
        {
            var testCases = new JsonLightSerializerTestCase[]
            {
                // Single entity reference link
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.DeferredLink("http://odata.org/erl")
                                     .WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataIdAnnotationName + @""":""http://odata.org/erl""
                        }"
                },
                // Collection of entity reference links
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.LinkCollection()
                                     .Item(PayloadBuilder.DeferredLink("http://odata.org/erl1"))
                                     .Item(PayloadBuilder.DeferredLink("http://odata.org/erl2"))
                                     .WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          """ + JsonLightConstants.ODataValuePropertyName + @""":[
                            { """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataIdAnnotationName + @""":""http://odata.org/erl1"" },
                            { """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataIdAnnotationName + @""":""http://odata.org/erl2"" }
                          ]
                        }"
                },
                // Collection of entity reference links with inline count and next link
                new JsonLightSerializerTestCase
                {
                    PayloadElement = PayloadBuilder.LinkCollection()
                                     .Item(PayloadBuilder.DeferredLink("http://odata.org/erl1"))
                                     .Item(PayloadBuilder.DeferredLink("http://odata.org/erl2"))
                                     .InlineCount(42)
                                     .NextLink("http://odata.org/nextlink")
                                     .WithContextUri("http://odata.org/metadatauri"),
                    ExpectedJson = @"
                        {
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + @""":""http://odata.org/metadatauri"",
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataCountAnnotationName + @""": 42,
                          """ + JsonLightConstants.ODataValuePropertyName + @""":[
                            { """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataIdAnnotationName + @""":""http://odata.org/erl1"" },
                            { """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataIdAnnotationName + @""":""http://odata.org/erl2"" }
                          ],
                          """ + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataNextLinkAnnotationName + @""":""http://odata.org/nextlink""
                        }"
                },
            };

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

                this.JsonValueComparer.Compare(expectedValue, actualValue);
            });
        }
        private static ODataPayloadElement CreatePayloadElement(IEdmModel model, ODataPayloadKind payloadKind, ReaderTestConfiguration testConfig)
        {
            IEdmEntitySet          citySet              = model.EntityContainer.FindEntitySet("Cities");
            IEdmEntityType         cityType             = model.EntityTypes().Single(e => e.Name == "CityType");
            IEdmProperty           cityNameProperty     = cityType.Properties().Single(e => e.Name == "Name");
            IEdmNavigationProperty policeStationNavProp = cityType.NavigationProperties().Single(e => e.Name == "PoliceStation");
            IEdmOperationImport    primitiveCollectionResultOperation = model.EntityContainer.FindOperationImports("PrimitiveCollectionResultOperation").Single();
            IEdmOperationImport    serviceOp1 = model.EntityContainer.FindOperationImports("ServiceOperation1").Single();

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

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

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

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

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

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

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

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

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

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

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

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

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

            case ODataPayloadKind.Unsupported:      // fall through
            default:
                throw new NotSupportedException();
            }
        }
Esempio n. 10
0
        public void ReadEntityReferenceLinksTest()
        {
            // NOTE: No need for the payload generator here since entity reference links can only appear at the top level.
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = TestEntityReferenceLinks.CreateEntityReferenceLinksDescriptors(this.Settings);

            // make sure this also works with metadata
            EdmModel      model    = (EdmModel)Test.OData.Utils.Metadata.TestModels.BuildTestModel();
            EdmEntityType cityType = (EdmEntityType)model.FindDeclaredType("TestModel.CityType");
            EdmEntitySet  citySet  = (EdmEntitySet)model.EntityContainersAcrossModels().First().FindEntitySet("Cities");

            testDescriptors = testDescriptors.Concat(
                testDescriptors.Select(td =>
                                       new PayloadReaderTestDescriptor(td)
            {
                PayloadElement  = ((LinkCollection)td.PayloadElement.DeepCopy()).ExpectedNavigationProperty(citySet, cityType, "DOL"),
                PayloadEdmModel = model
            }));

            // add some error cases
            IEnumerable <PayloadReaderTestDescriptor> errorDescriptors = new PayloadReaderTestDescriptor[]
            {
                // null link in a collection
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement  = PayloadBuilder.LinkCollection().Item(PayloadBuilder.DeferredLink(null)).ExpectedNavigationProperty(citySet, cityType, "DOL"),
                    PayloadEdmModel = model,
                    // Top-level EntityReferenceLinks payload read requests are not allowed.
                    SkipTestConfiguration  = t => t.IsRequest,
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException = tc.Format == ODataFormat.Atom
                                    ? ODataExpectedExceptions.ODataException("ODataAtomDeserializer_RelativeUriUsedWithoutBaseUriSpecified", string.Empty)
                                    : ODataExpectedExceptions.ODataException("ODataJsonLightEntityReferenceLinkDeserializer_EntityReferenceLinkUrlCannotBeNull")
                    },
                },

                //// empty link in a collection
                //new PayloadReaderTestDescriptor(this.Settings)
                //{
                //    PayloadElement = PayloadBuilder.LinkCollection().Item(PayloadBuilder.DeferredLink(string.Empty)).ExpectedNavigationProperty(citySet, cityType, "DOL"),
                //    PayloadModel = model,
                //    // Top-level EntityReferenceLinks payload read requests are not allowed.
                //    SkipTestConfiguration = t => t.IsRequest,
                //    ExpectedResultCallback = tc =>
                //            new PayloadReaderTestExpectedResult (this.Settings.ExpectedResultSettings)
                //            {
                //                ExpectedException = tc.Format == ODataFormat.Json
                //                ? null
                //                : ODataExpectedExceptions.ODataException(
                //                    tc.Format == ODataFormat.Atom
                //                        ? "ODataAtomDeserializer_RelativeUriUsedWithoutBaseUriSpecified"
                //                        : "ODataJsonDeserializer_RelativeUriUsedWithoutBaseUriSpecified")
                //            },
                //},

                //// invalid Uri format in a collection
                //new PayloadReaderTestDescriptor(this.Settings)
                //{
                //    PayloadElement = PayloadBuilder.LinkCollection().Item(PayloadBuilder.DeferredLink("foo-is-not-a-link")).ExpectedNavigationProperty(citySet, cityType, "DOL"),
                //    PayloadModel = model,
                //    // Top-level EntityReferenceLinks payload read requests are not allowed.
                //    SkipTestConfiguration = t => t.IsRequest,
                //    ExpectedResultCallback = tc =>
                //            new PayloadReaderTestExpectedResult (this.Settings.ExpectedResultSettings)
                //            {
                //                ExpectedException = tc.Format == ODataFormat.Json
                //                ? null
                //                : ODataExpectedExceptions.ODataException(
                //                    tc.Format == ODataFormat.Atom
                //                        ? "ODataAtomDeserializer_RelativeUriUsedWithoutBaseUriSpecified"
                //                        : "ODataJsonDeserializer_RelativeUriUsedWithoutBaseUriSpecified")
                //            },
                //},
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.Concat(errorDescriptors),
                this.ReaderTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                if (testConfiguration.Format == ODataFormat.Json && testDescriptor.PayloadEdmModel == null)
                {
                    // Ignore test cases without model in JSON Light
                    return;
                }

                ReaderTestConfiguration testConfigClone = new ReaderTestConfiguration(testConfiguration);
                if (testConfiguration.Format == ODataFormat.Json)
                {
                    testConfigClone.MessageReaderSettings.BaseUri = null;
                }

                testDescriptor.RunTest(testConfigClone);
            });
        }
        public void InvalidEntityReferenceLinksReaderAtomTest()
        {
            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = new PayloadReaderTestDescriptor[]
            {
                #region Wrong name and namespace
                // Wrong name
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.LinkCollection().XmlRepresentation("<m:Ref></m:Ref>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntityReferenceLinkDeserializer_InvalidEntityReferenceLinksStartElement", "Ref", TestAtomConstants.ODataMetadataNamespace)
                },
                // Wrong namespace
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement    = PayloadBuilder.LinkCollection().XmlRepresentation("<m:ref></m:ref>"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomEntityReferenceLinkDeserializer_InvalidEntityReferenceLinksStartElement", "ref", TestAtomConstants.ODataMetadataNamespace)
                },
                #endregion

                #region Duplicate error elements
                // duplicate 'm:count' element
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.LinkCollection().InlineCount(1).XmlRepresentation("<feed><m:count>1</m:count><m:count>2</m:count><m:ref id=\"http://odata.org/refid\"></m:ref></feed>"),
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedPayloadElement = PayloadBuilder.LinkCollection(),
                        ExpectedException      = ODataExpectedExceptions.ODataException("ODataAtomEntityReferenceLinkDeserializer_MultipleEntityReferenceLinksElementsWithSameName", TestAtomConstants.ODataMetadataNamespace, TestAtomConstants.ODataCountElementName)
                    }
                },

                // duplicate 'd:next' element
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.LinkCollection().NextLink("http://odata.org/next1").XmlRepresentation("<feed><d:next>http://odata.org/next1</d:next><d:next>http://odata.org/next2</d:next></feed>"),
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedPayloadElement = PayloadBuilder.LinkCollection(),
                        ExpectedException      = ODataExpectedExceptions.ODataException("ODataAtomEntityReferenceLinkDeserializer_MultipleEntityReferenceLinksElementsWithSameName", TestAtomConstants.ODataNamespace, TestAtomConstants.ODataNextLinkElementName)
                    }
                },
                #endregion Duplicate error elements

                #region Element content in string elements
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.LinkCollection().InlineCount(1).XmlRepresentation("<feed><m:count><foo></foo>1<bar /></m:count></feed>"),
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedPayloadElement = PayloadBuilder.LinkCollection(),
                        ExpectedException      = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element"),
                    }
                },
                new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement         = PayloadBuilder.LinkCollection().NextLink("http://odata.org/next1").XmlRepresentation("<feed><d:next><foo></foo>http://odata.org/next1<bar /></d:next></feed>"),
                    ExpectedResultCallback = tc =>
                                             new PayloadReaderTestExpectedResult(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedPayloadElement = PayloadBuilder.LinkCollection(),
                        ExpectedException      = ODataExpectedExceptions.ODataException("XmlReaderExtension_InvalidNodeInStringValue", "Element"),
                    }
                },
                #endregion Element content in string elements
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }
        public void EntityReferenceLinksReaderAtomTest()
        {
            const string link1String = "http://odata.org/deferred1";
            const string link2String = "http://odata.org/deferred2";
            const string nextString  = "http://odata.org/next";

            DeferredLink link1 = PayloadBuilder.DeferredLink(link1String);
            DeferredLink link2 = PayloadBuilder.DeferredLink(link2String);

            #region Extra attributes on the <feed> element
            var linksElementPayloads = new[]
            {
                // extra attributes on <links> element without content
                new { PayloadElement = PayloadBuilder.LinkCollection(), Template = "<feed {0} />", },

                // extra attributes on <m:count> element
                new { PayloadElement = PayloadBuilder.LinkCollection().InlineCount(1), Template = "<feed><m:count {0}>1</m:count></feed>", },

                // extra attributes on <d:next> element
                new { PayloadElement = PayloadBuilder.LinkCollection().NextLink("http://odata.org/next"), Template = "<feed><d:next {0}>http://odata.org/next</d:next></feed>", },
            };

            string[] attributes = new string[]
            {
                "foo='bar'",
                "m:foo='bar'",
                "foo=''",
                "lang='invalid'",
            };

            IEnumerable <PayloadReaderTestDescriptor> testDescriptors = linksElementPayloads.SelectMany(linkPayload =>
                                                                                                        attributes.Select(attribute =>
            {
                var payloadElement = linkPayload.PayloadElement.DeepCopy();
                string xmlRep      = string.Format(CultureInfo.InvariantCulture, linkPayload.Template, attribute);
                payloadElement     = payloadElement.XmlRepresentation(xmlRep);

                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                });
            }));
            #endregion Extra attributes on the <links> element

            #region Extra padding between the elements
            var extraPaddingPayloads = new[]
            {
                new { PayloadElement = PayloadBuilder.LinkCollection(), Template = "<feed>{0}</feed>", },
                new { PayloadElement = PayloadBuilder.LinkCollection().InlineCount(1), Template = "<feed>{0}<m:count>1</m:count></feed>", },
                new { PayloadElement = PayloadBuilder.LinkCollection().InlineCount(1), Template = "<feed><m:count>1</m:count>{0}</feed>", },
                new { PayloadElement = PayloadBuilder.LinkCollection().NextLink(nextString), Template = "<feed>{0}<d:next>http://odata.org/next</d:next></feed>", },
                new { PayloadElement = PayloadBuilder.LinkCollection().NextLink(nextString), Template = "<feed><d:next>http://odata.org/next</d:next>{0}</feed>", },
                new { PayloadElement = PayloadBuilder.LinkCollection().InlineCount(1).NextLink(nextString), Template = "<feed><m:count>1</m:count>{0}<d:next>http://odata.org/next</d:next></feed>", },
                new { PayloadElement = PayloadBuilder.LinkCollection().Item(link1).InlineCount(1).NextLink(nextString), Template = "<feed><m:count>1</m:count>{0}<m:ref id =\"" + link1String + "\"/><d:next>" + nextString + "</d:next></feed>", },
                new { PayloadElement = PayloadBuilder.LinkCollection().Item(link1).InlineCount(1).NextLink(nextString), Template = "<feed><m:count>1</m:count><m:ref id=\"" + link1String + "\"/>{0}<d:next>" + nextString + "</d:next></feed>", },
                new { PayloadElement = PayloadBuilder.LinkCollection().Item(link1).Item(link2).InlineCount(2).NextLink(nextString), Template = "<feed><m:count>2</m:count><m:ref id=\"" + link1String + "\"/>{0}<m:ref id=\"" + link2String + "\"/><d:next>" + nextString + "</d:next></feed>", },
            };

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

            IEnumerable <PayloadReaderTestDescriptor> extraPaddingTestDescriptors = extraPaddingPayloads.SelectMany(extraPaddingPayload =>
                                                                                                                    xmlPaddingToIgnore.Select(xmlPadding =>
            {
                var payloadElement = extraPaddingPayload.PayloadElement.DeepCopy();
                string xmlRep      = string.Format(CultureInfo.InvariantCulture, extraPaddingPayload.Template, xmlPadding);
                payloadElement     = payloadElement.XmlRepresentation(xmlRep);

                return(new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                });
            }));
            testDescriptors = testDescriptors.Concat(extraPaddingTestDescriptors);
            #endregion Extra padding between the elements

            #region Extra elements in the <feed> content
            LinkCollection links = PayloadBuilder.LinkCollection()
                                   .InlineCount(2)
                                   .Item(PayloadBuilder.DeferredLink(link1String))
                                   .Item(PayloadBuilder.DeferredLink(link2String))
                                   .NextLink(nextString);

            XElement ref1Element = new XElement(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataRefElementName);
            ref1Element.SetAttributeValue(TestAtomConstants.AtomIdElementName, link1String);

            XElement ref2Element = new XElement(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataRefElementName);
            ref1Element.SetAttributeValue(TestAtomConstants.AtomIdElementName, link2String);

            XElement xmlRepresentation = new XElement(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName,
                                                      new XElement(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataCountElementName, "2"),
                                                      ref1Element,
                                                      ref2Element,
                                                      new XElement(TestAtomConstants.ODataXNamespace + TestAtomConstants.ODataNextLinkElementName, nextString));

            XElement[] extraElements = new XElement[]
            {
                new XElement(XName.Get("foo"), "bar"),
                new XElement(XName.Get("foo"), new XElement(XName.Get("bar"))),
                new XElement(XName.Get("foo"), new XAttribute(XName.Get("bar"), "attribute-value")),
                new XElement(TestAtomConstants.ODataMetadataXNamespace + "foo", "bar"),
                new XElement(TestAtomConstants.ODataMetadataXNamespace + "foo", new XElement(TestAtomConstants.ODataMetadataXNamespace + "bar")),
                new XElement(XName.Get("foo"), new XAttribute(TestAtomConstants.ODataMetadataXNamespace + "bar", "attribute-value")),
                // "Ref" element in the OData metadaata namespace, should be ignored, "ref" is expected
                new XElement(TestAtomConstants.ODataMetadataXNamespace + "Ref"),
                // "uri" element in the OData namespace, should be ignored, OData metadata namespace is expected
                new XElement(TestAtomConstants.ODataXNamespace + "ref"),
            };

            IEnumerable <PayloadReaderTestDescriptor> extraElementTestDescriptors = extraElements.SelectMany(extraElement =>
            {
                return(InjectElement(extraElement, xmlRepresentation).Select(linksWithInjectedElement =>
                                                                             new PayloadReaderTestDescriptor(this.Settings)
                {
                    PayloadElement = links.DeepCopy().XmlRepresentation(linksWithInjectedElement),
                }
                                                                             ));
            });
            testDescriptors = testDescriptors.Concat(extraElementTestDescriptors);
            #endregion Extra elements in the <links> content

            #region Various payload orders for an error element
            links = PayloadBuilder.LinkCollection()
                    .InlineCount(1)
                    .Item(PayloadBuilder.DeferredLink(link1String))
                    .NextLink(nextString);

            ref1Element = new XElement(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataRefElementName);
            ref1Element.SetAttributeValue(TestAtomConstants.AtomIdElementName, link1String);

            xmlRepresentation = new XElement(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomFeedElementName,
                                             new XElement(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataCountElementName, "1"),
                                             ref1Element,
                                             new XElement(TestAtomConstants.ODataXNamespace + TestAtomConstants.ODataNextLinkElementName, nextString));

            IEnumerable <PayloadReaderTestDescriptor> payloadOrderTestDescriptors = GeneratePayloadOrders(xmlRepresentation).Select(xmlRep =>
                                                                                                                                    new PayloadReaderTestDescriptor(this.Settings)
            {
                PayloadElement = links.DeepCopy().XmlRepresentation(xmlRep),
            }
                                                                                                                                    );

            testDescriptors = testDescriptors.Concat(payloadOrderTestDescriptors);
            #endregion Various payload orders for an error element

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.ReaderTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testDescriptor.RunTest(testConfiguration);
            });
        }