public void WithContentHeadersDictionaryShouldPopulateCorrectHeaders()
        {
            var httpRequestMessage = MyWebApi
                                     .Controller <WebApiController>()
                                     .WithHttpRequestMessage(request => request
                                                             .WithStringContent(StringContent)
                                                             .WithContentHeaders(new Dictionary <string, IEnumerable <string> >
            {
                { TestHeader, new[] { TestHeaderValue, AnotherTestHeaderValue } },
            }))
                                     .AndProvideTheHttpRequestMessage();

            Assert.IsTrue(httpRequestMessage.Content.Headers.Contains(TestHeader));
            Assert.IsTrue(httpRequestMessage.Content.Headers.First(h => h.Key == TestHeader).Value.Contains(TestHeaderValue));
            Assert.IsTrue(httpRequestMessage.Content.Headers.First(h => h.Key == TestHeader).Value.Contains(AnotherTestHeaderValue));
        }
        public void WithStringContentAndActionShouldNotThrowExceptionWithCorrectAssertions()
        {
            var request = new HttpRequestMessage();

            request.Headers.Add("StringContent", "StringContent");

            MyWebApi
            .Controller <WebApiController>()
            .Calling(c => c.HttpResponseMessageWithStringContent())
            .ShouldReturn()
            .HttpResponseMessage()
            .WithStringContent(content =>
            {
                Assert.AreEqual("Test string", content);
            });
        }
Exemplo n.º 3
0
        public void WithHttpRequestMessageShouldPopulateCorrectRequestAndReturnOk()
        {
            var request = new HttpRequestMessage
            {
                Method = HttpMethod.Post
            };

            request.Headers.Add("TestHeader", "TestHeaderValue");

            MyWebApi
            .Controller <WebApiController>()
            .WithHttpRequestMessage(request)
            .Calling(c => c.CustomRequestAction())
            .ShouldReturn()
            .Ok();
        }
Exemplo n.º 4
0
        public void LinkGenerationShouldWorkCorrectlyWithCustomBaseAddress()
        {
            MyWebApi
            .IsUsingDefaultHttpConfiguration(TestObjectFactory.GetCustomInlineConstraintResolver())
            .WithBaseAddress("http://mytestedasp.net");

            MyWebApi
            .Controller <WebApiController>()
            .Calling(c => c.WithGeneratedLink(1))
            .ShouldReturn()
            .Created()
            .AtLocation("http://mytestedasp.net/api/test?id=1");

            RemoteServer.DisposeGlobal();
            MyWebApi.IsUsing(TestObjectFactory.GetHttpConfigurationWithRoutes());
        }
 public void WithAuthenticationHeaderChallengesShouldThrowExceptionWhenResultDoesNotContainExactlyAllProvidedHeadersWithWrongDataAndBuilder()
 {
     MyWebApi
     .Controller <WebApiController>()
     .Calling(c => c.UnauthorizedActionWithChallenges())
     .ShouldReturn()
     .Unauthorized()
     .WithAuthenticationHeaderChallenges(
         authHeaders =>
         authHeaders
         .ContainingHeader(header => header.WithScheme("TestScheme").WithParameter("TestParameter"))
         .AndAlso()
         .ContainingHeader(header => header.WithScheme("YetAnotherScheme").WithParameter("YetAnotherParameter"))
         .AndAlso()
         .ContainingHeader(header => header.WithScheme("Scheme")));
 }
Exemplo n.º 6
0
        public void WithModelStateShouldThrowExceptionWhenModelStateHasMoreErrors()
        {
            var requestModelWithErrors = TestObjectFactory.GetRequestModelWithErrors();
            var modelState             = new ModelStateDictionary();

            modelState.AddModelError("Integer", "The field Integer must be between 1 and 2147483647.");
            modelState.AddModelError("RequiredString", "The RequiredString field is not required.");
            modelState.AddModelError("RequiredString", "The RequiredString field is required.");

            MyWebApi
            .Controller <WebApiController>()
            .Calling(c => c.BadRequestWithModelState(requestModelWithErrors))
            .ShouldReturn()
            .BadRequest()
            .WithModelState(modelState);
        }
 public void AddRatingShouldAddARatingAndReturnItsInt()
 {
     MyWebApi
     .Controller <UserRatingsController>()
     .WithResolvedDependencies(DummyServices.GetDummyUserRatingsService())
     .Calling(c => c.AddRating(new UserRatingResponseModel
     {
         ClientId = "Test",
         HitmanId = "Test2",
         Rating   = 1
     }))
     .ShouldReturn()
     .Ok()
     .WithResponseModelOfType <int>()
     .Passing(r => r == DummyRepositories.NumberOfTestObjects - 1);
 }
