/// <summary>
        /// Called to write the payload to the specified <paramref name="messageWriter"/>.
        /// </summary>
        /// <param name="messageWriter">The <see cref="ODataMessageWriterTestWrapper"/> to use for writing the payload.</param>
        /// <param name="testConfiguration">The test configuration to generate the payload for.</param>
        protected override void WritePayload(ODataMessageWriterTestWrapper messageWriter, WriterTestConfiguration testConfiguration)
        {
            ODataPayloadElement payload = this.PayloadElement.DeepCopy();

            if (testConfiguration.Format == ODataFormat.Json)
            {
                payload.Accept(new ODataPayloadJsonNormalizer());
                //Fixup added as odatalib requires ids on feeds even though it can't be represented in json
                payload.Accept(new AddFeedIDFixup());
            }
            else if (testConfiguration.Format == ODataFormat.Atom)
            {
                // TODO: Remove visitor
                payload.Accept(new ODataPayloadElementNullIDVisitor());
            }

            ODataPayloadElementToObjectModelConverter converter = new ODataPayloadElementToObjectModelConverter(!testConfiguration.IsRequest);

            if (this.PayloadKind != ODataPayloadKind.Batch)
            {
                this.settings.ObjectModelToMessageWriter.WriteMessage(messageWriter, this.PayloadKind, converter.Convert(payload));
            }
            else
            {
                TestWriterUtils.WriteBatchPayload(messageWriter,
                                                  payload,
                                                  converter,
                                                  this.settings.ObjectModelToMessageWriter,
                                                  this.Model,
                                                  this.settings.Assert,
                                                  testConfiguration,
                                                  true);
            }
        }
Exemple #2
0
        public void RawValueErrorTests()
        {
            var primitiveValueCases = new[]
            {
                new
                {   // invalid value (non-primitive)
                    Value = (object)new ODataCollectionValue(),
                    ExpectedErrorMessage = "The value of type 'Microsoft.OData.ODataCollectionValue' could not be converted to a raw string."
                },
                new
                {   // invalid value (entry)
                    Value = (object)new ODataResource(),
                    ExpectedErrorMessage = "The value of type 'Microsoft.OData.ODataResource' could not be converted to a raw string."
                },
                new
                {   // null value
                    Value = (object)null,
                    ExpectedErrorMessage = "Cannot write the value 'null' in raw format.",
                },
            };

            var testCases = primitiveValueCases.Select(p => new PayloadWriterTestDescriptor <object>(this.Settings, p.Value, CreateErrorResultCallback(p.ExpectedErrorMessage, p.Value, this.Settings.ExpectedResultSettings)));

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                // include (non-raw) writer test configurations to validate the expected exception for non-raw formats
                this.WriterTestConfigurationProvider.DefaultFormatConfigurationsWithIndent.Concat(
                    this.WriterTestConfigurationProvider.AtomFormatConfigurationsWithIndent),
                (testCase, testConfiguration) =>
            {
                TestWriterUtils.WriteAndVerifyRawContent(testCase, testConfiguration, this.Assert, this.Logger);
            });
        }
Exemple #3
0
        public void EntityReferenceLinkErrorTest()
        {
            string resultUriString = "http://odata.org/linkresult";
            ODataEntityReferenceLink resultLink = new ODataEntityReferenceLink {
                Url = new Uri(resultUriString)
            };

            PayloadWriterTestDescriptor <ODataEntityReferenceLink>[] testCases = new PayloadWriterTestDescriptor <ODataEntityReferenceLink>[]
            {
                new PayloadWriterTestDescriptor <ODataEntityReferenceLink>(this.Settings, resultLink, (string)null, (string)null),
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                TestWriterUtils.InvalidSettingSelectors,
                (testCase, testConfiguration, selector) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testConfiguration.Format == ODataFormat.Json)
                {
                    testCase.Model = CreateModelWithNavProps();
                    var edmModel   = testCase.GetMetadataProvider();
                }

                TestWriterUtils.WriteWithStreamErrors(
                    testCase,
                    selector,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLink(testCase.PayloadItems.Single()),
                    this.Assert);
            });
        }
