[Ignore] // Remove Atom
        // [TestMethod, Variation(Description = "Verifies that sync and async calls cannot be mixed on a single writer.")]
        public void SyncAsyncMismatchTest()
        {
            // ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                TestCalls,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                new bool[] { false, true },
                new bool[] { false, true },
                (testCall, testConfiguration, writingFeed, testSynchronousCall) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                using (TestStream memoryStream = new TestStream())
                {
                    // We purposely don't use the using pattern around the messageWriter here. Disposing the message writer will
                    // fail here because the writer is not left in a valid state.
                    var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert);

                    // Note that the CreateODataWriter call will call either sync or async variant based on the testConfiguration
                    // which is independent axis to the testSynchronousCall and thus we will end up with async creation but sync write
                    // and vice versa.
                    ODataWriter odataWriter       = messageWriter.CreateODataWriter(writingFeed);
                    ODataWriterTestWrapper writer = (ODataWriterTestWrapper)odataWriter;
                    if (testCall.AssumesFeedWriter)
                    {
                        if (!writingFeed)
                        {
                            // Skip this case since we need feed writer for this case.
                            return;
                        }
                    }
                    else
                    {
                        if (writingFeed)
                        {
                            writer.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                    }

                    this.Assert.ExpectedException <ODataException>(
                        () =>
                    {
                        if (testSynchronousCall)
                        {
                            testCall.Sync(writer);
                        }
                        else
                        {
                            testCall.Async(writer);
                        }
                    },
                        testConfiguration.Synchronous == testSynchronousCall ?
                        null :
                        testSynchronousCall ?
                        "A synchronous operation was called on an asynchronous writer. Calls on a writer instance must be either all synchronous or all asynchronous." :
                        "An asynchronous operation was called on a synchronous writer. Calls on a writer instance must be either all synchronous or all asynchronous.");
                }
            });
        }
Esempio n. 2
0
        /// <summary>
        /// Returns all interesting payloads for a property.
        /// </summary>
        /// <param name="testDescriptor">Test descriptor which will end up writing a single entry with a single property.
        /// The entry is not going to be used, but the property from it will.</param>
        /// <returns>Enumeration of test descriptors which will include the original property in some interesting scenarios.</returns>
        public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > PropertyPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor)
        {
            ODataResource tempEntry = testDescriptor.PayloadItems[0] as ODataResource;

            Debug.Assert(tempEntry != null, "A single entry payload is expected.");
            ODataProperty property = tempEntry.Properties.First();

            // Note - the property can be null - it is a valid test case !!!!

            var payloadCases = new WriterPayloadCase <ODataItem>[] {
                new WriterPayloadCase <ODataItem>()  // Single property on an entry
                {
                    GetPayloadItems = () => {
                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        entry.Properties = new ODataProperty[] { property };
                        return(new ODataItem[] { entry });
                    },
                    AtomFragmentExtractor = (testConfiguration, result) =>
                    {
                        return(TestAtomUtils.ExtractPropertiesFromEntry(result).Element(TestAtomConstants.ODataXNamespace + property.Name));
                    },
                    //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
                },

                // TODO: Add other interesting payloads for properties - more properties in an entry, inside a complex property, inside a collection of complex and so on
            };

            return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases));
        }
Esempio n. 3
0
        private Action <WriterTestConfiguration> WriteServiceDocument(Func <XElement, XElement> fragmentExtractor, string expectedXml)
        {
            var sampleWorkspace = ObjectModelUtils.CreateDefaultWorkspace();

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

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

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    new PayloadWriterTestDescriptor <ODataServiceDocument>(this.Settings, sampleWorkspace, expectedXml, null, fragmentExtractor, null, /*disableXmlNamespaceNormalization*/ true),
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(sampleWorkspace),
                    this.Assert,
                    actualSettings,
                    baselineLogger: this.Logger);
            });
        }
