Exemple #1
0
        [Ignore] // Remove Atom
        // [TestMethod, Variation(Description = "Test feed payloads.")]
        public void TaupoTopLevelFeedTest()
        {
            EntitySetInstance entitySet = new EntitySetInstance(PayloadGenerator.GenerateAtomPayloads().First())
                                          .WithDefaultAtomFeedAnnotations();

            this.CombinatorialEngineProvider.RunCombinations(
                new[] { entitySet },
                this.WriterTestConfigurationProvider.AtomFormatConfigurationsWithIndent,
                (testCase, testConfiguration) =>
            {
                WriterTestConfiguration newConfiguration = testConfiguration.Clone();
                newConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                this.WriteAndVerifyODataPayloadElement(testCase, newConfiguration);
            });

            // The ID annotation is added for JSON as even though JSON has no way to represent the ID ODataLib requires it.
            entitySet = new EntitySetInstance(PayloadGenerator.GenerateJsonPayloads().ToArray()).WithDefaultAtomIDAnnotation();

            // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight
            //this.CombinatorialEngineProvider.RunCombinations(
            //    new[] { entitySet },
            //    this.WriterTestConfigurationProvider.JsonLightFormatConfigurationsWithIndent,
            //    (testCase, testConfiguration) =>
            //    {
            //        this.WriteAndVerifyODataPayloadElement(testCase, testConfiguration);
            //    });
        }
Exemple #2
0
        /// <summary>
        /// Called to get the expected result of the test.
        /// </summary>
        /// <param name="testConfiguration">The test configuration to use.</param>
        /// <returns>The expected result.</returns>
        protected override WriterTestExpectedResults GetExpectedResult(WriterTestConfiguration testConfiguration)
        {
            WriterTestExpectedResults expectedResult = base.GetExpectedResult(testConfiguration);

            if (expectedResult == null)
            {
                ODataErrorException errorException   = null;
                Exception           regularException = null;
                if (this.ExpectedException != null)
                {
                    errorException   = this.ExpectedException as ODataErrorException;
                    regularException = errorException == null ? this.ExpectedException : null;
                }

                return(new MetadataWriterTestExpectedResult(this.settings.ExpectedResultSettings)
                {
                    EdmVersion = this.EdmVersion,
                    ExpectedException = regularException,
                    ExpectedODataErrorException = errorException,
                    ExpectedODataExceptionMessage = this.ExpectedODataExceptionMessage,
                });
            }
            else
            {
                return(expectedResult);
            }
        }
Exemple #3
0
        private void InvokeBatchWriterAction(
            ODataBatchWriterTestWrapper writer,
            BatchWriterAction writerAction,
            WriterTestConfiguration testConfiguration,
            bool readOperationReady,
            BatchWriterStatesTestSetupResult setupResult)
        {
            switch (writerAction)
            {
            case BatchWriterAction.StartBatch:
                writer.WriteStartBatch();
                break;

            case BatchWriterAction.EndBatch:
                writer.WriteEndBatch();
                break;

            case BatchWriterAction.StartChangeset:
                writer.WriteStartChangeset();
                break;

            case BatchWriterAction.EndChangeset:
                writer.WriteEndChangeset();
                break;

            case BatchWriterAction.Operation:
                if (testConfiguration.IsRequest)
                {
                    writer.CreateOperationRequestMessage(readOperationReady ? "GET" : "POST", new Uri("http://odata.org"), "4");
                }
                else
                {
                    writer.CreateOperationResponseMessage();
                }

                break;

            case BatchWriterAction.GetOperationStream:
                GetOperationStream(setupResult == null ? null : setupResult.Message, testConfiguration);
                break;

            case BatchWriterAction.DisposeOperationStream:
                Stream s = setupResult == null ? null : setupResult.MessageStream;
                if (s != null)
                {
                    try
                    {
                        s.Dispose();
                    }
                    catch (ObjectDisposedException e)
                    {
                        // Replace the disposed exception with OData exception so that our type checks work correctly.
                        // No need to verify that the Dispose thrown the right type of the exception.
                        throw new ODataException(e.Message);
                    }
                }
                break;
            }
        }
Exemple #4
0
        /// <summary>
        /// Unwraps top-level multiple JSON results from the "d" and/or "results" wrappers as appropriate depending on <paramref name="testConfiguration"/>.
        /// </summary>
        /// <param name="testConfiguration">The test configuration to consider.</param>
        /// <param name="value">The value to unwrap.</param>
        /// <returns>Unwrapped value.</returns>
        public static JsonValue UnwrapTopLevelResults(WriterTestConfiguration testConfiguration, JsonValue value)
        {
            value = UnwrapTopLevelValue(testConfiguration, value);
            value = GetFeedItemsArray(testConfiguration, value);

            TrimSurroundingWhitespaces(value);

            return(value);
        }
