Ejemplo n.º 1
0
        private void CreateTestDescriptorsAndRunTests(FeedMetadataTestCase[] testCases, Func <PayloadWriterTestDescriptor <ODataItem>, IEnumerable <PayloadWriterTestDescriptor <ODataItem> > > payloads)
        {
            // Convert test cases to test descriptions
            IEnumerable <Func <ODataFeed> > feedCreators = new Func <ODataFeed>[] { () => ObjectModelUtils.CreateDefaultFeed(), () => ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(), };
            var testDescriptors = testCases.SelectMany(testCase => feedCreators.Select(feedCreator =>
            {
                ODataFeed feed            = feedCreator();
                AtomFeedMetadata metadata = feed.Atom();
                this.Assert.IsNotNull(metadata, "Expected default feed metadata on a default feed.");
                testCase.CustomizeMetadata(metadata);
                ODataItem[] payloadItems = testCase.CustomizePayload == null ? new ODataItem[] { feed } : testCase.CustomizePayload(feed);
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, payloadItems, testConfiguration =>
                {
                    if (testCase.SkipTestConfiguration != null && testCase.SkipTestConfiguration(testConfiguration))
                    {
                        return null;
                    }
                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Xml = testCase.Xml, FragmentExtractor = testCase.Extractor, ExpectedException2 = testCase.ExpectedException
                    };
                }));
            }));

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void EntryValidationTest()
        {
            var testCases = new[] {
                new { // type name must not be empty
                    InvalidateEntry   = new Action <ODataResource>(entry => entry.TypeName = string.Empty),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_TypeNameMustNotBeEmpty")
                },
            };

            // Convert test cases to test descriptions
            var testDescriptors = testCases.Select(testCase =>
            {
                ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                testCase.InvalidateEntry(entry);
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                   new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    ExpectedException2 = testCase.ExpectedException
                }));
            });

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.EntryPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 3
0
        public void RelativeUriTest()
        {
            var testCases = new[]
            {
                new
                {
                    BaseUri     = new Uri("http://odata.org/"),
                    RelativeUri = new Uri("relative", UriKind.Relative),
                },
                new
                {
                    BaseUri     = new Uri("http://odata.org/"),
                    RelativeUri = new Uri("relative that needs escaping", UriKind.Relative),
                },
                new
                {
                    BaseUri     = new Uri("http://odata.org/a/b/"),
                    RelativeUri = new Uri("../../relative that needs escaping", UriKind.Relative),
                },
            };

            var testDescriptors = uriTestCases.SelectMany(uriTestCase => testCases.Select(testCase =>
            {
                return(new
                {
                    TestCase = uriTestCase,
                    BaseUri = testCase.BaseUri,
                    Descriptor = new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        uriTestCase.ItemFunc(testCase.RelativeUri),
                        CreateUriTestCaseExpectedResultCallback(testCase.BaseUri, testCase.RelativeUri, uriTestCase))
                });
            }));

            //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(c => false),
                new bool[] { false, true },
                (testDescriptor, testConfiguration, implementUrlResolver) =>
            {
                if (testConfiguration.Format == ODataFormat.Json && testDescriptor.TestCase.JsonExtractor != null)
                {
                    PayloadWriterTestDescriptor <ODataItem> payloadTestDescriptor = testDescriptor.Descriptor;
                    if (implementUrlResolver)
                    {
                        payloadTestDescriptor             = new PayloadWriterTestDescriptor <ODataItem>(payloadTestDescriptor);
                        payloadTestDescriptor.UrlResolver = new TestUrlResolver();
                    }

                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.BaseUri = testDescriptor.BaseUri;
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                    TestWriterUtils.WriteAndVerifyODataPayload(payloadTestDescriptor, testConfiguration, this.Assert, this.Logger);
                }
            });
        }