Exemple #4
0
        /// <summary>
        /// Creates an <see cref="ODataCollectionWriter"/> for the specified format and the specified version and
        /// invokes the specified methods on it. It then parses
        /// the written Xml/JSON and compares it to the expected result as specified in the descriptor.
        /// </summary>
        /// <param name="descriptor">The test descriptor to process.</param>
        /// <param name="testConfiguration">The configuration of the test.</param>
        /// <param name="assert">The assertion handler to report errors to.</param>
        /// <param name="baselineLogger">Logger to log baseline.</param>
        internal static void WriteAndVerifyCollectionPayload(CollectionWriterTestDescriptor descriptor, WriterTestConfiguration testConfiguration, AssertionHandler assert, BaselineLogger baselineLogger)
        {
            baselineLogger.LogConfiguration(testConfiguration);
            baselineLogger.LogModelPresence(descriptor.Model);

            // serialize to a memory stream
            using (var memoryStream = new MemoryStream())
                using (var testMemoryStream = new TestStream(memoryStream, ignoreDispose: true))
                {
                    TestMessage testMessage = null;
                    Exception   exception   = TestExceptionUtils.RunCatching(() =>
                    {
                        using (var messageWriter = TestWriterUtils.CreateMessageWriter(testMemoryStream, testConfiguration, assert, out testMessage, null, descriptor.Model))
                        {
                            IEdmTypeReference itemTypeReference = descriptor.ItemTypeParameter;
                            ODataCollectionWriter writer        = itemTypeReference == null
                            ? messageWriter.CreateODataCollectionWriter()
                            : messageWriter.CreateODataCollectionWriter(itemTypeReference);
                            WriteCollectionPayload(messageWriter, writer, true, descriptor);
                        }
                    });
                    exception = TestExceptionUtils.UnwrapAggregateException(exception, assert);

                    WriterTestExpectedResults expectedResults = descriptor.ExpectedResultCallback(testConfiguration);
                    TestWriterUtils.ValidateExceptionOrLogResult(testMessage, testConfiguration, expectedResults, exception, assert, descriptor.TestDescriptorSettings.ExpectedResultSettings.ExceptionVerifier, baselineLogger);
                    TestWriterUtils.ValidateContentType(testMessage, expectedResults, true, assert);
                }
        }
Exemple #5
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);
            });
        }
Exemple #6
0
        private Action <WriterTestConfiguration> WriteEntityReferenceLinks(Func <XElement, XElement> fragmentExtractor, string expectedXml)
        {
            var sampleLinks = new ODataEntityReferenceLinks();

            return((testConfiguration) =>
            {
                PayloadWriterTestDescriptor <ODataEntityReferenceLinks> descriptor = new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>(
                    this.Settings,
                    sampleLinks,
                    expectedXml,
                    null,
                    fragmentExtractor,
                    null,
                    /*disableXmlNamespaceNormalization*/ true);
                // Top-level EntityReferenceLinks payload write requests are not allowed.
                if (testConfiguration.IsRequest)
                {
                    descriptor.ExpectedResultCallback = (testConfig) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = ODataExpectedExceptions.ODataException("ODataMessageWriter_EntityReferenceLinksInRequestNotAllowed")
                    };
                }
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    descriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLinks(sampleLinks),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
Exemple #7
0
        private Action <WriterTestConfiguration> WriteEntityReferenceLink(Func <XElement, XElement> fragmentExtractor, string expectedXml, bool isClient, string odataNamespace)
        {
            var sampleLink = new ODataEntityReferenceLink {
                Url = new Uri("http://odata.org/link")
            };

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

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    descriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteEntityReferenceLink(sampleLink),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        [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.");
                }
            });
        }