Esempio n. 4
0
        public void SetNextLinkAfterFeedStartTests()
        {
            var testPayloads = this.CreateFeedNextLinkDescriptors().ToArray();

            foreach (var descriptor in testPayloads)
            {
                // Replace each feed with one without the next link value, and an action to write it back
                // after writing Feed Start.
                var nextLink = new Uri(descriptor.PayloadItems.OfType <ODataFeed>().Single().NextPageLink.OriginalString);
                var newFeed  = ObjectModelUtils.CreateDefaultFeed().WithAnnotation(new WriteFeedCallbacksAnnotation {
                    AfterWriteStartCallback = (f) => f.NextPageLink = nextLink
                });
                descriptor.PayloadItems = new ReadOnlyCollection <ODataItem>(new List <ODataItem> {
                    newFeed
                });
            }

            this.CombinatorialEngineProvider.RunCombinations(
                testPayloads.PayloadCases(WriterPayloads.FeedPayloads),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testDescriptor, testConfiguration) =>
            {
                if (testDescriptor.IsGeneratedPayload && (testConfiguration.Format == ODataFormat.Json || testDescriptor.Model != null))
                {
                    return;
                }

                TestWriterUtils.WriteAndVerifyODataEdmPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Esempio n. 5
0
        private void InvokeWriterAction(ODataMessageWriterTestWrapper messageWriter, ODataWriter writer, WriterAction writerAction)
        {
            switch (writerAction)
            {
            case WriterAction.StartResource:
                writer.WriteStart(ObjectModelUtils.CreateDefaultEntry());
                break;

            case WriterAction.StartFeed:
                writer.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                break;

            case WriterAction.StartLink:
                writer.WriteStart(ObjectModelUtils.CreateDefaultCollectionLink());
                break;

            case WriterAction.End:
                writer.WriteEnd();
                break;

            case WriterAction.Error:
                messageWriter.WriteError(new ODataError(), false);
                break;
            }
        }
        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);
            });
        }
Esempio n. 7
0
        /// <summary>
        /// Returns all interesting payloads for a navigation link itself. That is the ODataNestedResourceInfo without any subsequent events.
        /// </summary>
        /// <param name="testDescriptor">Test descriptor which will end up writing a single navigation link.</param>
        /// <returns>Enumeration of test descriptors which will include the original navigation link in some interesting scenarios.</returns>
        public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > NavigationLinkOnlyPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor)
        {
            ODataNestedResourceInfo navigationLink = testDescriptor.PayloadItems[0] as ODataNestedResourceInfo;

            Debug.Assert(navigationLink != null, "Navigation link payload expected.");
            Debug.Assert(navigationLink.IsCollection.HasValue, "ODataNestedResourceInfo.IsCollection required.");

            var payloadCases = new WriterPayloadCase <ODataItem>[] {
                new WriterPayloadCase <ODataItem>()  // Just the link as non-expanded
                {
                    GetPayloadItems = () => new ODataItem[] { navigationLink }
                },
                new WriterPayloadCase <ODataItem>()  // The link with expanded entry
                {
                    GetPayloadItems = () => {
                        if (navigationLink.IsCollection.Value)
                        {
                            return(new ODataItem[] { navigationLink, ObjectModelUtils.CreateDefaultFeed() });
                        }
                        else
                        {
                            return(new ODataItem[] { navigationLink, ObjectModelUtils.CreateDefaultEntry() });
                        }
                    }
                }
            };

            // Apply the cases here and then wrap the link in some entry/feed cases
            return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases).PayloadCases(NavigationLinkPayloads));
        }
Esempio n. 8
0
        /// <summary>
        /// Returns all interesting payloads for a value.
        /// </summary>
        /// <param name="testDescriptor">Test descriptor which will end up writing a single entry with a single property.
        /// The entry is not going to be used, the property is not going to be used, but the property value from it will.</param>
        /// <returns>Enumeration of test descriptors which will include the original value in some interesting scenarios.</returns>
        public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > ValuePayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor)
        {
            ODataResource tempEntry = testDescriptor.PayloadItems[0] as ODataResource;

            Debug.Assert(tempEntry != null, "A single entry payload is expected.");
            ODataProperty property = tempEntry.Properties.First();

            Debug.Assert(property != null, "A single property is expected.");
            object propertyValue = property.Value;

            var payloadCases = new WriterPayloadCase <ODataItem>[] {
                new WriterPayloadCase <ODataItem>()  // Value of a property
                {
                    GetPayloadItems = () => {
                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        entry.Properties = new ODataProperty[] { new ODataProperty()
                                                                 {
                                                                     Name = "TestProperty", Value = propertyValue
                                                                 } };
                        return(new ODataItem[] { entry });
                    },
                    AtomFragmentExtractor = (testConfiguration, result) =>
                    {
                        return(TestAtomUtils.ExtractPropertiesFromEntry(result).Element(TestAtomConstants.ODataXNamespace + property.Name));
                    },
                    //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
                },
                new WriterPayloadCase <ODataItem>()  // Value as item in a collection
                {
                    ShouldSkip      = testConfiguration => propertyValue is ODataCollectionValue,
                    GetPayloadItems = () => {
                        ODataResource entry = ObjectModelUtils.CreateDefaultEntry();
                        entry.Properties = new ODataProperty[] { new ODataProperty()
                                                                 {
                                                                     Name = "TestProperty", Value = new ODataCollectionValue()
                                                                     {
                                                                         Items = new object[] { propertyValue }
                                                                     }
                                                                 } };
                        return(new ODataItem[] { entry });
                    },
                    AtomFragmentExtractor = (testConfiguration, result) =>
                    {
                        return(TestAtomUtils.ExtractPropertiesFromEntry(result).Element(TestAtomConstants.ODataXNamespace + property.Name));
                    },
                    //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
                },

                // TODO: Add other interesting payloads for property values
            };

            // Combine with property payloads to get interesting places where the property itself is used.
            return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases).PayloadCases(PropertyPayloads));
        }
Esempio n. 9
0
        private PayloadWriterTestDescriptor <ODataItem> CreateDefaultFeedMetadataDescriptor(bool withModel)
        {
            EdmModel model = null;

            if (withModel)
            {
                model = new EdmModel();
            }

            ODataResourceSet feed = ObjectModelUtils.CreateDefaultFeed("CustomersSet", "CustomerType", model);

            EdmEntitySet  customerSet  = null;
            EdmEntityType customerType = null;

            if (model != null)
            {
                var container = model.FindEntityContainer("DefaultContainer");
                customerSet  = container.FindEntitySet("CustomersSet") as EdmEntitySet;
                customerType = model.FindType("TestModel.CustomerType") as EdmEntityType;
            }

            return(new PayloadWriterTestDescriptor <ODataItem>(
                       this.Settings,
                       feed,
                       (testConfiguration) =>
            {
                if (testConfiguration.Format == ODataFormat.Json)
                {
                    return new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Json = string.Join("$(NL)",
                                           "{",
                                           "\"" + JsonLightConstants.ODataPropertyAnnotationSeparator + JsonLightConstants.ODataContextAnnotationName + "\":\"http://odata.org/test/$metadata#CustomersSet\",\"value\":[",
                                           string.Empty,
                                           "]",
                                           "}"),
                        FragmentExtractor = (result) => result.RemoveAllAnnotations(true)
                    };
                }
                else
                {
                    string formatName = testConfiguration.Format == null ? "null" : testConfiguration.Format.GetType().Name;
                    throw new NotSupportedException("Invalid format detected: " + formatName);
                }
            })
            {
                // JSON Light does not support writing without model
                SkipTestConfiguration = tc => model == null && tc.Format == ODataFormat.Json,
                Model = model,
                PayloadEdmElementContainer = customerSet,
                PayloadEdmElementType = customerType,
            });
        }
Esempio n. 10
0
        public void FatalExceptionTest()
        {
            ODataResource entry = ObjectModelUtils.CreateDefaultEntry();

            this.CombinatorialEngineProvider.RunCombinations(
                new ODataItem[] { entry },
                new bool[] { true, false }, // flush
                // TODO: also enable this test for the sync scenarios
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => !tc.Synchronous),
                (payload, flush, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                using (var memoryStream = new TestStream())
                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert))
                    {
                        ODataWriter writer = messageWriter.CreateODataWriter(isFeed: false);
                        ODataWriterCoreInspector inspector = new ODataWriterCoreInspector(writer);

                        // close the memory stream so that any attempt to flush will cause a fatal error
                        memoryStream.CloseInner();

                        // write the payload and call FlushAsync() to trigger a fatal exception
                        Exception ex = TestExceptionUtils.RunCatching(() => TestWriterUtils.WritePayload(messageWriter, writer, true, entry));
                        this.Assert.IsNotNull(ex, "Expected exception but none was thrown.");
                        NotSupportedException notSupported = null;
#if SILVERLIGHT || WINDOWS_PHONE
                        var baseEx = ex.GetBaseException();
                        this.Assert.IsNotNull(baseEx, "BaseException of exception:" + ex.ToString() + " should not be null");
                        notSupported = baseEx as NotSupportedException;
                        this.Assert.IsNotNull(notSupported, "Expected NotSupportedException but " + baseEx.GetType().FullName + " was reported.");
#else
                        notSupported = TestExceptionUtils.UnwrapAggregateException(ex, this.Assert) as NotSupportedException;
                        this.Assert.IsNotNull(notSupported, "Expected NotSupportedException but " + ex.ToString() + " was reported.");
#endif

                        this.Assert.AreEqual("Stream does not support writing.", notSupported.Message, "Did not find expected error message.");
                        this.Assert.IsTrue(inspector.IsInErrorState, "Writer is not in expected 'Error' state.");

                        if (flush)
                        {
                            // Flush should work in error state.
                            writer.Flush();
                        }

                        // in all cases we have to be able to dispose the writer without problems.
                    }
            });
        }
Esempio n. 11
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);
            });
        }
Esempio n. 12
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));
 }
Esempio n. 13
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);
            });
        }
Esempio n. 16
0
        public void WriteAfterExceptionTest()
        {
            // create a default entry and then set both read and edit links to null to provoke an exception during writing
            ODataResource faultyEntry = ObjectModelUtils.CreateDefaultEntry();

            this.Assert.IsNull(faultyEntry.EditLink, "entry.EditLink == null");

            ODataResource    defaultEntry = ObjectModelUtils.CreateDefaultEntry();
            ODataResourceSet defaultFeed  = ObjectModelUtils.CreateDefaultFeed();

            this.CombinatorialEngineProvider.RunCombinations(
                new ODataItem[] { faultyEntry },
                new ODataItem[] { defaultFeed, defaultEntry },
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations,
                (faultyPayload, contentPayload, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                using (var memoryStream = new TestStream())
                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert))
                    {
                        ODataWriter writer = messageWriter.CreateODataWriter(isFeed: false);
                        ODataWriterCoreInspector inspector = new ODataWriterCoreInspector(writer);

                        // write the invalid entry and expect an exception
                        this.Assert.ExpectedException(
                            () => TestWriterUtils.WritePayload(messageWriter, writer, false, faultyEntry),
                            ODataExpectedExceptions.ODataException("WriterValidationUtils_EntriesMustHaveNonEmptyId"),
                            this.ExceptionVerifier);
                        this.Assert.IsTrue(inspector.IsInErrorState, "Writer is not in expected 'error' state.");

                        // now write some non-error content which is invalid to do
                        Exception ex = TestExceptionUtils.RunCatching(() => TestWriterUtils.WritePayload(messageWriter, writer, false, contentPayload));
                        ex           = TestExceptionUtils.UnwrapAggregateException(ex, this.Assert);
                        this.Assert.IsNotNull(ex, "Expected exception but none was thrown");
                        this.Assert.IsTrue(ex is ODataException, "Expected an ODataException instance but got a " + ex.GetType().FullName + ".");
                        this.Assert.IsTrue(ex.Message.Contains("Cannot transition from state 'Error' to state "), "Did not find expected start of error message.");
                        this.Assert.IsTrue(ex.Message.Contains("Nothing can be written once the writer entered the error state."), "Did not find expected end of error message in '" + ex.Message + "'.");
                        this.Assert.IsTrue(inspector.IsInErrorState, "Writer is not in expected 'error' state.");
                        writer.Flush();
                    }
            });
        }
Esempio n. 17
0
        public void FeedInvalidContentTests()
        {
            ODataFeed defaultFeed = ObjectModelUtils.CreateDefaultFeed();

            ODataItem[] invalidPayload1 = new ODataItem[] { defaultFeed, defaultFeed };

            var testCases = new[]
            {
                new
                {
                    Items         = invalidPayload1,
                    ExpectedError = "Cannot transition from state 'Feed' to state 'Feed'. The only valid action in state 'Feed' is to write an entry."
                }
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                ODataFormatUtils.ODataFormats.Where(f => f != null),

// Async  test configuration is not supported for Phone and Silverlight
#if !SILVERLIGHT && !WINDOWS_PHONE
                new bool[] { false, true },
#else
                new bool[] { true },
#endif
                (testCase, format, synchronous) =>
            {
                using (var memoryStream = new TestStream())
                {
                    ODataMessageWriterSettings settings = new ODataMessageWriterSettings();
                    settings.Version = ODataVersion.V4;
                    settings.SetServiceDocumentUri(ServiceDocumentUri);

                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, new WriterTestConfiguration(format, settings, false, synchronous), this.Assert))
                    {
                        ODataWriter writer = messageWriter.CreateODataWriter(isFeed: true);
                        TestExceptionUtils.ExpectedException <ODataException>(
                            this.Assert,
                            () => TestWriterUtils.WritePayload(messageWriter, writer, true, testCase.Items),
                            testCase.ExpectedError);
                    }
                }
            });
        }
Esempio n. 18
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 EntityReferenceLinksValidationTest()
        {
            var testCases = new[] {
                new {
                    InvalidateEntityReferenceLinks = new Action <ODataEntityReferenceLinks>(entityReferenceLinks => entityReferenceLinks.Links = new ODataEntityReferenceLink[] { null }),
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_EntityReferenceLinksLinkMustNotBeNull"),
                },
            };

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

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

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLinks(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
                return;
            });
        }
Esempio n. 20
0
        /// <summary>
        /// Returns all interesting payloads for a navigation link.
        /// </summary>
        /// <param name="testDescriptor">Test descriptor which will end up writing a single navigation link.</param>
        /// <returns>Enumeration of test descriptors which will include the original navigation link in some interesting scenarios.</returns>
        public static IEnumerable <PayloadWriterTestDescriptor <ODataItem> > NavigationLinkPayloads(PayloadWriterTestDescriptor <ODataItem> testDescriptor)
        {
            ODataNestedResourceInfo navigationLink = testDescriptor.PayloadItems[0] as ODataNestedResourceInfo;

            Debug.Assert(navigationLink != null, "Link payload expected.");

            var payloadCases = new WriterPayloadCase <ODataItem>[] {
                new WriterPayloadCase <ODataItem>()  // Single link on top-level entry
                {
                    GetPayloadItems       = () => new ODataItem[] { ObjectModelUtils.CreateDefaultEntry() }.Concat(testDescriptor.PayloadItems),
                    AtomFragmentExtractor = (testConfiguration, result) =>
                    {
                        return(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                               .Where(linkElement => linkElement.Attribute(TestAtomConstants.AtomLinkRelationAttributeName).Value.StartsWith(TestAtomConstants.ODataNavigationPropertiesRelatedLinkRelationPrefix))
                               .First());
                    },
                },

                // TODO: Add other interesting payloads for links - in expanded entry, in expanded feed
            };

            return(ApplyPayloadCases <ODataItem>(testDescriptor, payloadCases));
        }
        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);
            });
        }
        private static ODataServiceDocument CreateWorkspace(bool createMetadataFirst, string workspaceName = null, IEnumerable <CollectionInfo> incomingCollections = null, IEnumerable <SingletonInfo> incomingSingletons = null)
        {
            ODataServiceDocument serviceDocument = ObjectModelUtils.CreateDefaultWorkspace();


            if (incomingCollections != null)
            {
                var collections = new List <ODataEntitySetInfo>();
                foreach (var collectionInfo in incomingCollections)
                {
                    var collection = new ODataEntitySetInfo()
                    {
                        Url = new Uri(collectionInfo.Url, UriKind.RelativeOrAbsolute), Name = collectionInfo.Name, Title = collectionInfo.TitleAnnotation
                    };
                    collections.Add(collection);
                }

                serviceDocument.EntitySets = collections;
            }

            if (incomingSingletons != null)
            {
                var singletons = new List <ODataSingletonInfo>();
                foreach (var singletonInfo in incomingSingletons)
                {
                    var singleton = new ODataSingletonInfo()
                    {
                        Url = new Uri(singletonInfo.Url, UriKind.RelativeOrAbsolute), Name = singletonInfo.Name, Title = singletonInfo.TitleAnnotation
                    };
                    singletons.Add(singleton);
                }

                serviceDocument.Singletons = singletons;
            }

            return(serviceDocument);
        }
Esempio n. 23
0
        public void WriteAfterDisposeTest()
        {
            this.CombinatorialEngineProvider.RunCombinations(
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations,
                (testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                using (var stream = new TestStream())
                {
                    ODataWriter writer;
                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(stream, testConfiguration, this.Assert))
                    {
                        writer = messageWriter.CreateODataWriter(isFeed: true);
                        // Message writer is disposed outside of this scope.
                    }

                    this.VerifyWriterAlreadyDisposed(() => writer.WriteStart(ObjectModelUtils.CreateDefaultFeed()));
                    this.VerifyWriterAlreadyDisposed(() => writer.WriteStart(ObjectModelUtils.CreateDefaultEntry()));
                    this.VerifyWriterAlreadyDisposed(() => writer.WriteStart(ObjectModelUtils.CreateDefaultCollectionLink()));
                }
            });
        }
        public void EntityReferenceLinkValidationTest()
        {
            var testCases = new[] {
                new {
                    InvalidateEntityReferenceLink = new Action <ODataEntityReferenceLink>(entityReferenceLink => entityReferenceLink.Url = null),
                    ExpectedException             = ODataExpectedExceptions.ODataException("WriterValidationUtils_EntityReferenceLinkUrlMustNotBeNull"),
                },
            };

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

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

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

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

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

                TestWriterUtils.WriteAndVerifyODataPayload((PayloadWriterTestDescriptor <ODataItem>)testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void 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 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);
            });
        }
        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);
            });
        }
Esempio n. 29
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.");
                    }
                }
            });
        }
Esempio 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);
            });
        }