Ejemplo n.º 4
0
        public void FeedIdTest()
        {
            var testCases = new[]
            {
                new
                {
                    Id  = (Uri)null,
                    Xml = (string)null,
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriter_FeedsMustHaveNonEmptyId"),
                },
                new
                {
                    Id  = new Uri("urn:id"),
                    Xml = @"<id xmlns=""" + TestAtomConstants.AtomNamespace + @""">urn:id</id>",
                    ExpectedException = (ExpectedException)null,
                },
            };

            var testDescriptors = testCases.Select(tc =>
            {
                ODataFeed feed = ObjectModelUtils.CreateDefaultFeed();
                feed.Id        = tc.Id;

                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           feed,
                           testConfiguration =>
                {
                    this.Assert.AreEqual(ODataFormat.Atom, testConfiguration.Format, "Only ATOM feeds support ID.");
                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Xml = tc.Xml,
                        FragmentExtractor = (element) => element.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomIdElementName).Single(),
                        ExpectedException2 = tc.ExpectedException,
                    };
                }));
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.FeedPayloads),
                this.WriterTestConfigurationProvider.AtomFormatConfigurationsWithIndent.Where(tc => !tc.IsRequest),
                (testPayload, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testPayload, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 5
0
 private Action <WriterTestConfiguration> WriteEntry(Func <XElement, XElement> fragmentExtractor, Func <ODataVersion, string> expectedXml)
 {
     return((testConfiguration) => TestWriterUtils.WriteAndVerifyODataPayload(
                new PayloadWriterTestDescriptor <ODataItem>(
                    this.Settings,
                    ObjectModelUtils.CreateDefaultEntry(),
                    expectedXml(testConfiguration.Version),
                    null,
                    fragmentExtractor,
                    null,
                    /*disableXmlNamespaceNormalization*/ true),
                testConfiguration,
                this.Assert,
                this.Logger));
 }
Ejemplo n.º 6
0
        public void AtomTextConstructMetadataOnODataItemWriterTest()
        {
            var testDescriptors = this.CreateTextConstructTestDescriptors();

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases <AtomTextConstruct, ODataItem>(WriterPayloads.AtomTextConstructPayloadsForItem),
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void PropertyValidationTest()
        {
            var testCases = new[] {
                new { // null property is not valid
                    Property          = (ODataProperty)null,
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_PropertyMustNotBeNull")
                },
                new { // null property name is not valid
                    Property = new ODataProperty()
                    {
                        Name = null
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_PropertiesMustHaveNonEmptyName")
                },
                new { // empty property name is not valid
                    Property = new ODataProperty()
                    {
                        Name = string.Empty
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_PropertiesMustHaveNonEmptyName")
                },
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           new ODataResource()
                {
                    Properties = new ODataProperty[] { testCase.Property }
                },
                           testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    ExpectedException2 = testCase.ExpectedException
                }));
            });

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 8
0
        public void EntryReadAndEditLinkMetadataWriterTest()
        {
            Func <XElement, XElement> fragmentExtractor = (e) => e.Element(TestAtomConstants.AtomXNamespace + "link");

            // Convert test cases to test descriptions; first for the entry's self link
            var selfLinkTestDescriptors = linkMetadataTestCases.Select(testCase =>
            {
                ODataEntry entry      = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();
                entry.Atom().SelfLink = testCase.LinkMetadata("self", readLinkHref);
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                   new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.ExpectedXml == null ? null : testCase.ExpectedXml("self", readLinkHref, null, null),
                    ExpectedException2 = testCase.ExpectedException == null ? null : testCase.ExpectedException("self", readLinkHref),
                    FragmentExtractor = fragmentExtractor
                }));
            });

            // now the ones for the entry's edit link
            var editLinkTestDescriptors = linkMetadataTestCases.Select(testCase =>
            {
                ODataEntry entry      = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();
                entry.ReadLink        = null;
                entry.EditLink        = new Uri(editLinkHref);
                entry.Atom().EditLink = testCase.LinkMetadata("edit", editLinkHref);
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                   new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.ExpectedXml == null ? null : testCase.ExpectedXml("edit", editLinkHref, null, null),
                    ExpectedException2 = testCase.ExpectedException == null ? null : testCase.ExpectedException("edit", editLinkHref),
                    FragmentExtractor = fragmentExtractor
                }));
            });

            var testDescriptors = selfLinkTestDescriptors.Concat(editLinkTestDescriptors);

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void DefaultStreamValidationTest()
        {
            var testCases = new[] {
                new { // empty content type is invalid
                    InvalidateDefaultStream = new Action <ODataStreamReferenceValue>(mediaResource => mediaResource.ContentType = string.Empty),
                    ExpectedException       = ODataExpectedExceptions.ODataException("WriterValidationUtils_StreamReferenceValueEmptyContentType"),
                },
                new { // null read link and non-empty content type is invalid
                    InvalidateDefaultStream = new Action <ODataStreamReferenceValue>(mediaResource => { mediaResource.ReadLink = null; mediaResource.ContentType = "mime/type"; }),
                    ExpectedException       = ODataExpectedExceptions.ODataException("WriterValidationUtils_DefaultStreamWithContentTypeWithoutReadLink"),
                },
                new { // non-null read link and null content type is invalid
                    InvalidateDefaultStream = new Action <ODataStreamReferenceValue>(mediaResource => { mediaResource.ReadLink = new Uri("http://odata.org"); mediaResource.ContentType = null; }),
                    ExpectedException       = ODataExpectedExceptions.ODataException("WriterValidationUtils_DefaultStreamWithReadLinkWithoutContentType"),
                },
                new { // etag without an edit link is invalid
                    InvalidateDefaultStream = new Action <ODataStreamReferenceValue>(mediaResource => { mediaResource.ETag = "someetag"; mediaResource.EditLink = null; }),
                    ExpectedException       = ODataExpectedExceptions.ODataException("WriterValidationUtils_StreamReferenceValueMustHaveEditLinkToHaveETag"),
                },
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                ODataStreamReferenceValue mediaResource = ObjectModelUtils.CreateDefaultStream();
                testCase.InvalidateDefaultStream(mediaResource);
                ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                entry.MediaResource = mediaResource;
                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           entry,
                           testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    ExpectedException2 = testCase.ExpectedException
                }));
            });

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void NavigationLinkValidationTest()
        {
            var testCases = new[] {
                new NavigationLinkValidationTestCase { // null link name is not valid
                    InvalidateLink    = link => link.Name = null,
                    ExpectedException = link => ODataExpectedExceptions.ODataException("ValidationUtils_LinkMustSpecifyName"),
                },
                new NavigationLinkValidationTestCase { // empty link name is not valid
                    InvalidateLink    = link => link.Name = string.Empty,
                    ExpectedException = link => ODataExpectedExceptions.ODataException("ValidationUtils_LinkMustSpecifyName"),
                },
                new NavigationLinkValidationTestCase { // null link Url is not valid
                    InvalidateLink        = link => link.Url = null,
                    ExpectedException     = link => ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyUrl", link.Name),
                    SkipTestConfiguration = (testConfiguration) => testConfiguration.Format == ODataFormat.Json || testConfiguration.IsRequest
                },
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                ODataNestedResourceInfo link = ObjectModelUtils.CreateDefaultCollectionLink();
                testCase.InvalidateLink(link);
                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           link,
                           testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    ExpectedException2 = testCase.ExpectedException(link)
                })
                {
                    SkipTestConfiguration = testCase.SkipTestConfiguration
                });
            });

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.NavigationLinkOnlyPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor.DeferredLinksToEntityReferenceLinksInRequest(testConfiguration), testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 11
0
        public void DefaultStreamEditLinkMetadataWriterTest()
        {
            Func <XElement, XElement> fragmentExtractor = (e) => e.Elements(TestAtomConstants.AtomXNamespace + "link").Last();

            // NOTE: no self-link test cases since the self link is represented as the <content> element and not customizable through link metadata
            var testDescriptors = linkMetadataTestCases.Select(testCase =>
            {
                ODataEntry entry = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();
                ODataStreamReferenceValue streamReferenceValue = new ODataStreamReferenceValue()
                {
                    ReadLink    = new Uri(readLinkHref),
                    EditLink    = new Uri(editLinkHref),
                    ContentType = linkMediaType,
                };

                AtomStreamReferenceMetadata streamReferenceMetadata = new AtomStreamReferenceMetadata()
                {
                    EditLink = testCase.LinkMetadata("edit-media", editLinkHref)
                };

                streamReferenceValue.SetAnnotation <AtomStreamReferenceMetadata>(streamReferenceMetadata);
                entry.MediaResource = streamReferenceValue;

                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                   new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.ExpectedXml == null ? null : testCase.ExpectedXml("edit-media", editLinkHref, null, null),
                    ExpectedException2 = testCase.ExpectedException == null ? null : testCase.ExpectedException("edit-media", editLinkHref),
                    FragmentExtractor = fragmentExtractor
                }));
            });

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void CollectionValidationTest()
        {
            var testCases = new[] {
                new { // empty type name is not valid
                    Collection = new ODataCollectionValue()
                    {
                        TypeName = string.Empty
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_TypeNameMustNotBeEmpty"),
                },
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           new ODataResource()
                {
                    Properties = new ODataProperty[] { new ODataProperty()
                                                       {
                                                           Name = "CollectionProperty", Value = testCase.Collection
                                                       } }
                },
                           testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    ExpectedException2 = testCase.ExpectedException
                }));
            });

            //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.ValuePayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 13
0
        public void ComplexValueValidationTest()
        {
            var testCases = new[] {
                new { // empty type name is not valid
                    ComplexValue = new ODataComplexValue()
                    {
                        TypeName = ""
                    },
                    ExpectedExceptionMessage = "An empty type name was found; the name of a type cannot be an empty string."
                },
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           new ODataEntry()
                {
                    Properties = new ODataProperty[] { new ODataProperty()
                                                       {
                                                           Name = "ComplexProperty", Value = testCase.ComplexValue
                                                       } }
                },
                           testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    ExpectedODataExceptionMessage = testCase.ExpectedExceptionMessage
                }));
            });

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.ValuePayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => tc.Format == ODataFormat.Atom),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void BaseUriValidationTest()
        {
            string relativeUriString = "abc/pqr/";
            Uri    absoluteUri       = new Uri("http://odata.org");
            Uri    relativeUri       = absoluteUri.MakeRelativeUri(new Uri(absoluteUri, relativeUriString));

            string expectedError = "The base URI '" + relativeUriString + "' specified in ODataMessageWriterSettings.BaseUri is invalid; it must either be null or an absolute URI.";

            ODataResource entry           = ObjectModelUtils.CreateDefaultEntry();
            var           testDescriptors = new []
            {
                new
                {
                    BaseUri        = relativeUri,
                    TestDescriptor = new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                                 new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedODataExceptionMessage = expectedError
                    })
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations,
                (testDescriptor, testConfiguration) =>
            {
                // clone the test configuration and set an invalid base Uri
                ODataMessageWriterSettings settings = testConfiguration.MessageWriterSettings.Clone();
                settings.BaseUri = testDescriptor.BaseUri;

                WriterTestConfiguration config =
                    new WriterTestConfiguration(testConfiguration.Format, settings, testConfiguration.IsRequest, testConfiguration.Synchronous);

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor.TestDescriptor, config, this.Assert, this.Logger);
            });
        }
        public void ETagValidationTest()
        {
            string[] etagValues = new string[]
            {
                "\"",
                "W/\"",
                "W/",
                "etagValue",
                "etagValue\"",
                "\"etagValue",
                "etag\"Value",
                "\"etagV\"alue\"",
                "W/etagValue",
                "W/etagValue\"",
                "W/\"etagValue",
                "W/etag\"Value",
                "W/\"etagV\"alue\""
            };

            var testDescriptors = etagValues.SelectMany(etagValue =>
            {
                var stream1 = new ODataStreamReferenceValue()
                {
                    ReadLink = new Uri("http://foo/", UriKind.RelativeOrAbsolute), EditLink = new Uri("http://foo/", UriKind.RelativeOrAbsolute), ContentType = "customType/customSubtype", ETag = etagValue
                };

                WriterTestDescriptor.WriterTestExpectedResultCallback formatSelector =
                    testConfiguration => (WriterTestExpectedResults) new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings);

                return(new[]
                {
                    // entity etag
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        new ODataResource()
                    {
                        ETag = etagValue, Properties = ObjectModelUtils.CreateDefaultPrimitiveProperties(), SerializationInfo = SerializationInfo
                    },
                        formatSelector),
                    // default stream etag
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        new ODataResource()
                    {
                        MediaResource = stream1, Properties = ObjectModelUtils.CreateDefaultPrimitiveProperties(), SerializationInfo = SerializationInfo
                    },
                        formatSelector),
                    // named stream etag
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        new ODataResource()
                    {
                        Properties = new ODataProperty[] { new ODataProperty()
                                                           {
                                                               Name = "Stream1", Value = stream1
                                                           } }, SerializationInfo = SerializationInfo
                    },
                        formatSelector)
                    {
                        // No stream properties in requests
                        SkipTestConfiguration = tc => tc.IsRequest
                    },
                });
            });

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void NamedStreamValidationTest()
        {
            var testCases = new NamedStreamValidationTestCase[] {
                // null property is not valid
                new NamedStreamValidationTestCase
                {
                    StreamProperty    = (ODataProperty)null,
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataResource.Properties"),
                },
                // null property name is not valid
                new NamedStreamValidationTestCase
                {
                    StreamProperty = new ODataProperty()
                    {
                        Name = null, Value = new ODataStreamReferenceValue()
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_PropertiesMustHaveNonEmptyName"),
                },
                // empty property name is not valid
                new NamedStreamValidationTestCase
                {
                    StreamProperty = new ODataProperty()
                    {
                        Name = string.Empty, Value = new ODataStreamReferenceValue()
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_PropertiesMustHaveNonEmptyName"),
                },
                // ReadLink and EditLink cannot be both null
                new NamedStreamValidationTestCase
                {
                    StreamProperty = new ODataProperty()
                    {
                        Name = "Stream1", Value = new ODataStreamReferenceValue()
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_StreamReferenceValueMustHaveEditLinkOrReadLink"),
                },
                // empty content type is not valid
                new NamedStreamValidationTestCase
                {
                    StreamProperty = new ODataProperty()
                    {
                        Name = "Stream1", Value = new ODataStreamReferenceValue()
                        {
                            ContentType = string.Empty
                        }
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_StreamReferenceValueEmptyContentType"),
                },
                // etag without an edit link is invalid
                new NamedStreamValidationTestCase
                {
                    StreamProperty = new ODataProperty()
                    {
                        Name = "Stream1", Value = new ODataStreamReferenceValue()
                        {
                            ReadLink = new Uri("someUri", UriKind.RelativeOrAbsolute), ETag = "\"etagValue\""
                        }
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_StreamReferenceValueMustHaveEditLinkToHaveETag"),
                },
                // relative read link without base uri is invalid
                new NamedStreamValidationTestCase
                {
                    StreamProperty = new ODataProperty()
                    {
                        Name = "Stream1", Value = new ODataStreamReferenceValue()
                        {
                            ReadLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                        }
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataWriter_RelativeUriUsedWithoutBaseUriSpecified", "someUri"),
                },
                // relative edit link without base uri is invalid
                new NamedStreamValidationTestCase
                {
                    StreamProperty = new ODataProperty()
                    {
                        Name = "Stream1", Value = new ODataStreamReferenceValue()
                        {
                            EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                        }
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataWriter_RelativeUriUsedWithoutBaseUriSpecified", "someUri"),
                },
            };

            var testDescriptors = testCases.Select(testCase =>
                                                   new PayloadWriterTestDescriptor <ODataItem>(
                                                       this.Settings,
                                                       new ODataResource()
            {
                Properties = new ODataProperty[] { testCase.StreamProperty }
            },
                                                       testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
            {
                ExpectedException2 = testCase.ExpectedException
            }));

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.NamedStreamPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 17
0
        public void PersonMetadataWriterTest()
        {
            string testEmail = "*****@*****.**";
            string testName  = "Test Author 1";
            string testUri   = "http://odata.org/authors/1";

            var testCases = new[]
            {
                new
                {
                    Person = new AtomPersonMetadata()
                    {
                        Name  = testName,
                        Email = testEmail,
                        Uri   = new Uri(testUri)
                    },
                    Xml = string.Join(
                        "$(NL)",
                        @"<author xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <name>" + testName + @"</name>",
                        @"  <uri>" + testUri + @"</uri>",
                        @"  <email>" + testEmail + @"</email>",
                        @"</author>"),
                    ExpectedException = (string)null
                },
                new
                {
                    Person = new AtomPersonMetadata()
                    {
                        Name  = null,
                        Email = testEmail,
                        Uri   = new Uri(testUri)
                    },
                    Xml = string.Join(
                        "$(NL)",
                        @"<author xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <name />",
                        @"  <uri>" + testUri + @"</uri>",
                        @"  <email>" + testEmail + @"</email>",
                        @"</author>"),
                    ExpectedException = (string)null
                },
                new
                {
                    Person = new AtomPersonMetadata()
                    {
                        Name  = testName,
                        Email = null,
                        Uri   = null
                    },
                    Xml = string.Join(
                        "$(NL)",
                        @"<author xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <name>" + testName + @"</name>",
                        @"</author>"),
                    ExpectedException = (string)null
                },
                new
                {
                    Person = (AtomPersonMetadata)testName,
                    Xml    = string.Join(
                        "$(NL)",
                        @"<author xmlns=""" + TestAtomConstants.AtomNamespace + @""">",
                        @"  <name>" + testName + @"</name>",
                        @"</author>"),
                    ExpectedException = (string)null
                },
            };

            Func <XElement, XElement> fragmentExtractor = (e) => e.Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomAuthorElementName);

            // Convert test cases to test descriptions
            var testDescriptors = testCases.Select(testCase =>
            {
                ODataEntry entry           = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();
                AtomEntryMetadata metadata = entry.Atom();
                this.Assert.IsNotNull(metadata, "Expected default entry metadata on a default entry.");
                metadata.Authors = new AtomPersonMetadata[] { testCase.Person };
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                   new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.Xml, ExpectedODataExceptionMessage = testCase.ExpectedException, FragmentExtractor = fragmentExtractor
                }));
            });

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 18
0
        public void BaseUriErrorTest()
        {
            Uri baseUri = new Uri("http://odata.org");
            Uri testUri = new Uri("http://odata.org/relative");
            IEnumerable <Func <Uri, BaseUriErrorTestCase> > testCaseFuncs = new Func <Uri, BaseUriErrorTestCase>[]
            {
                relativeUri => new BaseUriErrorTestCase
                {   // next page link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed();
                        feed.NextPageLink     = relativeUri;
                        return(new [] { feed });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // entry read link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        entry.ReadLink      = relativeUri;
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // entry edit link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        entry.EditLink      = relativeUri;
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // media resource (default stream) read link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataStreamReferenceValue mediaResource = new ODataStreamReferenceValue();
                        mediaResource.ContentType = "image/jpg";
                        mediaResource.ReadLink    = relativeUri;
                        ODataResource entry       = ObjectModelUtils.CreateDefaultEntry();
                        entry.MediaResource       = mediaResource;
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // media resource (default stream) edit link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataStreamReferenceValue mediaResource = new ODataStreamReferenceValue();
                        mediaResource.ContentType = "image/jpg";    // required
                        mediaResource.ReadLink    = testUri;        // required
                        mediaResource.EditLink    = relativeUri;
                        ODataResource entry       = ObjectModelUtils.CreateDefaultEntry();
                        entry.MediaResource       = mediaResource;
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // link Url
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataNestedResourceInfo link = ObjectModelUtils.CreateDefaultCollectionLink();
                        link.Url = relativeUri;

                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        return(new ODataItem[] { entry, link });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // association link Url
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataNestedResourceInfo link = ObjectModelUtils.CreateDefaultSingletonLink();
                        link.AssociationLinkUrl      = relativeUri;

                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        return(new ODataItem[] { entry, link });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // named stream read link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataStreamReferenceValue namedStream = new ODataStreamReferenceValue()
                        {
                            ContentType = "image/jpg",
                            ReadLink    = relativeUri,
                        };
                        ODataResource entry    = ObjectModelUtils.CreateDefaultEntry();
                        ODataProperty property = new ODataProperty()
                        {
                            Name  = "NamedStream",
                            Value = namedStream
                        };

                        entry.Properties = new[] { property };
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // named stream edit link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataStreamReferenceValue namedStream = new ODataStreamReferenceValue()
                        {
                            ContentType = "image/jpg",
                            ReadLink    = testUri,
                            EditLink    = relativeUri
                        };
                        ODataResource entry    = ObjectModelUtils.CreateDefaultEntry();
                        ODataProperty property = new ODataProperty()
                        {
                            Name  = "NamedStream",
                            Value = namedStream
                        };

                        entry.Properties = new[] { property };
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: feed generator Uri
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed();
                        return(new [] { feed });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: feed logo
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed();
                        return(new [] { feed });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: feed icon
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed();
                        return(new [] { feed });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: feed author
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed();
                        return(new [] { feed });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: feed contributor
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed();
                        return(new [] { feed });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: feed link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed();
                        return(new [] { feed });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: entry author
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: entry contributor
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
                relativeUri => new BaseUriErrorTestCase
                {   // Atom metadata: entry link
                    ItemFunc = new Func <IEnumerable <ODataItem> >(() =>
                    {
                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        return(new [] { entry });
                    }),
                    Formats = new [] { ODataFormat.Json }
                },
            };

            // ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            Uri testRelativeUri    = baseUri.MakeRelativeUri(testUri);
            Uri invalidRelativeUri = new Uri("../invalid/relative/uri", UriKind.Relative);

            this.CombinatorialEngineProvider.RunCombinations(
                testCaseFuncs,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(c => false),
                new Uri[] { testRelativeUri, invalidRelativeUri },
                new bool[] { false, true },
                (testCaseFunc, testConfiguration, uri, implementUrlResolver) =>
            {
                var testCase       = testCaseFunc(uri);
                var testDescriptor = new
                {
                    Descriptor = new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        testCase.ItemFunc(),
                        testConfig => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = ODataExpectedExceptions.ODataException("ODataWriter_RelativeUriUsedWithoutBaseUriSpecified", uri.OriginalString)
                    }),
                    Formats = testCase.Formats
                };

                if (testDescriptor.Formats.Contains(testConfiguration.Format))
                {
                    PayloadWriterTestDescriptor <ODataItem> payloadTestDescriptor = testDescriptor.Descriptor;
                    TestUrlResolver urlResolver = null;
                    if (implementUrlResolver)
                    {
                        payloadTestDescriptor             = new PayloadWriterTestDescriptor <ODataItem>(payloadTestDescriptor);
                        urlResolver                       = new TestUrlResolver();
                        payloadTestDescriptor.UrlResolver = urlResolver;
                    }

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

                    TestWriterUtils.WriteAndVerifyODataPayload(payloadTestDescriptor, testConfiguration, this.Assert, this.Logger);

                    if (implementUrlResolver)
                    {
                        this.Assert.AreEqual(1, urlResolver.Calls.Where(call => call.Value.OriginalString == uri.OriginalString).Count(), "The resolver should be called exactly once for each URL.");
                    }
                }
            });
        }
Ejemplo n.º 19
0
        public void AbsoluteUriTest()
        {
            Uri[] baseUris = new Uri[]
            {
                null,
                // Standard
                new Uri("http://odata.org/"),
                new Uri("http://second.odata.org/"),
                // Reserved Characters
                new Uri("http://odata.org/MyC%2B%2BService.svc/"), // +
                new Uri("http://odata.org/My%24Service.svc/"),     // $
                new Uri("http://odata.org/My%26Service.svc/"),     // &
                new Uri("http://odata.org/My%2FService.svc/"),     // /
                new Uri("http://odata.org/My%3DService.svc/"),     // =
                new Uri("http://odata.org/My%3FService.svc/"),     // ?
                new Uri("http://odata.org/My%2CService.svc/"),     // ,
                new Uri("http://odata.org/My%3AService.svc/"),     // :
                new Uri("http://odata.org/My%40Service.svc/"),     // @
                //Unsafe Characters
                new Uri("http://odata.org/My%20Service.svc/"),     // space
                new Uri("http://odata.org/My%22Service.svc/"),     // "
                new Uri("http://odata.org/My%23Service.svc/"),     // #
                new Uri("http://odata.org/My%25Service.svc/"),     // %
                new Uri("http://odata.org/My%5CService.svc/"),     // \
                new Uri("http://odata.org/My%7EService.svc/"),     // ~
                new Uri("http://odata.org/My%5EService.svc/"),     // ^
                new Uri("http://odata.org/My%5BService.svc/"),     // [
                new Uri("http://odata.org/My%5DService.svc/"),     // ]
                new Uri("http://odata.org/My%60Service.svc/"),     // `
                new Uri("http://odata.org/My%7CService.svc/"),     // |
                new Uri("http://odata.org/My%7BService.svc/"),     // {
                new Uri("http://odata.org/My%7DService.svc/"),     // }
                // Others
                new Uri("http://odata.org:80/MyService.svc/"),
                new Uri("http://odata.org/My_Service.svc/"),
                new Uri("http://odata.org/My-Service.svc/"),
                new Uri("http://odata.org/My31572Service.svc/"),
            };

            Uri[] testUris = new Uri[]
            {
                new Uri("http://odata.org/testuri"),
                new Uri("http://odata.org/testuri?$filter=3.14E%2B%20ne%20null"),
                new Uri("http://odata.org/testuri?$filter='foo%20%26%20'%20ne%20null"),
                new Uri("http://odata.org/testuri?$filter=not%20endswith(Name,'%2B')"),
                new Uri("http://odata.org/testuri?$filter=geo.distance(Point,%20geometry'SRID=0;Point(6.28E%2B3%20-2.1e%2B4)')%20eq%20null"),
            };

            var testDescriptors = uriTestCases
                                  .SelectMany(testCase => testUris
                                              .SelectMany(testUri => baseUris
                                                          .Select(baseUri =>
            {
                return(new
                {
                    TestCase = testCase,
                    BaseUri = baseUri,
                    Descriptor = new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        testCase.ItemFunc(testUri),
                        CreateUriTestCaseExpectedResultCallback(baseUri, testUri, testCase))
                });
            })));

            // ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(c => false),
                new bool[] { false, true },
                (testDescriptor, testConfiguration, implementUrlResolver) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testConfiguration.Format == ODataFormat.Json && testDescriptor.TestCase.JsonExtractor != null)
                {
                    PayloadWriterTestDescriptor <ODataItem> payloadTestDescriptor = testDescriptor.Descriptor;
                    if (implementUrlResolver)
                    {
                        payloadTestDescriptor             = new PayloadWriterTestDescriptor <ODataItem>(payloadTestDescriptor);
                        payloadTestDescriptor.UrlResolver = new TestUrlResolver();
                    }

                    TestWriterUtils.WriteAndVerifyODataPayload(payloadTestDescriptor, testConfiguration, this.Assert, this.Logger);
                }
            });
        }
        public void AssociationLinkMetadataValidationTest()
        {
            EdmModel model = new EdmModel();

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

            model.AddElement(container);

            var edmEntityTypeOrderType = new EdmEntityType("TestModel", "OrderType");

            model.AddElement(edmEntityTypeOrderType);

            var edmEntityTypeCustomerType = new EdmEntityType("TestModel", "CustomerType");

            edmEntityTypeCustomerType.AddKeys(new EdmStructuralProperty(edmEntityTypeCustomerType, "ID", EdmCoreModel.Instance.GetInt32(false)));
            edmEntityTypeCustomerType.AddStructuralProperty("PrimitiveProperty", EdmCoreModel.Instance.GetString(true));
            var edmNavigationPropertyAssociationLinkOne = edmEntityTypeCustomerType.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo {
                Name = "Orders", Target = edmEntityTypeOrderType, TargetMultiplicity = EdmMultiplicity.Many
            });
            var edmNavigationPropertyAssociationLinkTwo = edmEntityTypeCustomerType.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo {
                Name = "BestFriend", Target = edmEntityTypeCustomerType, TargetMultiplicity = EdmMultiplicity.One
            });

            model.AddElement(edmEntityTypeCustomerType);

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

            model.AddElement(edmEntityTypeOpenCustomerType);

            var customerSet = container.AddEntitySet("Customers", edmEntityTypeCustomerType);
            var orderSet    = container.AddEntitySet("Orders", edmEntityTypeOrderType);

            customerSet.AddNavigationTarget(edmNavigationPropertyAssociationLinkOne, orderSet);
            customerSet.AddNavigationTarget(edmNavigationPropertyAssociationLinkTwo, customerSet);

            Uri associationLinkUrl = new Uri("http://odata.org/associationlink");

            var testCases = new[]
            {
                // Valid collection
                new
                {
                    TypeName          = "TestModel.CustomerType",
                    NavigationLink    = ObjectModelUtils.CreateDefaultCollectionLink("Orders"),
                    ExpectedException = (ExpectedException)null,
                },
                // Valid singleton
                new
                {
                    TypeName          = "TestModel.CustomerType",
                    NavigationLink    = ObjectModelUtils.CreateDefaultSingletonLink("BestFriend"),
                    ExpectedException = (ExpectedException)null,
                },
                // Undeclared on closed type
                new
                {
                    TypeName          = "TestModel.CustomerType",
                    NavigationLink    = ObjectModelUtils.CreateDefaultCollectionLink("NonExistant"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_PropertyDoesNotExistOnType", "NonExistant", "TestModel.CustomerType"),
                },
                // Undeclared on open type
                new
                {
                    TypeName          = "TestModel.OpenCustomerType",
                    NavigationLink    = ObjectModelUtils.CreateDefaultCollectionLink("NonExistant"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_OpenNavigationProperty", "NonExistant", "TestModel.OpenCustomerType"),
                },
                // Declared but of wrong kind
                new
                {
                    TypeName          = "TestModel.CustomerType",
                    NavigationLink    = ObjectModelUtils.CreateDefaultSingletonLink("PrimitiveProperty"),
                    ExpectedException = ODataExpectedExceptions.ODataException("ValidationUtils_NavigationPropertyExpected", "PrimitiveProperty", "TestModel.CustomerType", "Structural"),
                },
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                entry.TypeName      = testCase.TypeName;
                ODataNestedResourceInfo navigationLink = testCase.NavigationLink;
                navigationLink.AssociationLinkUrl      = associationLinkUrl;

                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           new ODataItem[] { entry, navigationLink },
                           tc => (WriterTestExpectedResults) new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    ExpectedException2 = testCase.ExpectedException
                })
                {
                    Model = model,
                    PayloadEdmElementContainer = customerSet
                });
            });

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void AssociationLinkOnNavigationLinkTest()
        {
            EdmModel model = new EdmModel();

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

            model.AddElement(container);

            var edmEntityTypeOrderType = new EdmEntityType("TestModel", "OrderType");

            model.AddElement(edmEntityTypeOrderType);

            var edmEntityTypeCustomerType = new EdmEntityType("TestModel", "CustomerType");
            var edmNavigationPropertyAssociationLinkOne = edmEntityTypeCustomerType.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo {
                Name = "NavProp1", Target = edmEntityTypeOrderType, TargetMultiplicity = EdmMultiplicity.One
            });
            var edmNavigationPropertyAssociationLinkTwo = edmEntityTypeCustomerType.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo {
                Name = "NavProp2", Target = edmEntityTypeOrderType, TargetMultiplicity = EdmMultiplicity.Many
            });

            model.AddElement(edmEntityTypeCustomerType);

            var customerSet = container.AddEntitySet("Customers", edmEntityTypeCustomerType);
            var orderSet    = container.AddEntitySet("Orders", edmEntityTypeOrderType);

            customerSet.AddNavigationTarget(edmNavigationPropertyAssociationLinkOne, orderSet);
            customerSet.AddNavigationTarget(edmNavigationPropertyAssociationLinkTwo, orderSet);

            var testCases = new[]
            {
                // Both nav link URL and association link URL
                new {
                    NavigationLink = new ODataNestedResourceInfo()
                    {
                        Name = "NavProp1", IsCollection = false, Url = new Uri("http://odata.org/navlink"), AssociationLinkUrl = new Uri("http://odata.org/assoclink")
                    },
                    PropertyName = "NavProp1",
                    Atom         = BuildXmlNavigationLink("NavProp1", "application/atom+xml;type=entry", "http://odata.org/navlink"),
                    JsonLight    =
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("NavProp1", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navlink\"," +
                        "\"" + JsonLightUtils.GetPropertyAnnotationName("NavProp1", JsonLightConstants.ODataAssociationLinkUrlAnnotationName) + "\":\"http://odata.org/assoclink\""
                },
                // Just nav link URL
                new {
                    NavigationLink = new ODataNestedResourceInfo()
                    {
                        Name = "NavProp1", IsCollection = false, Url = new Uri("http://odata.org/navlink"), AssociationLinkUrl = null
                    },
                    PropertyName = "NavProp1",
                    Atom         = BuildXmlNavigationLink("NavProp1", "application/atom+xml;type=entry", "http://odata.org/navlink"),
                    JsonLight    = "\"" + JsonLightUtils.GetPropertyAnnotationName("NavProp1", JsonLightConstants.ODataNavigationLinkUrlAnnotationName) + "\":\"http://odata.org/navlink\""
                },
                // Just association link URL
                new {
                    NavigationLink = new ODataNestedResourceInfo()
                    {
                        Name = "NavProp1", IsCollection = false, Url = null, AssociationLinkUrl = new Uri("http://odata.org/assoclink")
                    },
                    PropertyName = "NavProp1",
                    Atom         = (string)null,
                    JsonLight    = "\"" + JsonLightUtils.GetPropertyAnnotationName("NavProp1", JsonLightConstants.ODataAssociationLinkUrlAnnotationName) + "\":\"http://odata.org/assoclink\""
                },
                // Navigation link with both URLs null
                new {
                    NavigationLink = new ODataNestedResourceInfo()
                    {
                        Name = "NavProp1", IsCollection = false, Url = null, AssociationLinkUrl = null
                    },
                    PropertyName = "NavProp1",
                    Atom         = (string)null,
                    JsonLight    = string.Empty
                }
            };

            IEnumerable <PayloadWriterTestDescriptor <ODataItem> > testDescriptors = testCases.Select(testCase =>
            {
                ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                entry.TypeName      = "TestModel.CustomerType";
                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           new ODataItem[] { entry, testCase.NavigationLink, null },
                           (testConfiguration) =>
                {
                    if (testConfiguration.Format == ODataFormat.Json)
                    {
                        return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Json = string.Join(
                                "$(NL)",
                                "{",
                                testCase.JsonLight,
                                "}"),
                            FragmentExtractor = (result) =>
                            {
                                var links = result.Object().GetPropertyAnnotations(testCase.PropertyName).ToList();
                                var jsonResult = new JsonObject();
                                links.ForEach(l =>
                                {
                                    // NOTE we remove all annoatations here and in particular the text annotations to be able to easily compare
                                    //      against the expected results. This however means that we do not distinguish between the indented and non-indented case here.
                                    l.RemoveAllAnnotations(true);
                                    jsonResult.Add(l);
                                });
                                return jsonResult;
                            }
                        };
                    }
                    else
                    {
                        this.Settings.Assert.Fail("Unknown format '{0}'.", testConfiguration.Format);
                        return null;
                    }
                })
                {
                    Model = model,
                    PayloadEdmElementContainer = customerSet
                });
            });

            // With and without model
            testDescriptors = testDescriptors.SelectMany(td =>
                                                         new[]
            {
                td,
                new PayloadWriterTestDescriptor <ODataItem>(td)
                {
                    Model = null,
                    PayloadEdmElementContainer = null
                }
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.EntryPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(testConfiguration => !testConfiguration.IsRequest),
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testDescriptor.Model == null && testConfiguration.Format == ODataFormat.Json)
                {
                    return;
                }

                if (testDescriptor.IsGeneratedPayload && testDescriptor.Model != null)
                {
                    return;
                }

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 22
0
        public void CategoryMetadataOnEntryWriterTest()
        {
            var testCases = this.CreateAtomCategoryTestCases();

            Func <XElement, XElement> fragmentExtractor = (e) =>
            {
                var categoryElement = e.Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomCategoryElementName);
                return(categoryElement ?? new XElement("missingCategory"));
            };

            // Convert test cases to test descriptions
            IEnumerable <PayloadWriterTestDescriptor <ODataItem> > testDescriptors = testCases.Select(testCase =>
            {
                ODataEntry entry           = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();
                AtomEntryMetadata metadata = entry.Atom();
                this.Assert.IsNotNull(metadata, "Expected default entry metadata on a default entry.");
                metadata.Categories = new AtomCategoryMetadata[] { testCase.Category };
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                   new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.Xml, ExpectedException2 = testCase.ExpectedException, FragmentExtractor = fragmentExtractor
                }));
            });

            // Add tests for category with type name
            string testTypeName = "TestModel.TestTypeName";
            string testLabel    = "Test category 1 label";
            var    categoryWithTypeNameTestCases = new[]
            {
                // Clean merge, no conflicts
                new AtomCategoryTestCase
                {
                    Category = new AtomCategoryMetadata()
                    {
                        Term   = null,
                        Scheme = null,
                        Label  = testLabel,
                    },
                    Xml = @"<category term=""" + testTypeName + @""" scheme=""" + TestAtomConstants.ODataSchemeNamespace + @""" label=""" + testLabel + @""" xmlns=""" + TestAtomConstants.AtomNamespace + @""" />",
                    ExpectedException = null
                },
                // Patch, conflicting values match
                new AtomCategoryTestCase
                {
                    Category = new AtomCategoryMetadata()
                    {
                        Term   = testTypeName,
                        Scheme = TestAtomConstants.ODataSchemeNamespace,
                        Label  = testLabel,
                    },
                    Xml = @"<category term=""" + testTypeName + @""" scheme=""" + TestAtomConstants.ODataSchemeNamespace + @""" label=""" + testLabel + @""" xmlns=""" + TestAtomConstants.AtomNamespace + @""" />",
                    ExpectedException = null
                },
                // Patch conflict on term
                new AtomCategoryTestCase
                {
                    Category = new AtomCategoryMetadata()
                    {
                        Term   = testTypeName.ToUpper(),
                        Scheme = TestAtomConstants.ODataSchemeNamespace,
                        Label  = testLabel,
                    },
                    Xml = @"<category term=""" + testTypeName + @""" scheme=""" + TestAtomConstants.ODataSchemeNamespace + @""" label=""" + testLabel + @""" xmlns=""" + TestAtomConstants.AtomNamespace + @""" />",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_CategoryTermsMustMatch", testTypeName, testTypeName.ToUpper())
                },
                // Patch conflict on scheme
                new AtomCategoryTestCase
                {
                    Category = new AtomCategoryMetadata()
                    {
                        Term   = testTypeName,
                        Scheme = TestAtomConstants.ODataSchemeNamespace.ToUpper(),
                        Label  = testLabel,
                    },
                    Xml = @"<category term=""" + testTypeName + @""" scheme=""" + TestAtomConstants.ODataSchemeNamespace + @""" label=""" + testLabel + @""" xmlns=""" + TestAtomConstants.AtomNamespace + @""" />",
                    ExpectedException = ODataExpectedExceptions.ODataException("ODataAtomWriterMetadataUtils_CategorySchemesMustMatch", TestAtomConstants.ODataSchemeNamespace, TestAtomConstants.ODataSchemeNamespace.ToUpper())
                },
            };

            testDescriptors = testDescriptors.Concat(categoryWithTypeNameTestCases.Select(testCase =>
            {
                ODataEntry entry           = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();
                entry.TypeName             = testTypeName;
                AtomEntryMetadata metadata = entry.Atom();
                this.Assert.IsNotNull(metadata, "Expected default entry metadata on a default entry.");
                metadata.CategoryWithTypeName = testCase.Category;
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                   new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = testCase.Xml, ExpectedException2 = testCase.ExpectedException, FragmentExtractor = fragmentExtractor
                }));
            }));

            // Add all the categories as the category with type name on entry which has no type name.
            // This verifies that the writer won't write the category with type name if there's no type name.
            testDescriptors = testDescriptors.Concat(testCases.Select(testCase =>
            {
                ODataEntry entry           = ObjectModelUtils.CreateDefaultEntryWithAtomMetadata();
                AtomEntryMetadata metadata = entry.Atom();
                this.Assert.IsNotNull(metadata, "Expected default entry metadata on a default entry.");
                metadata.CategoryWithTypeName = testCase.Category;
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, entry, testConfiguration =>
                                                                   new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = "<missingCategory />", ExpectedException2 = null, FragmentExtractor = fragmentExtractor
                }));
            }));

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void EntryDefaultStreamTest()
        {
            string readLink               = "http://odata.org/read";
            Uri    readLinkUri            = new Uri(readLink);
            string editLink               = "http://odata.org/edit";
            Uri    editLinkUri            = new Uri(editLink);
            string contentType            = "application/binary";
            string etag                   = "\"myetagvalue\"";
            string atomEscapedEtag        = "&quot;myetagvalue&quot;";
            string outOfContentProperties = "<m:properties xmlns:m=\"" + TestAtomConstants.ODataMetadataNamespace + "\"><d:ID xmlns:d=\"" + TestAtomConstants.ODataNamespace + "\">foo</d:ID></m:properties>";

            var testCases = new[]
            {
                new {  // Completely empty default stream is valid and should not produce any MLE/MR related values in the payload
                    DefaultStream = new ODataStreamReferenceValue(),
                    Atom          = outOfContentProperties,
                },
                new {  // Bare minimum for valid default stream
                    DefaultStream = new ODataStreamReferenceValue()
                    {
                        ReadLink = readLinkUri, EditLink = null, ContentType = contentType, ETag = null
                    },
                    Atom = "<content type=\"" + contentType + "\" src=\"" + readLinkUri + "\" xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />" +
                           outOfContentProperties
                },
                new {  // with edit link
                    DefaultStream = new ODataStreamReferenceValue()
                    {
                        ReadLink = readLinkUri, EditLink = editLinkUri, ContentType = contentType, ETag = null
                    },
                    Atom = "<content type=\"" + contentType + "\" src=\"" + readLinkUri + "\" xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />" +
                           "<link rel=\"edit-media\" href=\"" + editLink + "\" xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />" +
                           outOfContentProperties
                },
                new {  // just edit link
                    DefaultStream = new ODataStreamReferenceValue()
                    {
                        ReadLink = null, EditLink = editLinkUri, ContentType = null, ETag = null
                    },
                    Atom = "<link rel=\"edit-media\" href=\"" + editLink + "\" xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />" +
                           outOfContentProperties
                },
                // etag without edit link is invalid and is covered in input validation tests
                new {  // with edit link and etag
                    DefaultStream = new ODataStreamReferenceValue()
                    {
                        ReadLink = readLinkUri, EditLink = editLinkUri, ContentType = contentType, ETag = etag
                    },
                    Atom = "<content type=\"" + contentType + "\" src=\"" + readLinkUri + "\" xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />" +
                           "<link rel=\"edit-media\" href=\"" + editLink + "\" p2:etag=\"" + atomEscapedEtag + "\" xmlns:p2=\"" + TestAtomConstants.ODataMetadataNamespace + "\" " +
                           "xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />" +
                           outOfContentProperties
                }
            };

            var testDescriptors = testCases.Select(testCase =>
            {
                ODataEntry entry = ObjectModelUtils.CreateDefaultEntry();
                entry.Properties = new ODataProperty[] { new ODataProperty {
                                                             Name = "ID", Value = "foo"
                                                         } };
                entry.MediaResource = testCase.DefaultStream;
                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           entry,
                           (testConfiguration) =>
                {
                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Xml = "<DefaultStream>" + testCase.Atom + "</DefaultStream>",
                        FragmentExtractor = (result) =>
                        {
                            var content = result.Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomContentElementName);
                            content = content == null ? null : new XElement(content.Name, content.Attributes());
                            var mediaEditLink = result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                                                .Where(l => (string)l.Attribute(TestAtomConstants.AtomLinkRelationAttributeName) == TestAtomConstants.ODataStreamPropertyEditMediaSegmentName);
                            var properties = result.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.AtomPropertiesElementName);
                            return new XElement("DefaultStream", content, mediaEditLink, properties);
                        }
                    };
                }));
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.EntryPayloads),
                this.WriterTestConfigurationProvider.AtomFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, 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);
            });
        }
Ejemplo n.º 25
0
        public void StreamPropertiesNegativeTests()
        {
            EdmModel model = new EdmModel();

            EdmComplexType edmComplexType = new EdmComplexType("TestModel", "MyComplexType");

            edmComplexType.AddStructuralProperty("Stream1", EdmCoreModel.Instance.GetStream(false));
            model.AddElement(edmComplexType);

            EdmEntityType edmEntityType = new EdmEntityType("TestModel", "EntityTypeForStreams");

            edmEntityType.AddStructuralProperty("Complex", new EdmComplexTypeReference(edmComplexType, false));
            edmEntityType.AddStructuralProperty("Collection", EdmCoreModel.GetCollection(new EdmComplexTypeReference(edmComplexType, false)));
            edmEntityType.AddStructuralProperty("Int32Collection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetInt32(false)));
            edmEntityType.AddStructuralProperty("NamedStreamCollection", EdmCoreModel.GetCollection(EdmCoreModel.Instance.GetStream(false)));
            model.AddElement(edmEntityType);

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

            model.AddElement(edmEntityContainer);

            var entitySet = edmEntityContainer.AddEntitySet("EntitySetForStreams", edmEntityType);

            var testCases = new[] {
                // Note that negative test cases to validate the content of an ODataStreamReferenceValue are in WriteInputValidationTests.cs.
                // TODO: We need to add these test cases for writing top level properties and metadata as well.
                new { // named stream properties are not allowed on complex types
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Complex",
                        Value = new ODataComplexValue()
                        {
                            TypeName   = "TestModel.MyComplexType",
                            Properties = new[]
                            {
                                new ODataProperty()
                                {
                                    Name  = "Stream1",
                                    Value = new ODataStreamReferenceValue()
                                    {
                                        EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                    }
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                },
                new { // named stream properties are not allowed on complex collection types
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Collection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("TestModel.MyComplexType"),
                            Items    = new[]
                            {
                                new ODataComplexValue()
                                {
                                    TypeName   = "TestModel.MyComplexType",
                                    Properties = new[]
                                    {
                                        new ODataProperty()
                                        {
                                            Name  = "Stream1",
                                            Value = new ODataStreamReferenceValue()
                                            {
                                                EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ODataWriter_StreamPropertiesMustBePropertiesOfODataEntry"),
                },
                // TODO: Add the following case for the top-level collection writer as well.
                new { // named stream collection properties are not allowed.
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "Int32Collection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("Edm.Int32"),
                            Items    = new[]
                            {
                                new ODataStreamReferenceValue()
                                {
                                    EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                },
                new { // named stream collection properties are not allowed - with valid type.
                    NamedStreamProperty = new ODataProperty()
                    {
                        Name  = "NamedStreamCollection",
                        Value = new ODataCollectionValue()
                        {
                            TypeName = EntityModelUtils.GetCollectionTypeName("Edm.Stream"),
                            Items    = new[]
                            {
                                new ODataStreamReferenceValue()
                                {
                                    EditLink = new Uri("someUri", UriKind.RelativeOrAbsolute)
                                }
                            }
                        }
                    },
                    ExpectedExceptionWithoutModel = ODataExpectedExceptions.ODataException("ValidationUtils_StreamReferenceValuesNotSupportedInCollections"),
                    ExpectedExceptionWithModel    = ODataExpectedExceptions.ODataException("EdmLibraryExtensions_CollectionItemCanBeOnlyPrimitiveEnumComplex"),
                },
            };

            var testDescriptors = testCases.SelectMany(testCase =>
            {
                ODataEntry entry = new ODataEntry()
                {
                    TypeName          = "TestModel.EntityTypeForStreams",
                    Properties        = new ODataProperty[] { testCase.NamedStreamProperty },
                    SerializationInfo = new ODataFeedAndEntrySerializationInfo()
                    {
                        NavigationSourceEntityTypeName = "TestModel.EntityTypeForStreams",
                        ExpectedTypeName     = "TestModel.EntityTypeForStreams",
                        NavigationSourceName = "MySet"
                    }
                };
                return(new []
                {
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        entry,
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = testCase.ExpectedExceptionWithoutModel
                    })
                    {
                        Model = null,
                    },
                    new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        entry,
                        testConfiguration => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = testCase.ExpectedExceptionWithModel
                    })
                    {
                        Model = model,
                        PayloadEdmElementContainer = entitySet,
                        PayloadEdmElementType = edmEntityType,
                    },
                });
            });

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

                if (testDescriptor.Model == null && testConfiguration.Format == ODataFormat.Json)
                {
                    return;
                }

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 26
0
        public void WriterStreamPropertiesTests()
        {
            Uri baseUri             = new Uri("http://www.odata.org/", UriKind.Absolute);
            Uri relativeReadLinkUri = new Uri("readlink", UriKind.RelativeOrAbsolute);
            Uri relativeEditLinkUri = new Uri("editlink", UriKind.RelativeOrAbsolute);
            Uri absoluteReadLinkUri = new Uri(baseUri, relativeReadLinkUri.OriginalString);
            Uri absoluteEditLinkUri = new Uri(baseUri, relativeEditLinkUri.OriginalString);

            string contentType        = "application/binary";
            string etag               = "\"myetagvalue\"";
            string streamPropertyName = "stream1";

            var namedStreamProperties = new[]
            {
                // with only read link
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri, ContentType = contentType
                    }
                },
                // with only edit link
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = relativeEditLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = relativeEditLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = absoluteEditLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = absoluteEditLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        EditLink = absoluteEditLinkUri, ContentType = contentType, ETag = etag
                    }
                },
                // with both edit and read link
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = relativeReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType
                    }
                },
                new ODataProperty {
                    Name = streamPropertyName, Value = new ODataStreamReferenceValue {
                        ReadLink = absoluteReadLinkUri, EditLink = relativeEditLinkUri, ContentType = contentType, ETag = etag
                    }
                },
            };

            var testCases = namedStreamProperties.Select(property =>
            {
                var propertyName         = property.Name;
                var streamReferenceValue = (ODataStreamReferenceValue)property.Value;
                return(new StreamPropertyTestCase
                {
                    NamedStreamProperty = property,
                    GetExpectedAtomPayload = (testConfiguration) =>
                    {
                        return
                        (streamReferenceValue.ReadLink == null
                                    ? string.Empty
                                    : (
                             "<link rel=\"http://docs.oasis-open.org/odata/ns/mediaresource/" + property.Name + "\" " +
                             (streamReferenceValue.ContentType == null ? string.Empty : "type=\"" + streamReferenceValue.ContentType + "\" ") +
                             "title=\"" + property.Name + "\" " +
                             "href=\"" + (((ODataStreamReferenceValue)property.Value).ReadLink.IsAbsoluteUri ? absoluteReadLinkUri.OriginalString : relativeReadLinkUri.OriginalString) + "\" " +
                             "xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />")) +

                        (streamReferenceValue.EditLink == null
                                    ? string.Empty
                                    : (
                             "<link rel=\"http://docs.oasis-open.org/odata/ns/edit-media/" + property.Name + "\" " +
                             (streamReferenceValue.ContentType == null ? string.Empty : "type=\"" + streamReferenceValue.ContentType + "\" ") +
                             "title=\"" + property.Name + "\" " +
                             "href=\"" + (((ODataStreamReferenceValue)property.Value).EditLink.IsAbsoluteUri ? absoluteEditLinkUri.OriginalString : relativeEditLinkUri.OriginalString) + "\" " +
                             (streamReferenceValue.ETag == null ? string.Empty : "m:etag=\"" + streamReferenceValue.ETag.Replace("\"", "&quot;") + "\" xmlns:m=\"" + TestAtomConstants.ODataMetadataNamespace + "\" ") +
                             "xmlns=\"" + TestAtomConstants.AtomNamespace + "\" />"));
                    },
                    GetExpectedJsonLightPayload = (testConfiguration) =>
                    {
                        return JsonLightWriterUtils.CombineProperties(
                            (streamReferenceValue.EditLink == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaEditLinkAnnotationName) + "\":\"" + absoluteEditLinkUri.OriginalString + "\"")),
                            (streamReferenceValue.ReadLink == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaReadLinkAnnotationName) + "\":\"" + absoluteReadLinkUri.OriginalString + "\"")),
                            (streamReferenceValue.ContentType == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaContentTypeAnnotationName) + "\":\"" + streamReferenceValue.ContentType + "\"")),
                            (streamReferenceValue.ETag == null ? string.Empty : ("\"" + JsonLightUtils.GetPropertyAnnotationName(propertyName, JsonLightConstants.ODataMediaETagAnnotationName) + "\":\"" + streamReferenceValue.ETag.Replace("\"", "\\\"") + "\"")));
                    },
                });
            });

            var testDescriptors = testCases.SelectMany(testCase =>
            {
                EdmModel model = new EdmModel();

                EdmEntityType edmEntityType = new EdmEntityType("TestModel", "StreamPropertyEntityType");
                EdmStructuralProperty edmStructuralProperty = edmEntityType.AddStructuralProperty("Id", EdmPrimitiveTypeKind.Int32, false);
                edmEntityType.AddKeys(new IEdmStructuralProperty[] { edmStructuralProperty });
                model.AddElement(edmEntityType);

                EdmEntityContainer edmEntityContainer = new EdmEntityContainer("TestModel", "DefaultContainer");
                model.AddElement(edmEntityContainer);

                EdmEntitySet edmEntitySet = new EdmEntitySet(edmEntityContainer, "StreamPropertyEntitySet", edmEntityType);
                edmEntityContainer.AddElement(edmEntitySet);

                ODataEntry entry = new ODataEntry()
                {
                    Id       = ObjectModelUtils.DefaultEntryId,
                    ReadLink = ObjectModelUtils.DefaultEntryReadLink,
                    TypeName = edmEntityType.FullName()
                };

                var streamReference = (ODataStreamReferenceValue)testCase.NamedStreamProperty.Value;
                bool needBaseUri    = (streamReference.ReadLink != null && !streamReference.ReadLink.IsAbsoluteUri) || (streamReference.EditLink != null && !streamReference.EditLink.IsAbsoluteUri);
                entry.Properties    = new ODataProperty[] { testCase.NamedStreamProperty };

                var resultDescriptor = new PayloadWriterTestDescriptor <ODataItem>(
                    this.Settings,
                    entry,
                    (testConfiguration) =>
                {
                    if (testConfiguration.Format == ODataFormat.Atom)
                    {
                        return(new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Xml = "<NamedStream>" + testCase.GetExpectedAtomPayload(testConfiguration) + "</NamedStream>",
                            FragmentExtractor = result => result,
                        });
                    }
                    else if (testConfiguration.Format == ODataFormat.Json)
                    {
                        return(new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Json = string.Join(
                                "$(NL)",
                                "{",
                                testCase.GetExpectedJsonLightPayload(testConfiguration),
                                "}"),
                            FragmentExtractor = result => result.RemoveAllAnnotations(true),
                        });
                    }
                    else
                    {
                        throw new NotSupportedException("Unsupported ODataFormat found: " + testConfiguration.Format.ToString());
                    }
                })
                {
                    Model = model,
                    PayloadEdmElementContainer = edmEntityContainer,
                    PayloadEdmElementType      = edmEntityType,
                };

                var resultTestCases = new List <StreamPropertyTestDescriptor>();
                if (needBaseUri)
                {
                    resultTestCases.Add(new StreamPropertyTestDescriptor {
                        BaseUri = baseUri, TestDescriptor = resultDescriptor
                    });
                }
                else
                {
                    resultTestCases.Add(new StreamPropertyTestDescriptor {
                        BaseUri = null, TestDescriptor = resultDescriptor
                    });
                    resultTestCases.Add(new StreamPropertyTestDescriptor {
                        BaseUri = baseUri, TestDescriptor = resultDescriptor
                    });
                    resultTestCases.Add(new StreamPropertyTestDescriptor {
                        BaseUri = new Uri("http://mybaseuri/", UriKind.Absolute), TestDescriptor = resultDescriptor
                    });
                }

                return(resultTestCases);
            });

            var testDescriptorBaseUriPairSet = testDescriptors.SelectMany(descriptor =>
                                                                          WriterPayloads.NamedStreamPayloads(descriptor.TestDescriptor).Select(namedStreamPayload =>
                                                                                                                                               new Tuple <PayloadWriterTestDescriptor <ODataItem>, Uri>(namedStreamPayload, descriptor.BaseUri)));

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptorBaseUriPairSet,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptorBaseUriPair, testConfiguration) =>
            {
                var testDescriptor = testDescriptorBaseUriPair.Item1;

                if (testDescriptor.IsGeneratedPayload && testConfiguration.Format == ODataFormat.Json)
                {
                    return;
                }

                ODataMessageWriterSettings settings = testConfiguration.MessageWriterSettings.Clone();
                settings.PayloadBaseUri             = testDescriptorBaseUriPair.Item2;
                settings.SetServiceDocumentUri(ServiceDocumentUri);

                WriterTestConfiguration config =
                    new WriterTestConfiguration(testConfiguration.Format, settings, testConfiguration.IsRequest, testConfiguration.Synchronous);

                if (testConfiguration.IsRequest)
                {
                    ODataEntry payloadEntry           = (ODataEntry)testDescriptor.PayloadItems[0];
                    ODataProperty firstStreamProperty = payloadEntry.Properties.Where(p => p.Value is ODataStreamReferenceValue).FirstOrDefault();
                    this.Assert.IsNotNull(firstStreamProperty, "firstStreamProperty != null");

                    testDescriptor = new PayloadWriterTestDescriptor <ODataItem>(testDescriptor)
                    {
                        ExpectedResultCallback = tc => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            ExpectedException2 = ODataExpectedExceptions.ODataException("WriterValidationUtils_StreamPropertyInRequest", firstStreamProperty.Name)
                        }
                    };
                }

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, config, this.Assert, this.Logger);
            });
        }
        public void AssociationLinkTest()
        {
            string associationLinkName1 = "AssociationLinkOne";
            string linkUrl1             = "http://odata.org/associationlink";
            Uri    linkUrlUri1          = new Uri(linkUrl1);
            string associationLinkName2 = "AssociationLinkTwo";
            string linkUrl2             = "http://odata.org/associationlink2";
            Uri    linkUrlUri2          = new Uri(linkUrl2);

            EdmModel model = new EdmModel();

            var edmEntityTypeOrderType = new EdmEntityType("TestModel", "OrderType");

            model.AddElement(edmEntityTypeOrderType);

            var edmEntityTypeCustomerType = new EdmEntityType("TestModel", "CustomerType");
            var edmNavigationPropertyAssociationLinkOne = edmEntityTypeCustomerType.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo {
                Name = associationLinkName1, Target = edmEntityTypeOrderType, TargetMultiplicity = EdmMultiplicity.One
            });
            var edmNavigationPropertyAssociationLinkTwo = edmEntityTypeCustomerType.AddUnidirectionalNavigation(
                new EdmNavigationPropertyInfo {
                Name = associationLinkName2, Target = edmEntityTypeOrderType, TargetMultiplicity = EdmMultiplicity.Many
            });

            model.AddElement(edmEntityTypeCustomerType);

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

            model.AddElement(container);

            var customerSet = container.AddEntitySet("Customers", edmEntityTypeCustomerType);
            var orderSet    = container.AddEntitySet("Orders", edmEntityTypeOrderType);

            customerSet.AddNavigationTarget(edmNavigationPropertyAssociationLinkOne, orderSet);
            customerSet.AddNavigationTarget(edmNavigationPropertyAssociationLinkTwo, orderSet);

            var testCases = new[]
            {
                new {
                    NavigationLink = ObjectModelUtils.CreateDefaultNavigationLink(associationLinkName1, linkUrlUri1),
                    Atom           = BuildXmlAssociationLink(associationLinkName1, "application/xml", linkUrl1),
                    JsonLight      = (string)null,
                },
                new {
                    NavigationLink = ObjectModelUtils.CreateDefaultNavigationLink(associationLinkName2, linkUrlUri2),
                    Atom           = BuildXmlAssociationLink(associationLinkName2, "application/xml", linkUrl2),
                    JsonLight      = (string)null
                },
            };

            var testCasesWithMultipleLinks = testCases.Variations()
                                             .Select(tcs =>
                                                     new
            {
                NavigationLinks = tcs.Select(tc => tc.NavigationLink),
                Atom            = string.Concat(tcs.Select(tc => tc.Atom)),
                JsonLight       = string.Join(",", tcs.Where(tc => tc.JsonLight != null).Select(tc => tc.JsonLight))
            });

            var testDescriptors = testCasesWithMultipleLinks.Select(testCase =>
            {
                ODataResource entry    = ObjectModelUtils.CreateDefaultEntry();
                entry.TypeName         = "TestModel.CustomerType";
                List <ODataItem> items = new ODataItem[] { entry }.ToList();
                foreach (var navLink in testCase.NavigationLinks)
                {
                    items.Add(navLink);
                    items.Add(null);
                }

                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           items,
                           (testConfiguration) =>
                {
                    var firstAssocLink = testCase.NavigationLinks == null ? null : testCase.NavigationLinks.FirstOrDefault();
                    if (testConfiguration.Format == ODataFormat.Json)
                    {
                        return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Json = string.Join(
                                "$(NL)",
                                "{",
                                testCase.JsonLight,
                                "}"),
                            FragmentExtractor = (result) =>
                            {
                                var associationLinks = result.Object().GetAnnotationsWithName("@" + JsonLightConstants.ODataAssociationLinkUrlAnnotationName).ToList();
                                var jsonResult = new JsonObject();
                                associationLinks.ForEach(l =>
                                {
                                    // NOTE we remove all annoatations here and in particular the text annotations to be able to easily compare
                                    //      against the expected results. This however means that we do not distinguish between the indented and non-indented case here.
                                    l.RemoveAllAnnotations(true);
                                    jsonResult.Add(l);
                                });
                                return jsonResult;
                            },
                        };
                    }
                    else
                    {
                        this.Settings.Assert.Fail("Unknown format '{0}'.", testConfiguration.Format);
                        return null;
                    }
                })
                {
                    Model = model,
                    PayloadEdmElementContainer = customerSet
                });
            });

            // With and without model
            testDescriptors = testDescriptors.SelectMany(td =>
                                                         new[]
            {
                td,
                new PayloadWriterTestDescriptor <ODataItem>(td)
                {
                    Model = null,
                    PayloadEdmElementContainer = null
                }
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.EntryPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testDescriptor.Model == null && testConfiguration.Format == ODataFormat.Json)
                {
                    return;
                }

                if (testDescriptor.IsGeneratedPayload && testDescriptor.Model != null)
                {
                    return;
                }

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 28
0
        public void ExpandedLinkWithNullNavigationTests()
        {
            ODataNavigationLink expandedEntryLink = ObjectModelUtils.CreateDefaultCollectionLink();

            expandedEntryLink.IsCollection = false;

            ODataNavigationLink expandedEntryLink2 = ObjectModelUtils.CreateDefaultCollectionLink();

            expandedEntryLink2.IsCollection = false;
            expandedEntryLink2.Name         = expandedEntryLink2.Name + "2";

            ODataEntry defaultEntry = ObjectModelUtils.CreateDefaultEntry();
            ODataFeed  defaultFeed  = ObjectModelUtils.CreateDefaultFeed();
            ODataEntry nullEntry    = ObjectModelUtils.ODataNullEntry;

            PayloadWriterTestDescriptor.WriterTestExpectedResultCallback successCallback = (testConfiguration) =>
            {
                if (testConfiguration.Format == ODataFormat.Atom)
                {
                    return(new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Xml = new XElement(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName).ToString(),
                        FragmentExtractor = (result) =>
                        {
                            return result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                            .First(e => e.Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName) != null)
                            .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName);
                        }
                    });
                }
                else
                {
                    return(new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Json = "null", //new JsonPrimitiveValue(null).ToText(testConfiguration.MessageWriterSettings.Indent),
                        FragmentExtractor = (result) =>
                        {
                            return JsonUtils.UnwrapTopLevelValue(testConfiguration, result).Object().Properties.First(p => p.Name == ObjectModelUtils.DefaultLinkName).Value;
                        }
                    });
                }
            };

            Func <ExpectedException, PayloadWriterTestDescriptor.WriterTestExpectedResultCallback> errorCallback = (expectedException) =>
            {
                return((testConfiguration) =>
                {
                    return new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = expectedException,
                    };
                });
            };

            var testCases = new PayloadWriterTestDescriptor <ODataItem>[]
            {
                // navigation to a null entry
                new PayloadWriterTestDescriptor <ODataItem>(
                    this.Settings,
                    new ODataItem[] { defaultEntry, expandedEntryLink, nullEntry },
                    successCallback),

                // navigation to a null entry twice
                new PayloadWriterTestDescriptor <ODataItem>(
                    this.Settings,
                    new ODataItem[] { defaultEntry, expandedEntryLink, nullEntry, null, null, expandedEntryLink2, nullEntry, null },
                    successCallback),

                // top level null entry.
                new PayloadWriterTestDescriptor <ODataItem>(
                    this.Settings,
                    new ODataItem[] { nullEntry },
                    errorCallback(new ExpectedException(typeof(ArgumentNullException)))),

                // navigation to a null entry twice in expanded link
                // this actually throws ArgumentNullException when WriteStart() for the second nullEntry is called since
                // the state has been changed from NavigationLink to ExpandedLink after the first one.
                // TODO: check if ArgumentNullException needs to change the WriterState.
                new PayloadWriterTestDescriptor <ODataItem>(
                    this.Settings,
                    new ODataItem[] { defaultEntry, expandedEntryLink, nullEntry, null, nullEntry },
                    errorCallback(new ExpectedException(typeof(ArgumentNullException)))),

                // Null entry inside a feed, same as above this throws ArgumentNullException but state is not put to error state.
                new PayloadWriterTestDescriptor <ODataItem>(
                    this.Settings,
                    new ODataItem[] { defaultFeed, nullEntry },
                    errorCallback(new ExpectedException(typeof(ArgumentNullException)))),
            };

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent.Where(tc => tc.Format == ODataFormat.Atom),
                (testCase, testConfig) =>
            {
                testConfig = testConfig.Clone();
                testConfig.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                TestWriterUtils.WriteAndVerifyODataPayload(testCase, testConfig, this.Assert, this.Logger);
            });
        }
Ejemplo n.º 29
0
        public void ResolverUriTest()
        {
            Uri inputUri          = new Uri("inputUri", UriKind.Relative);
            Uri resultRelativeUri = new Uri("resultRelativeUri", UriKind.Relative);
            Uri resultAbsoluteUri = new Uri("http://odata.org/absoluteresolve");

            var resolvers = new[]
            {
                // Resolver which always returns relative URL
                new
                {
                    Resolver = new Func <Uri, Uri, Uri>((baseUri, payloadUri) => {
                        if (payloadUri.OriginalString == inputUri.OriginalString)
                        {
                            return(resultRelativeUri);
                        }
                        else
                        {
                            return(null);
                        }
                    }),
                    ResultUri = resultRelativeUri
                },
                // Resolver which always returns absolute URL
                new
                {
                    Resolver = new Func <Uri, Uri, Uri>((baseUri, payloadUri) => {
                        if (payloadUri.OriginalString == inputUri.OriginalString)
                        {
                            return(resultAbsoluteUri);
                        }
                        else
                        {
                            return(null);
                        }
                    }),
                    ResultUri = resultAbsoluteUri
                }
            };

            var testDescriptors = uriTestCases.SelectMany(testCase => resolvers.Select(resolver =>
            {
                return(new
                {
                    TestCase = testCase,
                    Descriptor = new PayloadWriterTestDescriptor <ODataItem>(
                        this.Settings,
                        testCase.ItemFunc(inputUri),
                        CreateUriTestCaseExpectedResultCallback(/*baseUri*/ null, resolver.ResultUri, testCase))
                    {
                        UrlResolver = new TestUrlResolver()
                        {
                            ResolutionCallback = resolver.Resolver
                        }
                    }
                });
            }));

            // ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors,
                new bool[] { false, true },
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(c => false),
                (testDescriptor, runInBatch, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if ((!testConfiguration.IsRequest || !testDescriptor.TestCase.ResponseOnly) &&
                    (testConfiguration.Format == ODataFormat.Json && testDescriptor.TestCase.JsonExtractor != null))
                {
                    var td = testDescriptor.Descriptor.DeferredLinksToEntityReferenceLinksInRequest(testConfiguration);
                    if (!runInBatch)
                    {
                        TestWriterUtils.WriteAndVerifyODataPayload(td, testConfiguration, this.Assert, this.Logger);
                    }
                    else
                    {
                        testConfiguration = testConfiguration.Clone();
                        testConfiguration.MessageWriterSettings.EnableMessageStreamDisposal = true;
                        var batchDescriptor = new List <BatchWriterTestDescriptor.InvocationAndOperationDescriptor>();
                        if (testConfiguration.IsRequest)
                        {
                            batchDescriptor.Add(BatchWriterUtils.StartBatch());
                            batchDescriptor.Add(BatchWriterUtils.StartChangeSet());
                            batchDescriptor.Add(BatchWriterUtils.ChangeSetRequest(
                                                    "PUT",
                                                    new Uri("http://odata.org"),
                                                    null,
                                                    null,
                                                    new BatchWriterUtils.ODataPayload()
                            {
                                Items = td.PayloadItems.ToArray(),
                                WriterTestExpectedResults = td.ExpectedResultCallback(testConfiguration),
                                TestConfiguration         = testConfiguration
                            }));
                            batchDescriptor.Add(BatchWriterUtils.EndChangeSet());
                            batchDescriptor.Add(BatchWriterUtils.EndBatch());
                        }
                        else
                        {
                            batchDescriptor.Add(BatchWriterUtils.StartBatch());
                            batchDescriptor.Add(BatchWriterUtils.QueryOperationResponse(
                                                    200,
                                                    new BatchWriterUtils.ODataPayload()
                            {
                                Items = td.PayloadItems.ToArray(),
                                WriterTestExpectedResults = td.ExpectedResultCallback(testConfiguration),
                                TestConfiguration         = testConfiguration
                            }));
                            batchDescriptor.Add(BatchWriterUtils.EndBatch());
                        }

                        var batchTd = new BatchWriterTestDescriptor(
                            this.BatchSettings,
                            batchDescriptor.ToArray(),
                            (Dictionary <string, string>)null,
                            new Uri("http://odata.org/service"),
                            td.UrlResolver);

                        ODataMessageWriterSettings batchWriterSettings = testConfiguration.MessageWriterSettings.Clone();
                        batchWriterSettings.SetContentType(null);
                        WriterTestConfiguration batchTestConfiguration = new WriterTestConfiguration(
                            null,
                            batchWriterSettings,
                            testConfiguration.IsRequest,
                            testConfiguration.Synchronous);
                        BatchWriterUtils.WriteAndVerifyBatchPayload(batchTd, batchTestConfiguration, testConfiguration, this.Assert);
                    }
                }
            });
        }
Ejemplo n.º 30
0
        public void ActionAndFunctionTest()
        {
            // <m:action Metadata=URI title?="title" target=URI />

            Uri    actionMetadata  = new Uri("http://odata.org/test/$metadata#defaultAction");
            Uri    actionMetadata2 = new Uri("#action escaped relative metadata", UriKind.Relative);
            Uri    actionMetadata3 = new Uri("../#action escaped relative metadata", UriKind.Relative);
            string actionTitle     = "Default Action";
            Uri    actionTarget    = new Uri("http://odata.org/defaultActionTarget");
            Uri    actionTarget2   = new Uri("http://odata.org/defaultActionTarget2");

            ODataAction action_r1_t1 = new ODataAction()
            {
                Metadata = actionMetadata, Title = actionTitle, Target = actionTarget
            };
            ODataAction action_r1_t2 = new ODataAction()
            {
                Metadata = actionMetadata, Title = actionTitle, Target = actionTarget2
            };
            ODataAction action_r2_t1 = new ODataAction()
            {
                Metadata = actionMetadata2, Title = actionTitle, Target = actionTarget
            };
            ODataAction action_r3_t1 = new ODataAction()
            {
                Metadata = actionMetadata3, Title = actionTitle, Target = actionTarget
            };

            Uri    functionMetadata  = new Uri("http://odata.org/test/$metadata#defaultFunction");
            Uri    functionMetadata2 = new Uri("#function escaped relative metadata", UriKind.Relative);
            Uri    functionMetadata3 = new Uri("\\#function escaped relative metadata", UriKind.Relative);
            string functionTitle     = "Default Function";
            Uri    functionTarget    = new Uri("http://odata.org/defaultFunctionTarget");
            Uri    functionTarget2   = new Uri("http://odata.org/defaultFunctionTarget2");

            ODataFunction function_r1_t1 = new ODataFunction()
            {
                Metadata = functionMetadata, Title = functionTitle, Target = functionTarget
            };
            ODataFunction function_r1_t2 = new ODataFunction()
            {
                Metadata = functionMetadata, Title = functionTitle, Target = functionTarget2
            };
            ODataFunction function_r2_t1 = new ODataFunction()
            {
                Metadata = functionMetadata2, Title = functionTitle, Target = functionTarget
            };
            ODataFunction function_r3_t1 = new ODataFunction()
            {
                Metadata = functionMetadata3, Title = functionTitle, Target = functionTarget
            };

            var actionCases = new[]
            {
                new {
                    ODataActions = new ODataAction[] { action_r1_t1 },
                    Atom         = GetAtom(action_r1_t1),
                    JsonLight    = GetJsonLightForRelGroup(action_r1_t1),
                },
                new {
                    ODataActions = new ODataAction[] { action_r1_t1, action_r1_t2 },
                    Atom         = GetAtom(action_r1_t1) + GetAtom(action_r1_t2),
                    JsonLight    = GetJsonLightForRelGroup(action_r1_t1, action_r1_t2),
                },
                new {
                    ODataActions = new ODataAction[] { action_r1_t1, action_r2_t1 },
                    Atom         = GetAtom(action_r1_t1) + GetAtom(action_r2_t1),
                    JsonLight    = GetJsonLightForRelGroup(action_r1_t1) + "," + GetJsonLightForRelGroup(action_r2_t1),
                },
                new {
                    ODataActions = new ODataAction[] { action_r1_t1, action_r2_t1, action_r1_t2 },
                    Atom         = GetAtom(action_r1_t1) + GetAtom(action_r2_t1) + GetAtom(action_r1_t2),
                    JsonLight    = GetJsonLightForRelGroup(action_r1_t1, action_r1_t2) + "," + GetJsonLightForRelGroup(action_r2_t1),
                },
                new {
                    ODataActions = new ODataAction[] { action_r3_t1 },
                    Atom         = GetAtom(action_r3_t1),
                    JsonLight    = GetJsonLightForRelGroup(action_r3_t1),
                },
            };

            var functionCases = new[]
            {
                new {
                    ODataFunctions = new ODataFunction[] { function_r1_t1 },
                    Atom           = GetAtom(function_r1_t1),
                    JsonLight      = GetJsonLightForRelGroup(function_r1_t1),
                },
                new {
                    ODataFunctions = new ODataFunction[] { function_r1_t1, function_r1_t2 },
                    Atom           = GetAtom(function_r1_t1) + GetAtom(function_r1_t2),
                    JsonLight      = GetJsonLightForRelGroup(function_r1_t1, function_r1_t2),
                },
                new {
                    ODataFunctions = new ODataFunction[] { function_r1_t1, function_r2_t1 },
                    Atom           = GetAtom(function_r1_t1) + GetAtom(function_r2_t1),
                    JsonLight      = GetJsonLightForRelGroup(function_r1_t1) + "," + GetJsonLightForRelGroup(function_r2_t1),
                },
                new {
                    ODataFunctions = new ODataFunction[] { function_r1_t1, function_r2_t1, function_r1_t2 },
                    Atom           = GetAtom(function_r1_t1) + GetAtom(function_r2_t1) + GetAtom(function_r1_t2),
                    JsonLight      = GetJsonLightForRelGroup(function_r1_t1, function_r1_t2) + "," + GetJsonLightForRelGroup(function_r2_t1),
                },
                new {
                    ODataFunctions = new ODataFunction[] { function_r3_t1 },
                    Atom           = GetAtom(function_r3_t1),
                    JsonLight      = GetJsonLightForRelGroup(function_r3_t1),
                },
            };

            var queryResults =
                from actionCase in actionCases
                from functionCase in functionCases
                select new
            {
                actionCase.ODataActions,
                functionCase.ODataFunctions,
                Atom      = string.Concat(actionCase.Atom, functionCase.Atom),
                JsonLight = string.Join(",", new[] { actionCase.JsonLight, functionCase.JsonLight }.Where(x => x != null))
            };

            EdmModel           model = new EdmModel();
            EdmEntityType      edmEntityTypeCustomer  = model.EntityType("Customer", "TestModel");
            EdmEntityContainer edmEntityContainer     = model.EntityContainer("DefaultContainer", "TestModel");
            EdmEntitySet       edmEntitySetCustermors = model.EntitySet("Customers", edmEntityTypeCustomer);

            var testDescriptors = queryResults.Select(testCase =>
            {
                ODataResource entry = ObjectModelUtils.CreateDefaultEntry("TestModel.Customer");

                if (testCase.ODataActions != null)
                {
                    foreach (var action in testCase.ODataActions)
                    {
                        entry.AddAction(action);
                    }
                }

                if (testCase.ODataFunctions != null)
                {
                    foreach (var function in testCase.ODataFunctions)
                    {
                        entry.AddFunction(function);
                    }
                }

                return(new PayloadWriterTestDescriptor <ODataItem>(
                           this.Settings,
                           entry,
                           (testConfiguration) =>
                {
                    if (testConfiguration.Format == ODataFormat.Json)
                    {
                        return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                        {
                            Json = string.Join(
                                "$(NL)",
                                "{",
                                testCase.JsonLight,
                                "}"),
                            ExpectedException2 =
                                entry.Actions != null && entry.Actions.Contains(null)
                                        ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataResource.Actions")
                                        : testConfiguration.IsRequest && entry.Actions != null && entry.Actions.Any()
                                            ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry))
                                            : entry.Actions != null && entry.Actions.Any(a => !a.Metadata.IsAbsoluteUri && !a.Metadata.OriginalString.StartsWith("#"))
                                                ? ODataExpectedExceptions.ODataException("ValidationUtils_InvalidMetadataReferenceProperty", entry.Actions.First(a => a.Metadata.OriginalString.Contains(" ")).Metadata.OriginalString)
                                            : entry.Functions != null && entry.Functions.Contains(null)
                                                ? ODataExpectedExceptions.ODataException("ValidationUtils_EnumerableContainsANullItem", "ODataResource.Functions")
                                                : testConfiguration.IsRequest && entry.Functions != null && entry.Functions.Any()
                                                    ? ODataExpectedExceptions.ODataException("WriterValidationUtils_OperationInRequest", GetFirstOperationMetadata(entry))
                                                        : entry.Functions != null && entry.Functions.Any(f => !f.Metadata.IsAbsoluteUri && !f.Metadata.OriginalString.StartsWith("#"))
                                                            ? ODataExpectedExceptions.ODataException("ValidationUtils_InvalidMetadataReferenceProperty", entry.Functions.First(f => f.Metadata.OriginalString.Contains(" ")).Metadata.OriginalString)
                                                    : null,
                            FragmentExtractor = (result) =>
                            {
                                var actionsAndFunctions = result.Object().Properties.Where(p => p.Name.Contains("#")).ToList();

                                var jsonResult = new JsonObject();
                                actionsAndFunctions.ForEach(p =>
                                {
                                    // NOTE we remove all annotations here and in particular the text annotations to be able to easily compare
                                    //      against the expected results. This however means that we do not distinguish between the indented and non-indented case here.
                                    p.RemoveAllAnnotations(true);
                                    jsonResult.Add(p);
                                });
                                return jsonResult;
                            }
                        };
                    }
                    else
                    {
                        string formatName = testConfiguration.Format == null ? "null" : testConfiguration.Format.GetType().Name;
                        throw new NotSupportedException("Invalid format detected: " + formatName);
                    }
                }));
            });

            this.CombinatorialEngineProvider.RunCombinations(
                testDescriptors.PayloadCases(WriterPayloads.EntryPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testConfiguration.Format == ODataFormat.Json)
                {
                    if (testDescriptor.IsGeneratedPayload)
                    {
                        return;
                    }

                    // We need a model, entity set and entity type for JSON Light
                    testDescriptor = new PayloadWriterTestDescriptor <ODataItem>(testDescriptor)
                    {
                        Model = model,
                        PayloadEdmElementContainer = edmEntitySetCustermors,
                        PayloadEdmElementType      = edmEntityTypeCustomer,
                    };
                }

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }