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 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 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 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 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 Task ConvertResponse_DisposesRequestAndResponse() { // Arrange Mock <HttpContextBase> contextMock = new Mock <HttpContextBase>() { DefaultValue = DefaultValue.Mock }; contextMock.SetupGet((hcb) => hcb.Response.OutputStream).Returns(Stream.Null); HttpRequestMessage request = new HttpRequestMessage(); HttpResponseMessage response = new HttpResponseMessage(); // 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 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"]); }
public void ConvertResponse_Returns_Error_Response_When_Formatter_Write_Task_Faults() { // Arrange Mock <JsonMediaTypeFormatter> formatterMock = new Mock <JsonMediaTypeFormatter>() { CallBase = true }; TaskCompletionSource <object> tcs = new TaskCompletionSource <object>(); try { // to capture stack trace inside this method throw new NotSupportedException("Expected error"); } catch (Exception ex) { tcs.SetException(ex); } 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 <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(MethodInfo.GetCurrentMethod().Name, innerError["StackTrace"].ToString()); }