Exemple #9
0
        private Action <WriterTestConfiguration> WriteServiceDocument(Func <XElement, XElement> fragmentExtractor, string expectedXml)
        {
            var sampleWorkspace = ObjectModelUtils.CreateDefaultWorkspace();

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

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

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    new PayloadWriterTestDescriptor <ODataServiceDocument>(this.Settings, sampleWorkspace, expectedXml, null, fragmentExtractor, null, /*disableXmlNamespaceNormalization*/ true),
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(sampleWorkspace),
                    this.Assert,
                    actualSettings,
                    baselineLogger: this.Logger);
            });
        }
 public void SyncAsyncMismatchTest()
 {
     this.CombinatorialEngineProvider.RunCombinations(
         TestCalls,
         this.WriterTestConfigurationProvider.DefaultFormatConfigurations,
         new bool[] { false, true },
         (testCall, testConfiguration, testSynchronousCall) =>
     {
         using (var 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);
             ODataBatchWriterTestWrapper writer = messageWriter.CreateODataBatchWriter();
             this.Assert.ExpectedException <ODataException>(
                 () =>
             {
                 if (testSynchronousCall)
                 {
                     testCall.Sync(writer, testConfiguration);
                 }
                 else
                 {
                     testCall.Async(writer, testConfiguration);
                 }
             },
                 testConfiguration.Synchronous == testSynchronousCall || testCall.ShouldNotFail ?
                 null :
                 testSynchronousCall ?
                 "A synchronous operation was called on an asynchronous batch writer. Calls on a batch writer instance must be either all synchronous or all asynchronous." :
                 "An asynchronous operation was called on a synchronous batch writer. Calls on a batch writer instance must be either all synchronous or all asynchronous.");
         }
     });
 }
        public void SyncAsyncMismatchTest()
        {
            this.CombinatorialEngineProvider.RunCombinations(
                TestCalls,
                this.WriterTestConfigurationProvider.JsonLightFormatConfigurations.Where(tc => tc.IsRequest),
                new bool[] { false, true },
                (testCall, testConfiguration, testSynchronousCall) =>
                {
                    using (var memoryStream = new TestStream())
                    using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert))
                    {
                        ODataParameterWriter parameterWriter = messageWriter.CreateODataParameterWriter(null /*functionImport*/);
                        ODataParameterWriterTestWrapper writer = (ODataParameterWriterTestWrapper)parameterWriter;

                        this.Assert.ExpectedException(
                            () =>
                            {
                                if (testSynchronousCall)
                                {
                                    testCall.Sync(writer);
                                }
                                else
                                {
                                    testCall.Async(writer);
                                }
                            },
                            testConfiguration.Synchronous == testSynchronousCall ?
                                null :
                                testSynchronousCall 
                                    ? ODataExpectedExceptions.ODataException("ODataParameterWriterCore_SyncCallOnAsyncWriter")
                                    : ODataExpectedExceptions.ODataException("ODataParameterWriterCore_AsyncCallOnSyncWriter"),
                            this.ExceptionVerifier);
                    }
                });
        }
Exemple #12
0
        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);
            });
        }
        private void CreateTestDescriptorsAndRunTests(FeedMetadataTestCase[] testCases, Func <PayloadWriterTestDescriptor <ODataItem>, IEnumerable <PayloadWriterTestDescriptor <ODataItem> > > payloads)
        {
            // Convert test cases to test descriptions
            IEnumerable <Func <ODataFeed> > feedCreators = new Func <ODataFeed>[] { () => ObjectModelUtils.CreateDefaultFeed(), () => ObjectModelUtils.CreateDefaultFeedWithAtomMetadata(), };
            var testDescriptors = testCases.SelectMany(testCase => feedCreators.Select(feedCreator =>
            {
                ODataFeed feed            = feedCreator();
                AtomFeedMetadata metadata = feed.Atom();
                this.Assert.IsNotNull(metadata, "Expected default feed metadata on a default feed.");
                testCase.CustomizeMetadata(metadata);
                ODataItem[] payloadItems = testCase.CustomizePayload == null ? new ODataItem[] { feed } : testCase.CustomizePayload(feed);
                return(new PayloadWriterTestDescriptor <ODataItem>(this.Settings, payloadItems, testConfiguration =>
                {
                    if (testCase.SkipTestConfiguration != null && testCase.SkipTestConfiguration(testConfiguration))
                    {
                        return null;
                    }
                    return new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        Xml = testCase.Xml, FragmentExtractor = testCase.Extractor, ExpectedException2 = testCase.ExpectedException
                    };
                }));
            }));

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Exemple #14
0
        public void EntityReferenceLinksErrorTest()
        {
            string resultUri1String             = "http://odata.org/linkresult1";
            string resultUri2String             = "http://odata.org/linkresult2";
            string resultUri3String             = "http://odata.org/linkresult3";
            ODataEntityReferenceLink resultUri1 = new ODataEntityReferenceLink {
                Url = new Uri(resultUri1String)
            };
            ODataEntityReferenceLink resultUri2 = new ODataEntityReferenceLink {
                Url = new Uri(resultUri2String)
            };
            ODataEntityReferenceLink resultUri3 = new ODataEntityReferenceLink {
                Url = new Uri(resultUri3String)
            };

            var testCase = new ODataEntityReferenceLinks
            {
                Links = new ODataEntityReferenceLink[] { resultUri1, resultUri2, resultUri3 },
            };

            PayloadWriterTestDescriptor <ODataEntityReferenceLinks>[] testCases = new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>[]
            {
                new PayloadWriterTestDescriptor <ODataEntityReferenceLinks>(
                    this.Settings,
                    testCase,
                    (testConfiguration) => new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    // Top-level EntityReferenceLinks payload write requests are not allowed.
                    ExpectedException2 = testConfiguration.IsRequest ? ODataExpectedExceptions.ODataException("ODataMessageWriter_EntityReferenceLinksInRequestNotAllowed") : null
                })
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                TestWriterUtils.InvalidSettingSelectors,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (descriptor, selector, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testConfiguration.Format == ODataFormat.Json)
                {
                    descriptor.Model = CreateModelWithNavProps();
                    var edmModel     = descriptor.GetMetadataProvider();
                }

                TestWriterUtils.WriteWithStreamErrors(
                    descriptor,
                    selector,
                    testConfiguration,
                    (messageWriter) =>
                {
                    messageWriter.WriteEntityReferenceLinks(testCase);
                },
                    this.Assert);
            });
        }
Exemple #15
0
        public void RelativeUriTest()
        {
            var testCases = new[]
            {
                new
                {
                    BaseUri     = new Uri("http://odata.org/"),
                    RelativeUri = new Uri("relative", UriKind.Relative),
                },
                new
                {
                    BaseUri     = new Uri("http://odata.org/"),
                    RelativeUri = new Uri("relative that needs escaping", UriKind.Relative),
                },
                new
                {
                    BaseUri     = new Uri("http://odata.org/a/b/"),
                    RelativeUri = new Uri("../../relative that needs escaping", UriKind.Relative),
                },
            };

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

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

                    testConfiguration = testConfiguration.Clone();
                    testConfiguration.MessageWriterSettings.BaseUri = testDescriptor.BaseUri;
                    testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                    TestWriterUtils.WriteAndVerifyODataPayload(payloadTestDescriptor, testConfiguration, this.Assert, this.Logger);
                }
            });
        }
Exemple #16
0
        public override void RunTest(ReaderTestConfiguration testConfiguration)
        {
            //TODO: Use Logger to verify result, right now this change is only to unblock writer testcase checkin
            BaselineLogger logger = null;

            if (this.ShouldSkipForTestConfiguration(testConfiguration))
            {
                return;
            }

            var originalPayload = this.PayloadElement;

            this.PayloadElement = this.PayloadElement.DeepCopy();

            // Create messages (payload gets serialized in createInputMessage)
            TestMessage readerMessage = this.CreateInputMessage(testConfiguration);
            var         settings      = new ODataMessageWriterSettings()
            {
                Version = testConfiguration.Version,
                BaseUri = testConfiguration.MessageReaderSettings.BaseUri,
                EnableMessageStreamDisposal = testConfiguration.MessageReaderSettings.EnableMessageStreamDisposal,
            };

            settings.SetContentType(testConfiguration.Format);

            WriterTestConfiguration writerConfig  = new WriterTestConfiguration(testConfiguration.Format, settings, testConfiguration.IsRequest, testConfiguration.Synchronous);
            TestMessage             writerMessage = TestWriterUtils.CreateOutputMessageFromStream(new TestStream(new MemoryStream()), writerConfig, this.PayloadKind, String.Empty, this.UrlResolver);

            IEdmModel model = this.GetMetadataProvider(testConfiguration);
            WriterTestExpectedResults expectedResult = this.GetExpectedResult(writerConfig);

            ExceptionUtilities.Assert(expectedResult != null, "The expected result could not be determined for the test. Did you specify it?");

            Exception exception = TestExceptionUtils.RunCatching(() =>
            {
                using (ODataMessageReaderTestWrapper messageReaderWrapper = TestReaderUtils.CreateMessageReader(readerMessage, model, testConfiguration))
                    using (ODataMessageWriterTestWrapper messageWriterWrapper = TestWriterUtils.CreateMessageWriter(writerMessage, model, writerConfig, this.settings.Assert))
                    {
                        var streamer = new ObjectModelReadWriteStreamer();
                        streamer.StreamMessage(messageReaderWrapper, messageWriterWrapper, this.PayloadKind, writerConfig);
                        expectedResult.VerifyResult(writerMessage, this.PayloadKind, writerConfig, logger);
                    }
            });

            this.PayloadElement = originalPayload;

            try
            {
                expectedResult.VerifyException(exception);
            }
            catch (Exception)
            {
                this.TraceFailureInformation(testConfiguration);
                throw;
            }
        }
        public void CategoryMetadataOnWorkspaceCollectionCategoriesWriterTest()
        {
            var testCases = this.CreateAtomCategoryTestCases();

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

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

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

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

                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testDescriptor,
                    testConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testDescriptor.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        /// <summary>
        /// Writes the payload to the stream using the given callback, then verifies the payload using the test deserializer
        /// </summary>
        /// <param name="originalPayload">The payload being tested, of which a copy will be made</param>
        /// <param name="message">The stream to write to</param>
        /// <param name="odataVersion">The OData protocol version to be used for writing payloads.</param>
        /// <param name="format">The current format</param>
        /// <param name="writeToStream">The callback to write to the stream</param>
        private void WriteAndLogODataPayload(ODataPayloadElement originalPayload, TestMessage message, ODataVersion odataVersion, ODataFormat format, Action <ODataPayloadElement> writeToStream)
        {
            ExceptionUtilities.CheckArgumentNotNull(originalPayload, "originalPayload");
            ExceptionUtilities.CheckArgumentNotNull(writeToStream, "writeToStream");

            // This is needed because we may modify the payload in use but the same is used in another iteration of the combinatorial engine
            var payload = originalPayload.DeepCopy();

            WriteToStream(format, writeToStream, payload);
            var newPayload = TestWriterUtils.ReadToString(message);

            this.Logger.LogPayload(newPayload);
        }
        private TestMessage CreateOutputMessage(Stream innerStream, WriterTestConfiguration testConfiguration, ODataPayloadElement payload)
        {
            TestStream messageStream = new TestStream(innerStream);

            TestWriterUtils.SetFailAsynchronousCalls(messageStream, testConfiguration.Synchronous);

            var boundary = this.PayloadElement.GetAnnotation <BatchBoundaryAnnotation>();

            // We create a new test configuration for batch because the payload indicates whether we are dealing with a request or a response and the configuration won't know that in advance
            var         newTestConfig = new WriterTestConfiguration(testConfiguration.Format, testConfiguration.MessageWriterSettings, this.PayloadElement is BatchRequestPayload, testConfiguration.Synchronous);
            TestMessage testMessage   = TestWriterUtils.CreateOutputMessageFromStream(messageStream, newTestConfig, this.PayloadKind, boundary.BatchBoundaryInHeader, this.UrlResolver);

            return(testMessage);
        }
        /// <summary>
        /// Verifies that the result of the test is what the test expected.
        /// </summary>
        /// <param name="stream">The stream after writing the message content. This method should use it
        /// to read the message content and verify it.</param>
        /// <param name="payloadKind">The payload kind specified in the test descriptor.</param>
        /// <param name="testConfiguration">The test configuration to use.</param>
        public override void VerifyResult(
            TestMessage message,
            ODataPayloadKind payloadKind,
            WriterTestConfiguration testConfiguration,
            BaselineLogger logger)
        {
            // Get observed payload
            var observed = TestWriterUtils.ReadToString(message);

            if (logger != null)
            {
                logger.LogPayload(TestWriterUtils.BaseLineFixup(observed));
            }
        }
Exemple #21
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.
                    }
            });
        }
        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);
            });
        }