Exemplo n.º 8
0
        public void ContainingFormattersShouldNotThrowExceptionWhenActionResultHasCorrectMediaTypeFormattersAsParams()
        {
            var mediaTypeFormatters = TestObjectFactory.GetFormatters().ToList();

            MyWebApi
            .Controller <WebApiController>()
            .Calling(c => c.OkResultWithContentNegotiatorAction())
            .ShouldReturn()
            .Ok()
            .ContainingMediaTypeFormatters(
                mediaTypeFormatters[0],
                mediaTypeFormatters[1],
                mediaTypeFormatters[2],
                mediaTypeFormatters[3],
                mediaTypeFormatters[4]);
        }
Exemplo n.º 9
0
        public void IsUsingShouldOverrideTheDefaultConfiguration()
        {
            // run two test cases in order to check the configuration is global
            var configs = new List <HttpConfiguration>();

            for (int i = 0; i < 2; i++)
            {
                var controller   = MyWebApi.Controller <WebApiController>().Controller;
                var actualConfig = controller.Configuration;

                Assert.IsNotNull(actualConfig);
                configs.Add(actualConfig);
            }

            Assert.AreSame(configs[0], configs[1]);
        }
Exemplo n.º 10
0
        public void GET_profiles_name_Should_Return_Named_User_Profile()
        {
            MyWebApi
            .Routes()
            .ShouldMap("api/profiles/Wizard")
            .To <ProfilesController>(c => c.GetProfileByName("Wizard"));

            MyWebApi
            .Controller <ProfilesController>()
            .WithTestRig(rig)
            .WithAuthenticatedUser(rig.WizardUser())
            .Calling(c => c.GetProfileByName("Wizard"))
            .ShouldReturn()
            .Ok()
            .WithResponseModelOfType <ProfileDto>()
            .Passing(dto => dto.Name == "Wizard" && dto.Uri.EndsWith("/api/profiles/Wizard"));
        }
        public void ShouldHavePostAttribute()
        {
            var member = new Membership(12)
            {
                Id      = 0,
                FkHotel = 9,
                Price   = 1200.000M
            };

            // tests whether action has specific attribute type
            MyWebApi
            .Controller <MembershipController>()
            .Calling(c => c.Post(member))
            .ShouldHave()
            .ActionAttributes(attributes => attributes
                              .ContainingAttributeOfType <HttpPostAttribute>());
        }