Exemple #5
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;
            }
        }
Exemple #6
0
 /// <summary>
 /// Called before the test is actually executed for the specified test configuration to determine if the test should be skipped.
 /// </summary>
 /// <param name="testConfiguration">The test configuration to use.</param>
 /// <returns>true if the test should be skipped for the <paramref name="testConfiguration"/> or false to run the test.</returns>
 /// <remarks>Derived classes should always call the base class and return true if the base class returned true.</remarks>
 protected override bool ShouldSkipForTestConfiguration(WriterTestConfiguration testConfiguration)
 {
     if (this.SkipTestConfiguration != null)
     {
         return(this.SkipTestConfiguration(testConfiguration));
     }
     else
     {
         return(false);
     }
 }
Exemple #7
0
 protected WriterTestExpectedResults GetExpectedResult(WriterTestConfiguration testConfiguration)
 {
     if (this.ExpectedResultCallback != null)
     {
         return(this.ExpectedResultCallback(testConfiguration));
     }
     else
     {
         return(null);
     }
 }
Exemple #8
0
        /// <summary>
        /// Gets the JSON array holding the entries of the given feed.
        /// </summary>
        /// <param name="testConfiguration">The test configuration to consider.</param>
        /// <param name="feed">The JSON value representing the feed.</param>
        /// <returns>A JSON array with the items in a feed.</returns>
        public static JsonArray GetFeedItemsArray(WriterTestConfiguration testConfiguration, JsonValue feed)
        {
            if (!testConfiguration.IsRequest)
            {
                feed = feed.Object().PropertyValue("results");
                ExceptionUtilities.CheckObjectNotNull(feed, "The specified JSON payload is not wrapped in the expected \"results\": wrapper.");
            }

            ExceptionUtilities.Assert(feed.JsonType == JsonValueType.JsonArray, "Feed contents must be an array.");
            return((JsonArray)feed);
        }
Exemple #9
0
        /// <summary>
        /// Unwraps top-level JSON payload from the "d" wrapper as appropriate depending on <paramref name="testConfiguration"/>.
        /// </summary>
        /// <param name="testConfiguration">The test configuration to consider.</param>
        /// <param name="value">The value to unwrap.</param>
        /// <returns>Unwrapped value.</returns>
        public static JsonValue UnwrapTopLevelValue(WriterTestConfiguration testConfiguration, JsonValue value)
        {
            if (!testConfiguration.IsRequest)
            {
                value = value.Object().PropertyValue("d");
                ExceptionUtilities.CheckObjectNotNull(value, "The specified JSON payload is not wrapped in the expected \"d\":{{}} wrapper.");
            }

            TrimSurroundingWhitespaces(value);

            return(value);
        }
        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)
        {
            this.settings.Assert.IsTrue(payloadKind == ODataPayloadKind.MetadataDocument, "Only metadata payload kind is supported.");

            // read the message content using the Taupo infrastructure
            ExceptionUtilities.CheckArgumentNotNull(message.TestStream, "stream != null");
            var observed = TestWriterUtils.ReadToString(message);

            if (logger != null)
            {
                logger.LogPayload(TestWriterUtils.BaseLineFixup(observed));
            }
        }
Exemple #12
0
        /// <summary>
        /// Compute the resulting string representation of a URI in a given test configuration.
        /// </summary>
        /// <param name="uri">The URI to convert to string.</param>
        /// <param name="testConfig">The test configuration to use.</param>
        /// <returns>The string representation of the <paramref name="uri"/> for the given test configuration.</returns>
        private string GetResultUri(Uri uri, WriterTestConfiguration testConfig)
        {
            Uri baseUri = testConfig.MessageWriterSettings.BaseUri;

            Debug.Assert(testConfig.Format == ODataFormat.Json, "Only ATOM and JSON lite are supported.");
            if (uri.IsAbsoluteUri)
            {
                return(uri.AbsoluteUri);
            }
            else if (baseUri != null)
            {
                // In JSON we expect the absolute URI if a base URI is present
                return(new Uri(baseUri, uri).AbsoluteUri);
            }
            else
            {
                // This will fail; return the original relative URI.
                return(uri.OriginalString);
            }
        }
