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 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.Response, null)); } }
public void Canceled_Generic_ReturnsCanceledTask() { Task <string> result = TaskHelpers.Canceled <string>(); Assert.NotNull(result); Assert.True(result.IsCanceled); }
public void TryParseInt32_AcceptsValidNumbers(string intValue, int expectedInt) { int actualInt; Assert.True(FormattingUtilities.TryParseInt32(intValue, out actualInt)); Assert.Equal(expectedInt, actualInt); }
public void GetMetadataForPropertiesCreatesMetadataForAllPropertiesOnModelWithPropertyValues() { // Arrange PropertyModel model = new PropertyModel { LocalAttributes = 42, MetadataAttributes = "hello", MixedAttributes = 21.12 }; TestableAssociatedMetadataProvider provider = new TestableAssociatedMetadataProvider(); // Act provider.GetMetadataForProperties(model, typeof(PropertyModel)).ToList(); // Call ToList() to force the lazy evaluation to evaluate // Assert CreateMetadataPrototypeParams local = provider.CreateMetadataPrototypeLog.Single(m => m.ContainerType == typeof(PropertyModel) && m.PropertyName == "LocalAttributes"); Assert.Equal(typeof(int), local.ModelType); Assert.True(local.Attributes.Any(a => a is RequiredAttribute)); CreateMetadataPrototypeParams metadata = provider.CreateMetadataPrototypeLog.Single(m => m.ContainerType == typeof(PropertyModel) && m.PropertyName == "MetadataAttributes"); Assert.Equal(typeof(string), metadata.ModelType); Assert.True(metadata.Attributes.Any(a => a is RangeAttribute)); CreateMetadataPrototypeParams mixed = provider.CreateMetadataPrototypeLog.Single(m => m.ContainerType == typeof(PropertyModel) && m.PropertyName == "MixedAttributes"); Assert.Equal(typeof(double), mixed.ModelType); Assert.True(mixed.Attributes.Any(a => a is RequiredAttribute)); Assert.True(mixed.Attributes.Any(a => a is RangeAttribute)); }
public void ApplyControllerSettings_Clone_Can_Enable_Tracing_When_Original_Disabled_It() { // Arrange bool calledTrace = false; HttpConfiguration config = new HttpConfiguration(); Mock <ITraceWriter> mockTracer = new Mock <ITraceWriter>() { CallBase = true }; mockTracer.Setup(m => m.Trace(It.IsAny <HttpRequestMessage>(), It.IsAny <string>(), It.IsAny <TraceLevel>(), It.IsAny <Action <TraceRecord> >())).Callback(() => { calledTrace = true; }); config.Initializer(config); // ensures TraceManager is called, but it will be a NOP HttpControllerSettings settings = new HttpControllerSettings(config); settings.Services.Replace(typeof(ITraceWriter), mockTracer.Object); // Act HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config); clonedConfig.Services.GetContentNegotiator().Negotiate(typeof(string), new HttpRequestMessage(), Enumerable.Empty <MediaTypeFormatter>()); // Assert Assert.True(calledTrace); }
public void ApplyControllerSettings_Clone_Inherits_Tracing_On_PerController_Formatters() { // Arrange bool calledTrace = false; HttpConfiguration config = new HttpConfiguration(); Mock <ITraceWriter> mockTracer = new Mock <ITraceWriter>() { CallBase = true }; mockTracer.Setup(m => m.Trace(It.IsAny <HttpRequestMessage>(), It.IsAny <string>(), It.IsAny <TraceLevel>(), It.IsAny <Action <TraceRecord> >())).Callback(() => { calledTrace = true; }); config.Services.Replace(typeof(ITraceWriter), mockTracer.Object); config.Initializer(config); // installs tracer on original config HttpControllerSettings settings = new HttpControllerSettings(config); Mock <MediaTypeFormatter> mockFormatter = new Mock <MediaTypeFormatter>() { CallBase = true }; settings.Formatters.Clear(); settings.Formatters.Add(mockFormatter.Object); // Act HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config); clonedConfig.Formatters[0].GetPerRequestFormatterInstance(typeof(string), new HttpRequestMessage(), new MediaTypeHeaderValue("application/mine")); // Assert Assert.True(calledTrace); }
public void ApplyControllerSettings_Clone_Inherits_Tracing_On_PerController_Services() { // Arrange bool calledTrace = false; HttpConfiguration config = new HttpConfiguration(); Mock <ITraceWriter> mockTracer = new Mock <ITraceWriter>() { CallBase = true }; mockTracer.Setup(m => m.Trace(It.IsAny <HttpRequestMessage>(), It.IsAny <string>(), It.IsAny <TraceLevel>(), It.IsAny <Action <TraceRecord> >())).Callback(() => { calledTrace = true; }); config.Services.Replace(typeof(ITraceWriter), mockTracer.Object); config.Initializer(config); // installs tracer on original config HttpControllerSettings settings = new HttpControllerSettings(config); Mock <IContentNegotiator> mockNegotiator = new Mock <IContentNegotiator>() { CallBase = true }; settings.Services.Replace(typeof(IContentNegotiator), mockNegotiator.Object); // Act HttpConfiguration clonedConfig = HttpConfiguration.ApplyControllerSettings(settings, config); clonedConfig.Services.GetContentNegotiator().Negotiate(typeof(string), new HttpRequestMessage(), Enumerable.Empty <MediaTypeFormatter>()); // Assert Assert.True(calledTrace); }
public void TryReadQueryAsTSucceeds() { UriBuilder address = new UriBuilder("http://some.host"); address.Query = "a=2"; SimpleObject1 so1; Assert.True(address.Uri.TryReadQueryAs <SimpleObject1>(out so1), "Expected 'true' reading valid data"); Assert.NotNull(so1); Assert.Equal(2, so1.a); address.Query = "b=true"; SimpleObject2 so2; Assert.True(address.Uri.TryReadQueryAs <SimpleObject2>(out so2), "Expected 'true' reading valid data"); Assert.NotNull(so2); Assert.True(so2.b, "Value should have been true"); address.Query = "c=hello"; SimpleObject3 so3; Assert.True(address.Uri.TryReadQueryAs <SimpleObject3>(out so3), "Expected 'true' reading valid data"); Assert.NotNull(so3); Assert.Equal("hello", so3.c); address.Query = "c="; Assert.True(address.Uri.TryReadQueryAs <SimpleObject3>(out so3), "Expected 'true' reading valid data"); Assert.NotNull(so3); Assert.Equal("", so3.c); address.Query = "c=null"; Assert.True(address.Uri.TryReadQueryAs <SimpleObject3>(out so3), "Expected 'true' reading valid data"); Assert.NotNull(so3); Assert.Equal("null", so3.c); }
public void IsAllMediaRange_ReturnsTrueForFullMediaTypeRanges(string mediaType) { MediaTypeHeaderValue mediaTypeHeaderValue = MediaTypeHeaderValue.Parse(mediaType); ParsedMediaTypeHeaderValue parsedMediaType = new ParsedMediaTypeHeaderValue(mediaTypeHeaderValue); Assert.True(parsedMediaType.IsAllMediaRange); }
public void GetControllerTypes_FindsTypes() { // Arrange DefaultHttpControllerTypeResolver resolver = new DefaultHttpControllerTypeResolver(); Mock <IAssembliesResolver> mockAssemblyResolver = new Mock <IAssembliesResolver>(); mockAssemblyResolver.Setup(a => a.GetAssemblies()).Returns(new List <Assembly> { null, new MockExportedTypesAssembly(ThrowException.ReflectionTypeLoadException, typeof(InvalidControllerStruct), typeof(ValidController), typeof(ControllerWrapper.InvalidNestedController), typeof(InvalidControllerWithInconsistentName)), new MockExportedTypesAssembly(ThrowException.Exception, typeof(InvalidControllerAbstract), typeof(InvalidControllerWithNoBaseType)), new MockExportedTypesAssembly(ThrowException.None, typeof(VALIDController), typeof(VALIDCONTROLLER), typeof(InvalidControllerStruct)), }); // Act ICollection <Type> actualControllerTypes = resolver.GetControllerTypes(mockAssemblyResolver.Object); // Assert Assert.Equal(3, actualControllerTypes.Count); Assert.True(actualControllerTypes.Contains(typeof(ValidController))); Assert.True(actualControllerTypes.Contains(typeof(VALIDController))); Assert.True(actualControllerTypes.Contains(typeof(VALIDCONTROLLER))); }
public void IsMimeMultipartContent(string boundary) { HttpContent content = CreateContent(boundary); Assert.NotNull(content); Assert.True(content.IsMimeMultipartContent()); }
public void ReadAsHttpResponseMessageAsync_Asp_ShouldBeDeserializedCorrectly() { string[] response = new string[] { @"HTTP/1.1 302 Found", @"Proxy-Connection: Keep-Alive", @"Connection: Keep-Alive", @"Content-Length: 124", @"Via: 1.1 RED-PRXY-23", @"Date: Thu, 30 Jun 2011 00:16:35 GMT", @"Location: /en-us/", @"Content-Type: text/html; charset=utf-8", @"Server: Microsoft-IIS/7.5", @"Cache-Control: private", @"P3P: CP=""ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI""", @"Set-Cookie: A=I&I=AxUFAAAAAAD7BwAA8Jx0njhGoW3MGASDmzeaGw!!&M=1; domain=.microsoft.com; expires=Sun, 30-Jun-2041 00:16:35 GMT; path=/", @"Set-Cookie: ADS=SN=175A21EF; domain=.microsoft.com; path=/", @"Set-Cookie: Sto.UserLocale=en-us; path=/", @"X-AspNetMvc-Version: 3.0", @"X-AspNet-Version: 4.0.30319", @"X-Powered-By: ASP.NET", @"Set-Cookie: A=I&I=AxUFAAAAAAD7BwAA8Jx0njhGoW3MGASDmzeaGw!!&M=1; domain=.microsoft.com; expires=Sun, 30-Jun-2041 00:16:35 GMT; path=/; path=/", @"Set-Cookie: ADS=SN=175A21EF; domain=.microsoft.com; path=/; path=/", @"P3P: CP=""ALL IND DSP COR ADM CONo CUR CUSo IVAo IVDo PSA PSD TAI TELo OUR SAMo CNT COM INT NAV ONL PHY PRE PUR UNI""", @"X-Powered-By: ASP.NET", }; string expectedEntity = @"<html><head><title>Object moved</title></head><body><h2>Object moved to <a href=""/en-us/"">here</a>.</h2></body></html>"; HttpContent content = CreateContent(false, response, expectedEntity); HttpResponseMessage httpResponse = content.ReadAsHttpResponseMessageAsync().Result; Assert.True(httpResponse.Headers.Contains("x-powered-by")); string actualEntity = httpResponse.Content.ReadAsStringAsync().Result; Assert.Equal(expectedEntity, actualEntity); }
public void MimeMultipartParserTestMultipartContent(string boundary) { MultipartContent content = new MultipartContent("mixed", boundary); content.Add(new StringContent("A")); content.Add(new StringContent("B")); content.Add(new StringContent("C")); MemoryStream memStream = new MemoryStream(); content.CopyToAsync(memStream).Wait(); memStream.Position = 0; byte[] data = memStream.ToArray(); for (var cnt = 1; cnt <= data.Length; cnt++) { MimeMultipartParser parser = CreateMimeMultipartParser(data.Length, boundary); Assert.NotNull(parser); int totalBytesConsumed; List <string> bodyParts; MimeMultipartParser.State state = ParseBufferInSteps(parser, data, cnt, out bodyParts, out totalBytesConsumed); Assert.Equal(MimeMultipartParser.State.BodyPartCompleted, state); Assert.Equal(data.Length, totalBytesConsumed); Assert.Equal(4, bodyParts.Count); Assert.Empty(bodyParts[0]); Assert.True(bodyParts[1].EndsWith("A")); Assert.True(bodyParts[2].EndsWith("B")); Assert.True(bodyParts[3].EndsWith("C")); } }
public void IsFormData_AcceptsFormDataMediaTypes(string mediaType) { HttpContent content = new StringContent(String.Empty); content.Headers.ContentType = MediaTypeHeaderValue.Parse(mediaType); Assert.True(content.IsFormData()); }
public void IsHttpResponseMessageContentRespondsTrue() { HttpContent content = new StringContent(String.Empty); content.Headers.ContentType = ParserData.HttpResponseMediaType; Assert.True(content.IsHttpResponseMessageContent(), "Content should be HTTP response."); }
public void IsJsonValueTypeReturnsTrue() { Assert.True(FormattingUtilities.IsJTokenType(typeof(JToken)), "Should return true"); Assert.True(FormattingUtilities.IsJTokenType(typeof(JValue)), "Should return true"); Assert.True(FormattingUtilities.IsJTokenType(typeof(JObject)), "Should return true"); Assert.True(FormattingUtilities.IsJTokenType(typeof(JArray)), "Should return true"); }
public void UseBufferedOutputStream_CausesContentLengthHeaderToBeSet(HttpContent content, bool expectedResult) { // Arrange & Act WebHostBufferPolicySelector selector = new WebHostBufferPolicySelector(); HttpResponseMessage response = new HttpResponseMessage(); response.Content = content; selector.UseBufferedOutputStream(response); 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 here because it is UseBufferedOutputStream's responsibility // to cause that to happen. HttpControllerHandler relies on this. Assert.True(isContentLengthInHeaders); Assert.Equal(contentLength.Value, long.Parse(contentLengthStrings[0])); } }
public void Canceled_ReturnsCanceledTask() { Task result = TaskHelpers.Canceled(); Assert.NotNull(result); Assert.True(result.IsCanceled); }
public void MatchMediaTypeMapping_ReturnsMatch() { // Arrange MockContentNegotiator negotiator = new MockContentNegotiator(); HttpRequestMessage request = new HttpRequestMessage(); MediaTypeHeaderValue mappingMediatype = MediaTypeHeaderValue.Parse("application/other"); MockMediaTypeMapping mockMediaTypeMapping = new MockMediaTypeMapping(mappingMediatype, 0.75); MockMediaTypeFormatter formatter = new MockMediaTypeFormatter(); formatter.MediaTypeMappings.Add(mockMediaTypeMapping); // Act MediaTypeFormatterMatch match = negotiator.MatchMediaTypeMapping(request, formatter); // Assert Assert.True(mockMediaTypeMapping.WasInvoked); Assert.Same(request, mockMediaTypeMapping.Request); Assert.Same(formatter, match.Formatter); Assert.Equal(mockMediaTypeMapping.MediaType, match.MediaType); Assert.Equal(mockMediaTypeMapping.MatchQuality, match.Quality); Assert.Equal(MediaTypeFormatterMatchRanking.MatchOnRequestWithMediaTypeMapping, match.Ranking); }
public void TryParseDate_AcceptsValidDates(string dateValue, DateTimeOffset expectedDate) { DateTimeOffset actualDate; Assert.True(FormattingUtilities.TryParseDate(dateValue, out actualDate)); Assert.Equal(expectedDate, actualDate); }
public void RunSynchronously_Executes_Action() { bool wasRun = false; Task t = TaskHelpers.RunSynchronously(() => { wasRun = true; }); t.WaitUntilCompleted(); Assert.True(wasRun); }
public void Constructor1SetsDerivedFormatters() { // force to array to get stable instances MediaTypeFormatter[] derivedFormatters = HttpUnitTestDataSets.DerivedFormatters.ToArray(); MediaTypeFormatterCollection collection = new MediaTypeFormatterCollection(derivedFormatters); Assert.True(derivedFormatters.SequenceEqual(collection)); }
public void CookieHeaderTryParse_AcceptsValidValues(CookieHeaderValue cookie, string expectedValue) { CookieHeaderValue header; bool result = CookieHeaderValue.TryParse(expectedValue, out header); Assert.True(result); Assert.Equal(expectedValue, header.ToString()); }
public void TryReadQueryAsJsonSucceeds(Uri address) { JObject value; Assert.True(address.TryReadQueryAsJson(out value), "Expected 'true' as result"); Assert.NotNull(value); Assert.IsType <JObject>(value); }
public void CanWriteType_ReturnsTrueOnJtoken() { TestJsonMediaTypeFormatter formatter = new TestJsonMediaTypeFormatter(); foreach (Type type in JTokenTypes) { Assert.True(formatter.CanWriteTypeProxy(type), "formatter should have returned false."); } }
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 FromResult_ReturnsCompletedTaskWithGivenResult() { string s = "ABC"; Task <string> result = TaskHelpers.FromResult(s); Assert.NotNull(result); Assert.True(result.Status == TaskStatus.RanToCompletion); Assert.Same(s, result.Result); }
public void FromError_Generic_ReturnsFaultedTaskWithGivenException() { var exception = new Exception(); Task <string> result = TaskHelpers.FromError <string>(exception); Assert.NotNull(result); Assert.True(result.IsFaulted); Assert.Same(exception, result.Exception.InnerException); }
public void FromErrors_Generic_ReturnsFaultedTaskWithGivenExceptions() { var exceptions = new[] { new Exception(), new InvalidOperationException() }; Task <string> result = TaskHelpers.FromErrors <string>(exceptions); Assert.NotNull(result); Assert.True(result.IsFaulted); Assert.Equal(exceptions, result.Exception.InnerExceptions.ToArray()); }