Exemple #23
0
        public void AtomTextConstructMetadataOnODataItemWriterTest()
        {
            var testDescriptors = this.CreateTextConstructTestDescriptors();

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Exemple #24
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));
 }
Exemple #25
0
        public void FeedInlineCountTests()
        {
            PayloadWriterTestDescriptor <ODataItem>[] testDescriptors = this.CreateFeedQueryCountDescriptors();

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

                TestWriterUtils.WriteAndVerifyODataEdmPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Exemple #26
0
        /// <summary>
        /// Creates an ODataWriter for the specified format and the specified version and
        /// writes the property in the descriptor to an in-memory stream. It then parses
        /// the written Xml and compares it to the expected result as specified in the descriptor.
        /// </summary>
        /// <param name="originalPayload">The payload to first clone and then write.</param>
        /// <param name="testConfiguration">Configuration for the test</param>
        /// <param name="model">The model to use.</param>
        protected void WriteAndVerifyODataProperty(ODataPayloadElement originalPayload, WriterTestConfiguration testConfiguration, IEdmModel model)
        {
            this.Logger.LogConfiguration(testConfiguration);
            this.Logger.LogModelPresence(model);

            using (var memoryStream = new TestStream())
            {
                TestMessage testMessage;
                using (ODataMessageWriterTestWrapper writer = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert, out testMessage, null, model))
                {
                    Action <ODataPayloadElement> writeElementToStream = payload => this.PropertyPayloadElementWriter.WriteProperty(writer.MessageWriter, payload);
                    this.WriteAndLogODataPayload(originalPayload, writer.Message, testConfiguration.Version, testConfiguration.Format, writeElementToStream);
                }
            }
        }
        public void PropertyValidationTest()
        {
            var testCases = new[] {
                new { // null property is not valid
                    Property          = (ODataProperty)null,
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_PropertyMustNotBeNull")
                },
                new { // null property name is not valid
                    Property = new ODataProperty()
                    {
                        Name = null
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_PropertiesMustHaveNonEmptyName")
                },
                new { // empty property name is not valid
                    Property = new ODataProperty()
                    {
                        Name = string.Empty
                    },
                    ExpectedException = ODataExpectedExceptions.ODataException("WriterValidationUtils_PropertiesMustHaveNonEmptyName")
                },
            };

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

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor, testConfiguration, this.Assert, this.Logger);
            });
        }
Exemple #28
0
        /// <summary>
        /// Creates an ODataWriter for the specified format and the specified version and
        /// writes the payload in the descriptor to an in-memory stream. It then parses
        /// the written Xml and compares it to the expected result as specified in the descriptor.
        /// </summary>
        /// <param name="originalPayload">expectedPayload to write and</param>
        /// <param name="testConfiguration">Configuration for the test</param>
        protected void WriteAndVerifyODataPayloadElement(ODataPayloadElement originalPayload, WriterTestConfiguration testConfiguration)
        {
            this.Logger.LogConfiguration(testConfiguration);

            bool feedWriter = originalPayload.ElementType == ODataPayloadElementType.EntitySetInstance;

            using (var memoryStream = new TestStream())
            {
                using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert))
                {
                    ODataWriter writer = messageWriter.CreateODataWriter(feedWriter);
                    Action <ODataPayloadElement> writeToStream = payload => this.PayloadElementWriter.WritePayload(writer, payload);
                    this.WriteAndLogODataPayload(originalPayload, messageWriter.Message, testConfiguration.Version, testConfiguration.Format, writeToStream);
                }
            }
        }
        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);
            });
        }
Exemple #30
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);
            });
        }