public void MediaTypeMappingTakesPrecedenceOverAcceptHeader() { // Prepare the request message _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); _request.Headers.Add("Browser", "IE"); _request.Headers.Add("Cookie", "ABC"); // Prepare the formatters List <MediaTypeFormatter> formatters = new List <MediaTypeFormatter>(); formatters.Add(new JsonMediaTypeFormatter()); formatters.Add(new XmlMediaTypeFormatter()); PlainTextFormatter frmtr = new PlainTextFormatter(); frmtr.SupportedMediaTypes.Clear(); frmtr.MediaTypeMappings.Clear(); frmtr.SupportedMediaTypes.Add(new MediaTypeHeaderValue("application/xml")); frmtr.MediaTypeMappings.Add(new MyMediaTypeMapping(new MediaTypeHeaderValue(("application/xml")))); formatters.Add(frmtr); // Act var result = _negotiator.Negotiate(typeof(string), _request, formatters); // Assert Assert.NotNull(result); Assert.Equal("application/xml", result.MediaType.MediaType); Assert.IsType <PlainTextFormatter>(result.Formatter); }
public void Create_CreatesEmptyCollection() { NameValueCollection nvc = HttpValueCollection.Create(); Assert.IsType <HttpValueCollection>(nvc); Assert.Equal(0, nvc.Count); }
public void CreateOfTBase(Type instanceType, Type baseType) { // Arrange Type activatorType = typeof(TypeActivator); MethodInfo createMethodInfo = null; foreach (MethodInfo methodInfo in activatorType.GetMethods()) { ParameterInfo[] parameterInfo = methodInfo.GetParameters(); if (methodInfo.Name == "Create" && methodInfo.ContainsGenericParameters && parameterInfo.Length == 1 && parameterInfo[0].ParameterType == typeof(Type)) { createMethodInfo = methodInfo; break; } } MethodInfo genericCreateMethodInfo = createMethodInfo.MakeGenericMethod(baseType); Func <object> instanceDelegate = (Func <object>)genericCreateMethodInfo.Invoke(null, new object[] { instanceType }); // Act object instance = instanceDelegate(); // Assert Assert.IsType(instanceType, instance); }
public void GetStreamValidation() { Stream stream0 = null; Stream stream1 = null; try { MultipartFormDataContent content = new MultipartFormDataContent(); content.Add(new StringContent("Not a file"), "notafile"); content.Add(new StringContent("This is a file"), "file", "filename"); MultipartFormDataStreamProvider instance = new MultipartFormDataStreamProvider(Path.GetTempPath()); stream0 = instance.GetStream(content.ElementAt(0).Headers); Assert.IsType <MemoryStream>(stream0); stream1 = instance.GetStream(content.ElementAt(1).Headers); Assert.IsType <FileStream>(stream1); Assert.Equal(1, instance.BodyPartFileNames.Count); Assert.Contains("BodyPart", instance.BodyPartFileNames.Values.ElementAt(0)); } finally { if (stream0 != null) { stream0.Close(); } if (stream1 != null) { stream1.Close(); } } }
public void Invalid_Action_In_Route() { // Arrange ApiController api = new UsersController(); HttpRouteData route = new HttpRouteData(new HttpRoute()); string actionName = "invalidOp"; route.Values.Add("action", actionName); HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(instance: api, routeData: route, request: new HttpRequestMessage() { Method = HttpMethod.Get }); Type controllerType = typeof(UsersController); controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerType.Name, controllerType); controllerContext.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; // Act & Assert var exception = Assert.Throws <HttpResponseException>(() => { HttpResponseMessage message = api.ExecuteAsync(controllerContext, CancellationToken.None).Result; }); Assert.Equal(HttpStatusCode.NotFound, exception.Response.StatusCode); var content = Assert.IsType <ObjectContent <HttpError> >(exception.Response.Content); Assert.Equal("No action was found on the controller 'UsersController' that matches the name 'invalidOp'.", ((HttpError)content.Value)["MessageDetail"]); }
public void ControllerContext_HasUrlHelperWithValidContext() { HttpControllerContext cc = new HttpControllerContext(); Assert.NotNull(cc.Url); Assert.IsType <UrlHelper>(cc.Url); Assert.Same(cc, cc.Url.ControllerContext); }
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 CreateType(Type instanceType, Type baseType) { // Arrange Func <object> instanceDelegate = TypeActivator.Create(instanceType); // Act object instance = instanceDelegate(); // Assert Assert.IsType(instanceType, instance); }
public void Create1_SetsInnerHandler() { // Arrange MockDelegatingHandler handler = new MockDelegatingHandler(); // Act HttpClient client = HttpClientFactory.Create(handler); // Assert Assert.IsType <HttpClientHandler>(handler.InnerHandler); }
public void RegisterForDispose_WhenResourceListDoesNotExist_CreatesListAndAddsResource() { _request.Properties.Remove(HttpPropertyKeys.DisposableRequestResourcesKey); _request.RegisterForDispose(_disposable); var list = Assert.IsType <List <IDisposable> >(_request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey]); Assert.Equal(1, list.Count); Assert.Same(_disposable, list[0]); }
public void Iterate_Generic_IfProvidedEnumerationContainsNullValue_ReturnsFaultedTaskWithNullReferenceException() { List <string> log = new List <string>(); Task <IEnumerable <object> > result = TaskHelpers.Iterate(NullTaskEnumerable_Generic(log)); Assert.NotNull(result); result.WaitUntilCompleted(); Assert.Equal(TaskStatus.Faulted, result.Status); Assert.IsType <NullReferenceException>(result.Exception.GetBaseException()); }
public void Negotiate_SelectsJsonFormatter_ForXHRAndJsonValueResponse() { // Arrange _request.Content = new StringContent("test"); _request.Headers.Add("x-requested-with", "XMLHttpRequest"); // Act var result = _negotiator.Negotiate(typeof(JToken), _request, new MediaTypeFormatterCollection()); Assert.Equal("application/json", result.MediaType.MediaType); Assert.IsType <JsonMediaTypeFormatter>(result.Formatter); }
public void Negotiate_SelectsJsonAsDefaultFormatter() { // Arrange _request.Content = new StringContent("test"); // Act var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection()); // Assert Assert.IsType <JsonMediaTypeFormatter>(result.Formatter); Assert.Equal(MediaTypeConstants.ApplicationJsonMediaType.MediaType, result.MediaType.MediaType); }
public void Negotiate_SelectsJsonFormatter_ForXhrRequestThatDoesNotSpecifyAcceptHeaders() { // Arrange _request.Content = new StringContent("test"); _request.Headers.Add("x-requested-with", "XMLHttpRequest"); // Act var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection()); // Assert Assert.Equal("application/json", result.MediaType.MediaType); Assert.IsType <JsonMediaTypeFormatter>(result.Formatter); }
public void CreateOfT(Type instanceType, Type baseType) { // Arrange Type activatorType = typeof(TypeActivator); MethodInfo createMethodInfo = activatorType.GetMethod("Create", Type.EmptyTypes); MethodInfo genericCreateMethodInfo = createMethodInfo.MakeGenericMethod(instanceType); Func <object> instanceDelegate = (Func <object>)genericCreateMethodInfo.Invoke(null, null); // Act object instance = instanceDelegate(); // Assert Assert.IsType(instanceType, instance); }
public void Negotiate_UsesRequestedFormatterForXHRAndMatchAllPlusOtherAcceptHeader() { // Arrange _request.Content = new StringContent("test"); _request.Headers.Add("x-requested-with", "XMLHttpRequest"); _request.Headers.Accept.ParseAdd("text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"); // XHR header sent by Firefox 3b5 // Act var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection()); // Assert Assert.Equal("application/xml", result.MediaType.MediaType); Assert.IsType <XmlMediaTypeFormatter>(result.Formatter); }
public void Negotiate_SelectsJsonFormatter_ForXHRAndMatchAllAcceptHeader() { // Accept _request.Content = new StringContent("test"); _request.Headers.Add("x-requested-with", "XMLHttpRequest"); _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("*/*")); // Act var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection()); // Assert Assert.Equal("application/json", result.MediaType.MediaType); Assert.IsType <JsonMediaTypeFormatter>(result.Formatter); }
public void Negotiate_SelectsXmlFormatter_ForXhrRequestThatAcceptsXml() { // Arrange _request.Content = new StringContent("test"); _request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml")); _request.Headers.Add("x-requested-with", "XMLHttpRequest"); // Act var result = _negotiator.Negotiate(typeof(string), _request, new MediaTypeFormatterCollection()); // Assert Assert.Equal("application/xml", result.MediaType.MediaType); Assert.IsType <XmlMediaTypeFormatter>(result.Formatter); }
public Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream() { // Arrange TFormatter formatter = new TFormatter(); MemoryStream memStream = new MemoryStream(ExpectedSampleTypeByteRepresentation); HttpContentHeaders contentHeaders = FormattingUtilities.CreateEmptyContentHeaders(); contentHeaders.ContentLength = null; // Act return(formatter.ReadFromStreamAsync(typeof(SampleType), memStream, contentHeaders, null).ContinueWith( readTask => { // Assert var value = Assert.IsType <SampleType>(readTask.Result); Assert.Equal(42, value.Number); Assert.True(memStream.CanRead); })); }
public void Negotiate_RespectsFormatterOrdering_ForXhrRequestThatDoesNotSpecifyAcceptHeaders() { // Arrange _request.Content = new StringContent("test"); _request.Headers.Add("x-requested-with", "XMLHttpRequest"); MediaTypeFormatterCollection formatters = new MediaTypeFormatterCollection(new MediaTypeFormatter[] { new XmlMediaTypeFormatter(), new JsonMediaTypeFormatter(), new FormUrlEncodedMediaTypeFormatter() }); // Act var result = _negotiator.Negotiate(typeof(string), _request, formatters); // Assert Assert.Equal("application/json", result.MediaType.MediaType); Assert.IsType <JsonMediaTypeFormatter>(result.Formatter); }
public void CreateResponse_PerformsContentNegotiationAndCreatesContentUsingResults() { // Arrange XmlMediaTypeFormatter formatter = new XmlMediaTypeFormatter(); _negotiatorMock.Setup(r => r.Negotiate(typeof(string), _request, _config.Formatters)) .Returns(new ContentNegotiationResult(formatter, null)); _config.ServiceResolver.SetService(typeof(IContentNegotiator), _negotiatorMock.Object); // Act var response = HttpRequestMessageExtensions.CreateResponse <string>(_request, HttpStatusCode.NoContent, "42", _config); // Assert Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Same(_request, response.RequestMessage); var objectContent = Assert.IsType <ObjectContent <string> >(response.Content); Assert.Equal("42", objectContent.Value); Assert.Same(formatter, objectContent.Formatter); }
public void GetStream() { Stream stream0 = null; Stream stream1 = null; try { string tempPath = Path.GetTempPath(); MultipartFormDataContent content = new MultipartFormDataContent(); content.Add(new StringContent("Content 1"), "NoFile"); content.Add(new StringContent("Content 2"), "File", "Filename"); MultipartFileStreamProvider provider = new MultipartFileStreamProvider(tempPath); stream0 = provider.GetStream(content, content.ElementAt(0).Headers); stream1 = provider.GetStream(content, content.ElementAt(1).Headers); Assert.IsType <FileStream>(stream0); Assert.IsType <FileStream>(stream1); Assert.Equal(2, provider.FileData.Count); string partialFileName = String.Format("{0}BodyPart_", tempPath); Assert.Contains(partialFileName, provider.FileData[0].LocalFileName); Assert.Contains(partialFileName, provider.FileData[1].LocalFileName); Assert.Same(content.ElementAt(0).Headers.ContentDisposition, provider.FileData[0].Headers.ContentDisposition); Assert.Same(content.ElementAt(1).Headers.ContentDisposition, provider.FileData[1].Headers.ContentDisposition); } finally { if (stream0 != null) { stream0.Close(); } if (stream1 != null) { stream1.Close(); } } }
public Task ReadFromStreamAsync_WhenContentLengthIsNull_ReadsDataButDoesNotCloseStream() { // Arrange TFormatter formatter = new TFormatter(); MemoryStream memStream = new MemoryStream(ExpectedSampleTypeByteRepresentation); HttpContent content = new StringContent(String.Empty); HttpContentHeaders contentHeaders = content.Headers; contentHeaders.ContentLength = null; // Act return(formatter.ReadFromStreamAsync(typeof(SampleType), memStream, content, null).ContinueWith( readTask => { // Assert Assert.Equal(TaskStatus.RanToCompletion, readTask.Status); Assert.True(memStream.CanRead); var value = Assert.IsType <SampleType>(readTask.Result); Assert.Equal(42, value.Number); })); }
public void Create_InitializesCorrectly(IEnumerable <KeyValuePair <string, string> > input) { NameValueCollection nvc = HttpValueCollection.Create(input); int count = input.Count(); Assert.IsType <HttpValueCollection>(nvc); Assert.Equal(count, nvc.Count); int index = 0; foreach (KeyValuePair <string, string> kvp in input) { string expectedKey = kvp.Key ?? String.Empty; string expectedValue = kvp.Value ?? String.Empty; string actualKey = nvc.AllKeys[index]; string actualValue = nvc[index]; index++; Assert.Equal(expectedKey, actualKey); Assert.Equal(expectedValue, actualValue); } }