Exemple #13
0
        public void RawPrimitiveValueTests()
        {
            var testCases = new PayloadWriterTestDescriptor <object> []
            {
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)(double)1, "1", null, TextPlainContentType),                                                                                   // double
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)new byte[] { 0, 1, 0, 1 }, (string)null, new byte[] { 0, 1, 0, 1 }, ApplicationOctetStreamContentType),                        // binary
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)(Single)1, "1", (byte[])null, TextPlainContentType),                                                                           // single
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)true, "true", (byte[])null, TextPlainContentType),                                                                             // boolean
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)(byte)1, "1", (byte[])null, TextPlainContentType),                                                                             // byte
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)DateTimeOffset.Parse("2010-10-10T10:10:10Z"), "2010-10-10T10:10:10Z", (byte[])null, TextPlainContentType),                     // DateTimeOffset
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)DateTimeOffset.Parse("2010-10-10T10:10:10+01:00"), "2010-10-10T10:10:10+01:00", (byte[])null, TextPlainContentType),           // DateTimeOffset (2)
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)DateTimeOffset.Parse("2010-10-10T10:10:10-08:00"), "2010-10-10T10:10:10-08:00", (byte[])null, TextPlainContentType),           // DateTimeOffset (3)
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)(decimal)1, "1", (byte[])null, TextPlainContentType),                                                                          // Decimal
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)new Guid("11111111-2222-3333-4444-555555555555"), "11111111-2222-3333-4444-555555555555", (byte[])null, TextPlainContentType), // Guid
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)(sbyte)1, "1", (byte[])null, TextPlainContentType),                                                                            // SByte
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)(Int16)1, "1", (byte[])null, TextPlainContentType),                                                                            // Int16
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)(Int32)1, "1", (byte[])null, TextPlainContentType),                                                                            // Int32
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)(Int64)1, "1", (byte[])null, TextPlainContentType),                                                                            // Int64
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)"1", "1", (byte[])null, TextPlainContentType),                                                                                 // string
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)TimeSpan.FromMinutes(12.34), "PT12M20.4S", (byte[])null, TextPlainContentType),                                                // Duration
                new PayloadWriterTestDescriptor <object>(this.Settings, (object)string.Empty, string.Empty, (byte[])null, TextPlainContentType),                                                               // empty
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.DefaultFormatConfigurationsWithIndent,
                (testCase, testConfiguration) =>
            {
                // fix up the accept header for binary content
                bool binaryPayload = testCase.PayloadItems.Single() is byte[];
                if (binaryPayload)
                {
                    ODataMessageWriterSettings settings = testConfiguration.MessageWriterSettings.Clone();
                    settings.SetContentType("application/octet-stream", null);
                    testConfiguration = new WriterTestConfiguration(testConfiguration.Format, settings, testConfiguration.IsRequest, testConfiguration.Synchronous);
                }

                TestWriterUtils.WriteAndVerifyRawContent(testCase, testConfiguration, this.Assert, this.Logger);
            });
        }
        public void WorkspaceNamesTests()
        {
            string[] workspaceNames = new string[] { null, string.Empty, "MyWorkspaceName" };

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

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurationsWithIndent,
                (testCase, testConfig) =>
            {
                WriterTestConfiguration newConfiguration = testConfig.Clone();
                newConfiguration.MessageWriterSettings.PayloadBaseUri = new Uri(baseUri);
                newConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);
                TestWriterUtils.WriteAndVerifyTopLevelContent(
                    testCase,
                    newConfiguration,
                    (messageWriter) => messageWriter.WriteServiceDocument(testCase.PayloadItems.Single()),
                    this.Assert,
                    baselineLogger: this.Logger);
            });
        }
        /// <summary>
        /// Runs the test specified by this test descriptor.
        /// </summary>
        /// <param name="testConfiguration">The test configuration to use for running the test.</param>
        public override void RunTest(WriterTestConfiguration testConfiguration, BaselineLogger logger)
        {
            if (this.ShouldSkipForTestConfiguration(testConfiguration))
            {
                return;
            }

            // Wrap the memory stream in a non-disposing stream so we can dump the message content
            // even in the case of a failure where the message stream normally would get disposed.
            logger.LogConfiguration(testConfiguration);
            logger.LogModelPresence(this.Model);
            this.messageStream = new NonDisposingStream(new MemoryStream());
            TestMessage message = this.CreateOutputMessage(this.messageStream, testConfiguration, this.PayloadElement);
            IEdmModel   model   = this.GetMetadataProvider();
            WriterTestExpectedResults expectedResult = this.GetExpectedResult(testConfiguration);

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

            Exception exception = TestExceptionUtils.RunCatching(() =>
            {
                // 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);
                using (ODataMessageWriterTestWrapper messageWriterWrapper = TestWriterUtils.CreateMessageWriter(message, model, newTestConfig, this.settings.Assert, null))
                {
                    this.WritePayload(messageWriterWrapper, testConfiguration);
                    expectedResult.VerifyResult(message, this.PayloadKind, testConfiguration, logger);
                }
            });

            try
            {
                expectedResult.VerifyException(exception);
            }
            catch (Exception failureException)
            {
                this.TraceFailureInformation(message, this.messageStream, testConfiguration);
                throw failureException;
            }
        }
