private void RunTestCase(ConvertToUriLiteralTestCase testCase, ODataVersion version = ODataVersion.V4, IEdmModel model = null) { // Negative Test if (testCase.ExpectedException != null) { TestExceptionUtils.ExpectedException( this.Assert, () => { ODataUriUtils.ConvertToUriLiteral(testCase.Parameter, version, model); }, testCase.ExpectedException, this.ExceptionVerifier ); } else // Positive Test { string actualValue = ODataUriUtils.ConvertToUriLiteral(testCase.Parameter, version, model); object expectedValue = testCase.ExpectedValues; if (expectedValue == null) { expectedValue = testCase.ExpectedValue; } if (!expectedValue.Equals(actualValue)) { throw new ODataTestException(string.Format( "Different JSON.{0}Expected:{0}{1}{0}Actual:{0}{2}{0}", Environment.NewLine, expectedValue, actualValue)); } } }
public void GetVersionUtilTest() { //positive tests this.Assert.AreEqual(ODataUtils.StringToODataVersion(DataServiceVersion4), ODataVersion.V4, "Failed to parse Data Service Version string"); this.Assert.AreEqual(ODataUtils.StringToODataVersion(DataServiceVersion4 + ";"), ODataVersion.V4, "Failed to parse Data Service Version string"); this.Assert.AreEqual(ODataUtils.StringToODataVersion(DataServiceVersion4 + ";anything"), ODataVersion.V4, "Failed to parse Data Service Version string"); this.Assert.AreEqual(ODataUtils.ODataVersionToString(ODataVersion.V4), DataServiceVersion4, "Failed to parse Data Service Version enum"); //negative tests string[] invalidVersionStrings = { "randomstring", "V1.0", "1.5", "randomstring;1.0", "5.0", "1" }; foreach (string s in invalidVersionStrings) { TestExceptionUtils.ExpectedException( this.Assert, () => { ODataUtils.StringToODataVersion(s); }, ODataExpectedExceptions.ODataException("ODataUtils_UnsupportedVersionHeader", s), this.ExceptionVerifier ); } }
public void ContentTypeHeaderParsingErrorTest() { var testCases = new ContentTypeTestCase[] { new ContentTypeTestCase { ContentType = null, ExpectedException = ODataExpectedExceptions.ODataContentTypeException("ODataMessageReader_NoneOrEmptyContentTypeHeader") }, new ContentTypeTestCase { ContentType = string.Empty, ExpectedException = ODataExpectedExceptions.ODataContentTypeException("ODataMessageReader_NoneOrEmptyContentTypeHeader") }, new ContentTypeTestCase { ContentType = ";foo=bar", ExpectedException = ODataExpectedExceptions.ODataContentTypeException("HttpUtils_MediaTypeRequiresSlash", ";foo=bar") }, new ContentTypeTestCase { ContentType = "application/*", ExpectedException = ODataExpectedExceptions.ODataContentTypeException("ODataMessageReader_WildcardInContentType", "application/*") }, new ContentTypeTestCase { ContentType = "*/*", ExpectedException = ODataExpectedExceptions.ODataContentTypeException("ODataMessageReader_WildcardInContentType", "*/*") }, new ContentTypeTestCase { ContentType = "application/json, application/xml", ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_NoOrMoreThanOneContentTypeSpecified", "application/json, application/xml") }, }; this.CombinatorialEngineProvider.RunCombinations( testCases, this.ReaderTestConfigurationProvider.AllFormatConfigurations.Where(tc => tc.Format != ODataFormat.Json), (testCase, testConfiguration) => { // create a message reader and call GetFormat; this should fail with the expected error message TestMessage testMessage = TestReaderUtils.CreateInputMessageFromStream(new TestStream(), testConfiguration); testMessage.SetHeader(Microsoft.OData.Core.ODataConstants.ContentTypeHeader, testCase.ContentType); testMessage.SetHeader(Microsoft.OData.Core.ODataConstants.ContentLengthHeader, testCase.ContentLength.ToString()); TestExceptionUtils.ExpectedException( this.Assert, () => { using (ODataMessageReaderTestWrapper messageReader = TestReaderUtils.CreateMessageReader(testMessage, null, testConfiguration)) { ODataFormat actualFormat = messageReader.DetectPayloadKind().Single().Format; } }, testCase.ExpectedException, this.ExceptionVerifier); }); }
/// <summary> /// Verifies that the result of the test (the message reader) is what the test expected. /// </summary> /// <param name="messageReader">The message reader which is the result of the test. This method should use it to read the results /// of the parsing and verify those.</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( ODataMessageReaderTestWrapper messageReader, ODataPayloadKind payloadKind, ReaderTestConfiguration testConfiguration) { // First compare the payload kind detection results. IEnumerable <ODataPayloadKindDetectionResult> actualDetectionResults = messageReader.DetectPayloadKind(); this.VerifyPayloadKindDetectionResult(actualDetectionResults); // Then try to read the message as the detected kind if requested if (this.ReadDetectedPayloads) { bool firstResult = true; foreach (PayloadKindDetectionResult result in this.ExpectedDetectionResults) { if (firstResult) { // For the first result use the existing message reader firstResult = false; } else { // For all subsequent results we need to reset the test stream and create a new message reader // over it. this.TestMessage.Reset(); messageReader = TestReaderUtils.CreateMessageReader(this.TestMessage, result.Model, testConfiguration); // Detect the payload kinds again and make sure we can also read the subsequent payload kinds // immediately after detection. actualDetectionResults = messageReader.DetectPayloadKind(); this.VerifyPayloadKindDetectionResult(actualDetectionResults); } TestExceptionUtils.ExpectedException( this.settings.Assert, () => { using (messageReader) { this.settings.MessageToObjectModelReader.ReadMessage( messageReader, result.PayloadKind, result.Model, new PayloadReaderTestDescriptor.ReaderMetadata(result.ExpectedType), /*expectedBatchPayload*/ null, testConfiguration); } }, result.ExpectedException, this.settings.ExceptionVerifier); } } }
private FilterClause BindFilter(IEdmModel model, string filter, string errorMessage) { FilterClause actualFilter = null; TestExceptionUtils.ExpectedException <ODataException>( this.Assert, () => { string query = "/TypesWithPrimitiveProperties?$filter=" + filter; ODataUri actual = QueryNodeUtils.BindQuery(query, model); // the filter node should be the top-level node in the query tree actualFilter = (FilterClause)actual.Filter; }, errorMessage, null); return(actualFilter); }
public void FeedInvalidContentTests() { ODataFeed defaultFeed = ObjectModelUtils.CreateDefaultFeed(); ODataItem[] invalidPayload1 = new ODataItem[] { defaultFeed, defaultFeed }; var testCases = new[] { new { Items = invalidPayload1, ExpectedError = "Cannot transition from state 'Feed' to state 'Feed'. The only valid action in state 'Feed' is to write an entry." } }; this.CombinatorialEngineProvider.RunCombinations( testCases, ODataFormatUtils.ODataFormats.Where(f => f != null), // Async test configuration is not supported for Phone and Silverlight #if !SILVERLIGHT && !WINDOWS_PHONE new bool[] { false, true }, #else new bool[] { true }, #endif (testCase, format, synchronous) => { using (var memoryStream = new TestStream()) { ODataMessageWriterSettings settings = new ODataMessageWriterSettings(); settings.Version = ODataVersion.V4; settings.SetServiceDocumentUri(ServiceDocumentUri); using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, new WriterTestConfiguration(format, settings, false, synchronous), this.Assert)) { ODataWriter writer = messageWriter.CreateODataWriter(isFeed: true); TestExceptionUtils.ExpectedException <ODataException>( this.Assert, () => TestWriterUtils.WritePayload(messageWriter, writer, true, testCase.Items), testCase.ExpectedError); } } }); }
public void CustomQueryOptionBinderTest() { var metadata = QueryTestMetadata.BuildTestMetadata(this.PrimitiveTypeResolver, this.UntypedDataServiceProviderFactory); var testCases = new[] { new QueryOptionTestCase { Query = "/Customers?$foo=12", ExpectedExceptionMessage = "The system query option '$foo' is not supported." }, new QueryOptionTestCase { Query = "/Customers?a=b", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode("a", "b") } }, new QueryOptionTestCase { Query = "/Customers?a=b&c=d", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode("a", "b"), new CustomQueryOptionNode("c", "d") } }, new QueryOptionTestCase { Query = "/Customers?a=b&a=c", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode("a", "b"), new CustomQueryOptionNode("a", "c") } }, new QueryOptionTestCase { Query = "/Customers?foo", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode(null, "foo") } }, new QueryOptionTestCase { Query = "/Customers?foo=", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode("foo", string.Empty) } }, new QueryOptionTestCase { Query = "/Customers?&", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode(null, string.Empty), new CustomQueryOptionNode(null, string.Empty) } }, new QueryOptionTestCase { Query = "/Customers?a=b&", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode("a", "b"), new CustomQueryOptionNode(null, string.Empty) } }, new QueryOptionTestCase { Query = "/Customers?&&", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode(null, string.Empty), new CustomQueryOptionNode(null, string.Empty), new CustomQueryOptionNode(null, string.Empty) } }, new QueryOptionTestCase { Query = "/Customers?a=b&&", ExpectedQueryOptions = new CustomQueryOptionNode[] { new CustomQueryOptionNode("a", "b"), new CustomQueryOptionNode(null, string.Empty), new CustomQueryOptionNode(null, string.Empty) } }, }; this.CombinatorialEngineProvider.RunCombinations( testCases, (testCase) => { TestExceptionUtils.ExpectedException <ODataException>( this.Assert, () => { SemanticTree actual = QueryNodeUtils.BindQuery(testCase.Query, metadata); QueryNodeUtils.VerifyQueryNodesAreEqual( testCase.ExpectedQueryOptions, actual.CustomQueryOptions, this.Assert); }, testCase.ExpectedExceptionMessage, null); }); }
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); } }); }
/// <summary> /// Verifies that the specified action fails with argument being null exception. /// </summary> /// <param name="action">The action to execute.</param> private void VerifyArgumentNullException(Action action) { // TODO: Support raw error message verification for non-product exceptions TestExceptionUtils.ExpectedException(this.Assert, action, new ExpectedException(typeof(ArgumentNullException)), this.ExceptionVerifier); }
public void DisposeAfterExceptionTest() { // create a default entry and then set both read and edit links to null to provoke an exception during writing ODataResource entry = ObjectModelUtils.CreateDefaultEntry(); this.Assert.IsNull(entry.EditLink, "entry.EditLink == null"); this.CombinatorialEngineProvider.RunCombinations( new ODataItem[] { entry }, new bool[] { true, false }, // writeError new bool[] { true, false }, // flush this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(c => c.IsRequest == false), (payload, writeError, flush, testConfiguration) => { testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); // try writing to a memory stream using (var memoryStream = new TestStream()) using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert)) { ODataWriter writer = messageWriter.CreateODataWriter(isFeed: false); ODataWriterCoreInspector inspector = new ODataWriterCoreInspector(writer); try { // write the invalid entry and expect an exception TestExceptionUtils.ExpectedException( this.Assert, () => TestWriterUtils.WritePayload(messageWriter, writer, false, entry), ODataExpectedExceptions.ODataException("WriterValidationUtils_EntriesMustHaveNonEmptyId"), this.ExceptionVerifier); this.Assert.IsTrue(inspector.IsInErrorState, "Writer is not in expected 'error' state."); if (writeError) { // now write an error which is the only valid thing to do ODataAnnotatedError error = new ODataAnnotatedError { Error = new ODataError() { Message = "DisposeAfterExceptionTest error message." } }; Exception ex = TestExceptionUtils.RunCatching(() => TestWriterUtils.WritePayload(messageWriter, writer, false, error)); this.Assert.IsNull(ex, "Unexpected error '" + (ex == null ? "<none>" : ex.Message) + "' while writing an error."); this.Assert.IsTrue(inspector.IsInErrorState, "Writer is not in expected 'error' state."); } if (flush) { writer.Flush(); } } catch (ODataException oe) { if (writeError && !flush) { this.Assert.AreEqual("A writer or stream has been disposed with data still in the buffer. You must call Flush or FlushAsync before calling Dispose when some data has already been written.", oe.Message, "Did not find expected error message"); this.Assert.IsTrue(inspector.IsInErrorState, "Writer is not in expected 'error' state."); } else { this.Assert.Fail("Caught an unexpected ODataException: " + oe.Message + "."); } } } }); }
/// <summary> /// Verifies that the action fails due to the fact that the writer was already disposed. /// </summary> /// <param name="action">The action to execute.</param> private void VerifyWriterAlreadyDisposed(Action action) { TestExceptionUtils.ExpectedException(this.Assert, action, new ExpectedException(typeof(ObjectDisposedException)), this.ExceptionVerifier); }
public void ExpandedLinkWithMultiplicityTests() { ODataNavigationLink expandedEntryLink = ObjectModelUtils.CreateDefaultCollectionLink(); expandedEntryLink.IsCollection = false; ODataNavigationLink expandedFeedLink = ObjectModelUtils.CreateDefaultCollectionLink(); expandedFeedLink.IsCollection = true; ODataEntry defaultEntry = ObjectModelUtils.CreateDefaultEntry(); ODataFeed defaultFeed = ObjectModelUtils.CreateDefaultFeed(); ODataEntityReferenceLink defaultEntityReferenceLink = ObjectModelUtils.CreateDefaultEntityReferenceLink(); ODataEntry officeEntry = ObjectModelUtils.CreateDefaultEntry("TestModel.OfficeType"); ODataEntry officeWithNumberEntry = ObjectModelUtils.CreateDefaultEntry("TestModel.OfficeWithNumberType"); ODataEntry cityEntry = ObjectModelUtils.CreateDefaultEntry("TestModel.CityType"); // CityHall is a nav prop with multiplicity '*' of type 'TestModel.OfficeType' ODataNavigationLink cityHallLinkIsCollectionNull = ObjectModelUtils.CreateDefaultCollectionLink("CityHall", /*isCollection*/ null); ODataNavigationLink cityHallLinkIsCollectionTrue = ObjectModelUtils.CreateDefaultCollectionLink("CityHall", /*isCollection*/ true); ODataNavigationLink cityHallLinkIsCollectionFalse = ObjectModelUtils.CreateDefaultCollectionLink("CityHall", /*isCollection*/ false); // PoliceStation is a nav prop with multiplicity '1' of type 'TestModel.OfficeType' ODataNavigationLink policeStationLinkIsCollectionNull = ObjectModelUtils.CreateDefaultCollectionLink("PoliceStation", /*isCollection*/ null); ODataNavigationLink policeStationLinkIsCollectionTrue = ObjectModelUtils.CreateDefaultCollectionLink("PoliceStation", /*isCollection*/ true); ODataNavigationLink policeStationLinkIsCollectionFalse = ObjectModelUtils.CreateDefaultCollectionLink("PoliceStation", /*isCollection*/ false); ExpectedException expandedEntryLinkWithFeedContentError = ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionFalseWithFeedContent", "http://odata.org/link"); ExpectedException expandedFeedLinkWithEntryContentError = ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionTrueWithEntryContent", "http://odata.org/link"); ExpectedException expandedFeedLinkWithEntryMetadataError = ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionTrueWithEntryMetadata", "http://odata.org/link"); ExpectedException expandedEntryLinkWithFeedMetadataErrorResponse = ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionFalseWithFeedMetadata", "http://odata.org/link"); ExpectedException expandedFeedLinkPayloadWithEntryMetadataErrorRequest = ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkWithFeedPayloadAndEntryMetadata", "http://odata.org/link"); ExpectedException expandedFeedLinkPayloadWithEntryMetadataErrorResponse = ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionTrueWithEntryMetadata", "http://odata.org/link"); ExpectedException expandedEntryLinkPayloadWithFeedMetadataErrorResponse = ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkIsCollectionFalseWithFeedMetadata", "http://odata.org/link"); ExpectedException expandedEntryLinkPayloadWithFeedMetadataError = ODataExpectedExceptions.ODataException("WriterValidationUtils_ExpandedLinkWithEntryPayloadAndFeedMetadata", "http://odata.org/link"); ExpectedException multipleItemsInExpandedLinkError = ODataExpectedExceptions.ODataException("ODataWriterCore_MultipleItemsInNavigationLinkContent", "http://odata.org/link"); ExpectedException entityReferenceLinkInResponseError = ODataExpectedExceptions.ODataException("ODataWriterCore_EntityReferenceLinkInResponse"); IEdmModel model = Microsoft.Test.OData.Utils.Metadata.TestModels.BuildTestModel(); var testCases = new ExpandedLinkMultiplicityTestCase[] { #region IsCollection flag does not match payload new ExpandedLinkMultiplicityTestCase { // Expanded link with IsCollection is 'false' and feed payload Items = new ODataItem[] { defaultEntry, expandedEntryLink, defaultFeed }, ExpectedError = tc => expandedEntryLinkWithFeedContentError, }, new ExpandedLinkMultiplicityTestCase { // Expanded link with IsCollection is 'true' and entry payload Items = new ODataItem[] { defaultEntry, expandedFeedLink, defaultEntry }, ExpectedError = tc => expandedFeedLinkWithEntryContentError, }, #endregion IsCollection flag does not match payload #region IsCollection == null; check compatibility of entity types of navigation property and entity in expanded link new ExpandedLinkMultiplicityTestCase { // Expanded link of singleton type without IsCollection value and an entry of a non-matching entity type; Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionNull, cityEntry }, ExpectedError = tc => tc.Format == ODataFormat.Atom || !tc.IsRequest ? ODataExpectedExceptions.ODataException("WriterValidationUtils_EntryTypeInExpandedLinkNotCompatibleWithNavigationPropertyType", "TestModel.CityType", "TestModel.OfficeType") : ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyIsCollection", "PoliceStation"), Model = model, }, new ExpandedLinkMultiplicityTestCase { // Expanded link of singleton type without IsCollection value and an entry of a matching entity type; no error expected. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionNull, officeEntry }, ExpectedError = tc => tc.Format == ODataFormat.Json && !tc.IsRequest ? null : ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyIsCollection", "PoliceStation"), Model = model, }, new ExpandedLinkMultiplicityTestCase { // Expanded link of singleton type without IsCollection and an entry of a derived entity type; no error expected. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionNull, officeWithNumberEntry }, ExpectedError = tc => tc.Format == ODataFormat.Json && !tc.IsRequest ? null : ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyIsCollection", "PoliceStation"), Model = model, }, new ExpandedLinkMultiplicityTestCase { // Expanded link of collection type without IsCollection value and an entry of a non-matching entity type; Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionNull, defaultFeed, cityEntry }, ExpectedError = tc => tc.Format == ODataFormat.Json && !tc.IsRequest ? ODataExpectedExceptions.ODataException("WriterValidationUtils_EntryTypeInExpandedLinkNotCompatibleWithNavigationPropertyType", "TestModel.CityType", "TestModel.OfficeType") : ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyIsCollection", "CityHall"), Model = model, }, new ExpandedLinkMultiplicityTestCase { // Expanded link of collection type without IsCollection value and an entry of a matching entity type; no error expected. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionNull, defaultFeed, officeEntry }, ExpectedError = tc => tc.Format == ODataFormat.Json && !tc.IsRequest ? null : ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyIsCollection", "CityHall"), Model = model, }, new ExpandedLinkMultiplicityTestCase { // Expanded link of collection type without IsCollection and an entry of a derived entity type; no error expected. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionNull, defaultFeed, officeWithNumberEntry }, ExpectedError = tc => tc.Format == ODataFormat.Json && !tc.IsRequest ? null : ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyIsCollection", "CityHall"), Model = model, }, #endregion IsCollection == null; check compatibility of entity types of navigation property and entity in expanded link #region Expanded link with entry content new ExpandedLinkMultiplicityTestCase { // Entry content, IsCollection == false, singleton nav prop; should not fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionFalse, officeEntry }, }, new ExpandedLinkMultiplicityTestCase { // Entry content, IsCollection == true, singleton nav prop; should fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionTrue, officeEntry }, ExpectedError = tc => expandedFeedLinkWithEntryContentError, }, new ExpandedLinkMultiplicityTestCase { // Entry content, IsCollection == false, collection nav prop; should fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionFalse, officeEntry }, ExpectedError = tc => tc.IsRequest ? expandedEntryLinkPayloadWithFeedMetadataError : expandedEntryLinkPayloadWithFeedMetadataErrorResponse, Model = model }, new ExpandedLinkMultiplicityTestCase { // Entry content, IsCollection == true, collection nav prop; should fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionTrue, officeEntry }, ExpectedError = tc => expandedFeedLinkWithEntryContentError, Model = model }, new ExpandedLinkMultiplicityTestCase { // Entry content, IsCollection == null, singleton nav prop; should not fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionNull, officeEntry }, ExpectedError = tc => tc.IsRequest || tc.Format == ODataFormat.Atom ? ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyIsCollection", "PoliceStation") : null, Model = model, }, new ExpandedLinkMultiplicityTestCase { // Entry content, IsCollection == null, collection nav prop; should fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionNull, officeEntry }, ExpectedError = tc => expandedEntryLinkPayloadWithFeedMetadataError, Model = model, }, #endregion Expanded collection link with entry content #region Expanded link with feed content new ExpandedLinkMultiplicityTestCase { // Feed content, IsCollection == false, singleton nav prop; should fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionFalse, defaultFeed, officeEntry }, ExpectedError = tc => expandedEntryLinkWithFeedContentError, }, new ExpandedLinkMultiplicityTestCase { // Feed content, IsCollection == true, singleton nav prop; should fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionTrue, defaultFeed, officeEntry }, ExpectedError = tc => tc.IsRequest ? expandedFeedLinkPayloadWithEntryMetadataErrorRequest : expandedFeedLinkPayloadWithEntryMetadataErrorResponse, Model = model }, new ExpandedLinkMultiplicityTestCase { // Feed content, IsCollection == false, collection nav prop; should fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionFalse, defaultFeed, officeEntry }, ExpectedError = tc => tc.IsRequest ? expandedEntryLinkWithFeedContentError : expandedEntryLinkWithFeedMetadataErrorResponse, Model = model }, new ExpandedLinkMultiplicityTestCase { // Feed content, IsCollection == true, collection nav prop; should not fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionTrue, defaultFeed, officeEntry }, Model = model }, new ExpandedLinkMultiplicityTestCase { // Feed content, IsCollection == null, singleton nav prop; should fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionNull, defaultFeed, officeEntry }, ExpectedError = tc => expandedFeedLinkPayloadWithEntryMetadataErrorRequest, Model = model, }, new ExpandedLinkMultiplicityTestCase { // Feed content, IsCollection == null, collection nav prop; should not fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionNull, defaultFeed, officeEntry }, ExpectedError = tc => tc.IsRequest || tc.Format == ODataFormat.Atom ? ODataExpectedExceptions.ODataException("WriterValidationUtils_NavigationLinkMustSpecifyIsCollection", "CityHall") : null, Model = model, }, #endregion Expanded collection link with entry content #region Expanded link with entity reference link content new ExpandedLinkMultiplicityTestCase { // Single ERL (entity reference link) content, IsCollection == false, singleton nav prop; should not fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionFalse, defaultEntityReferenceLink }, ExpectedError = tc => tc.IsRequest ? null : entityReferenceLinkInResponseError }, new ExpandedLinkMultiplicityTestCase { // Multiple ERL (entity reference link) content, IsCollection == false, singleton nav prop; should not fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionFalse, defaultEntityReferenceLink, defaultEntityReferenceLink }, ExpectedError = tc => tc.IsRequest ? multipleItemsInExpandedLinkError : entityReferenceLinkInResponseError, }, new ExpandedLinkMultiplicityTestCase { // Single ERL content, IsCollection == true, singleton nav prop; should fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionTrue, defaultEntityReferenceLink }, ExpectedError = tc => expandedFeedLinkWithEntryMetadataError, Model = model, }, new ExpandedLinkMultiplicityTestCase { // Multiple ERL content, IsCollection == true, singleton nav prop; should fail. Items = new ODataItem[] { cityEntry, policeStationLinkIsCollectionTrue, defaultEntityReferenceLink, defaultEntityReferenceLink }, ExpectedError = tc => expandedFeedLinkWithEntryMetadataError, Model = model, }, new ExpandedLinkMultiplicityTestCase { // Single ERL content, IsCollection == false, collection nav prop; should not fail (metadata mismatch explicitly allowed). Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionFalse, defaultEntityReferenceLink }, ExpectedError = tc => tc.IsRequest ? null : expandedEntryLinkWithFeedMetadataErrorResponse, Model = model, }, new ExpandedLinkMultiplicityTestCase { // Multiple ERL content, IsCollection == false, collection nav prop; should fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionFalse, defaultEntityReferenceLink, defaultEntityReferenceLink }, ExpectedError = tc => tc.IsRequest ? multipleItemsInExpandedLinkError : expandedEntryLinkWithFeedMetadataErrorResponse, Model = model, }, new ExpandedLinkMultiplicityTestCase { // Single ERL content, IsCollection == true, collection nav prop; should not fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionTrue, defaultEntityReferenceLink }, ExpectedError = tc => tc.IsRequest ? null : entityReferenceLinkInResponseError, Model = model, }, new ExpandedLinkMultiplicityTestCase { // Multiple ERL content, IsCollection == true, collection nav prop; should not fail. Items = new ODataItem[] { cityEntry, cityHallLinkIsCollectionTrue, defaultEntityReferenceLink, defaultEntityReferenceLink }, ExpectedError = tc => tc.IsRequest ? null : entityReferenceLinkInResponseError, Model = model, }, //// NOTE: Not testing the cases where IsCollection == null here since ERL payloads are only allowed in //// requests where IsCollection is required (in ATOM and JSON) #endregion Expanded link with entity reference link content }; // TODO: Fix places where we've lost JsonVerbose coverage to add JsonLight this.CombinatorialEngineProvider.RunCombinations( testCases, this.WriterTestConfigurationProvider.ExplicitFormatConfigurations.Where(tc => tc.Format == ODataFormat.Atom), (testCase, testConfiguration) => { testConfiguration = testConfiguration.Clone(); testConfiguration.MessageWriterSettings.SetServiceDocumentUri(ServiceDocumentUri); using (var memoryStream = new TestStream()) using (var messageWriter = TestWriterUtils.CreateMessageWriter(memoryStream, testConfiguration, this.Assert, null, testCase.Model)) { ODataWriter writer = messageWriter.CreateODataWriter(isFeed: false); TestExceptionUtils.ExpectedException( this.Assert, () => TestWriterUtils.WritePayload(messageWriter, writer, true, testCase.Items), testCase.ExpectedError == null ? null : testCase.ExpectedError(testConfiguration), this.ExceptionVerifier); } }); }
public void BatchContentTypeHeaderParsingTest() { IEnumerable <ContentTypeTestCase> testCases = new ContentTypeTestCase[] { // correct batch content type new ContentTypeTestCase { ContentType = "multipart/mixed;boundary=--aa_bb_cc--", ExpectedFormat = ODataFormat.Batch, }, // missing batch boundary new ContentTypeTestCase { ContentType = "multipart/mixed", ExpectedFormat = ODataFormat.Batch, ExpectedException = ODataExpectedExceptions.ODataException("MediaTypeUtils_BoundaryMustBeSpecifiedForBatchPayloads", "multipart/mixed", "boundary") }, // multiple batch boundary parameters new ContentTypeTestCase { ContentType = "multipart/mixed;boundary=boundary1;boundary=boundary2", ExpectedFormat = ODataFormat.Batch, ExpectedException = ODataExpectedExceptions.ODataException("MediaTypeUtils_BoundaryMustBeSpecifiedForBatchPayloads", "multipart/mixed;boundary=boundary1;boundary=boundary2", "boundary") }, // invalid batch content types new ContentTypeTestCase { ContentType = "multipart/bar", ExpectedFormat = ODataFormat.Batch, ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Batch), "multipart/bar") }, new ContentTypeTestCase { ContentType = "foo/mixed", ExpectedFormat = ODataFormat.Batch, ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Batch), "foo/mixed") }, new ContentTypeTestCase { ContentType = "abc/pqr", ExpectedFormat = ODataFormat.Batch, ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Batch), "abc/pqr") }, new ContentTypeTestCase { ContentType = ApplicationJson, ExpectedFormat = ODataFormat.Batch, ExpectedException = ODataExpectedExceptions.ODataContentTypeException("MediaTypeUtils_CannotDetermineFormatFromContentType", TestMediaTypeUtils.GetSupportedMediaTypes(ODataPayloadKind.Batch), ApplicationJson) } }; this.CombinatorialEngineProvider.RunCombinations( testCases, this.ReaderTestConfigurationProvider.DefaultFormatConfigurations, (testCase, testConfiguration) => { // create a message reader and call GetFormat; this should fail with the expected error message TestMessage testMessage = TestReaderUtils.CreateInputMessageFromStream(new TestStream(), testConfiguration); testMessage.SetHeader(Microsoft.OData.Core.ODataConstants.ContentTypeHeader, testCase.ContentType); TestExceptionUtils.ExpectedException( this.Assert, () => { using (ODataMessageReaderTestWrapper messageReader = TestReaderUtils.CreateMessageReader(testMessage, null, testConfiguration)) { messageReader.CreateODataBatchReader(); ODataFormat actualFormat = ODataUtils.GetReadFormat(messageReader.MessageReader); this.Assert.AreEqual(testCase.ExpectedFormat, actualFormat, "Formats don't match."); } }, testCase.ExpectedException, this.ExceptionVerifier); }); }
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); } }); }
public void OrderByBinderTest() { IEdmModel model = QueryTestMetadata.BuildTestMetadata(this.PrimitiveTypeResolver, this.UntypedDataServiceProviderFactory); // TODO: add an error test where the input collection to the order-by is a singleton ResourceRangeVariable entityRangeVariable = new ResourceRangeVariable("dummy", model.ResolveTypeReference("TestNS.Customer", false).AsEntity(), model.FindEntityContainer("BinderTestMetadata").FindEntitySet("Customers")); OrderByTestCase[] testCases = new OrderByTestCase[] { new OrderByTestCase() { OrderBy = new string[] { "true" }, ExpectedOrderByExpressions = new SingleValueNode[] { new ConstantNode(true) } }, new OrderByTestCase() { OrderBy = new string[] { "Name" }, ExpectedOrderByExpressions = new SingleValueNode[] { new SingleValuePropertyAccessNode( new ResourceRangeVariableReferenceNode(entityRangeVariable.Name, entityRangeVariable), model.ResolveProperty("TestNS.Customer.Name") ) } }, new OrderByTestCase() { OrderBy = new string[] { "3" }, ExpectedOrderByExpressions = new SingleValueNode[] { new ConstantNode(3) } }, new OrderByTestCase() { OrderBy = new string[] { "null" }, ExpectedOrderByExpressions = new SingleValueNode[] { new ConstantNode(null) } }, new OrderByTestCase() { OrderBy = new string[] { "Address" }, ExpectedExceptionMessage = "The $orderby expression must evaluate to a single value of primitive type." }, new OrderByTestCase() { OrderBy = new string[] { "Emails" }, ExpectedExceptionMessage = "The $orderby expression must evaluate to a single value of primitive type." }, new OrderByTestCase() { OrderBy = new string[] { "NonExistant" }, ExpectedExceptionMessage = "Could not find a property named 'NonExistant' on type 'TestNS.Customer'." }, new OrderByTestCase() { OrderBy = new string[] { "Name", "ID" }, ExpectedOrderByExpressions = new SingleValueNode[] { new SingleValuePropertyAccessNode( new ResourceRangeVariableReferenceNode(entityRangeVariable.Name, entityRangeVariable), model.ResolveProperty("TestNS.Customer.Name") ), new SingleValuePropertyAccessNode( new ResourceRangeVariableReferenceNode(entityRangeVariable.Name, entityRangeVariable), model.ResolveProperty("TestNS.Customer.ID") ), } }, new OrderByTestCase() { OrderBy = new string[] { "Name", "Address" }, ExpectedExceptionMessage = "The $orderby expression must evaluate to a single value of primitive type." }, new OrderByTestCase() { OrderBy = new string[] { "Name", "Emails" }, ExpectedExceptionMessage = "The $orderby expression must evaluate to a single value of primitive type." }, new OrderByTestCase() { OrderBy = new string[] { "Name", "NonExistant" }, ExpectedExceptionMessage = "Could not find a property named 'NonExistant' on type 'TestNS.Customer'." }, }; this.CombinatorialEngineProvider.RunCombinations( testCases, new OrderByDirection?[] { null, OrderByDirection.Ascending, OrderByDirection.Descending }, (testCase, direction) => { string orderByDirection = direction == null ? string.Empty : direction == OrderByDirection.Ascending ? " asc" : " desc"; this.Assert.IsTrue(testCase.OrderBy.Length > 0, "Need at least one order-by expression"); StringBuilder queryBuilder = new StringBuilder("/Customers?$orderby="); for (int i = 0; i < testCase.OrderBy.Length; ++i) { if (i > 0) { queryBuilder.Append(", "); } queryBuilder.Append(testCase.OrderBy[i]); queryBuilder.Append(orderByDirection); } TestExceptionUtils.ExpectedException <ODataException>( this.Assert, () => { ODataUri actual = QueryNodeUtils.BindQuery(queryBuilder.ToString(), model); // construct the expected order-by node OrderByClause orderByNode = null; for (int i = testCase.ExpectedOrderByExpressions.Length - 1; i >= 0; --i) { orderByNode = new OrderByClause( orderByNode, testCase.ExpectedOrderByExpressions[i], direction ?? OrderByDirection.Ascending, new ResourceRangeVariable(ExpressionConstants.It, model.ResolveTypeReference("TestNS.Customer", false).AsEntity(), model.FindEntityContainer("BinderTestMetadata").FindEntitySet("Customers")) ); } QueryNodeUtils.VerifyOrderByClauseAreEqual( orderByNode, actual.OrderBy, this.Assert); }, testCase.ExpectedExceptionMessage, null); }); }
private static void RunHeaderTest( Func <IEnumerable <KeyValuePair <string, string> > > getHeadersFunc, bool writing, Func <string, string> getHeaderFunc, Action <string, string> setHeaderAction, AssertionHandler assert, IExceptionVerifier exceptionVerifier) { assert.IsNotNull(getHeadersFunc(), "Non-null headers expected."); assert.AreEqual(0, getHeadersFunc().Count(), "Empty header collection expected."); assert.IsNull(getHeaderFunc("a"), "Unexpectedly found header."); ExpectedException expectedException = writing ? null : ODataExpectedExceptions.ODataException("ODataMessage_MustNotModifyMessage"); TestExceptionUtils.ExpectedException( assert, () => { setHeaderAction("a", "b"); assert.AreEqual(1, getHeadersFunc().Count(), "One header expected."); assert.AreEqual("b", getHeaderFunc("a"), "Header not found or invalid header value."); List <KeyValuePair <string, string> > expectedHeaders = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("a", "b") }; VerificationUtils.VerifyEnumerationsAreEqual( expectedHeaders, getHeadersFunc(), (first, second, assert2) => assert2.AreEqual(first, second, "Items differ."), (item) => item.Key + " = " + item.Value, assert); setHeaderAction("a", "c"); assert.AreEqual(1, getHeadersFunc().Count(), "One header expected."); assert.AreEqual("c", getHeaderFunc("a"), "Header not found or invalid header value."); expectedHeaders[0] = new KeyValuePair <string, string>("a", "c"); VerificationUtils.VerifyEnumerationsAreEqual( expectedHeaders, getHeadersFunc(), (first, second, assert2) => assert2.AreEqual(first, second, "Items differ."), (item) => item.Key + " = " + item.Value, assert); setHeaderAction("d", "e"); assert.AreEqual(2, getHeadersFunc().Count(), "Two headers expected."); assert.AreEqual("c", getHeaderFunc("a"), "Header not found or invalid header value."); assert.AreEqual("e", getHeaderFunc("d"), "Header not found or invalid header value."); expectedHeaders.Add(new KeyValuePair <string, string>("d", "e")); VerificationUtils.VerifyEnumerationsAreEqual( expectedHeaders, getHeadersFunc(), (first, second, assert2) => assert2.AreEqual(first, second, "Items differ."), (item) => item.Key + " = " + item.Value, assert); setHeaderAction("d", null); setHeaderAction("a", null); assert.AreEqual(0, getHeadersFunc().Count(), "Empty header collection expected."); assert.IsNull(getHeaderFunc("a"), "Unexpectedly found header."); }, expectedException, exceptionVerifier); }
public void SkipAndTopBinderTest() { IEdmModel model = QueryTestMetadata.BuildTestMetadata(this.PrimitiveTypeResolver, this.UntypedDataServiceProviderFactory); var testCases = new[] { new SkipTopTestCase { Query = "/Customers?$skip=2", ExpectedSkipClause = 2 }, new SkipTopTestCase { Query = "/Customers?$top=2", ExpectedTopClause = 2 }, new SkipTopTestCase { Query = "/Customers?$skip=3&$top=2", ExpectedTopClause = 2, ExpectedSkipClause = 3 }, new SkipTopTestCase { Query = "/Customers?$top=2&$skip=3", ExpectedTopClause = 2, ExpectedSkipClause = 3 }, // TODO: enable those? /* * new SkipTopTestCase * { * Query = "/Customers(0)?$top=100", * ExpectedExceptionMessage = "The $top query option cannot be applied to the query path. Top can only be applied to a collection of entities." * }, * new SkipTopTestCase * { * Query = "/Customers(0)?$skip=100", * ExpectedExceptionMessage = "The $skip query option cannot be applied to the query path. Skip can only be applied to a collection of entities." * }, * new SkipTopTestCase * { * Query = "/Customers(0)?$skip=100&top=100", * ExpectedExceptionMessage = "The $skip query option cannot be applied to the query path. Skip can only be applied to a collection of entities." * }, * new SkipTopTestCase * { * Query = "/Customers(0)?top=100&$skip=100", * ExpectedExceptionMessage = "The $skip query option cannot be applied to the query path. Skip can only be applied to a collection of entities." * }, */ }; this.CombinatorialEngineProvider.RunCombinations( testCases, (testCase) => { TestExceptionUtils.ExpectedException <ODataException>( this.Assert, () => { ODataUri actual = QueryNodeUtils.BindQuery(testCase.Query, model); if (testCase.ExpectedSkipClause != null) { Assert.AreEqual(testCase.ExpectedSkipClause, actual.Skip, "Skip amounts are not equal!"); } if (testCase.ExpectedTopClause != null) { Assert.AreEqual(testCase.ExpectedTopClause, actual.Top, "Top amounts are not equal!"); } }, testCase.ExpectedExceptionMessage, null); }); }