public void CreatePoint_InvalidPayload_400() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var endpoint = API_ROUTE_LOCAL + "/api/point"; controller.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var point = new PointCreateDTO { Longitude = 179, Latitude = 85, Description = "desc", Name = "name", }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); controller.Request = request; NegotiatedContentResult <string> response = (NegotiatedContentResult <string>)controller.Post(null); Assert.AreEqual(response.StatusCode, HttpStatusCode.BadRequest); }
public void ReadPoint_Unauthorized_401() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); var point = _tu.CreatePointObject(179, 81); point = _tu.CreatePointInDb(point); var endpoint = API_ROUTE_LOCAL + "/api/point/" + point.Id; controller.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); controller.Request = request; NegotiatedContentResult <string> response = (NegotiatedContentResult <string>)controller.Get(point.Id.ToString()); Assert.AreEqual(response.StatusCode, HttpStatusCode.Unauthorized); }
public void UpdatePoint_NonExisting_404() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var point = _tu.CreatePointObject(179, 81); var endpoint = API_ROUTE_LOCAL + "/api/point/" + point.Id; controller.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); controller.Request = request; var pointPost = new PointUpdateDTO { Longitude = point.Longitude, Latitude = point.Latitude, Description = "updatedDescription", Name = "updatedName", Id = point.Id }; NegotiatedContentResult <string> result = (NegotiatedContentResult <string>)controller.Put(pointPost); Assert.AreEqual(result.StatusCode, HttpStatusCode.NotFound); }
private static async Task <HttpResponseMessage> Handler400( HttpActionExecutedContext context, CancellationToken cancellationToken) { ValidationException validationException = context.Exception as ValidationException; if (validationException != null) { var exceptionResult = new NegotiatedContentResult <IEnumerable <ValidationResultDto> >( HttpStatusCode.BadRequest, validationException.ValidationResults.Select(r => new ValidationResultDto(r)), context.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(), context.Request, new MediaTypeFormatterCollection()); return(await exceptionResult.ExecuteAsync(cancellationToken)); } var odataException = context.Exception as ODataException; if (odataException != null) { return(context.Request.CreateErrorResponse(HttpStatusCode.BadRequest, context.Exception)); } return(null); }
public async Task MemberReserveBookNotAvailable() { try { var input = Input.TestCaseInput1(); var inputItem = input.Item1; var inputMember = input.Item2; var inputBookStatusView = input.Item3; var inputLoanRequirement = input.Item4; inputItem.SerialItems = new List <SerialItem>(); var controller = GetMockedLoanController(inputItem, inputMember, inputBookStatusView); IHttpActionResult response = await controller.LoanBookAsync(inputLoanRequirement).ConfigureAwait(false); NegotiatedContentResult <string> result = (NegotiatedContentResult <string>)response; Assert.AreEqual("Required book is not available.", result.Content); } catch (Exception e) { Console.WriteLine(e); throw; } }
public void CreatePoint_InvalidLongLat_400() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var endpoint = API_ROUTE_LOCAL + "/api/point"; _pointController.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var point = new PointCreateDTO { Longitude = 185, Latitude = 85, Description = "bad longitude value", Name = "test bad point", }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); _pointController.Request = request; //out of range Longitude should throw InvalidPointException // and return a 400 NegotiatedContentResult <string> response = (NegotiatedContentResult <string>)_pointController.Post(point); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); Assert.AreEqual("Longitude/Latitude value invalid.", response.Content.ToString()); }
private static async Task <HttpResponseMessage> HandleChangeSetValidationException( HttpActionExecutedContext context, bool useVerboseErros, CancellationToken cancellationToken) { if (context.Exception is ChangeSetValidationException validationException) { var result = new { error = new { code = string.Empty, innererror = new { message = validationException.Message, type = validationException.GetType().FullName }, message = "Validaion failed for one or more objects.", validationentries = validationException.ValidationResults }, }; var exceptionResult = new NegotiatedContentResult <object>( (HttpStatusCode)422, result, context.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(), context.Request, new MediaTypeFormatterCollection()); return(await exceptionResult.ExecuteAsync(cancellationToken).ConfigureAwait(false)); } return(null); }
public void WhenICallTheHealthCheckController() { _healthCheckController = new HealthCheckController( new HealthCheckService(new HealthCheckFactory(_databaseCheck.Object), new HealthCheckResponseBuilder())); _result = (NegotiatedContentResult <HealthCheckResponse>)_healthCheckController.Get(); }
public void DeletePoint_200() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var point = _tu.CreatePointObject(179, 81); point = _tu.CreatePointInDb(point); var endpoint = API_ROUTE_LOCAL + "/api/point/" + point.Id; controller.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); controller.Request = request; OkResult response = (OkResult)controller.Delete(point.Id.ToString()); NegotiatedContentResult <string> result404 = (NegotiatedContentResult <string>)controller.Get(point.Id.ToString()); Assert.IsInstanceOfType(response, typeof(OkResult)); Assert.AreEqual(result404.StatusCode, HttpStatusCode.NotFound); }
public void GetAllUsers_UserIsNotAdministrator_400() { newUser = _tu.CreateUserObject(); newUser.IsAdministrator = false; Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var endpoint = API_ROUTE_LOCAL + "/users"; _umController.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); _umController.Request = request; //user is not adminstrator and therefore cannot return all users. // should result in an UserIsNotAdministratorException // and return a 401 NegotiatedContentResult <string> response = (NegotiatedContentResult <string>)_umController.GetAllUsers(); Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); Assert.AreEqual("Non-administrators cannot view all users.", response.Content.ToString()); }
public void UpdatePoint_InvalidPayload_400() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var point = _tu.CreatePointObject(179, 81); point = _tu.CreatePointInDb(point); var endpoint = API_ROUTE_LOCAL + "/api/point/" + point.Id; controller.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); controller.Request = request; NegotiatedContentResult <string> result = (NegotiatedContentResult <string>)controller.Put(null); Assert.AreEqual(result.StatusCode, HttpStatusCode.BadRequest); }
public static void AssertCreatedResponse <TExpected>(NegotiatedContentResult <TExpected> contentResult) { Assert.IsNotNull(contentResult); Assert.IsNotNull(contentResult.Content); Assert.AreEqual(contentResult.StatusCode, HttpStatusCode.Created); Assert.IsInstanceOf(typeof(TExpected), contentResult.Content); }
public void DeleteUser_NoUserId_412() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var endpoint = API_ROUTE_LOCAL + "/users/delete/"; _umController.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); _umController.Request = request; //passing null parameter creates InvalidModelPayloadException that should be caught // and return a 400 NegotiatedContentResult <string> response = (NegotiatedContentResult <string>)_umController.DeleteUser((string)null); Assert.AreEqual(HttpStatusCode.PreconditionFailed, response.StatusCode); }
public void DeleteUser_SessionExpired_401() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); //_tu.CreateSessionInDb(newSession); var endpoint = API_ROUTE_LOCAL + "/user/delete"; _umController.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); _umController.Request = request; //passing user with no session should result in SessionNotFoundException // and return a 401 NegotiatedContentResult <string> response = (NegotiatedContentResult <string>)_umController.DeleteUser(newUser.Id.ToString()); Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); }
public void Put() { // Arrange PersonsController controller = new PersonsController(); controller.PS.PersonRepository.RemoveAll(P => P.LastName.Length > 0); controller.Post("Talapaneni Hemanth Male Yellow 2017/12/01"); controller.Post("Halapaneni Temanth Female Green 2018/2/1"); controller.Post("Balapaneni Remanth Female Blue 2014/5/01"); controller.Post("Malapaneni Bemanth Male Red 2015/11/1"); List <Person> Persons = new List <Person>(); // Act IHttpActionResult actionResult = controller.Put("Malapaneni", "Malapaneni Demanth Male Red 2015/11/1"); // Assert Assert.IsNotNull(actionResult); Assert.IsInstanceOfType(actionResult, typeof(NegotiatedContentResult <string>)); NegotiatedContentResult <string> Result = (NegotiatedContentResult <string>)actionResult; Assert.AreEqual(HttpStatusCode.OK, Result.StatusCode); // Act actionResult = controller.Get("dob"); // Assert Assert.IsNotNull(actionResult); Assert.IsInstanceOfType(actionResult, typeof(OkNegotiatedContentResult <List <Person> >)); OkNegotiatedContentResult <List <Person> > result = (OkNegotiatedContentResult <List <Person> >)actionResult; Persons = result.Content; Assert.AreEqual(4, Persons.Count); Assert.AreEqual("Demanth", Persons[1].FirstName); }
public void Delete_InvalidUserId_400() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var badId = "q7h493proannaosnfdo"; var endpoint = API_ROUTE_LOCAL + "/users/delete/"; _umController.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); _umController.Request = request; //passing a incorrectly formatted user Id should result in an InvalidGuidException // and return a 400 NegotiatedContentResult <string> response = (NegotiatedContentResult <string>)_umController.DeleteUser(badId); Assert.AreEqual(HttpStatusCode.BadRequest, response.StatusCode); }
public void DeleteUserSSO_InvalidtokenSignature_401() { newUser = _tu.CreateUserObject(); Session newSession = _tu.CreateSessionObject(newUser); _tu.CreateSessionInDb(newSession); var endpoint = API_ROUTE_LOCAL + "/sso/user/delete"; var _userController = new UserController(); _userController.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; var loginDTO = new LoginRequestPayload { SSOUserId = Guid.NewGuid().ToString(), Email = "*****@*****.**", Timestamp = 1928743091, Signature = "ahsbdkfhasjdfln", }; var request = new HttpRequestMessage(); request.Headers.Add("token", newSession.Token); _userController.Request = request; //invalid signature should throw and InvalidTokenSignatureException // and return a 401 NegotiatedContentResult <string> response = (NegotiatedContentResult <string>)_userController.DeleteViaSSO(loginDTO); Assert.AreEqual(HttpStatusCode.Unauthorized, response.StatusCode); }
public void PostWrongPayload_ShouldGetErrorMessage() { var controller = new TvProgramController(); controller.Request = new HttpRequestMessage() { Content = new System.Net.Http.StringContent(GetWrongPayload()) }; controller.Configuration = new HttpConfiguration(); var actionResult = controller.Index(); var expectResponse = @" { ""error"": ""Could not decode request: JSON parsing failed"" } "; NegotiatedContentResult <failureResposneDto> negResult = Xunit.Assert.IsType <NegotiatedContentResult <failureResposneDto> >(actionResult); Xunit.Assert.Equal(HttpStatusCode.BadRequest, negResult.StatusCode); Xunit.Assert.Equal( Regex.Replace(expectResponse, @"\s+", ""), Regex.Replace(JsonConvert.SerializeObject(negResult.Content), @"\s+", "")); }
public void DeleteNonExistingUser_Authorized_404() { var controller = new UserManagementController(); var admin = _ut.CreateUserObject(); admin.IsAdministrator = true; var adminSession = _ut.CreateSessionObject(admin); _ut.CreateSessionInDb(adminSession); var nonexistingUserToDelete = Guid.NewGuid().ToString(); var expectedStatusCode = HttpStatusCode.NotFound; var endpoint = API_Route_Local + "/user/delete/{userId}"; controller.Request = new HttpRequestMessage { RequestUri = new Uri(endpoint) }; controller.Request.Headers.Add("token", adminSession.Token); NegotiatedContentResult <string> actionresult = (NegotiatedContentResult <string>)controller.DeleteUser(nonexistingUserToDelete); Assert.AreEqual(expectedStatusCode, actionresult.StatusCode); }
public async Task MaxLoanLimitExceed() { try { var input = Input.TestCaseInput1(); var inputItem = input.Item1; var inputMember = input.Item2; var inputBookStatusView = input.Item3; var inputLoanRequirement = input.Item4; inputMember.Loan_Rule.Max_loan_book = 1; var controller = GetMockedLoanController(inputItem, inputMember, inputBookStatusView); IHttpActionResult response = await controller.LoanBookAsync(inputLoanRequirement).ConfigureAwait(false); NegotiatedContentResult <string> result = (NegotiatedContentResult <string>)response; Assert.AreEqual("Loan max limit exceeded.", result.Content); } catch (Exception e) { Console.WriteLine(e); throw; } }
public void DeleteEmployeeIfSuccess() { string empId = "6"; NegotiatedContentResult <string> actionresult = (NegotiatedContentResult <string>)employeeController.DeleteEmployeeById(empId); Assert.AreEqual <HttpStatusCode>(HttpStatusCode.NoContent, actionresult.StatusCode); Assert.AreEqual("", actionresult.Content); }
public void GetEmployeeById_NotFound() { string empId = "1"; string expected = "Employee Id Not Found"; NegotiatedContentResult <string> result = (NegotiatedContentResult <string>)employeeController.GetEmployeeById(empId); Assert.AreEqual(expected, result.Content); }
public void DeleteEmployee_NotFound() { string empId = "1"; string expected = "Employee Id does not Exist"; NegotiatedContentResult <string> actionresult = (NegotiatedContentResult <string>)employeeController.DeleteEmployeeById(empId); Assert.AreEqual(expected, actionresult.Content); }
public void Spending_Controller_Delete_ShouldHandleValidationFailure() { // Arrange _spendingRemove.Setup(c => c.Validate().IsValid).Returns(false); // Action IHttpActionResult callback = _spendingsController.Delete(_spendingRemove.Object); // Assert NegotiatedContentResult <IList <ValidationFailure> > httpResponse = callback.Should().BeOfType <NegotiatedContentResult <IList <ValidationFailure> > >().Subject; }
public void AddItemWithValidId() { // Act var resultRaw = _controller.AddItem(1, 1, 2); NegotiatedContentResult <ResponseDto> result = (NegotiatedContentResult <ResponseDto>)resultRaw; ////// Assert Assert.IsNotNull(result); Assert.IsNotNull(result.Content); Assert.AreEqual(HttpStatusCode.OK, result.Content.StatusCode); }
public void Transportador_Controller_Put_ShouldHandleNotFoundexception() { // Arrange _transportadorServicoMock.Setup(c => c.Atualizar(_transportadorAtualizarCmd.Object)).Throws <ExcecaoNaoEncontrado>(); // Action IHttpActionResult callback = _transportadorsControlador.Atualizar(_transportadorAtualizarCmd.Object); // Assert NegotiatedContentResult <ExceptionPayload> httpResponse = callback.Should().BeOfType <NegotiatedContentResult <ExceptionPayload> >().Subject; httpResponse.Content.CodigoErro.Should().Be((int)CodigosErros.NotFound); _transportadorServicoMock.Verify(s => s.Atualizar(_transportadorAtualizarCmd.Object), Times.Once); }
public void DeleteItem() { // Act var resultRaw = _controller.DeleteItem(2); NegotiatedContentResult <ResponseDto> result = (NegotiatedContentResult <ResponseDto>)resultRaw; // Assert Assert.IsNotNull(result); Assert.IsNotNull(result.Content); Assert.AreEqual(HttpStatusCode.OK, result.Content.StatusCode); Assert.AreEqual("Item with id: 2 successfully deleted.", result.Content.MessageDetail); }
public void DeleteItemWithInvalidId() { // Act var resultRaw = _controller.DeleteItem(234); NegotiatedContentResult <ResponseDto> result = (NegotiatedContentResult <ResponseDto>)resultRaw; // Assert Assert.IsNotNull(result); Assert.IsNotNull(result.Content); Assert.AreEqual(HttpStatusCode.BadRequest, result.Content.StatusCode); Assert.AreEqual("Item with id: 234 not found.", result.Content.MessageDetail); }
public void GetItemWithInValidId() { // Act var resultRaw = _controller.GetItem(232); NegotiatedContentResult <ResponseDto> result = (NegotiatedContentResult <ResponseDto>)resultRaw; // Assert Assert.IsNotNull(result); Assert.IsNotNull(result.Content); Assert.AreEqual(HttpStatusCode.BadRequest, result.Content.StatusCode); Assert.AreEqual("Not found", result.Content.Message); }
private ErrorMessageResult(string message, NegotiatedContentResult<HttpError>.IDependencyProvider dependencies) { if (message == null) { throw new ArgumentNullException("message"); } Contract.Assert(dependencies != null); _message = message; _dependencies = dependencies; }
public HttpStatusCode GivenHealthySystem_ReturnStatusOK(bool isSystemHealthy) { _mockHealthCheckService.Setup(x => x.CheckSystemHealth()) .Returns(new HealthCheckResponse() { IsSystemHealthy = isSystemHealthy }); _result = (NegotiatedContentResult <HealthCheckResponse>)_healthCheckController.Get(); return(_result.StatusCode); }
private static async Task<HttpResponseMessage> HandleChangeSetValidationException( HttpActionExecutedContext context, bool useVerboseErros, CancellationToken cancellationToken) { ChangeSetValidationException validationException = context.Exception as ChangeSetValidationException; if (validationException != null) { var exceptionResult = new NegotiatedContentResult<IEnumerable<ValidationResultDto>>( HttpStatusCode.BadRequest, validationException.ValidationResults.Select(r => new ValidationResultDto(r)), context.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(), context.Request, new MediaTypeFormatterCollection()); return await exceptionResult.ExecuteAsync(cancellationToken); } return null; }
/// <summary> /// The callback to execute when exception occurs. /// </summary> /// <param name="actionExecutedContext">The context where the action is executed.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns>The task object that represents the callback execution.</returns> public override async Task OnExceptionAsync( HttpActionExecutedContext actionExecutedContext, CancellationToken cancellationToken) { IHttpActionResult exceptionResult = null; ValidationException validationException = actionExecutedContext.Exception as ValidationException; if (validationException != null) { exceptionResult = new NegotiatedContentResult<IEnumerable<ValidationResultDto>>( HttpStatusCode.BadRequest, validationException.ValidationResults.Select(r => new ValidationResultDto(r)), actionExecutedContext.ActionContext.RequestContext.Configuration.Services.GetContentNegotiator(), actionExecutedContext.Request, new MediaTypeFormatterCollection()); } if (exceptionResult != null) { actionExecutedContext.Response = await exceptionResult.ExecuteAsync(cancellationToken); } }
public async Task NegotiatedContentResult_WritesHttpError() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.RequestServices = CreateServices(); var stream = new MemoryStream(); httpContext.Response.Body = stream; var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); var result = new NegotiatedContentResult<Product>(HttpStatusCode.Ambiguous, new Product()); // Act await result.ExecuteResultAsync(context); // Assert using (var reader = new StreamReader(stream)) { stream.Seek(0, SeekOrigin.Begin); var content = reader.ReadToEnd(); Assert.Equal("{\"Id\":0,\"Name\":null}", content); } }
public void ContentNegotiator_ForApiController_Throws_WhenConfigurationIsNull() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); ApiController controller = CreateController(); HttpControllerContext context = new HttpControllerContext(); using (HttpRequestMessage request = CreateRequest()) { controller.ControllerContext = context; NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content, controller); // Act & Assert Assert.Throws<InvalidOperationException>( () => { IContentNegotiator ignore = result.ContentNegotiator; }, "HttpControllerContext.Configuration must not be null."); } }
public void Formatters_Returns_InstanceProvided() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); IContentNegotiator contentNegotiator = CreateContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters(); NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content, contentNegotiator, request, expectedFormatters); // Act IEnumerable<MediaTypeFormatter> formatters = result.Formatters; // Assert Assert.Same(expectedFormatters, formatters); } }
private static void AssertHalModelResult(HttpStatusCode statusCode, string expectedLinkBase, bool forceHal, NegotiatedContentResult<HALResponse> result) { Assert.NotNull(result); Assert.Equal(statusCode, result.StatusCode); var model = result.Content; Assert.NotNull(model); Assert.NotNull(model.Config); Assert.Equal(forceHal, model.Config.ForceHAL); Assert.Equal(expectedLinkBase, model.Config.LinkBase); }
public void ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationSucceeds() { // Arrange HttpStatusCode expectedStatusCode = CreateStatusCode(); object expectedContent = CreateContent(); MediaTypeFormatter expectedFormatter = CreateFormatter(); MediaTypeHeaderValue expectedMediaType = CreateMediaType(); ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedFormatter, expectedMediaType); using (HttpRequestMessage expectedRequest = CreateRequest()) { IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters(); Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>(); spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns( negotiationResult); IContentNegotiator contentNegotiator = spy.Object; IHttpActionResult result = new NegotiatedContentResult<object>(expectedStatusCode, expectedContent, contentNegotiator, expectedRequest, expectedFormatters); // Act Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None); // Assert Assert.NotNull(task); task.WaitUntilCompleted(); using (HttpResponseMessage response = task.Result) { Assert.NotNull(response); Assert.Equal(expectedStatusCode, response.StatusCode); HttpContent content = response.Content; Assert.IsType<ObjectContent<object>>(content); ObjectContent<object> typedContent = (ObjectContent<object>)content; Assert.Same(expectedContent, typedContent.Value); Assert.Same(expectedFormatter, typedContent.Formatter); Assert.NotNull(typedContent.Headers); Assert.Equal(expectedMediaType, typedContent.Headers.ContentType); Assert.Same(expectedRequest, response.RequestMessage); } } }
public void ExecuteAsync_Returns_CorrectResponse_WhenContentNegotiationFails() { // Arrange HttpStatusCode statusCode = HttpStatusCode.Conflict; object content = CreateContent(); ContentNegotiationResult negotiationResult = null; using (HttpRequestMessage expectedRequest = CreateRequest()) { IEnumerable<MediaTypeFormatter> expectedFormatters = CreateFormatters(); Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>(); spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, expectedFormatters)).Returns( negotiationResult); IContentNegotiator contentNegotiator = spy.Object; IHttpActionResult result = new NegotiatedContentResult<object>(statusCode, content, contentNegotiator, expectedRequest, expectedFormatters); // Act Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None); // Assert Assert.NotNull(task); task.WaitUntilCompleted(); using (HttpResponseMessage response = task.Result) { Assert.NotNull(response); Assert.Equal(HttpStatusCode.NotAcceptable, response.StatusCode); Assert.Same(expectedRequest, response.RequestMessage); } } }
public void ExecuteAsync_ForApiController_ReturnsCorrectResponse_WhenContentNegotationSucceeds() { // Arrange HttpStatusCode expectedStatusCode = CreateStatusCode(); object expectedContent = CreateContent(); ApiController controller = CreateController(); MediaTypeFormatter expectedInputFormatter = CreateFormatter(); MediaTypeFormatter expectedOutputFormatter = CreateFormatter(); MediaTypeHeaderValue expectedMediaType = CreateMediaType(); ContentNegotiationResult negotiationResult = new ContentNegotiationResult(expectedOutputFormatter, expectedMediaType); Expression<Func<IEnumerable<MediaTypeFormatter>, bool>> formattersMatch = (f) => f != null && f.AsArray().Length == 1 && f.AsArray()[0] == expectedInputFormatter ? true : false; using (HttpRequestMessage expectedRequest = CreateRequest()) { Mock<IContentNegotiator> spy = new Mock<IContentNegotiator>(); spy.Setup(n => n.Negotiate(typeof(object), expectedRequest, It.Is(formattersMatch))).Returns( negotiationResult); IContentNegotiator contentNegotiator = spy.Object; using (HttpConfiguration configuration = CreateConfiguration(expectedInputFormatter, contentNegotiator)) { controller.Configuration = configuration; controller.Request = expectedRequest; IHttpActionResult result = new NegotiatedContentResult<object>(expectedStatusCode, expectedContent, controller); // Act Task<HttpResponseMessage> task = result.ExecuteAsync(CancellationToken.None); // Assert Assert.NotNull(task); task.WaitUntilCompleted(); using (HttpResponseMessage response = task.Result) { Assert.NotNull(response); Assert.Equal(expectedStatusCode, response.StatusCode); HttpContent content = response.Content; Assert.IsType<ObjectContent<object>>(content); ObjectContent<object> typedContent = (ObjectContent<object>)content; Assert.Same(expectedContent, typedContent.Value); Assert.Same(expectedOutputFormatter, typedContent.Formatter); Assert.NotNull(typedContent.Headers); Assert.Equal(expectedMediaType, typedContent.Headers.ContentType); Assert.Same(expectedRequest, response.RequestMessage); } } } }
public void ContentNegotiator_ForApiController_EvaluatesOnce() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); IContentNegotiator expectedContentNegotiator = CreateContentNegotiator(); ApiController controller = CreateController(); using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), expectedContentNegotiator)) using (HttpRequestMessage request = CreateRequest()) { controller.Configuration = configuration; controller.Request = request; NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content, controller); IContentNegotiator ignore = result.ContentNegotiator; configuration.Services.Replace(typeof(IContentNegotiator), CreateContentNegotiator()); // Act IContentNegotiator contentNegotiator = result.ContentNegotiator; // Assert Assert.Same(expectedContentNegotiator, contentNegotiator); } }
public void Request_ForApiController_EvaluatesOnce() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); ApiController controller = CreateController(); using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator())) { controller.Configuration = configuration; NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content, controller); using (HttpRequestMessage expectedRequest = CreateRequest()) { controller.Request = expectedRequest; HttpRequestMessage ignore = result.Request; using (HttpRequestMessage otherRequest = CreateRequest()) { controller.Request = otherRequest; // Act HttpRequestMessage request = result.Request; // Assert Assert.Same(expectedRequest, request); } } } }
public void Formatters_ForApiController_EvaluatesOnce() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); ApiController controller = CreateController(); MediaTypeFormatter expectedFormatter = CreateFormatter(); IContentNegotiator contentNegotiator = CreateContentNegotiator(); using (HttpConfiguration earlyConfiguration = CreateConfiguration(expectedFormatter, contentNegotiator)) using (HttpRequestMessage request = CreateRequest()) { controller.Configuration = earlyConfiguration; controller.Request = request; NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content, controller); IEnumerable<MediaTypeFormatter> ignore = result.Formatters; using (HttpConfiguration lateConfiguration = CreateConfiguration(CreateFormatter(), contentNegotiator)) { controller.Configuration = lateConfiguration; // Act IEnumerable<MediaTypeFormatter> formatters = result.Formatters; // Assert Assert.NotNull(formatters); Assert.Equal(1, formatters.Count()); Assert.Same(expectedFormatter, formatters.Single()); } } }
public void ContentNegotiator_ForApiController_Throws_WhenServiceIsNull() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); ApiController controller = CreateController(); using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), null)) using (HttpRequestMessage request = CreateRequest()) { controller.Configuration = configuration; NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content, controller); // Act & Assert Assert.Throws<InvalidOperationException>( () => { IContentNegotiator ignore = result.ContentNegotiator; }, "The provided configuration does not have an instance of the " + "'System.Net.Http.Formatting.IContentNegotiator' service registered."); } }
public void Request_ForApiController_Throws_WhenControllerRequestIsNull() { // Arrange HttpStatusCode statusCode = CreateStatusCode(); object content = CreateContent(); ApiController controller = CreateController(); Assert.Null(controller.Request); using (HttpConfiguration configuration = CreateConfiguration(CreateFormatter(), CreateContentNegotiator())) { controller.Configuration = configuration; NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(statusCode, content, controller); // Act & Assert InvalidOperationException exception = Assert.Throws<InvalidOperationException>(() => { HttpRequestMessage ignore = result.Request; }, "ApiController.Request must not be null."); } }
public void StatusCode_Returns_ValueProvided() { // Arrange HttpStatusCode expectedStatusCode = CreateStatusCode(); object content = CreateContent(); IContentNegotiator contentNegotiator = CreateContentNegotiator(); using (HttpRequestMessage request = CreateRequest()) { IEnumerable<MediaTypeFormatter> formatters = CreateFormatters(); NegotiatedContentResult<object> result = new NegotiatedContentResult<object>(expectedStatusCode, content, contentNegotiator, request, formatters); // Act HttpStatusCode statusCode = result.StatusCode; // Assert Assert.Equal(expectedStatusCode, statusCode); } }
public async Task NegotiatedContentResult_SetsStatusCode() { // Arrange var httpContext = new DefaultHttpContext(); httpContext.RequestServices = CreateServices(); var stream = new MemoryStream(); httpContext.Response.Body = stream; var context = new ActionContext(httpContext, new RouteData(), new ActionDescriptor()); var result = new NegotiatedContentResult<Product>(HttpStatusCode.Ambiguous, new Product()); // Act await result.ExecuteResultAsync(context); // Assert Assert.Equal(300, context.HttpContext.Response.StatusCode); }