public void ExecuteAsync_RemovesInnerControllerFromReleaseListAndAddsItselfInstead() { // Arrange var request = new HttpRequestMessage(); var context = ContextUtil.CreateControllerContext(request: request); var mockController = new Mock <IHttpController>(); var mockDisposable = mockController.As <IDisposable>(); mockController.Setup(c => c.ExecuteAsync(context, CancellationToken.None)) .Callback <HttpControllerContext, CancellationToken>((cc, ct) => cc.Request.RegisterForDispose(mockDisposable.Object)) .Returns(() => TaskHelpers.FromResult(new HttpResponseMessage())) .Verifiable(); context.ControllerDescriptor = _controllerDescriptor; context.Controller = mockController.Object; var traceWriter = new TestTraceWriter(); var tracer = new HttpControllerTracer(request, mockController.Object, traceWriter); // Act ((IHttpController)tracer).ExecuteAsync(context, CancellationToken.None).WaitUntilCompleted(); // Assert IEnumerable <IDisposable> disposables = (IEnumerable <IDisposable>)request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey]; Assert.Contains(tracer, disposables); Assert.DoesNotContain(mockDisposable.Object, disposables); }
public void ExceptionConstructorWithoutDetail_AddsCorrectDictionaryItems() { HttpError error = new HttpError(new ArgumentException("error", new Exception()), false); Assert.Contains(new KeyValuePair <string, object>("Message", "An error has occurred."), error); Assert.False(error.ContainsKey("ExceptionMessage")); Assert.False(error.ContainsKey("ExceptionType")); Assert.False(error.ContainsKey("StackTrace")); Assert.False(error.ContainsKey("InnerException")); }
public void Enumerating_OnlyIncludesHttpRoutes() { var aspNetRoute = new Mock <RouteBase>().Object; _aspNetRoutes.Add("foo", aspNetRoute); var httpRoute = new Mock <IHttpRoute>().Object; _webApiRoutes.Add("bar", httpRoute); List <object> objects = new List <object>(_webApiRoutes); Assert.Contains(httpRoute, objects); Assert.DoesNotContain(aspNetRoute, objects); }
public void OnActionExecuted_WhenFilterQueryIsInvalid_SetsBadRequestResponseMessage(string query) { // Arrange _request.RequestUri = new Uri(String.Format("http://localhost/?{0}", query)); _response.Content = new ObjectContent <IQueryable <string> >(Enumerable.Empty <string>().AsQueryable(), new JsonMediaTypeFormatter()); _request.Properties[HttpPropertyKeys.HttpConfigurationKey] = new HttpConfiguration(); // Act _filter.OnActionExecuted(_actionExecutedContext); // Assert Assert.Equal(HttpStatusCode.BadRequest, _actionExecutedContext.Response.StatusCode); Assert.Contains("The query specified in the URI is not valid.", _actionExecutedContext.Response.Content.ReadAsStringAsync().Result); }
public void ViewCreationDelegatesToActivatorCreateInstanceWhenDependencyResolverReturnsNull() { // Arrange var controllerContext = new ControllerContext(); var buildManager = new MockBuildManager("view path", typeof(NoParameterlessCtor)); var dependencyResolver = new Mock <IDependencyResolver>(); var view = new TestableBuildManagerCompiledView(controllerContext, "view path", dependencyResolver: dependencyResolver.Object) { BuildManager = buildManager }; // Act MissingMethodException ex = Assert.Throws <MissingMethodException>( // Depend on the fact that Activator.CreateInstance cannot create an object without a parameterless ctor () => view.Render(new Mock <ViewContext>().Object, new Mock <TextWriter>().Object) ); // Assert Assert.Contains("System.Activator.CreateInstance(", ex.StackTrace); }
public void ModelStateConstructorWithoutDetail_AddsCorrectDictionaryItems() { ModelStateDictionary modelState = new ModelStateDictionary(); modelState.AddModelError("[0].Name", "error1"); modelState.AddModelError("[0].Name", "error2"); modelState.AddModelError("[0].Address", "error"); modelState.AddModelError("[2].Name", new Exception("OH NO")); HttpError error = new HttpError(modelState, false); HttpError modelStateError = error["ModelState"] as HttpError; Assert.Contains(new KeyValuePair <string, object>("Message", "The request is invalid."), error); Assert.Contains("error1", modelStateError["[0].Name"] as IEnumerable <string>); Assert.Contains("error2", modelStateError["[0].Name"] as IEnumerable <string>); Assert.Contains("error", modelStateError["[0].Address"] as IEnumerable <string>); Assert.True(modelStateError.ContainsKey("[2].Name")); Assert.DoesNotContain("OH NO", modelStateError["[2].Name"] as IEnumerable <string>); }
public void SelectController_Throws_DuplicateController() { HttpConfiguration configuration = new HttpConfiguration(); Mock <IHttpControllerTypeResolver> controllerTypeResolver = new Mock <IHttpControllerTypeResolver>(); configuration.Services.Replace(typeof(IHttpControllerTypeResolver), controllerTypeResolver.Object); configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always; controllerTypeResolver .Setup(c => c.GetControllerTypes(It.IsAny <IAssembliesResolver>())) .Returns(new Collection <Type> { GetMockControllerType("Sample"), GetMockControllerType("SampLe"), GetMockControllerType("SAmpLE") }); HttpRequestMessage request = new HttpRequestMessage(); IHttpRouteData routeData1 = GetRouteData(); routeData1.Values["controller"] = "Sample"; request.Properties[HttpPropertyKeys.HttpRouteDataKey] = routeData1; request.Properties[HttpPropertyKeys.HttpConfigurationKey] = configuration; DefaultHttpControllerSelector selector = new DefaultHttpControllerSelector(configuration); // Act var ex = Assert.Throws <InvalidOperationException>( () => selector.SelectController(request)); // Assert string message = ex.Message; Assert.Contains( "Multiple types were found that match the controller named 'Sample'. This can happen if the route that services this request ('') found multiple controllers defined with the same name but differing namespaces, which is not supported.\r\n\r\nThe request for 'Sample' has found the following matching controllers:", message); var duplicateControllers = message.Split(':')[1].Split('\n').Select(str => str.Trim()); Assert.Contains("FullSampleController", duplicateControllers); Assert.Contains("FullSampLeController", duplicateControllers); Assert.Contains("FullSAmpLEController", duplicateControllers); }
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"); MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(tempPath); stream0 = provider.GetStream(content, content.ElementAt(0).Headers); stream1 = provider.GetStream(content, content.ElementAt(1).Headers); Assert.IsType <MemoryStream>(stream0); Assert.IsType <FileStream>(stream1); Assert.Equal(1, provider.FileData.Count); string partialFileName = String.Format("{0}BodyPart_", tempPath); Assert.Contains(partialFileName, provider.FileData[0].LocalFileName); Assert.Same(content.ElementAt(1).Headers.ContentDisposition, provider.FileData[0].Headers.ContentDisposition); } finally { if (stream0 != null) { stream0.Close(); } if (stream1 != null) { stream1.Close(); } } }
public void HttpError_Roundtrips_WithJsonFormatter() { HttpError error = new HttpError("error") { { "ErrorCode", 42 }, { "Data", new[] { "a", "b", "c" } } }; MediaTypeFormatter formatter = new JsonMediaTypeFormatter(); MemoryStream stream = new MemoryStream(); formatter.WriteToStreamAsync(typeof(HttpError), error, stream, content: null, transportContext: null).Wait(); stream.Position = 0; HttpError roundtrippedError = formatter.ReadFromStreamAsync(typeof(HttpError), stream, content: null, formatterLogger: null).Result as HttpError; Assert.NotNull(roundtrippedError); Assert.Equal("error", roundtrippedError.Message); Assert.Equal(42L, roundtrippedError["ErrorCode"]); JArray data = roundtrippedError["Data"] as JArray; Assert.Equal(3, data.Count); Assert.Contains("a", data); Assert.Contains("b", data); Assert.Contains("c", data); }
public void StringConstructor_AddsCorrectDictionaryItems() { HttpError error = new HttpError("something bad happened"); Assert.Contains(new KeyValuePair <string, object>("Message", "something bad happened"), error); }