Exemple #1
0
        private Action <WriterTestConfiguration> WriteEntityReferenceLink(Func <XElement, XElement> fragmentExtractor, string expectedXml, bool isClient, string odataNamespace)
        {
            var sampleLink = new ODataEntityReferenceLink {
                Url = new Uri("http://odata.org/link")
            };

            return((testConfiguration) =>
            {
                PayloadWriterTestDescriptor <ODataEntityReferenceLink> descriptor = null;
                descriptor = new PayloadWriterTestDescriptor <ODataEntityReferenceLink>(
                    this.Settings,
                    sampleLink,
                    expectedXml,
                    null,
                    fragmentExtractor,
                    null);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    descriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLink(sampleLink),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #2
0
        private Action <WriterTestConfiguration> WriteEntityReferenceLinks(Func <XElement, XElement> fragmentExtractor, string expectedXml)
        {
            var sampleLinks = new ODataEntityReferenceLinks();

            return((testConfiguration) =>
            {
                PayloadWriterTestDescriptor <ODataEntityReferenceLinks> descriptor = new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>(
                    this.Settings,
                    sampleLinks,
                    expectedXml,
                    null,
                    fragmentExtractor,
                    null,
                    /*disableXmlNamespaceNormalization*/ true);
                // Top-level EntityReferenceLinks payload write requests are not allowed.
                if (testConfiguration.IsRequest)
                {
                    descriptor.ExpectedResultCallback = (testConfig) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = ODataExpectedExceptions.ODataException("ODataMessageWriter_EntityReferenceLinksInRequestNotAllowed")
                    };
                }
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    descriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLinks(sampleLinks),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #3
0
        private Action <WriterTestConfiguration> WriteServiceDocument(Func <XElement, XElement> fragmentExtractor, string expectedXml)
        {
            var sampleWorkspace = ObjectModelUtils.CreateDefaultWorkspace();

            return((testConfiguration) =>
            {
                if (testConfiguration.IsRequest)
                {
                    return;
                }

                ODataMessageWriterSettings actualSettings = testConfiguration.MessageWriterSettings;
                if (actualSettings.PayloadBaseUri == null)
                {
                    actualSettings = actualSettings.Clone();
                    actualSettings.PayloadBaseUri = new Uri("http://odata.org");
                }

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    new PayloadWriterTestDescriptor <ODataServiceDocument>(this.Settings, sampleWorkspace, expectedXml, null, fragmentExtractor, null, /*disableXmlNamespaceNormalization*/ true),
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(sampleWorkspace),
                    this.Assert,
                    actualSettings,
                    baselineLogger: this.Logger);
            });
        }
        public void CategoryMetadataOnWorkspaceCollectionCategoriesWriterTest()
        {
            var testCases = this.CreateAtomCategoryTestCases();

            // Convert test cases to test descriptions
            var testDescriptors = testCases.Select(testCase =>
            {
                AtomResourceCollectionMetadata metadata = new AtomResourceCollectionMetadata
                {
                    Categories = new AtomCategoriesMetadata
                    {
                        Categories = new[] { testCase.Category }
                    }
                };

                ODataEntitySetInfo collection = new ODataEntitySetInfo {
                    Url = new Uri("http://odata.org/collection")
                };
                collection.SetAnnotation(metadata);
                ODataServiceDocument serviceDocument = new ODataServiceDocument {
                    EntitySets = new[] { collection }
                };

                return(new PayloadWriterTestDescriptor <ODataServiceDocument>(
                           this.Settings,
                           serviceDocument,
                           testConfiguration =>
                           new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.Xml,
                    ExpectedException2 = testCase.ExpectedException,
                    FragmentExtractor = result => result
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingWorkspaceElementName)
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCollectionElementName)
                                        .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCategoriesElementName)
                                        .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomCategoryElementName)
                }));
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #5
0
        public void EntityReferenceLinkTest()
        {
            ODataEntityReferenceLink[] resultLinks = new ODataEntityReferenceLink[]
            {
                new ODataEntityReferenceLink {
                    Url = new Uri("http://odata.org/linkresult")
                },
                new ODataEntityReferenceLink {
                    Url = new Uri("relative", UriKind.Relative)
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                resultLinks,
                TestWriterUtils.ODataBehaviorKinds,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (resultLink, behaviorKind, testConfiguration) =>
            {
                bool expectMetadataNamespace = false;
                PayloadWriterTestDescriptor <ODataEntityReferenceLink> testDescriptor =
                    new PayloadWriterTestDescriptor <ODataEntityReferenceLink>(
                        this.Settings,
                        resultLink,
                        CreateExpectedCallback(resultLink, expectMetadataNamespace, "http://odata.org/test/$metadata#$ref"));

                // When writing JSON lite, always provide a model and a non-null nav prop.
                // The error cases when a model isn't provided or the nav prop is null are tested in JsonLightEntityReferenceLinkWriterTests
                if (testConfiguration.Format == ODataFormat.Json)
                {
                    testDescriptor.Model = CreateModelWithNavProps();
                    var model            = testDescriptor.GetMetadataProvider();
                }

                testConfiguration = testConfiguration.CloneAndApplyBehavior(behaviorKind);
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLink(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #6
0
        [Ignore] // Remove Atom
        // [TestMethod, Variation(Description = "Validates the payloads for various top-level errors written using ODataMessageWriter.WriteError().")]
        public void TopLevelODataMessageWriterErrorTest()
        {
            this.CombinatorialEngineProvider.RunCombinations(
                this.CreateODataErrorTestDescriptors(/*throwOnRequest*/ true, /*topLevel*/ true),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.MessageQuotas.MaxNestingDepth = this.customSetRecursionDepthLimit;

                ODataAnnotatedError error = (ODataAnnotatedError)testDescriptor.PayloadItems.Single();

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteError(error.Error, error.IncludeDebugInformation),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #7
0
        public void AtomTextConstructMetadataOnODataWorkspaceWriterTest()
        {
            var testDescriptors = this.CreateTextConstructTestDescriptors();

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases <AtomTextConstruct, ODataServiceDocument>(WriterPayloads.AtomTextConstructPayloadsForWorkspace),
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        public void EntityReferenceLinksValidationTest()
        {
            var testCases = new[] {
                new {
                    InvalidateEntityReferenceLinks = new Action <ODataEntityReferenceLinks>(entityReferenceLinks => entityReferenceLinks.Links = new ODataEntityReferenceLink[] { null }),
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_EntityReferenceLinksLinkMustNotBeNull"),
                },
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                ODataEntityReferenceLinks entityReferenceLinks = ObjectModelUtils.CreateDefaultEntityReferenceLinks();
                testCase.InvalidateEntityReferenceLinks(entityReferenceLinks);
                return(new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>(
                           this.Settings,
                           entityReferenceLinks,
                           testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    // Top-level EntityReferenceLinks payload write requests are not allowed.
                    ExpectedException2 = testConfiguration.IsRequest ?
                                         ODataExpectedExceptions.ODataException("ODataMessageWriter_EntityReferenceLinksInRequestNotAllowed") : testCase.ExpectedException
                }));
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLinks(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
                return;
            });
        }
        public void WorkspaceNamesTests()
        {
            string[] workspaceNames = new string[] { null, string.Empty, "MyWorkspaceName" };

            var testCases = workspaceNames.Select(name => new PayloadWriterTestDescriptor <ODataServiceDocument>(this.Settings, CreateWorkspace(/*createMetadataFirst*/ true, name), this.CreateExpectedResultCallback(baseUri, name)));

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testCase, testConfig) =>
            {
                WriterTestConfiguration newConfiguration = testConfig.Clone();
                newConfiguration.MessageWriterSettings.PayloadBaseUri = new Uri(baseUri);
                newConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testCase,
                    newConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testCase.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #10
0
        private Action <WriterTestConfiguration> WriteProperty(Func <XElement, XElement> fragmentExtractor, Func <ODataVersion, string> expectedXml)
        {
            var sampleProperty = new ODataProperty()
            {
                Name = "Property", Value = 42
            };

            return((testConfiguration) =>
            {
                TestWriterUtils.WriteAndVerifyTopLevelContent(new PayloadWriterTestDescriptor <ODataProperty>(
                                                                  this.Settings,
                                                                  sampleProperty,
                                                                  expectedXml(testConfiguration.Version),
                                                                  null,
                                                                  fragmentExtractor,
                                                                  null,
                                                                  /*disableXmlNamespaceNormalization*/ true),
                                                              testConfiguration,
                                                              (messageWriter) => messageWriter.WriteProperty(sampleProperty),
                                                              this.Assert,
                                                              baselineLogger: this.Logger);
            });
        }
Exemple #11
0
        private Action <WriterTestConfiguration> WriteError(Func <XElement, XElement> fragmentExtractor, string expectedXml)
        {
            var sampleError = new ODataError();

            return((testConfiguration) =>
            {
                if (testConfiguration.IsRequest)
                {
                    return;
                }
                TestWriterUtils.WriteAndVerifyTopLevelContent(new PayloadWriterTestDescriptor <ODataError>(
                                                                  this.Settings,
                                                                  sampleError,
                                                                  expectedXml,
                                                                  null,
                                                                  fragmentExtractor,
                                                                  null,
                                                                  /*disableXmlNamespaceNormalization*/ true),
                                                              testConfiguration,
                                                              (messageWriter) => messageWriter.WriteError(sampleError, false),
                                                              this.Assert,
                                                              baselineLogger: this.Logger);
            });
        }
        public void AtomCategoriesMetadataTest()
        {
            var testCases = new []
            {
                // Empty categories
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata(),
                    Xml = "<categories xmlns='http://www.w3.org/2007/app'/>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with href
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Href = new Uri("http://odata.org/href")
                    },
                    Xml = "<categories href='http://odata.org/href' xmlns='http://www.w3.org/2007/app'/>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with href and non-null empty categories (null and empty collection should be treated the same)
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Href = new Uri("http://odata.org/href"), Categories = new AtomCategoryMetadata[0]
                    },
                    Xml = "<categories href='http://odata.org/href' xmlns='http://www.w3.org/2007/app'/>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with fixed yes
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Fixed = true
                    },
                    Xml = "<categories fixed='yes' xmlns='http://www.w3.org/2007/app'/>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with fixed no
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Fixed = false
                    },
                    Xml = "<categories fixed='no' xmlns='http://www.w3.org/2007/app'/>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with scheme
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Scheme = "http://odata.org/scheme"
                    },
                    Xml = "<categories scheme='http://odata.org/scheme' xmlns='http://www.w3.org/2007/app'/>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with scheme and fixed
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Fixed = true, Scheme = "http://odata.org/scheme"
                    },
                    Xml = "<categories fixed='yes' scheme='http://odata.org/scheme' xmlns='http://www.w3.org/2007/app'/>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with single category
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Categories = new [] { new AtomCategoryMetadata {
                                                  Term = "myterm", Scheme = "http://odata.org/scheme"
                                              } }
                    },
                    Xml = "<categories xmlns='http://www.w3.org/2007/app'><atom:category term='myterm' scheme='http://odata.org/scheme' xmlns:atom='http://www.w3.org/2005/Atom'/></categories>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with two categories
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Categories = new [] {
                            new AtomCategoryMetadata {
                                Term = "myterm", Scheme = "http://odata.org/scheme"
                            },
                            new AtomCategoryMetadata {
                                Term = "second", Scheme = "http://odata.org/scheme2"
                            }
                        }
                    },
                    Xml = "<categories xmlns='http://www.w3.org/2007/app'>" +
                          "<atom:category term='myterm' scheme='http://odata.org/scheme' xmlns:atom='http://www.w3.org/2005/Atom'/>" +
                          "<atom:category term='second' scheme='http://odata.org/scheme2' xmlns:atom='http://www.w3.org/2005/Atom'/>" +
                          "</categories>",
                    ExpectedException = (ExpectedException)null
                },
                // Categories with href and fixed (error)
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Href = new Uri("http://odata.org/href"), Fixed = true
                    },
                    Xml = string.Empty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_CategoriesHrefWithOtherValues")
                },
                // Categories with href and scheme (error)
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Href = new Uri("http://odata.org/href"), Scheme = "http://odata.org/scheme"
                    },
                    Xml = string.Empty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_CategoriesHrefWithOtherValues")
                },
                // Categories with href and non-empty categories (error)
                new
                {
                    CategoriesMetadata = new AtomCategoriesMetadata()
                    {
                        Href = new Uri("http://odata.org/href"), Categories = new [] { new AtomCategoryMetadata() }
                    },
                    Xml = string.Empty,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_CategoriesHrefWithOtherValues")
                },
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                ODataEntitySetInfo collection = new ODataEntitySetInfo {
                    Url = new Uri("http://odata.org/url")
                };
                AtomResourceCollectionMetadata metadata = new AtomResourceCollectionMetadata()
                {
                    Categories = testCase.CategoriesMetadata
                };
                collection.SetAnnotation(metadata);
                ODataServiceDocument serviceDocument = new ODataServiceDocument {
                    EntitySets = new [] { collection }
                };
                return(new PayloadWriterTestDescriptor <ODataServiceDocument>(
                           this.Settings,
                           new [] { serviceDocument },
                           tc =>
                {
                    if (testCase.ExpectedException != null)
                    {
                        return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            ExpectedException2 = testCase.ExpectedException
                        };
                    }
                    else
                    {
                        return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Xml = testCase.Xml,
                            FragmentExtractor = result =>
                                                result
                                                .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingWorkspaceElementName)
                                                .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCollectionElementName)
                                                .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCategoriesElementName)
                        };
                    }
                }));
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        public void EntityReferenceLinkValidationTest()
        {
            var testCases = new[] {
                new {
                    InvalidateEntityReferenceLink = new Action <ODataEntityReferenceLink>(entityReferenceLink => entityReferenceLink.Url = null),
                    ExpectedException             = ODataExpectedExceptions.ODataException("WriterValidationUtils_EntityReferenceLinkUrlMustNotBeNull"),
                },
            };

            var testDescriptors = testCases.SelectMany(testCase =>
            {
                ODataEntityReferenceLink entityReferenceLink = ObjectModelUtils.CreateDefaultEntityReferenceLink();
                testCase.InvalidateEntityReferenceLink(entityReferenceLink);
                ODataEntityReferenceLinks entityReferenceLinks = ObjectModelUtils.CreateDefaultEntityReferenceLinks();
                testCase.InvalidateEntityReferenceLink(entityReferenceLinks.Links.First());

                return(new PayloadWriterTestDescriptor[]
                {
                    // Top level entity reference link
                    new PayloadWriterTestDescriptor <ODataEntityReferenceLink>(
                        this.Settings,
                        entityReferenceLink,
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = testCase.ExpectedException
                    }),
                    // Entity reference link in entity reference links
                    new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>(
                        this.Settings,
                        entityReferenceLinks,
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        // Top-level EntityReferenceLinks payload write requests are not allowed.
                        ExpectedException2 = testConfiguration.IsRequest ?
                                             ODataExpectedExceptions.ODataException("ODataMessageWriter_EntityReferenceLinksInRequestNotAllowed") : testCase.ExpectedException
                    }),
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        new ODataItem[] { ObjectModelUtils.CreateDefaultEntry(), ObjectModelUtils.CreateDefaultSingletonLink(), entityReferenceLink, null, null },
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = testConfiguration.IsRequest ? testCase.ExpectedException : ODataExpectedExceptions.ODataException("ODataWriterCore_EntityReferenceLinkInResponse")
                    }),
                });
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                PayloadWriterTestDescriptor <ODataEntityReferenceLink> entityReferenceLinkTestDescriptor = testDescriptor as PayloadWriterTestDescriptor <ODataEntityReferenceLink>;
                if (entityReferenceLinkTestDescriptor != null)
                {
                    TestWriterUtils.WriteAndVerifyTopLevelContent(
                        entityReferenceLinkTestDescriptor,
                        testConfiguration,
                        (messageWriter) => messageWriter.WriteEntityReferenceLink(entityReferenceLinkTestDescriptor.PayloadItems.Single()),
                        this.Assert,
                        baselineLogger: this.Logger);
                    return;
                }

                PayloadWriterTestDescriptor <ODataEntityReferenceLinks> entityReferenceLinksTestDescriptor = testDescriptor as PayloadWriterTestDescriptor <ODataEntityReferenceLinks>;
                if (entityReferenceLinksTestDescriptor != null)
                {
                    TestWriterUtils.WriteAndVerifyTopLevelContent(
                        entityReferenceLinksTestDescriptor,
                        testConfiguration,
                        (messageWriter) => messageWriter.WriteEntityReferenceLinks(entityReferenceLinksTestDescriptor.PayloadItems.Single()),
                        this.Assert,
                        baselineLogger: this.Logger);
                    return;
                }

                TestWriterUtils.WriteAndVerifyODataPayload((PayloadWriterTestDescriptor <ODataItem>)testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void SingletonTests()
        {
            const string baseUri = "http://odata.org/";

            int[] singletonSizes = new int[] { 0, 1, 3 };

            IList <SingletonInfo> coreSignletons = new string[] { "Singleton1", "Singleton2", "Singleton3" }.Select(
                name => new SingletonInfo {
                Name = name, Url = name, TitleAnnotation = name
            }).ToList();
            IList <SingletonInfo> additionalSingletons = new string[] { "Additional1", "Additional2" }.Select(
                name => new SingletonInfo {
                Name = name, Url = name, TitleAnnotation = name
            }).ToList();

            bool[] includeAdditionalSingletons = new bool[] { true, false };

            IEnumerable <SingletonInfo[]> singletonArrays = null;

            foreach (int length in singletonSizes)
            {
                if (singletonArrays == null)
                {
                    singletonArrays = coreSignletons.Variations(length);
                }
                else
                {
                    singletonArrays = singletonArrays.Concat(coreSignletons.Variations(length));
                }
            }

            bool[] useMetadata = new bool[] { true, false };
            bool[] setTitle    = new bool[] { true, false };

            const string workspaceName = null;

            var testDescriptors = singletonArrays
                                  .SelectMany(collectionArray =>
                                              includeAdditionalSingletons.Select(flag => flag ? collectionArray.Concat(additionalSingletons) : collectionArray))
                                  .SelectMany(singletonArray2 => setTitle.Select(setTitleFlag => setTitleFlag ? singletonArray2.Select(c => new SingletonInfo {
                Name = c.Name, Url = c.Url, TitleAnnotation = c.Url
            }) : singletonArray2))
                                  .Select(singletonArray3 =>
                                          new PayloadWriterTestDescriptor <ODataServiceDocument>(
                                              this.Settings,
                                              CreateWorkspace(/*createMetadataFirst*/ true, workspaceName, null, singletonArray3),
                                              CreateExpectedResultCallback(baseUri, workspaceName, null, singletonArray3))
            {
                Model = CreateMetadata(null, singletonArray3)
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfig) =>
            {
                WriterTestConfiguration newConfiguration = testConfig.Clone();
                newConfiguration.MessageWriterSettings.PayloadBaseUri = new Uri(baseUri);
                newConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    newConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #15
0
        public void EntityReferenceLinksPropertyAccessOrderTest()
        {
            //// NOTE: this tests is important as Astoria relies on this behavior. Astoria only provides a next link after all the entity reference
            ////       links have been written so we must not access the next link before that point.

            ODataEntityReferenceLink entityReferenceLink1 = new ODataEntityReferenceLink {
                Url = new Uri("http://odata.org/linkresult1")
            };
            ODataEntityReferenceLink entityReferenceLink2 = new ODataEntityReferenceLink {
                Url = new Uri("http://odata.org/linkresult2")
            };
            ODataEntityReferenceLink entityReferenceLink3 = new ODataEntityReferenceLink {
                Url = new Uri("http://odata.org/linkresult3")
            };

            Uri  nextPageLink          = new Uri("http://odata.org/nextpage");
            Uri  incorrectNextPageLink = new Uri("http://odata.org/incorrectnextpage");
            long correctCountValue     = 3;

            // the expected result instance
            ODataEntityReferenceLinks expectedResult = new ODataEntityReferenceLinks
            {
                Count        = 3,
                Links        = new ODataEntityReferenceLink[] { entityReferenceLink1, entityReferenceLink2, entityReferenceLink3 },
                NextPageLink = nextPageLink
            };

            PayloadWriterTestDescriptor.WriterTestExpectedResultCallback expectedResultCallback = this.CreateExpectedCallback(expectedResult, /*forceNextLinkAndCountAtEnd*/ true);

            this.CombinatorialEngineProvider.RunCombinations(
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => !tc.IsRequest),
                (testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                // The instance with the proper inline count set but an incorrect next link; as we enumerate the links themselves
                // we will invalidate the inline count and set the correct next link to guarantee the correct order of property accesses
                // NOTE: we need to create this new for each iteration since the checking enumerable can (intentionally) only be enumerated once.
                ODataEntityReferenceLinks testReferenceLink = new ODataEntityReferenceLinks
                {
                    Count = correctCountValue,
                    // In JSON lite, we will write the next link first if one is available.  Otherwise, we'll write it at the end.
                    NextPageLink = testConfiguration.Format == ODataFormat.Json ? null : incorrectNextPageLink
                };
                testReferenceLink.Links = new CheckingEntityReferenceLinkEnumerable(
                    testReferenceLink,
                    correctCountValue,
                    nextPageLink /* correct next link */,
                    entityReferenceLink1,
                    entityReferenceLink2,
                    entityReferenceLink3);

                PayloadWriterTestDescriptor <ODataEntityReferenceLinks> testDescriptor =
                    new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>(this.Settings, testReferenceLink, expectedResultCallback);

                IEdmNavigationProperty navProp = null;
                IEdmEntitySet entitySet        = null;
                // When writing JSON lite, always provide a model and a non-null nav prop.
                // The error cases when a model isn't provided or the nav prop is null are tested in JsonLightEntityReferenceLinkWriterTests
                if (testConfiguration.Format == ODataFormat.Json)
                {
                    testDescriptor.Model = CreateModelWithNavProps();
                    var edmModel         = testDescriptor.GetMetadataProvider();
                    navProp   = GetCollectionNavProp(edmModel);
                    entitySet = GetCollectionEntitySet(edmModel);
                }

                ODataEntityReferenceLinks entityReferenceLinks = testDescriptor.PayloadItems.Single();

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLinks(entityReferenceLinks),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #16
0
        public void EntityReferenceLinksTest()
        {
            string resultUri1String = "http://odata.org/linkresult1";
            string resultUri2String = "linkresult2";
            string resultUri3String = "http://odata.org/linkresult3";
            ODataEntityReferenceLink entityReferenceLink1 = new ODataEntityReferenceLink {
                Url = new Uri(resultUri1String)
            };
            ODataEntityReferenceLink entityReferenceLink2 = new ODataEntityReferenceLink {
                Url = new Uri(resultUri2String, UriKind.Relative)
            };
            ODataEntityReferenceLink entityReferenceLink3 = new ODataEntityReferenceLink {
                Url = new Uri(resultUri3String)
            };

            Uri nextPageLink         = new Uri("http://odata.org/nextpage");
            Uri relativeNextPageLink = new Uri("relative-nextpage", UriKind.Relative);

            long?[] inputCounts    = new long?[] { null, 1, 3, -1, -3, 0, long.MaxValue, long.MinValue };
            Uri[]   inputNextLinks = new Uri[] { nextPageLink, relativeNextPageLink, null };
            ODataEntityReferenceLink[][] inputReferenceLinks = new ODataEntityReferenceLink[][]
            {
                new ODataEntityReferenceLink[] { entityReferenceLink1, entityReferenceLink2, entityReferenceLink3 },
                new ODataEntityReferenceLink[] { entityReferenceLink1, entityReferenceLink3 },
                new ODataEntityReferenceLink[] { entityReferenceLink1 },
                new ODataEntityReferenceLink[0],
                null
            };

            var testCases = inputCounts.SelectMany(
                inputCount => inputNextLinks.SelectMany(
                    inputNextLink => inputReferenceLinks.Select(
                        inputReferenceLink => new ODataEntityReferenceLinks {
                Count = inputCount, Links = inputReferenceLink, NextPageLink = inputNextLink
            })));

            var testDescriptors = testCases.Select(
                testCase =>
                new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>(this.Settings, testCase, this.CreateExpectedCallback(testCase, /*forceNextLinkAndCountAtEnd*/ false)));

            // TODO: also cover the cases in protocol v1 (errors for inline count and next page link; different format for JSON)
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                ODataEntityReferenceLinks entityReferenceLinks = testDescriptor.PayloadItems.Single();

                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                // When writing JSON lite, always provide a model and a non-null nav prop.
                // The error cases when a model isn't provided or the nav prop is null are tested in JsonLightEntityReferenceLinkWriterTests
                if (testConfiguration.Format == ODataFormat.Json)
                {
                    testDescriptor.Model = CreateModelWithNavProps();
                    var edmModel         = testDescriptor.GetMetadataProvider();
                }

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLinks(entityReferenceLinks),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        public void AdditionalResourceCollectionTests()
        {
            IEdmModel model = this.CreateMetadata(new[] { new CollectionInfo {
                                                              Url = "EntitySet1"
                                                          }, new CollectionInfo {
                                                              Url = "EntitySet2"
                                                          } });
            IEdmEntityType entityType = (IEdmEntityType)model.FindType("TestNS.EntityType");

            var testCases = new[]
            {
                // duplicate resource collection name
                new
                {
                    Collections = new [] { new CollectionInfo {
                                               Url = "A"
                                           }, new CollectionInfo {
                                               Url = "A"
                                           } },
                    Model = (IEdmModel)null,
                },

                // resource collection name does not match metadata.
                new
                {
                    Collections = new [] { new CollectionInfo {
                                               Url = "SomeName"
                                           } },
                    Model = model,
                },
            };

            var testDescriptors = testCases.Select(tc => new PayloadWriterTestDescriptor <WorkspaceWithSettings>(
                                                       this.Settings,
                                                       new WorkspaceWithSettings()
            {
                ServiceDocument = CreateWorkspace(/*createMetadataFirst*/ false, null, tc.Collections),
            },
                                                       CreateExpectedResultCallback(baseUri, null, tc.Collections))
            {
                Model = tc.Model,
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfig) =>
            {
                WorkspaceWithSettings docWithSettings = testDescriptor.PayloadItems.Single();
                if (docWithSettings.WriterSettings != null)
                {
                    docWithSettings.WriterSettings.DisableMessageStreamDisposal = testConfig.MessageWriterSettings.DisableMessageStreamDisposal;
                }

                WriterTestConfiguration newConfiguration = testConfig.Clone();
                newConfiguration.MessageWriterSettings.PayloadBaseUri = new Uri(baseUri);
                newConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    newConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(docWithSettings.ServiceDocument),
                    this.Assert,
                    docWithSettings.WriterSettings,
                    baselineLogger: this.Logger);
            });
        }
        public void ServiceDocumentErrorTests()
        {
            IEdmModel model = this.CreateMetadata(new[] { new CollectionInfo()
                                                          {
                                                              Url = "EntitySet1"
                                                          }, new CollectionInfo()
                                                          {
                                                              Url = "EntitySet2"
                                                          } });

            var testCases = new[]
            {
                new
                {       // relative uri without any base Uri
                    Workspace = new Func <ODataServiceDocument>(() => {
                        var defaultWorkspace        = ObjectModelUtils.CreateDefaultWorkspace();
                        defaultWorkspace.EntitySets = new ODataEntitySetInfo[]
                        {
                            new ODataEntitySetInfo()
                            {
                                Url = new Uri("SomeUri", UriKind.Relative)
                            }
                        };
                        return(defaultWorkspace);
                    })(),
                    MessageWriterSettings = (ODataMessageWriterSettings)null,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataWriter_RelativeUriUsedWithoutBaseUriSpecified", "SomeUri"),
                    Model         = (IEdmModel)null,
                    OnlyForFormat = ODataFormat.Atom
                },
                new
                {       // empty relative uri without any base Uri
                    Workspace = new Func <ODataServiceDocument>(() => {
                        var defaultWorkspace        = ObjectModelUtils.CreateDefaultWorkspace();
                        defaultWorkspace.EntitySets = new ODataEntitySetInfo[]
                        {
                            new ODataEntitySetInfo()
                            {
                                Url = new Uri(string.Empty, UriKind.Relative)
                            }
                        };
                        return(defaultWorkspace);
                    })(),
                    MessageWriterSettings = (ODataMessageWriterSettings)null,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ODataWriter_RelativeUriUsedWithoutBaseUriSpecified", string.Empty),
                    Model         = (IEdmModel)null,
                    OnlyForFormat = ODataFormat.Atom
                },
                new
                {       // empty collection name
                    Workspace = new Func <ODataServiceDocument>(() => {
                        var defaultWorkspace        = ObjectModelUtils.CreateDefaultWorkspace();
                        defaultWorkspace.EntitySets = new ODataEntitySetInfo[]
                        {
                            new ODataEntitySetInfo()
                            {
                                Url = null
                            }
                        };
                        return(defaultWorkspace);
                    })(),
                    MessageWriterSettings = settingsWithBaseUri,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ValidationUtils_ResourceMustSpecifyUrl"),
                    Model         = (IEdmModel)null,
                    OnlyForFormat = (ODataFormat)null
                },
                new
                {       // null collection
                    Workspace = new Func <ODataServiceDocument>(() => {
                        var defaultWorkspace        = ObjectModelUtils.CreateDefaultWorkspace();
                        defaultWorkspace.EntitySets = new ODataEntitySetInfo[]
                        {
                            null
                        };
                        return(defaultWorkspace);
                    })(),
                    MessageWriterSettings = settingsWithBaseUri,
                    ExpectedException     = ODataExpectedExceptions.ODataException("ValidationUtils_WorkspaceResourceMustNotContainNullItem"),
                    Model         = (IEdmModel)null,
                    OnlyForFormat = (ODataFormat)null
                },
                new
                {       // no serviceDocument
                    Workspace             = (ODataServiceDocument)null,
                    MessageWriterSettings = settingsWithBaseUri,
                    ExpectedException     = new ExpectedException(typeof(ArgumentNullException)),
                    Model         = (IEdmModel)null,
                    OnlyForFormat = (ODataFormat)null
                },
            };

            var testDescriptors = testCases.Select(tc => new PayloadWriterTestDescriptor <WorkspaceWithSettings>(
                                                       this.Settings,
                                                       new WorkspaceWithSettings()
            {
                ServiceDocument = tc.Workspace,
                WriterSettings  = tc.MessageWriterSettings
            },
                                                       CreateErrorResultCallback(tc.ExpectedException, tc.OnlyForFormat, this.Settings.ExpectedResultSettings))
            {
                Model = tc.Model,
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfig) =>
            {
                testConfig = testConfig.Clone();
                testConfig.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                WorkspaceWithSettings docWithSettings = testDescriptor.PayloadItems.Single();
                if (docWithSettings.WriterSettings != null)
                {
                    docWithSettings.WriterSettings.DisableMessageStreamDisposal = testConfig.MessageWriterSettings.DisableMessageStreamDisposal;
                    docWithSettings.WriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                }

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfig,
                    (messageWriter) => messageWriter.WriteServiceDocument(docWithSettings.ServiceDocument),
                    this.Assert,
                    docWithSettings.WriterSettings,
                    baselineLogger: this.Logger);
            });
        }
Exemple #19
0
        public void TopLevelOpenPropertiesTest()
        {
            EdmModel edmModel  = new EdmModel();
            var      container = new EdmEntityContainer("TestModel", "DefaultContainer");

            edmModel.AddElement(container);

            var openCustomerType = new EdmEntityType("TestModel", "OpenCustomerType", null, isAbstract: false, isOpen: true);

            openCustomerType.AddKeys(openCustomerType.AddStructuralProperty("ID", EdmPrimitiveTypeKind.Int32, isNullable: false));
            edmModel.AddElement(openCustomerType);

            var addressType = new EdmComplexType("TestModel", "AddressType");

            addressType.AddStructuralProperty("Street", EdmPrimitiveTypeKind.String, isNullable: true);
            edmModel.AddElement(addressType);

            container.AddEntitySet("CustomerSet", openCustomerType);

            ISpatial pointValue = GeographyFactory.Point(32.0, -100.0).Build();

            IEnumerable <PropertyPayloadTestCase> testCases = new[]
            {
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level open primitive property.",
                    Property         = new ODataProperty {
                        Name = "Age", Value = (long)42
                    },
                    Model        = edmModel,
                    PropertyType = "Edm.Int64",
                    Json         = string.Join("$(NL)",
                                               "{{",
                                               "{0},\"value\":\"42\"",
                                               "}}")
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level open spatial property.",
                    Property         = new ODataProperty {
                        Name = "Location", Value = pointValue
                    },
                    Model        = edmModel,
                    PropertyType = "Edm.GeographyPoint",
                    Json         = string.Join("$(NL)",
                                               "{{",
                                               "{0}," +
                                               "\"" + JsonLightConstants.ODataValuePropertyName + "\":{{",
                                               "\"type\":\"Point\",\"coordinates\":[",
                                               "-100.0,32.0",
                                               "],\"crs\":{{",
                                               "\"type\":\"name\",\"properties\":{{",
                                               "\"name\":\"EPSG:4326\"",
                                               "}}",
                                               "}}",
                                               "}}",
                                               "}}")
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level open complex property.",
                    Property         = new ODataProperty {
                        Name = "Address", Value = new ODataComplexValue {
                            TypeName = "TestModel.AddressType"
                        }
                    },
                    Model        = edmModel,
                    PropertyType = "TestModel.AddressType",
                    Json         = string.Join("$(NL)",
                                               "{{",
                                               "{0}",
                                               "}}")
                },
            };

            IEnumerable <PayloadWriterTestDescriptor <ODataProperty> > testDescriptors = testCases.Select(testCase =>
                                                                                                          new PayloadWriterTestDescriptor <ODataProperty>(
                                                                                                              this.Settings,
                                                                                                              testCase.Property,
                                                                                                              tc => new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
            {
                Json = string.Format(
                    CultureInfo.InvariantCulture,
                    testCase.Json,
                    JsonLightWriterUtils.GetMetadataUrlPropertyForProperty(testCase.PropertyType)),
                FragmentExtractor = (result) => result.RemoveAllAnnotations(true)
            })
            {
                DebugDescription = testCase.DebugDescription,
                Model            = testCase.Model,
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.JsonLightFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteProperty(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #20
0
        public void WriteFloatingPointValue()
        {
            var edmModel = new EdmModel();

            IEnumerable <PropertyPayloadTestCase> testCases = new[]
            {
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level property float point type.",
                    Property         = new ODataProperty {
                        Name = "Speed", Value = float.PositiveInfinity
                    },
                    Model        = edmModel,
                    PropertyType = "Edm.Double",
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level property float point type.",
                    Property         = new ODataProperty {
                        Name = "Speed", Value = float.NegativeInfinity
                    },
                    Model        = edmModel,
                    PropertyType = "Edm.Double",
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level property float point type.",
                    Property         = new ODataProperty {
                        Name = "Speed", Value = double.PositiveInfinity
                    },
                    Model        = edmModel,
                    PropertyType = "Edm.Double",
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Top-level property float point type.",
                    Property         = new ODataProperty {
                        Name = "Speed", Value = double.NegativeInfinity
                    },
                    Model        = edmModel,
                    PropertyType = "Edm.Double",
                },
            };

            IEnumerable <PayloadWriterTestDescriptor <ODataProperty> > testDescriptors = testCases.Select(testCase =>
                                                                                                          new PayloadWriterTestDescriptor <ODataProperty>(
                                                                                                              this.Settings,
                                                                                                              testCase.Property,
                                                                                                              tc => new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
            {
                FragmentExtractor = (result) => result.RemoveAllAnnotations(true)
            })
            {
                DebugDescription = testCase.DebugDescription,
                Model            = testCase.Model,
            });


            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.JsonLightFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteProperty(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        public void WriteUntypedValueTest()
        {
            EdmModel edmModel = new EdmModel();

            var jsonType    = new EdmComplexType("TestModel", "JsonType");
            var jsonTypeRef = new EdmComplexTypeReference(jsonType, isNullable: true);

            edmModel.AddElement(jsonType);

            var collectionType    = new EdmCollectionType(jsonTypeRef);
            var collectionTypeRef = new EdmCollectionTypeReference(collectionType);

            var entityType = new EdmEntityType("TestModel", "EntityType");

            entityType.AddStructuralProperty("Value", jsonTypeRef);
            entityType.AddStructuralProperty("CollectionValue", collectionTypeRef);
            edmModel.AddElement(entityType);

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

            container.AddEntitySet("EntitySet", entityType);
            edmModel.AddElement(container);

            const string JsonFormat = "$(NL){{{0},\"Value\":{1}}}";

            IEnumerable <PropertyPayloadTestCase> testCases = new[]
            {
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Null.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataUntypedValue()
                        {
                            RawValue = "null"
                        }
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Integer.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataUntypedValue()
                        {
                            RawValue = "42"
                        }
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Float.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataUntypedValue()
                        {
                            RawValue = "3.1415"
                        }
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "String.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataUntypedValue()
                        {
                            RawValue = "\"string\""
                        }
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Array of elements of mixed types.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataUntypedValue()
                        {
                            RawValue = "[1, 2, \"abc\"]"
                        }
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Array of arrays.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataUntypedValue()
                        {
                            RawValue = "[ [1, \"abc\"], [2, \"def\"], [[3],[4, 5]] ]"
                        }
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Negative - empty RawValue",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataUntypedValue()
                        {
                            RawValue = string.Empty
                        },
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException(
                        TextRes.ODataJsonLightValueSerializer_MissingRawValueOnUntyped),
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Collection of Edm.Untyped elements.",
                    Property         = new ODataProperty
                    {
                        Name  = "CollectionValue",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = "Collection(TestModel.JsonType)",
                            Items    = new object[]
                            {
                                new ODataUntypedValue()
                                {
                                    RawValue = "\"string\""
                                },
                                new ODataUntypedValue()
                                {
                                    RawValue = "[1, 2, \"abc\"]"
                                },
                                new ODataUntypedValue()
                                {
                                    RawValue = "3.1415"
                                }
                            }
                        }
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Integer.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataPrimitiveValue(42)
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "Float.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataPrimitiveValue(3.1415)
                    },
                },
                new PropertyPayloadTestCase
                {
                    DebugDescription = "String.",
                    Property         = new ODataProperty
                    {
                        Name  = "Value",
                        Value = new ODataPrimitiveValue("string")
                    },
                },
            };

            IEnumerable <PayloadWriterTestDescriptor <ODataProperty> > testDescriptors = testCases.Select(testCase =>
                                                                                                          new PayloadWriterTestDescriptor <ODataProperty>(
                                                                                                              this.Settings,
                                                                                                              testCase.Property,
                                                                                                              tc => new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
            {
                Json = string.Format(
                    CultureInfo.InvariantCulture,
                    JsonFormat,
                    JsonLightWriterUtils.GetMetadataUrlPropertyForEntry("EntitySet"),
                    GetExpectedJson(testCase.Property.Value)),
                FragmentExtractor  = (result) => result.RemoveAllAnnotations(false),
                ExpectedException2 = testCase.ExpectedException,
            })
            {
                DebugDescription = testCase.DebugDescription,
                Model            = edmModel,
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.JsonLightFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) =>
                {
                    messageWriter.PrivateSettings.Validations = ~ValidationKinds.ThrowOnUndeclaredPropertyForNonOpenType;
                    messageWriter.WriteProperty(testDescriptor.PayloadItems.Single());
                },
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        public void AtomResourceCollectionMetadataTest()
        {
            var testCases = new[]
            {
                // No title specified - an empty one is used as it's required by the spec.
                new
                {
                    CustomizeMetadata = (Action <ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                    }),
                    Xml = "<Collection><title xmlns='http://www.w3.org/2005/Atom'/></Collection>"
                },
                // Simple title (other titles are tested in AtomTextConstructMetadataTests)
                new
                {
                    CustomizeMetadata = (Action <ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title = new AtomTextConstruct {
                            Text = "collection title"
                        };
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title></Collection>"
                },
                // With accept
                new
                {
                    CustomizeMetadata = (Action <ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title  = "collection title";
                        metadata.Accept = "mime/type";
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'>mime/type</accept></Collection>"
                },
                // With empty accept
                new
                {
                    CustomizeMetadata = (Action <ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title  = "collection title";
                        metadata.Accept = string.Empty;
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'></accept></Collection>"
                },
                // With categories
                new
                {
                    CustomizeMetadata = (Action <ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title      = "collection title";
                        metadata.Categories = new AtomCategoriesMetadata();
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><categories xmlns='http://www.w3.org/2007/app' /></Collection>"
                },
                // With accept and categories
                new
                {
                    CustomizeMetadata = (Action <ODataEntitySetInfo>)(collection => {
                        AtomResourceCollectionMetadata metadata = collection.Atom();
                        metadata.Title      = "collection title";
                        metadata.Accept     = "mime/type";
                        metadata.Categories = new AtomCategoriesMetadata();
                    }),
                    Xml = "<Collection><title type='text' xmlns='http://www.w3.org/2005/Atom'>collection title</title><accept xmlns='http://www.w3.org/2007/app'>mime/type</accept><categories xmlns='http://www.w3.org/2007/app' /></Collection>"
                },
            };

            Func <ODataEntitySetInfo>[] collectionCreators = new Func <ODataEntitySetInfo>[]
            {
                () => new ODataEntitySetInfo {
                    Url = new Uri("http://odata.org/url")
                },
                () => { var collection = new ODataEntitySetInfo {
                            Url = new Uri("http://odata.org/url")
                        }; collection.SetAnnotation(new AtomResourceCollectionMetadata()); return(collection); }
            };
            var testDescriptors = testCases.SelectMany(testCase =>
                                                       collectionCreators.Select(collectionCreator =>
            {
                ODataEntitySetInfo collection = collectionCreator();
                testCase.CustomizeMetadata(collection);
                ODataServiceDocument serviceDocument = new ODataServiceDocument {
                    EntitySets = new[] { collection }
                };
                return(new PayloadWriterTestDescriptor <ODataServiceDocument>(
                           this.Settings,
                           new[] { serviceDocument },
                           tc => new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.Xml,
                    FragmentExtractor = result =>
                                        new XElement("Collection",
                                                     result
                                                     .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingWorkspaceElementName)
                                                     .Element(TestAtomConstants.AtomPublishingXNamespace + TestAtomConstants.AtomPublishingCollectionElementName)
                                                     .Elements())
                }));
            }));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.AtomFormatConfigurations.Where(tc => !tc.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        public void WorkspaceNamesAndResourceCollectionTests()
        {
            const string baseUri = "http://odata.org/";

            int[] collectionSizes = new int[] { 0, 1, 3 };

            IList <CollectionInfo> coreCollections =
                new List <CollectionInfo>
            {
                new CollectionInfo {
                    Url = "EntitySet1"
                },
                new CollectionInfo {
                    Url = "EntitySet2"
                },
                new CollectionInfo {
                    Url = "EntitySet3"
                },
            };

            IList <CollectionInfo> additionalCollections =
                new List <CollectionInfo>
            {
                new CollectionInfo()
                {
                    Url = "Additional1"
                },
                new CollectionInfo()
                {
                    Url = "Additional2"
                },
            };

            bool[] includeAdditionalCollections = new bool[] { true, false };

            IEnumerable <CollectionInfo[]> collectionArrays = null;

            foreach (int length in collectionSizes)
            {
                if (collectionArrays == null)
                {
                    collectionArrays = coreCollections.Variations(length);
                }
                else
                {
                    collectionArrays = collectionArrays.Concat(coreCollections.Variations(length));
                }
            }

            bool[] useMetadata = new bool[] { true, false };
            bool[] setTitle    = new bool[] { true, false };

            string[] workspaceNames = new string[] { null, string.Empty, "MyWorkspaceName" };
            IEnumerable <PayloadWriterTestDescriptor <ODataServiceDocument> > testDescriptors = null;

            foreach (var name in workspaceNames)
            {
                var vals = collectionArrays
                           .SelectMany(collectionArray =>
                                       includeAdditionalCollections.Select(flag => flag ? collectionArray.Concat(additionalCollections) : collectionArray))
                           .SelectMany(collectionArray2 =>
                                       setTitle.Select(setTitleFlag => setTitleFlag ? collectionArray2.Select(c => new CollectionInfo {
                    Url = c.Url, TitleAnnotation = c.Url
                }) : collectionArray2))
                           .Select(collectionArray3 => new PayloadWriterTestDescriptor <ODataServiceDocument>(
                                       this.Settings,
                                       CreateWorkspace(/*createMetadataFirst*/ false, name, collectionArray3),
                                       CreateExpectedResultCallback(baseUri, name, collectionArray3))
                {
                    Model = CreateMetadata(collectionArray3)
                });

                if (testDescriptors == null)
                {
                    testDescriptors = vals;
                }
                else
                {
                    testDescriptors.Concat(vals);
                }
            }

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfig) =>
            {
                WriterTestConfiguration newConfiguration = testConfig.Clone();
                newConfiguration.MessageWriterSettings.PayloadBaseUri = new Uri(baseUri);
                newConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    newConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        public void ResourceCollectionNamePropertyTests()
        {
            // The behavior of the Name property depends on the format.
            // ATOM: We use it to populate the <title> element if no title has been specified on the ATOM metadata annotation. If there is both a title annotation and a Name property, they must match or else we'll fail.
            // JSON Light: The Name property is required and written to the "name" property in the format.

            IList <CollectionInfo> interestingCollections =
                new[]
            {
                // Non null collection name
                new CollectionInfo
                {
                    Name = "CollectionName",
                    Url  = "CollectionRelativeUrl",
                },
                // No name or title annotation
                new CollectionInfo
                {
                    Url = "CollectionRelativeUrl"
                },
                // Name and title annotation are both non null and are equal.
                new CollectionInfo
                {
                    Name            = "CollectionName",
                    Url             = "CollectionRelativeUrl",
                    TitleAnnotation = "CollectionName"
                },
                // Name and title annotation differ (expect failure in ATOM).
                new CollectionInfo
                {
                    Name            = "CollectionName",
                    Url             = "CollectionRelativeUrl",
                    TitleAnnotation = "CollectionTitle"
                }
            };

            var collectionArrays = interestingCollections.Variations(0, 1, 3);

            EdmModel           model = new EdmModel();
            EdmEntityContainer edmEntityContainer = new EdmEntityContainer("DefaultNamespace", "DefaultContainer");

            model.AddElement(edmEntityContainer);

            var testDescriptors = collectionArrays.Select(collectionArray => new PayloadWriterTestDescriptor <ODataServiceDocument>(
                                                              this.Settings,
                                                              CreateWorkspace(/*createMetadataFirst*/ false, /* workspaceName */ null, collectionArray),
                                                              CreateExpectedResultCallback(baseUri, /* workspaceName */ null, collectionArray))
            {
                Model = model,
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfig) =>
            {
                WriterTestConfiguration newConfiguration = testConfig.Clone();
                newConfiguration.MessageWriterSettings.PayloadBaseUri = new Uri(baseUri);
                newConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    newConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }