Exemple #1
0
        /// <summary>
        /// Gets the value of an enumeration option.
        /// </summary>
        /// <param name="enumerationType">The type of the enumeration.</param>
        /// <param name="value">The value to get from the enumeration.</param>
        /// <returns>The value of the option on the enumeration.</returns>
        public static object GetEnumerationValue(Type enumerationType, string value)
        {
            ExceptionUtilities.CheckArgumentNotNull(enumerationType, "enumerationType");
            ExceptionUtilities.CheckStringArgumentIsNotNullOrEmpty(value, "value");

            foreach (var enumValue in EnumExtensionMethods.GetValues(enumerationType))
            {
                if (enumValue.ToString() == value)
                {
                    return(enumValue);
                }
            }

            throw new ArgumentException(String.Format("Failed to find value '{0}' in enum type '{1}", value, enumerationType.Name));
        }
Exemple #2
0
        public void CollectionWriterStatesTest()
        {
            var testCases = new CollectionWriterStatesTestDescriptor[]
            {
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Start",
                    Setup            = null,
                    ExpectedResults  = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, null },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Start' to state 'Item'. The only valid actions in state 'Start' are to write the collection or to write nothing at all." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Start'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, null },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Collection",
                    Setup            = (mw, w, s) => {
                        w.WriteStart(new ODataCollectionStart {
                            Name = "foo"
                        });
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Collection' to state 'Collection'. The only valid actions in state 'Collection' are to write an item or to write the end of the collection." },
                        { CollectionWriterAction.Item, null },
                        { CollectionWriterAction.End, null },
                        { CollectionWriterAction.Error, null },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Item",
                    Setup            = (mw, w, s) => {
                        w.WriteStart(new ODataCollectionStart {
                            Name = "foo"
                        });
                        w.WriteItem(42);
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Item' to state 'Collection'. The only valid actions in state 'Item' are to write an item or the end of the collection." },
                        { CollectionWriterAction.Item, null },
                        { CollectionWriterAction.End, null },
                        { CollectionWriterAction.Error, null },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Completed",
                    Setup            = (mw, w, s) => {
                        w.WriteStart(new ODataCollectionStart {
                            Name = "foo"
                        });
                        w.WriteEnd();
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Completed' to state 'Collection'. Nothing further can be written once the writer has completed." },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Completed' to state 'Item'. Nothing further can be written once the writer has completed." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Completed'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, "Cannot transition from state 'Completed' to state 'Error'. Nothing further can be written once the writer has completed." },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "ODataExceptionThrown",
                    Setup            = (mw, w, s) => {
                        TestExceptionUtils.RunCatching(() => w.WriteItem(42));
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Error' to state 'Collection'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Error' to state 'Item'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Error'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, null },
                    }
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "FatalExceptionThrown",
                    Setup            = (mw, w, s) => {
                        // In JSON we can make the stream fail
                        s.FailNextCall = true;
                        w.WriteStart(new ODataCollectionStart {
                            Name = "foo"
                        });
                        TestExceptionUtils.RunCatching(() => w.Flush());
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Error' to state 'Collection'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Error' to state 'Item'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Error'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, null },
                    },
                    // There's no simple way to make the writer go into a fatal exception state with XmlWriter underneath.
                    // XmlWriter will move to an Error state if anything goes wrong with it, and thus we can't write into it anymore.
                    // As a result for example the in-stream error case for this one can't work as it should.
                    SkipForConfiguration = (tc) => tc.Format != ODataFormat.Json
                },
                new CollectionWriterStatesTestDescriptor {
                    DebugDescription = "Error",
                    Setup            = (mw, w, s) => {
                        mw.WriteError(new ODataError(), false);
                    },
                    ExpectedResults = new Dictionary <CollectionWriterAction, string> {
                        { CollectionWriterAction.Start, "Cannot transition from state 'Error' to state 'Collection'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.Item, "Cannot transition from state 'Error' to state 'Item'. Nothing can be written once the writer entered the error state." },
                        { CollectionWriterAction.End, "ODataCollectionWriter.WriteEnd was called in an invalid state ('Error'); WriteEnd is only supported in states 'Start', 'Collection', and 'Item'." },
                        { CollectionWriterAction.Error, "The WriteError method or the WriteErrorAsync method on the ODataMessageWriter has already been called to write an error payload. Only a single error payload can be written with each ODataMessageWriter instance." },
                    }
                },
            };

            //ToDo: Fix places where we've lost JsonVerbose coverage to add JsonLight
            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                EnumExtensionMethods.GetValues <CollectionWriterAction>().Cast <CollectionWriterAction>(),
                this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => false),
                (testCase, writerAction, testConfiguration) =>
            {
                using (TestStream stream = new TestStream())
                {
                    if (testCase.SkipForConfiguration != null && testCase.SkipForConfiguration(testConfiguration))
                    {
                        return;
                    }

                    // 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(stream, testConfiguration, this.Assert);
                    ODataCollectionWriter writer = messageWriter.CreateODataCollectionWriter();
                    if (testCase.Setup != null)
                    {
                        testCase.Setup(messageWriter, writer, stream);
                    }

                    string expectedException = testCase.ExpectedResults[writerAction];

                    this.Assert.ExpectedException <ODataException>(
                        () => InvokeCollectionWriterAction(messageWriter, writer, writerAction),
                        expectedException);
                }
            });
        }
Exemple #3
0
        public void BatchWriterStatesTest()
        {
            var testCases = new BatchWriterStatesTestDescriptor[]
            {
                // Start
                new BatchWriterStatesTestDescriptor {
                    Setup           = null,
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, null },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromStart") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromStart") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromStart") },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // BatchStarted
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchStarted") },
                        { BatchWriterAction.EndBatch, null },
                        { BatchWriterAction.StartChangeset, null },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // ChangeSetStarted
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromChangeSetStarted") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteBatchWithActiveChangeSet") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotStartChangeSetWithActiveChangeSet") },
                        { BatchWriterAction.EndChangeset, null },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = false
                },

                // OperationCreated - Read
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        if (tc.IsRequest)
                        {
                            return(new BatchWriterStatesTestSetupResult {
                                Message = w.CreateOperationRequestMessage("GET", new Uri("http://odata.org"))
                            });
                        }
                        else
                        {
                            return(new BatchWriterStatesTestSetupResult {
                                Message = w.CreateOperationResponseMessage()
                            });
                        }
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationCreated") },
                        { BatchWriterAction.EndBatch, null },
                        { BatchWriterAction.StartChangeset, null },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // OperationStreamRequested - Read
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        if (tc.IsRequest)
                        {
                            return(GetOperationStream(w.CreateOperationRequestMessage("GET", new Uri("http://odata.org")), tc));
                        }
                        else
                        {
                            return(GetOperationStream(w.CreateOperationResponseMessage(), tc));
                        }
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.GetOperationStream, ODataExpectedExceptions.ODataException("ODataBatchOperationMessage_VerifyNotCompleted") },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // OperationStreamDisposed - Read
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        BatchWriterStatesTestSetupResult result;
                        if (tc.IsRequest)
                        {
                            result = GetOperationStream(w.CreateOperationRequestMessage("GET", new Uri("http://odata.org")), tc);
                        }
                        else
                        {
                            result = GetOperationStream(w.CreateOperationResponseMessage(), tc);
                        }

                        result.MessageStream.Dispose();
                        return(result);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamDisposed") },
                        { BatchWriterAction.EndBatch, null },
                        { BatchWriterAction.StartChangeset, null },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, ODataExpectedExceptions.ODataException("ODataBatchOperationMessage_VerifyNotCompleted") },
                        // Calling IDisposable.Dispose  should not throw.
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // OperationCreated - Update
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        if (tc.IsRequest)
                        {
                            return(new BatchWriterStatesTestSetupResult {
                                Message = w.CreateOperationRequestMessage("POST", new Uri("http://odata.org"), "1")
                            });
                        }
                        else
                        {
                            return(new BatchWriterStatesTestSetupResult {
                                Message = w.CreateOperationResponseMessage()
                            });
                        }
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationCreated") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteBatchWithActiveChangeSet") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotStartChangeSetWithActiveChangeSet") },
                        { BatchWriterAction.EndChangeset, null },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = false
                },

                // OperationStreamRequested - Update
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        if (tc.IsRequest)
                        {
                            return(GetOperationStream(w.CreateOperationRequestMessage("POST", new Uri("http://odata.org"), "2"), tc));
                        }
                        else
                        {
                            return(GetOperationStream(w.CreateOperationResponseMessage(), tc));
                        }
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamRequested") },
                        { BatchWriterAction.GetOperationStream, ODataExpectedExceptions.ODataException("ODataBatchOperationMessage_VerifyNotCompleted") },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = false
                },

                // OperationStreamDisposed - Update
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        BatchWriterStatesTestSetupResult result;
                        if (tc.IsRequest)
                        {
                            result = GetOperationStream(w.CreateOperationRequestMessage("POST", new Uri("http://odata.org"), "3"), tc);
                        }
                        else
                        {
                            result = GetOperationStream(w.CreateOperationResponseMessage(), tc);
                        }

                        result.MessageStream.Dispose();
                        return(result);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromOperationContentStreamDisposed") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteBatchWithActiveChangeSet") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotStartChangeSetWithActiveChangeSet") },
                        { BatchWriterAction.EndChangeset, null },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, ODataExpectedExceptions.ODataException("ODataBatchOperationMessage_VerifyNotCompleted") },
                        // Calling IDisposable.Dispose  should not throw.
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = false
                },

                // ChangeSetCompleted
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteStartChangeset();
                        w.WriteEndChangeset();
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromChangeSetCompleted") },
                        { BatchWriterAction.EndBatch, null },
                        { BatchWriterAction.StartChangeset, null },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, null },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // BatchCompleted
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        w.WriteStartBatch();
                        w.WriteEndBatch();
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchCompleted") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchCompleted") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchCompleted") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataBatchWriter_InvalidTransitionFromBatchCompleted") },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },

                // FatalExceptionThrown
                new BatchWriterStatesTestDescriptor {
                    Setup = (w, s, tc) => {
                        s.FailNextCall = true;
                        w.WriteStartBatch();
                        if (tc.IsRequest)
                        {
                            w.CreateOperationRequestMessage("GET", new Uri("http://odata.org"));
                        }
                        else
                        {
                            w.CreateOperationResponseMessage();
                        }
                        TestExceptionUtils.RunCatching(() => w.Flush());
                        return(null);
                    },
                    ExpectedResults = new Dictionary <BatchWriterAction, ExpectedException> {
                        { BatchWriterAction.StartBatch, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "BatchStarted") },
                        { BatchWriterAction.EndBatch, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "BatchCompleted") },
                        { BatchWriterAction.StartChangeset, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "ChangeSetStarted") },
                        { BatchWriterAction.EndChangeset, ODataExpectedExceptions.ODataException("ODataBatchWriter_CannotCompleteChangeSetWithoutActiveChangeSet") },
                        { BatchWriterAction.Operation, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "OperationCreated") },
                        { BatchWriterAction.GetOperationStream, null },
                        { BatchWriterAction.DisposeOperationStream, null },
                    },
                    ReadOperationReady = true
                },
            };

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                EnumExtensionMethods.GetValues <BatchWriterAction>().Cast <BatchWriterAction>(),
                this.WriterTestConfigurationProvider.DefaultFormatConfigurations,
                (testCase, writerAction, testConfiguration) =>
            {
                using (TestStream stream = 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(stream, testConfiguration, this.Assert);
                    ODataBatchWriterTestWrapper writer           = messageWriter.CreateODataBatchWriter();
                    BatchWriterStatesTestSetupResult setupResult = null;
                    if (testCase.Setup != null)
                    {
                        setupResult = testCase.Setup(writer, stream, testConfiguration);
                    }

                    ExpectedException expectedException = testCase.ExpectedResults[writerAction];

                    TestExceptionUtils.ExpectedException(
                        this.Assert,
                        () => InvokeBatchWriterAction(writer, writerAction, testConfiguration, testCase.ReadOperationReady, setupResult),
                        expectedException,
                        this.ExceptionVerifier);
                }
            });
        }
        public void ContentTypeHeaderParsingTest()
        {
            IEnumerable <ContentTypeTestCase> testCases = new ContentTypeTestCase[]
            {
                #region Atom test cases
                new ContentTypeTestCase
                {
                    // only reading an entry or feed should succeed
                    ContentType    = "application/atom+xml;type=feed",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // only reading an entry or feed should succeed
                    ContentType    = "application/atom+xml;type=entry",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a feed, an entry, and metadata should succeed
                    ContentType    = "application/atom+xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a property, an entity reference link, entity reference links, a collection, a service document, and an error should succeed
                    ContentType    = "application/xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a property, an entity reference link, entity reference links, and a collection should succeed
                    ContentType    = "text/xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                new ContentTypeTestCase
                {
                    // reading a service document should succeed
                    ContentType    = "application/atomsvc+xml",
                    ExpectedFormat = ODataFormat.Atom,
                },
                #endregion Atom test cases

                #region RawValue test cases
                new ContentTypeTestCase
                {
                    // only reading a raw value will succeed
                    ContentType    = "text/plain",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk == ODataPayloadKind.Value ||
                                                  pk == ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only reading a raw value or binary value will succeed; raw values can be read as binary values when the content type is application/octet-stream
                    ContentType    = "application/octet-stream",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk == ODataPayloadKind.Value ||
                                                  pk == ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only raw value / binary value will succeed
                    ContentType    = "multipart/mixed",
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // Test for: MimeType allows 0x7F character, but ContentType parsing doesn't
                    ContentType    = "application/" + 0x7F,
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => false,
                },

                #endregion RawValue test cases

                #region JSON Lite test cases
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLight,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLightStreaming,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                new ContentTypeTestCase
                {
                    // only batch and raw value will fail (batch payload kind tested separately in BatchContentTypeHeaderParsingTest)
                    ContentType    = ApplicationJsonODataLightNonStreaming,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk =>
                                                  pk != ODataPayloadKind.Value &&
                                                  pk != ODataPayloadKind.BinaryValue,
                },
                #endregion JSON Lite test cases

                #region Error test cases
                new ContentTypeTestCase
                {
                    // unsupported content type; everything will fail
                    ContentType = "application/foo",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // unsupported content type with parameters; everything will fail
                    ContentType = "abc/pqr;a=b;c=d",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                new ContentTypeTestCase
                {
                    // "image/jpeg" is not supported, even for raw values.
                    ContentType = "image/jpeg",
                    ShouldSucceedForPayloadKind = pk => false,
                },
                #endregion Error test cases

                #region Content Type is null or empty
                new ContentTypeTestCase
                {
                    // null content type and zero content length should be default to Json if the payload kind is not binary value or value.
                    ContentType    = null,
                    ContentLength  = 0,
                    ExpectedFormat = ODataFormat.Json,
                    ShouldSucceedForPayloadKind = pk => true,
                    ShouldIgnoreTest            = pk => pk == ODataPayloadKind.BinaryValue || pk == ODataPayloadKind.Value
                },
                new ContentTypeTestCase
                {
                    // null content type and zero content length should be default to RawValue if the payload kind is binary value or value.
                    ContentType    = null,
                    ContentLength  = 0,
                    ExpectedFormat = ODataFormat.RawValue,
                    ShouldSucceedForPayloadKind = pk => true,
                    ShouldIgnoreTest            = pk => pk != ODataPayloadKind.Value
                },
                #endregion
            };

            string[] parameters = new string[]
            {
                "foo=bar",
                "foo1=bar1;foo2=bar2"
            };

            testCases = testCases.Concat(testCases.Where(tc => tc.ContentType != null).SelectMany(tc => parameters.Select(p => new ContentTypeTestCase(tc)
            {
                ContentType = tc.ContentType + ";" + p
            })));

            int oDataPayloadKindCount = EnumExtensionMethods.GetValues <ODataPayloadKind>().Length;

            this.Assert.AreEqual(oDataPayloadKindCount, TestReaderUtils.ODataPayloadKinds.Length, "The number of payload kind have changed, please update this test.");

            IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel();

            // We don't support batch payloads here; we test those separately in BatchContentTypeHeaderParsingTest
            IEnumerable <ODataPayloadKind> payloadKinds =
                TestReaderUtils.ODataPayloadKinds.Where(k => k != ODataPayloadKind.Batch && k != ODataPayloadKind.Unsupported);

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                payloadKinds,
                this.ReaderTestConfigurationProvider.AllFormatConfigurations,
                (testCase, payloadKind, testConfiguration) =>
            {
                testConfiguration = new ReaderTestConfiguration(testConfiguration);
                testConfiguration.MessageReaderSettings.EnableAtom = false;
                if (IgnoreTestCase(payloadKind, testConfiguration))
                {
                    return;
                }

                if (testCase.ShouldIgnoreTest != null && testCase.ShouldIgnoreTest(payloadKind))
                {
                    return;
                }

                string supportedMediaTypes;

                if (payloadKind == ODataPayloadKind.Value || payloadKind == ODataPayloadKind.BinaryValue)
                {
                    supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Value) + ", " + TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.BinaryValue);
                }
                else
                {
                    supportedMediaTypes = TestMediaTypeUtils.GetSupportedMediaTypes(payloadKind, /*includeAppJson*/ true);
                }

                ExpectedException expectedException = testCase.ExpectedException == null
                         ? testCase.ShouldSucceedForPayloadKind != null && testCase.ShouldSucceedForPayloadKind(payloadKind)
                             ? null
                             : ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", supportedMediaTypes, testCase.ContentType ?? "")
                         : testCase.ExpectedException;

                // Make sure to run success test cases only in configurations that will work.
                if (expectedException == null &&
                    testConfiguration.Format != null &&
                    testCase.ExpectedFormat != testConfiguration.Format)
                {
                    return;
                }

                ODataPayloadElement payloadElement = CreatePayloadElement(model, payloadKind, testConfiguration);

                // When we write a value with a content type different than 'text/plain', we will read it as binary.
                // Likewise, when we write a binary value with a 'text/plain' content type, we will read it as a string.
                Func <ReaderTestConfiguration, ODataPayloadElement> expectedResultElementFunc = null;
                if (payloadKind == ODataPayloadKind.Value && testCase.ContentType != null && !testCase.ContentType.StartsWith("text/plain"))
                {
                    expectedResultElementFunc = (testConfig) => ConvertToBinaryPayloadElement(payloadElement);
                }
                else if (payloadKind == ODataPayloadKind.BinaryValue && testCase.ContentType != null && testCase.ContentType.StartsWith("text/plain"))
                {
                    expectedResultElementFunc = (testConfig) => ConvertToStringPayloadElement(payloadElement);
                }

                ODataFormat expectedFormat = testCase.ExpectedFormat;

                ReaderContentTypeTestDescriptor testDescriptor = new ReaderContentTypeTestDescriptor(this.Settings)
                {
                    PayloadElement = payloadElement,
                    ExpectedResultPayloadElement = expectedResultElementFunc,
                    PayloadEdmModel   = model,
                    ExpectedFormat    = expectedFormat,
                    ContentType       = testCase.ContentType,
                    ExpectedException = expectedException
                };

                testDescriptor.RunTest(testConfiguration);
                testConfiguration.MessageReaderSettings.EnableAtom = true;
            });
        }
        private void WriterStatesTestImplementation(bool feedWriter)
        {
            var testCases = new WriterStatesTestDescriptor[]
            {
                // Start
                new WriterStatesTestDescriptor {
                    Setup           = null,
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, feedWriter ? ODataExpectedExceptions.ODataException("ODataWriterCore_CannotWriteTopLevelResourceWithResourceSetWriter") : (ExpectedException)null },
                        { WriterAction.StartFeed, feedWriter ? (ExpectedException)null : ODataExpectedExceptions.ODataException("ODataWriterCore_CannotWriteTopLevelResourceSetWithResourceWriter") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromStart", "Start", "NavigationLink") },
                        { WriterAction.End, ODataExpectedExceptions.ODataException("ODataWriterCore_WriteEndCalledInInvalidState", "Start") },
                        { WriterAction.Error, null },
                    }
                },

                // Entry
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                        w.WriteStart(ObjectModelUtils.CreateDefaultEntry());
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromResource", "Entry", "Entry") },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromResource", "Entry", "Feed") },
                        { WriterAction.StartLink, null },
                        { WriterAction.End, null },
                        { WriterAction.Error, null },
                    }
                },

                // Feed
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                        else
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultEntry()); w.WriteStart(ObjectModelUtils.CreateDefaultCollectionLink()); w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, null },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromResourceSet", "Feed", "Feed") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromResourceSet", "Feed", "NavigationLink") },
                        { WriterAction.End, null },
                        { WriterAction.Error, null },
                    }
                },

                // Link - single
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                        w.WriteStart(ObjectModelUtils.CreateDefaultEntry());
                        w.WriteStart(new ODataNestedResourceInfo {
                            Name = ObjectModelUtils.DefaultLinkName, Url = ObjectModelUtils.DefaultLinkUrl, IsCollection = false
                        });
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, null },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionFalseWithResourceSetContent", "http://odata.org/link") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidStateTransition", "NavigationLink", "NavigationLink") },
                        { WriterAction.End, null },
                        { WriterAction.Error, null },
                    },
                    SkipForTestConfiguration = tc => tc.IsRequest
                },

                // Link - collection
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed());
                        }
                        w.WriteStart(ObjectModelUtils.CreateDefaultEntry());
                        w.WriteStart(ObjectModelUtils.CreateDefaultCollectionLink());
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionTrueWithResourceContent", "http://odata.org/link") },
                        { WriterAction.StartFeed, null },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidStateTransition", "NavigationLink", "NavigationLink") },
                        { WriterAction.End, null },
                        { WriterAction.Error, null },
                    },
                    SkipForTestConfiguration = tc => tc.IsRequest
                },

                // Expanded link - there's no way to get to the expanded link state alone since the writer will always
                //   immediately transition to either entry or feed state instead.

                // Completed
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        if (feedWriter)
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultFeed()); w.WriteEnd();
                        }
                        else
                        {
                            w.WriteStart(ObjectModelUtils.CreateDefaultEntry()); w.WriteEnd();
                        }
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromCompleted", "Completed", "Entry") },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromCompleted", "Completed", "Feed") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromCompleted", "Completed", "NavigationLink") },
                        { WriterAction.End, ODataExpectedExceptions.ODataException("ODataWriterCore_WriteEndCalledInInvalidState", "Completed") },
                        { WriterAction.Error, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromCompleted", "Completed", "Error") },
                    }
                },

                // ODataExceptionThrown
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        TestExceptionUtils.RunCatching(() => w.WriteStart(ObjectModelUtils.CreateDefaultCollectionLink()));
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "Entry") },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "Feed") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "NavigationLink") },
                        { WriterAction.End, ODataExpectedExceptions.ODataException("ODataWriterCore_WriteEndCalledInInvalidState", "Error") },
                        { WriterAction.Error, null },
                    },
                    SkipForTestConfiguration = tc => tc.IsRequest,
                },

                // Error
                new WriterStatesTestDescriptor {
                    Setup = (mw, w, s) => {
                        mw.WriteError(new ODataError(), false);
                    },
                    ExpectedResults = new Dictionary <WriterAction, ExpectedException> {
                        { WriterAction.StartResource, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "Entry") },
                        { WriterAction.StartFeed, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "Feed") },
                        { WriterAction.StartLink, ODataExpectedExceptions.ODataException("ODataWriterCore_InvalidTransitionFromError", "Error", "NavigationLink") },
                        { WriterAction.End, ODataExpectedExceptions.ODataException("ODataWriterCore_WriteEndCalledInInvalidState", "Error") },
                        { WriterAction.Error, ODataExpectedExceptions.ODataException("ODataMessageWriter_WriteErrorAlreadyCalled") },
                    },
                    SkipForTestConfiguration = tc => tc.IsRequest,
                },
            };

            ExpectedException errorNotAllowedException = ODataExpectedExceptions.ODataException("ODataMessageWriter_ErrorPayloadInRequest");

            this.CombinatorialEngineProvider.RunCombinations(
                testCases,
                EnumExtensionMethods.GetValues <WriterAction>().Cast <WriterAction>(),
                this.WriterTestConfigurationProvider.AtomFormatConfigurations,
                (testCase, writerAction, testConfiguration) =>
            {
                testConfiguration = testConfiguration.Clone();
                testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri);

                if (testCase.SkipForTestConfiguration != null && testCase.SkipForTestConfiguration(testConfiguration))
                {
                    return;
                }

                ExpectedException expectedExceptionOnError;
                if (testCase.ExpectedResults.TryGetValue(WriterAction.Error, out expectedExceptionOnError))
                {
                    if (testConfiguration.IsRequest)
                    {
                        testCase = new WriterStatesTestDescriptor(testCase);
                        testCase.ExpectedResults[WriterAction.Error] = errorNotAllowedException;
                    }
                }

                using (TestStream stream = 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(stream, testConfiguration, this.Assert);
                    ODataWriter writer = messageWriter.CreateODataWriter(feedWriter);

                    TestExceptionUtils.ExpectedException(
                        this.Assert,
                        () =>
                    {
                        if (testCase.Setup != null)
                        {
                            testCase.Setup(messageWriter, writer, stream);
                        }
                        this.InvokeWriterAction(messageWriter, writer, writerAction);
                    },
                        testCase.ExpectedResults[writerAction],
                        this.ExceptionVerifier);
                }
            });
        }
Exemple #6
0
 public IActionResult GetTenderStatuses()
 {
     return(Ok(EnumExtensionMethods.GetValues <TenderStatus>()));
 }
Exemple #7
0
 public IActionResult GetPlacingWays()
 {
     return(Ok(EnumExtensionMethods.GetValues <PlacingWay>()));
 }