Exemple #16
0
        /// <summary>
        /// Depending on the passed in <paramref name="testConfiguration"/> wraps the specified <paramref name="json"/>
        /// in either the "d" or "results" wrapper or both.
        /// </summary>
        /// <param name="testConfiguration">The test configuration to consider.</param>
        /// <param name="countString">An optional string that represents the inline count.</param>
        /// <param name="nextLinkString">An optional string that represents the next page link.</param>
        /// <param name="jsonLines">The json payload to wrap.</param>
        /// <returns>The wrapped json payload.</returns>
        public static string WrapTopLevelResults(WriterTestConfiguration testConfiguration, string countString, string nextLinkString, string[] jsonLines)
        {
            if (!testConfiguration.IsRequest)
            {
                List <string> wrappedJsonLines = new List <string>();
                wrappedJsonLines.Add("{");

                for (int i = 0; i < jsonLines.Length; ++i)
                {
                    // remove the $(Indent) from the first line (if it exists) and add the 'results' property
                    if (i == 0)
                    {
                        if (countString != null)
                        {
                            wrappedJsonLines.Add(indentString + countString + ",\"results\":" + RemoveIndent(jsonLines[i]));
                        }
                        else
                        {
                            wrappedJsonLines.Add(indentString + "\"results\":" + RemoveIndent(jsonLines[i]));
                        }
                    }
                    else
                    {
                        wrappedJsonLines.Add(indentString + jsonLines[i]);
                    }
                }

                if (nextLinkString != null)
                {
                    int lastIx = wrappedJsonLines.Count - 1;
                    wrappedJsonLines[lastIx] = wrappedJsonLines[lastIx] + "," + nextLinkString;
                }

                wrappedJsonLines.Add("}");
                jsonLines = wrappedJsonLines.ToArray();
            }

            return(WrapTopLevelValue(testConfiguration, jsonLines));
        }
Exemple #17
0
        /// <summary>
        /// Called to create the input message for the reader test.
        /// </summary>
        /// <param name="innerStream">The <see cref="Stream"/> instance to be used as inner stream of the <see cref="TestStream"/>.</param>
        /// <param name="testConfiguration">The test configuration.</param>
        /// <returns>The newly created test message to use.</returns>
        protected override TestMessage CreateOutputMessage(Stream innerStream, WriterTestConfiguration testConfiguration)
        {
            Debug.Assert(innerStream is StreamingTestStream, "StreamingTestStream expected.");
            StreamingTestStream streamingTestStream = (StreamingTestStream)innerStream;

            if (testConfiguration.Synchronous)
            {
                streamingTestStream.FailAsynchronousCalls = true;
            }
            else
            {
                streamingTestStream.FailSynchronousCalls = true;
            }

            TestMessage testMessage = TestWriterUtils.CreateOutputMessageFromStream(
                streamingTestStream,
                testConfiguration,
                this.PayloadKind,
                this.PayloadElement.GetCustomContentTypeHeader(),
                this.UrlResolver);

            return(testMessage);
        }