Exemplo n.º 12
0
        public void AndProvideShouldReturnProperHttpRequestMessage()
        {
            var httpRequestMessage = MyWebApi
                                     .Controller <WebApiController>()
                                     .WithHttpRequestMessage(request
                                                             => request
                                                             .WithMethod(HttpMethod.Get)
                                                             .WithHeader("TestHeader", "TestHeaderValue"))
                                     .Calling(c => c.HttpResponseMessageAction())
                                     .ShouldReturn()
                                     .HttpResponseMessage()
                                     .AndProvideTheHttpRequestMessage();

            Assert.IsNotNull(httpRequestMessage);
            Assert.AreEqual(HttpMethod.Get, httpRequestMessage.Method);
            Assert.IsTrue(httpRequestMessage.Headers.Contains("TestHeader"));
        }
 public void ContainingContentHeadersShouldNotThrowExceptionWithCorrectDictionaryOfHeadersWithInvalidCount()
 {
     MyWebApi
     .Controller <WebApiController>()
     .Calling(c => c.HttpResponseMessageAction())
     .ShouldReturn()
     .HttpResponseMessage()
     .ContainingContentHeaders(new Dictionary <string, IEnumerable <string> >
     {
         { "TestHeader", new List <string> {
               "TestHeaderValue"
           } },
         { "AnotherTestHeader", new List <string> {
               "TestHeaderValue"
           } }
     });
 }
        public async Task DeletingImagesShouldWorkCorrectly()
        {
            var dummyImageService  = DummyServices.GetDummyImagesService();
            var currentImagesCount = dummyImageService.All().Count();

            var result = await MyWebApi
                         .Controller <ImagesController>()
                         .WithResolvedDependencies(dummyImageService)
                         .Calling(c => c.Delete(3))
                         .ShouldReturn()
                         .ResultOfType <Task <IHttpActionResult> >()
                         .AndProvideTheModel();

            var newImageCount = dummyImageService.All().Count();

            Assert.IsTrue(newImageCount == currentImagesCount - 1);
        }
 public void GetWithBothBiggerShouldReturnFiltered()
 {
     MyWebApi
     .Controller <CommentsController>()
     .WithResolvedDependencies(Services.GetCommentServices())
     .Calling(c => c.Get("TestUser 1", new QueryRealEstates()
     {
         Skip = 3, Take = 3
     }))
     .ShouldReturn()
     .Ok()
     .WithResponseModelOfType <List <CommentResponseModel> >()
     .Passing(model =>
     {
         Assert.AreEqual(0, model.Count);
     });
 }
        public void WithoutAnyConfigurationShouldInstantiateDefaultOne()
        {
            MyWebApi.IsUsing(null);

            var config = MyWebApi
                         .Controller <WebApiController>()
                         .WithHttpRequestMessage(request => request.WithMethod(HttpMethod.Get))
                         .Calling(c => c.CustomRequestAction())
                         .ShouldReturn()
                         .BadRequest()
                         .AndProvideTheController()
                         .Configuration;

            Assert.IsNotNull(config);

            MyWebApi.IsUsing(TestObjectFactory.GetHttpConfigurationWithRoutes());
        }
        public void CallingShouldHaveValidModelStateWhenThereAreNoModelErrors()
        {
            var requestModel = TestObjectFactory.GetValidRequestModel();

            var controller = MyWebApi
                             .Controller <WebApiController>()
                             .Calling(c => c.OkResultActionWithRequestBody(1, requestModel))
                             .ShouldReturn()
                             .Ok()
                             .AndProvideTheController();

            var modelState = controller.ModelState;

            Assert.IsTrue(modelState.IsValid);
            Assert.AreEqual(0, modelState.Values.Count);
            Assert.AreEqual(0, modelState.Keys.Count);
        }
        public void WithAuthenticatedNotCalledShouldNotHaveAuthorizedUser()
        {
            var controllerBuilder = MyWebApi
                                    .Controller <WebApiController>();

            controllerBuilder
            .Calling(c => c.AuthorizedAction())
            .ShouldReturn()
            .NotFound();

            var controllerUser = controllerBuilder.AndProvideTheController().User;

            Assert.AreEqual(false, controllerUser.IsInRole("Any"));
            Assert.AreEqual(null, controllerUser.Identity.Name);
            Assert.AreEqual(null, controllerUser.Identity.AuthenticationType);
            Assert.AreEqual(false, controllerUser.Identity.IsAuthenticated);
        }
        public void WithAuthenticatedUserUsingPrincipalShouldWorkCorrectly()
        {
            var controllerBuilder = MyWebApi
                                    .Controller <WebApiController>();

            controllerBuilder
            .WithAuthenticatedUser(TestObjectFactory.GetClaimsPrincipal())
            .Calling(c => c.AuthorizedAction())
            .ShouldReturn()
            .NotFound();

            var controllerUser = controllerBuilder.AndProvideTheController().User;

            Assert.AreEqual("CustomUser", controllerUser.Identity.Name);
            Assert.AreEqual(null, controllerUser.Identity.AuthenticationType);
            Assert.IsFalse(controllerUser.Identity.IsAuthenticated);
        }
 public void GetShouldReturnOkWhenProjectIsNotNull()
 {
     MyWebApi
     .Controller <ProjectsController>()
     .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService())
     .WithAuthenticatedUser()
     .Calling(c => c.Get("Valid"))
     .ShouldReturn()
     .Ok()
     .WithResponseModelOfType <SoftwareProjectDetailsResponseModel>()
     .Passing(pr =>
     {
         Assert.AreEqual(new DateTime(2015, 11, 5, 23, 47, 12), pr.CreatedOn);
         Assert.AreEqual("Test", pr.Name);
         Assert.AreEqual(0, pr.TotalUsers);
     });
 }
        public void CallingShouldPopulateModelStateWhenThereAreModelErrors()
        {
            var requestModel = TestObjectFactory.GetRequestModelWithErrors();

            var controller = MyWebApi
                             .Controller <WebApiController>()
                             .Calling(c => c.OkResultActionWithRequestBody(1, requestModel))
                             .ShouldReturn()
                             .Ok()
                             .AndProvideTheController();

            var modelState = controller.ModelState;

            Assert.IsFalse(modelState.IsValid);
            Assert.AreEqual(2, modelState.Values.Count);
            Assert.AreEqual("Integer", modelState.Keys.First());
            Assert.AreEqual("RequiredString", modelState.Keys.Last());
        }
        public void WithHttpConfigurationShouldOverrideTheDefaultOne()
        {
            var config = new HttpConfiguration();

            var controllerConfig = MyWebApi
                                   .Controller <WebApiController>()
                                   .WithHttpConfiguration(config)
                                   .AndProvideTheController()
                                   .Configuration;

            var controllerConfigFromApi = MyWebApi
                                          .Controller <WebApiController>()
                                          .WithHttpConfiguration(config)
                                          .AndProvideTheHttpConfiguration();

            Assert.AreSame(config, controllerConfig);
            Assert.AreSame(config, controllerConfigFromApi);
        }
        public void Initialize()
        {
            userManager         = new UserManager(new UserRepository(new EFDbContext(ContextEnum.BeatBuddyTest)));
            organisationManager = new OrganisationManager(new OrganisationRepository(new EFDbContext(ContextEnum.BeatBuddyTest)));
            user = userManager.CreateUser("*****@*****.**", "matthias", "test", "acidshards", "");

            _organisationControllerWithAuthenticatedUser = MyWebApi.Controller <OrganisationsController>()
                                                           .WithResolvedDependencyFor <IUserManager>(userManager)
                                                           .WithResolvedDependencyFor <IOrganisationManager>(organisationManager)
                                                           .WithAuthenticatedUser(
                u => u.WithIdentifier("NewId")
                .WithUsername(user.Email)
                .WithClaim(new System.Security.Claims.Claim(System.Security.Claims.ClaimTypes.Email, user.Email))
                .WithClaim(new System.Security.Claims.Claim("sub", user.Email))
                );

            organisation = organisationManager.CreateOrganisation("testorganisatie", "", user);
        }
