public void ConvertResponse_Creates_Correct_HttpResponseBase() { // Arrange MemoryStream memoryStream = new MemoryStream(); Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream); HttpResponseBase responseBase = contextMock.Object.Response; HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; response.Content = new ObjectContent <string>("hello", new JsonMediaTypeFormatter()); // Act Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response, request); task.Wait(); // Assert preparation -- deserialize the response memoryStream.Seek(0L, SeekOrigin.Begin); string responseString = null; using (var streamReader = new StreamReader(memoryStream)) { responseString = streamReader.ReadToEnd(); } // Assert Assert.Equal <int>((int)HttpStatusCode.OK, responseBase.StatusCode); Assert.True(responseBase.Headers["Content-Type"].StartsWith(JsonMediaTypeFormatter.DefaultMediaType.MediaType)); Assert.Equal("\"hello\"", responseString); }
public Task ConvertResponse_DisposesRequestAndResponseWithContent() { // Arrange Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; contextMock.SetupGet((hcb) => hcb.Response.OutputStream).Returns(Stream.Null); HttpRequestMessage request = new HttpRequestMessage() { Content = new StringContent("request") }; HttpResponseMessage response = new HttpResponseMessage() { Content = new StringContent("response") }; // Act return(HttpControllerHandler.ConvertResponse(contextMock.Object, response, request).ContinueWith( _ => { // Assert Assert.ThrowsObjectDisposed(() => request.Method = HttpMethod.Get, typeof(HttpRequestMessage).FullName); Assert.ThrowsObjectDisposed(() => response.StatusCode = HttpStatusCode.OK, typeof(HttpResponseMessage).FullName); })); }
public void SuppressFormsAuthenticationRedirect_RequireSuppressRedirect() { // Arrange Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; IDictionary contextItems = new Hashtable(); contextMock.SetupGet(hcb => hcb.Response.StatusCode).Returns(401); contextMock.SetupGet(hcb => hcb.Items).Returns(contextItems); PropertyInfo suppressRedirect = typeof(HttpResponseBase).GetProperty(SuppressFormsAuthRedirectModule.SuppressFormsAuthenticationRedirectPropertyName, BindingFlags.Instance | BindingFlags.Public); // Act HttpControllerHandler.EnsureSuppressFormsAuthenticationRedirect(contextMock.Object); // Assert if (suppressRedirect == null) { // .NET 4.0 Assert.True(contextItems.Contains(SuppressFormsAuthRedirectModule.DisableAuthenticationRedirectKey)); Assert.True((bool)contextItems[SuppressFormsAuthRedirectModule.DisableAuthenticationRedirectKey]); } else { // .NET 4.5 Assert.True((bool)suppressRedirect.GetValue(contextMock.Object, null)); } }
public void ConvertResponse_Returns_Error_Response_When_Formatter_Write_Throws_Immediately() { // Arrange Mock <JsonMediaTypeFormatter> formatterMock = new Mock <JsonMediaTypeFormatter>() { CallBase = true }; formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <object>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <TransportContext>())).Throws(new NotSupportedException("Expected error")); MemoryStream memoryStream = new MemoryStream(); Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream); HttpResponseBase responseBase = contextMock.Object.Response; HttpRequestMessage request = new HttpRequestMessage(); request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => true)); HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; response.Content = new ObjectContent <string>("hello", formatterMock.Object); // Act Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response, request); task.Wait(); // Assert preparation -- deserialize the HttpError response HttpError httpError = null; memoryStream.Seek(0L, SeekOrigin.Begin); using (StreamContent content = new StreamContent(memoryStream)) { content.Headers.ContentType = JsonMediaTypeFormatter.DefaultMediaType; httpError = content.ReadAsAsync <HttpError>().Result; } // Assert Assert.Equal <int>((int)HttpStatusCode.InternalServerError, responseBase.StatusCode); Assert.True(responseBase.Headers["Content-Type"].StartsWith(JsonMediaTypeFormatter.DefaultMediaType.MediaType)); Assert.Equal("An error has occurred.", httpError["Message"]); Assert.Equal("The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.", httpError["ExceptionMessage"]); Assert.Equal(typeof(InvalidOperationException).FullName, httpError["ExceptionType"]); Assert.True(httpError.ContainsKey("StackTrace")); HttpError innerError = (httpError["InnerException"] as JObject).ToObject <HttpError>(); Assert.NotNull(innerError); Assert.Equal(typeof(NotSupportedException).FullName, innerError["ExceptionType"].ToString()); Assert.Equal("Expected error", innerError["ExceptionMessage"]); Assert.Contains("System.Net.Http.HttpContent.CopyToAsync", innerError["StackTrace"].ToString()); }
public void ConvertRequest_Creates_HttpRequestMessage_For_All_HttpMethods(HttpMethod httpMethod) { // Arrange HttpContextBase contextBase = CreateStubContext(httpMethod.Method, new MemoryStream()); // Act HttpRequestMessage request = HttpControllerHandler.ConvertRequest(contextBase); // Assert Assert.Equal(httpMethod, request.Method); }
public void ConvertRequest_Creates_HttpRequestMessage_For_All_HttpMethods(HttpMethod httpMethod) { // Arrange Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForRequest(httpMethod.Method, new MemoryStream()); // Act HttpRequestMessage request = HttpControllerHandler.ConvertRequest(contextMock.Object); // Assert Assert.Equal(httpMethod, request.Method); }
public void ConvertRequest_Creates_Request_With_Content_For_Content_Methods(HttpMethod httpMethod) { // Arrange Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForRequest(httpMethod.Method, new MemoryStream()); // Act HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(contextMock.Object); // Assert Assert.NotNull(actualRequest.Content); }
public void Index() { GlobalConfiguration.Configuration.Routes.MapHttpRoute("wheather", "wheather/{areaCode}/{days}"); HttpRequest request = new HttpRequest("wheather.aspx", "http://www.artech.com/wheather/010/2", null); HttpResponse response = new HttpResponse(new StringWriter()); HttpContext context = new HttpContext(request, response); RouteData routeData = RouteTable.Routes.GetRouteData(new HttpContextWrapper(context)); HttpControllerHandler httpHandler = new HttpControllerHandler(routeData, new HttpRouteDataTraceHandler()); httpHandler.ProcessRequestAsync(context).Wait(); }
public void ConvertResponse_Returns_User_Response_When_Formatter_Write_Throws_HttpResponseException_With_Content() { // Arrange HttpResponseMessage errorResponse = new HttpResponseMessage(HttpStatusCode.MethodNotAllowed); errorResponse.Headers.Add("myHeader", "myValue"); errorResponse.Content = new StringContent("user message", Encoding.UTF8, "application/fake"); Mock <JsonMediaTypeFormatter> formatterMock = new Mock <JsonMediaTypeFormatter>() { CallBase = true }; formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <object>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <TransportContext>())).Throws(new HttpResponseException(errorResponse)); MemoryStream memoryStream = new MemoryStream(); Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream); HttpResponseBase responseBase = contextMock.Object.Response; HttpRequestMessage request = new HttpRequestMessage(); request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => true)); HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; response.Content = new ObjectContent <string>("hello", formatterMock.Object); // Act Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response, request); task.Wait(); // Assert preparation -- deserialize the response memoryStream.Seek(0L, SeekOrigin.Begin); string responseContent = null; using (var streamReader = new StreamReader(memoryStream)) { responseContent = streamReader.ReadToEnd(); } // Assert Assert.Equal <int>((int)errorResponse.StatusCode, responseBase.StatusCode); Assert.True(responseBase.Headers["Content-Type"].StartsWith("application/fake")); Assert.Equal("user message", responseContent); Assert.Equal("myValue", responseBase.Headers["myHeader"]); }
public void ProcessRequestAsync_Flows_TimedOutCancellationToken() { // Arrange ShortCircuitHandler spy = new ShortCircuitHandler(); CancellationToken timedOutToken = new CancellationToken(true); HttpContextBase contextBase = CreateStubContext("Get", Stream.Null, timedOutToken); HttpControllerHandler handler = new HttpControllerHandler(new RouteData(), spy); // Act var taskResult = handler.ProcessRequestAsyncCore(contextBase); // Assert Assert.Equal(timedOutToken, spy.CancelToken); }
public void ConvertResponse_Returns_InternalServerError_And_No_Content_When_Formatter_Write_Task_Faults_During_Error_Response() { // Arrange Mock <JsonMediaTypeFormatter> formatterMock = new Mock <JsonMediaTypeFormatter>() { CallBase = true }; TaskCompletionSource <object> tcs = new TaskCompletionSource <object>(); tcs.SetException(new NotSupportedException("Expected error")); // This formatter throws on any write attempt formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <object>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <TransportContext>())).Returns(tcs.Task); // Create a local config to hook to the request to condition // the formatter selection for the error response HttpConfiguration config = new HttpConfiguration(); config.Formatters.Clear(); config.Formatters.Add(formatterMock.Object); MemoryStream memoryStream = new MemoryStream(); Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream); HttpResponseBase responseBase = contextMock.Object.Response; HttpRequestMessage request = new HttpRequestMessage(); request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => true)); request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, config); HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; response.Content = new ObjectContent <string>("hello", formatterMock.Object); // Act Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response, request); task.Wait(); // Assert Assert.Equal <int>((int)HttpStatusCode.InternalServerError, responseBase.StatusCode); Assert.Equal(0, memoryStream.Length); Assert.Null(responseBase.Headers["Content-Type"]); }
public void WriteStreamedErrorResponseAsync_Aborts_When_Formatter_Write_Faults() { // Arrange TaskCompletionSource <object> tcs = new TaskCompletionSource <object>(); tcs.TrySetException(new NotSupportedException("Expected error")); Mock <JsonMediaTypeFormatter> formatterMock = new Mock <JsonMediaTypeFormatter>() { CallBase = true }; formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <object>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <TransportContext>())).Returns(tcs.Task); MemoryStream memoryStream = new MemoryStream(); Mock <HttpResponseBase> responseBaseMock = CreateMockHttpResponseBaseForResponse(memoryStream); responseBaseMock.Setup(m => m.Close()).Verifiable(); HttpResponseBase responseBase = responseBaseMock.Object; Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; contextMock.SetupGet(m => m.Response).Returns(responseBase); HttpRequestMessage request = new HttpRequestMessage(); request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => true)); HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; response.Content = new ObjectContent <string>("hello", formatterMock.Object); // Act Task task = HttpControllerHandler.WriteStreamedResponseContentAsync(responseBase, response.Content); task.Wait(); // Assert responseBaseMock.Verify(); }
public void ConvertRequest_Uses_HostBufferPolicySelector_To_Select_Buffered_Stream() { // Arrange Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForRequest("Post", new MemoryStream(new byte[] { 5 })); MemoryStream memoryStream = new MemoryStream(); // Act HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(contextMock.Object); actualRequest.Content.CopyToAsync(memoryStream).Wait(); byte[] actualBuffer = memoryStream.GetBuffer(); // Assert Assert.Equal(5, actualBuffer[0]); }
public void ConvertResponse_IfResponseHasNoCacheControlDefined_SetsNoCacheCacheabilityOnAspNetResponse() { // Arrange Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; HttpResponseMessage response = new HttpResponseMessage(); HttpRequestMessage request = new HttpRequestMessage(); // Act HttpControllerHandler.ConvertResponse(contextMock.Object, response, request); // Assert contextMock.Verify(c => c.Response.Cache.SetCacheability(HttpCacheability.NoCache)); }
public void WriteStreamedErrorResponseAsync_Aborts_When_Formatter_Write_Throws_Immediately() { // Arrange Mock <JsonMediaTypeFormatter> formatterMock = new Mock <JsonMediaTypeFormatter>() { CallBase = true }; formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <object>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <TransportContext>())).Throws(new NotSupportedException("Expected error")); MemoryStream memoryStream = new MemoryStream(); Mock <HttpRequestBase> requestBaseMock = new Mock <HttpRequestBase>(); requestBaseMock.Setup(m => m.Abort()).Verifiable(); HttpRequestBase requestBase = requestBaseMock.Object; HttpResponseBase responseBase = CreateMockHttpResponseBaseForResponse(memoryStream).Object; Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; contextMock.SetupGet(m => m.Response).Returns(responseBase); HttpContextBase contextBase = CreateStubContext(requestBase, responseBase); HttpRequestMessage request = new HttpRequestMessage(); request.SetIsLocal(new Lazy <bool>(() => true)); HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; response.Content = new ObjectContent <string>("hello", formatterMock.Object); // Act Task task = HttpControllerHandler.WriteStreamedResponseContentAsync(contextBase, response.Content); task.Wait(); // Assert requestBaseMock.Verify(); }
public void ProcessRequestAsync_Flows_ClientDisconnectedCancellationToken() { // Arrange ShortCircuitHandler spy = new ShortCircuitHandler(); CancellationToken clientDisconnectedToken = new CancellationToken(true); HttpRequestBase requestBase = CreateStubRequest("Get", Stream.Null); HttpResponseBase responseBase = CreateStubResponse(clientDisconnectedToken); HttpContextBase contextBase = CreateStubContext(requestBase, responseBase); HttpControllerHandler handler = new HttpControllerHandler(new RouteData(), spy); // Act var taskResult = handler.ProcessRequestAsyncCore(contextBase); // Assert taskResult.ThrowIfFaulted(); Assert.Equal(clientDisconnectedToken, spy.CancelToken); }
public void ConvertRequest_DoesLazyGetInputStream() { bool inputStreamCalled = false; HttpRequestBase stubRequest = CreateStubRequest(() => { inputStreamCalled = true; return(new MemoryStream()); }, buffered: true); HttpContextBase context = CreateStubContext(request: stubRequest, items: null); HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context); Assert.False(inputStreamCalled); var contentStream = actualRequest.Content.ReadAsStreamAsync().Result; Assert.True(inputStreamCalled); }
public void SuppressFormsAuthenticationRedirect_RequireSuppressRedirect() { // Arrange Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; IDictionary contextItems = new Hashtable(); contextMock.SetupGet(hcb => hcb.Response.StatusCode).Returns(401); contextMock.SetupGet(hcb => hcb.Items).Returns(contextItems); // Act HttpControllerHandler.EnsureSuppressFormsAuthenticationRedirect(contextMock.Object); // Assert Assert.True(contextMock.Object.Response.SuppressFormsAuthenticationRedirect); }
public void ConvertResponse_Returns_InternalServerError_And_No_Content_For_Null_HttpResponseMessage() { // Arrange MemoryStream memoryStream = new MemoryStream(); Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream); HttpResponseBase responseBase = contextMock.Object.Response; HttpRequestMessage request = new HttpRequestMessage(); // Act Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response: null, request: new HttpRequestMessage()); task.Wait(); // Assert Assert.Equal <int>((int)HttpStatusCode.InternalServerError, responseBase.StatusCode); Assert.Equal(0, memoryStream.Length); Assert.Null(responseBase.Headers["Content-Type"]); }
public void ConvertResponse_Returns_User_Response_When_Formatter_Write_Throws_HttpResponseException_With_No_Content() { // Arrange HttpResponseMessage errorResponse = new HttpResponseMessage(HttpStatusCode.MethodNotAllowed); errorResponse.Headers.Add("myHeader", "myValue"); Mock <JsonMediaTypeFormatter> formatterMock = new Mock <JsonMediaTypeFormatter>() { CallBase = true }; formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <object>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <TransportContext>())).Throws(new HttpResponseException(errorResponse)); MemoryStream memoryStream = new MemoryStream(); Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream); HttpResponseBase responseBase = contextMock.Object.Response; HttpRequestMessage request = new HttpRequestMessage(); request.SetIsLocal(new Lazy <bool>(() => true)); HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; response.Content = new ObjectContent <string>("hello", formatterMock.Object); // Act Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response, request); task.Wait(); memoryStream.Seek(0L, SeekOrigin.Begin); // Assert Assert.Equal <int>((int)errorResponse.StatusCode, responseBase.StatusCode); Assert.Equal(0, memoryStream.Length); Assert.Equal("myValue", responseBase.Headers["myHeader"]); Assert.Null(responseBase.Headers["Content-Type"]); }
public void ConvertRequest_Copies_Headers_And_Content_Headers() { // Arrange Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForRequest("Get", new MemoryStream()); HttpRequestBase requestBase = contextMock.Object.Request; NameValueCollection nameValues = requestBase.Headers; nameValues["myHeader"] = "myValue"; nameValues["Content-Type"] = "application/mine"; // Act HttpRequestMessage request = HttpControllerHandler.ConvertRequest(contextMock.Object); string[] headerValues = request.Headers.GetValues("myHeader").ToArray(); // Assert Assert.Equal("myValue", headerValues[0]); Assert.Equal("application/mine", request.Content.Headers.ContentType.MediaType); }
public void ConvertResponse_IfResponseHasCacheControlDefined_DoesNotSetCacheCacheabilityOnAspNetResponse() { // Arrange Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; HttpResponseMessage response = new HttpResponseMessage(); HttpRequestMessage request = new HttpRequestMessage(); response.Headers.CacheControl = new CacheControlHeaderValue { Public = true }; // Act HttpControllerHandler.ConvertResponse(contextMock.Object, response, request); // Assert contextMock.Verify(c => c.Response.Cache.SetCacheability(HttpCacheability.NoCache), Times.Never()); }
public void ConvertRequest_DoesNotAddOwinEnvironment_WhenItemsIsNull() { // Arrange using (MemoryStream ignoreStream = new MemoryStream()) { HttpRequestBase stubRequest = CreateStubRequest("IgnoreMethod", ignoreStream); IDictionary items = null; HttpContextBase context = CreateStubContext(stubRequest, items); // Act using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context)) { // Assert object ignore; bool found = actualRequest.Properties.TryGetValue(HttpControllerHandler.OwinEnvironmentKey, out ignore); Assert.False(found); } } }
public void IsOutputBufferingNecessary_Causes_Content_Length_Header_To_Be_Set(HttpContent content, bool isBuffered) { // Arrange & Act HttpControllerHandler.IsOutputBufferingNecessary(content); IEnumerable <string> contentLengthEnumerable; bool isContentLengthInHeaders = content.Headers.TryGetValues("Content-Length", out contentLengthEnumerable); string[] contentLengthStrings = isContentLengthInHeaders ? contentLengthEnumerable.ToArray() : new string[0]; long? contentLength = content.Headers.ContentLength; // Assert if (contentLength.HasValue && contentLength.Value >= 0) { // Setting the header is HttpContentHeader's responsibility, but we assert // it has happened because it is IsOutputBufferingNecessary's responsibility // to cause that to happen. HttpControllerHandler relies on this. Assert.True(isContentLengthInHeaders); Assert.Equal(contentLength.Value, long.Parse(contentLengthStrings[0])); } }
public void ConvertRequest_AddsOwinEnvironment_WhenPresentInHttpContext() { // Arrange using (MemoryStream ignoreStream = new MemoryStream()) { HttpRequestBase stubRequest = CreateStubRequest("IgnoreMethod", ignoreStream); IDictionary <string, object> expectedEnvironment = new Dictionary <string, object>(); IDictionary items = new Hashtable(); items.Add(HttpControllerHandler.OwinEnvironmentHttpContextKey, expectedEnvironment); HttpContextBase context = CreateStubContext(stubRequest, items); // Act using (HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context)) { IDictionary <string, object> environment = actualRequest.GetOwinEnvironment(); // Assert Assert.Same(expectedEnvironment, environment); } } }
public ConvertRequest_DoesLazyGetBufferlessInputStream_TestResults ConvertRequest_DoesLazyGetBufferlessInputStream() { bool inputStreamCalled = false; HttpRequestBase stubRequest = HttpControllerHandlerTest.CreateStubRequestBase(() => { inputStreamCalled = true; return(new MemoryStream()); }, buffered: false); HttpContextBase context = HttpControllerHandlerTest.CreateStubContextBase(request: stubRequest, items: null); GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new BufferOutputOnlyPolicySelector()); HttpRequestMessage actualRequest = HttpControllerHandler.ConvertRequest(context); ConvertRequest_DoesLazyGetBufferlessInputStream_TestResults results = new ConvertRequest_DoesLazyGetBufferlessInputStream_TestResults(); results.inputStreamCalledBeforeContentIsRead = inputStreamCalled; Stream contentStream = actualRequest.Content.ReadAsStreamAsync().Result; results.inputStreamCalledAfterContentIsRead = inputStreamCalled; return(results); }
public void OnEndRequest_IfWebApiControllerReturnsARedirect_DoNothing() { // Arrange HttpResponse response = new HttpResponse(null); IDictionary contextItems = new Hashtable(); Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; DisableRedirectStub disableRedirectStub = new DisableRedirectStub(contextItems, response); contextMock.SetupGet(hcb => hcb.Items).Returns(contextItems); response.StatusCode = 302; // Act HttpControllerHandler.EnsureSuppressFormsAuthenticationRedirect(contextMock.Object); SuppressFormsAuthRedirectModule.AllowAuthenticationRedirect(contextMock.Object); SuppressFormsAuthRedirectModule.EnsureRestoreUnauthorized(disableRedirectStub); // Assert Assert.Equal(302, response.StatusCode); }
public void IsOutputBufferingNecessary_Returns_Correct_Value(HttpContent content, bool isBuffered) { // Arrange & Act & Assert Assert.Equal(isBuffered, HttpControllerHandler.IsOutputBufferingNecessary(content)); }
public void ConvertResponse_Returns_InternalServerError_And_No_Content_When_Content_Negotiation_Cannot_Find_Formatter_For_Error_Response() { // Create a content negotiator that works attempting a normal response but fails when creating the error response. Mock <IContentNegotiator> negotiatorMock = new Mock <IContentNegotiator>() { CallBase = true }; negotiatorMock.Setup(m => m.Negotiate(It.IsAny <Type>(), It.IsAny <HttpRequestMessage>(), It.IsAny <IEnumerable <MediaTypeFormatter> >())) .Returns((Type t, HttpRequestMessage r, IEnumerable <MediaTypeFormatter> f) => { ContentNegotiationResult result = t == typeof(HttpError) ? null : new ContentNegotiationResult(f.First(), JsonMediaTypeFormatter.DefaultMediaType); return(result); }); // Arrange Mock <JsonMediaTypeFormatter> formatterMock = new Mock <JsonMediaTypeFormatter>() { CallBase = true }; // This formatter throws on any write attempt formatterMock.Setup(m => m.WriteToStreamAsync(It.IsAny <Type>(), It.IsAny <object>(), It.IsAny <Stream>(), It.IsAny <HttpContent>(), It.IsAny <TransportContext>())).Throws(new NotSupportedException("Expected error")); // Create a local config to hook to the request to condition // the formatter selection for the error response HttpConfiguration config = new HttpConfiguration(); config.Formatters.Clear(); config.Formatters.Add(formatterMock.Object); config.Services.Replace(typeof(IContentNegotiator), negotiatorMock.Object); MemoryStream memoryStream = new MemoryStream(); Mock <HttpContextBase> contextMock = CreateMockHttpContextBaseForResponse(memoryStream); HttpResponseBase responseBase = contextMock.Object.Response; HttpRequestMessage request = new HttpRequestMessage(); request.Properties.Add(HttpPropertyKeys.IsLocalKey, new Lazy <bool>(() => true)); request.Properties.Add(HttpPropertyKeys.HttpConfigurationKey, config); HttpResponseMessage response = new HttpResponseMessage() { RequestMessage = request }; response.Content = new ObjectContent <string>("hello", formatterMock.Object); // Act Task task = HttpControllerHandler.ConvertResponse(contextMock.Object, response, request); task.Wait(); // Assert Assert.Equal <int>((int)HttpStatusCode.InternalServerError, responseBase.StatusCode); Assert.Equal(0, memoryStream.Length); Assert.Null(responseBase.Headers["Content-Type"]); }