Exemple #18
0
        /// <summary>
        /// Runs the test specified by this test descriptor.
        /// </summary>
        /// <param name="testConfiguration">The test configuration to use for running the test.</param>
        public override void RunTest(WriterTestConfiguration testConfiguration, BaselineLogger logger = null)
        {
            //TODO: Use Logger to verify result, right now this change is only to unblock writer testcase checkin

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

            // Generate a StreamingTestStream with a NonDisposingStream.
            this.messageStream = new StreamingTestStream(new NonDisposingStream(new MemoryStream()));
            TestMessage message = this.CreateOutputMessage(this.messageStream, testConfiguration);
            IEdmModel   model   = this.GetMetadataProvider();
            StreamingWriterTestExpectedResults expectedResult = (StreamingWriterTestExpectedResults)this.GetExpectedResult(testConfiguration);

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

            Exception exception = TestExceptionUtils.RunCatching(() =>
            {
                using (ODataMessageWriterTestWrapper messageWriterWrapper = TestWriterUtils.CreateMessageWriter(message, model, testConfiguration, this.settings.Assert))
                {
                    this.WritePayload(messageWriterWrapper, testConfiguration);
                    expectedResult.ObservedElement = this.readObject;
                    expectedResult.VerifyResult(message, this.PayloadKind, testConfiguration);
                }
            });

            try
            {
                expectedResult.VerifyException(exception);
            }
            catch (Exception failureException)
            {
                this.TraceFailureInformation(message, this.messageStream, testConfiguration);
                throw failureException;
            }
        }
        public void BaseUriValidationTest()
        {
            string relativeUriString = "abc/pqr/";
            Uri    absoluteUri       = new Uri("http://odata.org");
            Uri    relativeUri       = absoluteUri.MakeRelativeUri(new Uri(absoluteUri, relativeUriString));

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

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

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

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

                TestWriterUtils.WriteAndVerifyODataPayload(testDescriptor.TestDescriptor, config, this.Assert, this.Logger);
            });
        }
        public void StreamMessage(ODataMessageReaderTestWrapper reader, ODataMessageWriterTestWrapper writer, ODataPayloadKind payloadKind, WriterTestConfiguration config)
        {
            ExceptionUtilities.CheckArgumentNotNull(reader, "reader is required");
            ExceptionUtilities.CheckArgumentNotNull(writer, "writer is required");
            ExceptionUtilities.CheckArgumentNotNull(payloadKind, "payloadKind is required");
            ExceptionUtilities.CheckArgumentNotNull(config, "config is required");

            this.testConfiguration = config;

            switch (payloadKind)
            {
            case ODataPayloadKind.Entry:
                this.StartRead(reader.CreateODataEntryReader(), writer.CreateODataEntryWriter());
                break;

            case ODataPayloadKind.Feed:
                this.StartRead(reader.CreateODataFeedReader(), writer.CreateODataFeedWriter());
                break;

            default:
                throw new NotSupportedException("ObjectModelReadWriteStreamer currently supports only feed and entry");
            }
            ;
        }
Exemple #21
0
        /// <summary>
        /// Depending on the passed in <paramref name="testConfiguration"/> wraps the specified <paramref name="json"/>
        /// in the start of the "d" wrapper but does not add the closing '}' for the "d" wrapper; used for error payloads.
        /// </summary>
        /// <param name="testConfiguration">The test configuration to consider.</param>
        /// <param name="jsonLines">The json payload (as separate lines) to (partially) wrap.</param>
        /// <returns>The partially wrapped json payload.</returns>
        public static string WrapTopLevelValuePartial(WriterTestConfiguration testConfiguration, params string[] jsonLines)
        {
            if (!testConfiguration.IsRequest)
            {
                string[] wrappedJsonLines = new string[jsonLines.Length + 1];
                wrappedJsonLines[0] = "{";

                for (int i = 0; i < jsonLines.Length; ++i)
                {
                    if (i == 0)
                    {
                        wrappedJsonLines[i + 1] = indentString + "\"d\":" + RemoveIndent(jsonLines[i]);
                    }
                    else
                    {
                        wrappedJsonLines[i + 1] = indentString + jsonLines[i];
                    }
                }

                jsonLines = wrappedJsonLines;
            }

            return(string.Join("$(NL)", jsonLines));
        }
Exemple #22
0
        /// <summary>
        /// Compute the resulting string representation of a URI in a given test configuration.
        /// </summary>
        /// <param name="uri">The URI to convert to string.</param>
        /// <param name="testConfig">The test configuration to use.</param>
        /// <returns>The string representation of the <paramref name="uri"/> for the given test configuration.</returns>
        private string GetResultUri(Uri uri, WriterTestConfiguration testConfig)
        {
            Uri baseUri = testConfig.MessageWriterSettings.PayloadBaseUri;

            if (testConfig.Format == ODataFormat.Atom)
            {
                if (uri.IsAbsoluteUri)
                {
                    return(uri.AbsoluteUri);
                }
                else
                {
                    // In ATOM we expect the original, relative URI in the payload if a base URI is present;
                    // If no base URI exists, we will fail so we don't consider the case here.
                    return(uri.OriginalString);
                }
            }
            else
            {
                Debug.Assert(testConfig.Format == ODataFormat.Json, "Only ATOM and JSON lite are supported.");
                if (uri.IsAbsoluteUri)
                {
                    return(uri.AbsoluteUri);
                }
                else if (baseUri != null)
                {
                    // In JSON we expect the absolute URI if a base URI is present
                    return(new Uri(baseUri, uri).AbsoluteUri);
                }
                else
                {
                    // This will fail; return the original relative URI.
                    return(uri.OriginalString);
                }
            }
        }
Exemple #23
0
        /// <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>
        protected override void WritePayload(ODataMessageWriterTestWrapper messageWriter, WriterTestConfiguration config)
        {
            Debug.Assert(messageWriter != null, "messageWriter != null");

            messageWriter.WriteMetadataDocument();
        }
Exemple #24
0
 /// <summary>
 /// Depending on the passed in <paramref name="testConfiguration"/> wraps the specified <paramref name="json"/>
 /// in either the "d" or "results" wrapper or both.
 /// </summary>
 /// <param name="testConfiguration">The test configuration to consider.</param>
 /// <param name="jsonLines">The json payload to wrap.</param>
 /// <returns>The wrapped json payload.</returns>
 public static string WrapTopLevelResults(WriterTestConfiguration testConfiguration, string[] jsonLines)
 {
     return(WrapTopLevelResults(testConfiguration, null, null, jsonLines));
 }
        private WriterTestExpectedResults CreateExpectedResults(WriterTestConfiguration testConfiguration, ProjectedPropertiesTestCase testCase, bool withModel)
        {
            if (testCase.ExpectedException != null)
            {
                ExpectedException expectedException = testCase.ExpectedException(withModel);
                if (expectedException != null)
                {
                    return(new WriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                    {
                        ExpectedException2 = expectedException
                    });
                }
            }

            if (testConfiguration.Format == ODataFormat.Atom)
            {
                #region Atom expected result
                var atomExpectedResults = new AtomWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Xml = new XElement("properties", testCase.ExpectedProperties.OrderBy(p => p).Select(p => new XElement(p))).ToString(),
                    FragmentExtractor = (result) =>
                    {
                        // Navigation links
                        IEnumerable <string> actualProperties;
                        if (result == null)
                        {
                            actualProperties = new string[0];
                        }
                        else
                        {
                            actualProperties = result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                                               .Where(link => link.Attribute(TestAtomConstants.AtomLinkRelationAttributeName).Value.StartsWith(TestAtomConstants.ODataNavigationPropertiesRelatedLinkRelationPrefix))
                                               .Select(link => link.Attribute(TestAtomConstants.AtomLinkTitleAttributeName).Value);
                            // Named stream links
                            actualProperties = actualProperties.Concat(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                                                                       .Where(link => link.Attribute(TestAtomConstants.AtomLinkRelationAttributeName).Value.StartsWith(TestAtomConstants.ODataStreamPropertyEditMediaRelatedLinkRelationPrefix))
                                                                       .Select(link => link.Attribute(TestAtomConstants.AtomLinkTitleAttributeName).Value));
                            // Association links
                            actualProperties = actualProperties.Concat(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                                                                       .Where(link => link.Attribute(TestAtomConstants.AtomLinkRelationAttributeName).Value.StartsWith(TestAtomConstants.ODataNavigationPropertiesAssociationLinkRelationPrefix))
                                                                       .Select(link => link.Attribute(TestAtomConstants.AtomLinkTitleAttributeName).Value));
                            // Properties
                            actualProperties = actualProperties.Concat(result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomContentElementName)
                                                                       .Elements(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.AtomPropertiesElementName)
                                                                       .Elements().Where(e => e.Name.Namespace == TestAtomConstants.ODataXNamespace)
                                                                       .Select(pe => pe.Name.LocalName));
                        }

                        return(new XElement("properties",
                                            actualProperties.OrderBy(p => p).Select(p => new XElement(p))));
                    }
                };

                if (testCase.NestedPayload)
                {
                    var originalFragmentExtractor = atomExpectedResults.FragmentExtractor;
                    atomExpectedResults.FragmentExtractor = (result) =>
                    {
                        // Verify that the Wrapping_ID property is not written
                        this.Assert.IsNull(result
                                           .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomContentElementName)
                                           .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.AtomPropertiesElementName),
                                           "There should be no other property but the nav link and thus no m:properties in the content.");
                        XElement expandedNavLinkElement = result.Elements(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomLinkElementName)
                                                          .Where(link => link.Attribute(TestAtomConstants.AtomLinkRelationAttributeName).Value
                                                                 .StartsWith(TestAtomConstants.ODataNavigationPropertiesRelatedLinkRelationPrefix + "Wrapping_ExpandedEntry"))
                                                          .SingleOrDefault();
                        return(originalFragmentExtractor(
                                   expandedNavLinkElement == null
                                ? null
                                : expandedNavLinkElement
                                   .Element(TestAtomConstants.ODataMetadataXNamespace + TestAtomConstants.ODataInlineElementName)
                                   .Element(TestAtomConstants.AtomXNamespace + TestAtomConstants.AtomEntryElementName)));
                    };
                }

                return(atomExpectedResults);

                #endregion Atom expected result
            }
            else if (testConfiguration.Format == ODataFormat.Json)
            {
                #region JSON Light expected result
                JsonArray expectedJson = new JsonArray();
                foreach (var p in testCase.ExpectedProperties.Distinct().OrderBy(p => p))
                {
                    expectedJson.Add(new JsonPrimitiveValue(p));
                }

                var jsonExpectedResults = new JsonWriterTestExpectedResults(this.Settings.ExpectedResultSettings)
                {
                    Json = expectedJson.ToText(/*writingJsonLight*/ true, testConfiguration.MessageWriterSettings.Indent),
                    FragmentExtractor = (result) =>
                    {
                        // Everything except association links
                        IEnumerable <string> actualProperties;
                        if (result == null)
                        {
                            actualProperties = new string[0];
                        }
                        else
                        {
                            List <string> propertyNames = new List <string>();

                            foreach (JsonProperty jsonProperty in result.Object().Properties)
                            {
                                string propertyName = jsonProperty.Name;
                                int    atIndex      = propertyName.IndexOf('@');
                                int    dotIndex     = propertyName.IndexOf('.');

                                if (dotIndex < 0)
                                {
                                    propertyNames.Add(propertyName);
                                }
                                else if (atIndex >= 0)
                                {
                                    propertyNames.Add(propertyName.Substring(0, atIndex));
                                }
                            }

                            actualProperties = propertyNames.Distinct();
                        }

                        JsonArray r = new JsonArray();
                        foreach (var p in actualProperties.OrderBy(p => p))
                        {
                            r.Add(new JsonPrimitiveValue(p));
                        }

                        return(r);
                    }
                };

                if (testCase.NestedPayload)
                {
                    var originalFragmentExtractor = jsonExpectedResults.FragmentExtractor;
                    jsonExpectedResults.FragmentExtractor = (result) =>
                    {
                        // Verify that the Wrapping_ID property is not written
                        JsonObject resultObject = result.Object();
                        this.Assert.IsNull(resultObject.Property("Wrapping_ID"), "No other property but the nav. link should be written.");
                        return(originalFragmentExtractor(
                                   resultObject.Property("Wrapping_ExpandedEntry") == null
                                ? null
                                : resultObject.PropertyObject("Wrapping_ExpandedEntry")));
                    };
                }

                return(jsonExpectedResults);

                #endregion JSON Light expected result
            }
            else
            {
                throw new TaupoInvalidOperationException("The format " + testConfiguration.Format.GetType().FullName + " is not supported.");
            }
        }
Exemple #26
0
        public void ResolverUriTest()
        {
            Uri inputUri          = new Uri("inputUri", UriKind.Relative);
            Uri resultRelativeUri = new Uri("resultRelativeUri", UriKind.Relative);
            Uri resultAbsoluteUri = new Uri("http://odata.org/absoluteresolve");

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

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

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

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

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

                        ODataMessageWriterSettings batchWriterSettings = testConfiguration.MessageWriterSettings.Clone();
                        batchWriterSettings.SetContentType(null);
                        WriterTestConfiguration batchTestConfiguration = new WriterTestConfiguration(
                            null,
                            batchWriterSettings,
                            testConfiguration.IsRequest,
                            testConfiguration.Synchronous);
                        BatchWriterUtils.WriteAndVerifyBatchPayload(batchTd, batchTestConfiguration, testConfiguration, this.Assert);
                    }
                }
            });
        }
        /// <summary>
        /// Verifies the result of the write-read.
        /// </summary>
        /// <param name="message">The test message is not used but is required to keep the method signature the same.</param>
        /// <param name="payloadKind">The payload kind is not used but is required to keep the method signature the same.</param>
        /// <param name="testConfiguration">The test configuration is used for some fixups.</param>
        public override void VerifyResult(TestMessage message, ODataPayloadKind payloadKind, WriterTestConfiguration testConfiguration, BaselineLogger logger = null)
        {
            //TODO: Use Logger to verify result, right now this change is only to unblock writer testcase checkin

            Debug.Assert(ObservedElement != null, "ObservedElement not provided");
            // Fixup the expected and get the content type
            ODataPayloadElement expected = this.ExpectedPayload.DeepCopy();
            ODataPayloadElement observed = this.ObservedElement.DeepCopy();

            observed.Accept(new RemoveTypeNameAnnotationFromComplexInCollection());
            expected.Accept(new ReorderProperties());
            expected.Accept(new RemoveComplexWithNoProperties());

            // Compare
            this.settings.PayloadElementComparer.Compare(expected, observed);
        }
 private static Stream GetMessageStream(ODataBatchOperationResponseMessage responseMessage, WriterTestConfiguration testConfiguration)
 {
     if (testConfiguration.Synchronous)
     {
         return(responseMessage.GetStream());
     }
     else
     {
         var t = responseMessage.GetStreamAsync();
         t.Wait();
         return(t.Result);
     }
 }