Exemplo n.º 24
0
        public void WithAuthenticatedUserShouldPopulateUserPropertyWithDefaultValues()
        {
            var controllerBuilder = MyWebApi
                                    .Controller <WebApiController>()
                                    .WithAuthenticatedUser();

            controllerBuilder
            .Calling(c => c.AuthorizedAction())
            .ShouldReturn()
            .Ok();

            var controllerUser = controllerBuilder.AndProvideTheController().User;

            Assert.AreEqual(false, controllerUser.IsInRole("Any"));
            Assert.AreEqual("TestUser", controllerUser.Identity.Name);
            Assert.AreEqual("Passport", controllerUser.Identity.AuthenticationType);
            Assert.AreEqual(true, controllerUser.Identity.IsAuthenticated);
        }
        public void WithContentHeaderAndMultipleValuesShouldPopulateCorrectHeader()
        {
            var headers = new[]
            {
                TestHeaderValue, AnotherTestHeaderValue
            };

            var httpRequestMessage = MyWebApi
                                     .Controller <WebApiController>()
                                     .WithHttpRequestMessage(request => request
                                                             .WithStringContent(StringContent)
                                                             .WithContentHeader(TestHeader, headers))
                                     .AndProvideTheHttpRequestMessage();

            Assert.IsTrue(httpRequestMessage.Content.Headers.Contains(TestHeader));
            Assert.IsTrue(httpRequestMessage.Content.Headers.First(h => h.Key == TestHeader).Value.Contains(TestHeaderValue));
            Assert.IsTrue(httpRequestMessage.Content.Headers.First(h => h.Key == TestHeader).Value.Contains(AnotherTestHeaderValue));
        }
        public async Task PostingImagesShouldCreateAnImageAndReturnItsId()
        {
            Random random = new Random();

            var result = await MyWebApi
                         .Controller <ImagesController>()
                         .WithResolvedDependencies(DummyServices.GetDummyImagesService())
                         .Calling(c => c.Post(new ImageRequestModel()
            {
                Name      = "SUPER COOL TEST IMAGE",
                Extension = "gif",
                Data      = "R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==",
                UserId    = "1",
            }))
                         .ShouldReturn()
                         .ResultOfType <Task <IHttpActionResult> >()
                         .AndProvideTheModel();

            //.WithResponseModelOfType<int>()
            //.Passing(c => c == DummyRepositories.NumberOfTestObjects + 1);
        }