Exemple #29
0
        /// <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)
        {
            Debug.Assert(this.messageStream != null, "Streaming test stream must have been created.");
            TestMessage testMessage = this.CreateInputMessageFromStream((TestStream)this.messageStream, testConfiguration, this.PayloadKind, string.Empty, this.UrlResolver);

            testMessage.SetContentType(testConfiguration.Format, this.PayloadKind);

            Exception exception = TestExceptionUtils.RunCatching(() =>
            {
                ODataMessageReaderSettings readerSettings = new ODataMessageReaderSettings(this.settings.MessageReaderSettings)
                {
                    DisableMessageStreamDisposal = testConfiguration.MessageWriterSettings.DisableMessageStreamDisposal,
                    EnableAtom = true
                };

                ReaderTestConfiguration readerConfig = new ReaderTestConfiguration(
                    testConfiguration.Format,
                    readerSettings,
                    testConfiguration.IsRequest,
                    testConfiguration.Synchronous);

                IEdmModel model = this.GetMetadataProvider();
                using (ODataMessageReaderTestWrapper messageReaderWrapper = TestReaderUtils.CreateMessageReader(testMessage, model, readerConfig))
                {
                    ODataPayloadElementToObjectModelConverter payloadElementToOMConverter = new ODataPayloadElementToObjectModelConverter(!testConfiguration.IsRequest);
                    ObjectModelToPayloadElementConverter reverseConverter = new ObjectModelToPayloadElementConverter();
                    ObjectModelWriteReadStreamer streamer = new ObjectModelWriteReadStreamer();
                    if (testConfiguration.Format == ODataFormat.Atom)
                    {
                        this.PayloadElement.Accept(new AddFeedIDFixup());
                    }

                    this.readObject = reverseConverter.Convert(streamer.WriteMessage(messageWriter, messageReaderWrapper, this.PayloadKind, payloadElementToOMConverter.Convert(this.PayloadElement)), !testConfiguration.IsRequest);
                }
            });
        }
Exemple #30
0
        private static BatchWriterStatesTestSetupResult GetOperationStream(object message, WriterTestConfiguration testConfiguration)
        {
            BatchWriterStatesTestSetupResult result = new BatchWriterStatesTestSetupResult {
                Message = message
            };

            ODataBatchOperationRequestMessage requestMessage = message as ODataBatchOperationRequestMessage;

            if (requestMessage != null)
            {
                if (testConfiguration.Synchronous)
                {
                    result.MessageStream = requestMessage.GetStream();
                    return(result);
                }
                else
                {
                    // TODO: 191417: Enable async Tests on Phone and Silverlight when Product Supports them
#if SILVERLIGHT || WINDOWS_PHONE
                    throw new TaupoNotSupportedException("This test is not supported in aSynchronous mode in Silverlight or Phone");
#else
                    var t = requestMessage.GetStreamAsync();
                    t.Wait();
                    result.MessageStream = t.Result;
                    return(result);
#endif
                }
            }

            ODataBatchOperationResponseMessage responseMessage = message as ODataBatchOperationResponseMessage;
            if (responseMessage != null)
            {
                if (testConfiguration.Synchronous)
                {
                    result.MessageStream = responseMessage.GetStream();
                    return(result);
                }
                else
                {
                    // TODO: Enable async Tests on Phone and Silverlight when Product Supports them
#if SILVERLIGHT || WINDOWS_PHONE
                    throw new TaupoNotSupportedException("This test is not supported in aSynchronous mode in Silverlight or Phone");
#else
                    var t = responseMessage.GetStreamAsync();
                    t.Wait();
                    result.MessageStream = t.Result;
                    return(result);
#endif
                }
            }

            return(null);
        }