Exemplo n.º 27
0
 public void AtLocationWithBuilderShouldNotThrowExceptionIfTheLocationIsCorrect()
 {
     MyWebApi
     .Controller <WebApiController>()
     .Calling(c => c.RedirectActionWithUri())
     .ShouldReturn()
     .Redirect()
     .AtLocation(location =>
                 location
                 .WithHost("somehost.com")
                 .AndAlso()
                 .WithAbsolutePath("/someuri/1")
                 .AndAlso()
                 .WithPort(80)
                 .AndAlso()
                 .WithScheme("http")
                 .AndAlso()
                 .WithFragment(string.Empty)
                 .AndAlso()
                 .WithQuery("?query=Test"));
 }
        public void WithSetupShouldSetCorrectPropertiesToController()
        {
            var actionContext = new HttpActionContext();
            var user          = TestObjectFactory.GetClaimsPrincipal();
            var config        = new HttpConfiguration();

            var controller = MyWebApi
                             .Controller <WebApiController>()
                             .WithSetup(c =>
            {
                c.ActionContext = actionContext;
                c.User          = user;
                c.Configuration = config;
            })
                             .AndProvideTheController();

            Assert.NotNull(controller);
            Assert.AreSame(actionContext, controller.ActionContext);
            Assert.AreSame(user, controller.User);
            Assert.AreSame(config, controller.Configuration);
        }
        public void PostShouldValidateModelState()
        {
            MyWebApi
            .Controller <ProjectsController>()
            .WithResolvedDependencyFor(TestObjectFactory.GetProjectsService())
            .Calling(c => c.Post(TestObjectFactory.GetInvalidModel()))
            .ShouldHave()
            .InvalidModelState();


            //var controller = new ProjectsController(TestObjectFactory.GetProjectsService());
            //controller.Configuration = new HttpConfiguration();

            //var model = TestObjectFactory.GetInvalidModel();

            //controller.Validate(model);

            //var result = controller.Post(model);

            //Assert.IsFalse(controller.ModelState.IsValid);
        }
        public void AndAlsoShouldBuildCorrectHttpRequestMessage()
        {
            var httpRequestMessage = MyWebApi
                                     .Controller <WebApiController>()
                                     .WithHttpRequestMessage(request
                                                             => request
                                                             .WithMethod("GET")
                                                             .AndAlso()
                                                             .WithRequestUri(RequestUri)
                                                             .AndAlso()
                                                             .WithVersion("1.1")
                                                             .AndAlso()
                                                             .WithStringContent(StringContent))
                                     .AndProvideTheHttpRequestMessage();

            Assert.AreEqual(HttpMethod.Get, httpRequestMessage.Method);
            Assert.AreEqual(new Uri(RequestUri), httpRequestMessage.RequestUri);
            Assert.AreEqual(new Version(1, 1), httpRequestMessage.Version);
            Assert.IsAssignableFrom <StringContent>(httpRequestMessage.Content);
            Assert.AreEqual(StringContent, httpRequestMessage.Content.ReadAsStringAsync().Result);
        }