Example #1
0
    public async Task ExecuteResultAsync_PassesCorrectValuesToRedirect(bool permanentRedirect)
    {
        // Arrange
        var expectedUrl = "SampleAction";

        var httpContext  = new Mock <HttpContext>();
        var httpResponse = new Mock <HttpResponse>();

        httpContext.SetupGet(c => c.RequestServices)
        .Returns(CreateServices());
        httpContext.SetupGet(c => c.Response)
        .Returns(httpResponse.Object);

        var actionContext = new ActionContext(
            httpContext.Object,
            new RouteData(),
            new ActionDescriptor());

        var urlHelper = GetUrlHelper(actionContext, expectedUrl);
        var result    = new RedirectToPageResult("/MyPage", null, new { id = 10, test = "value" }, permanentRedirect)
        {
            UrlHelper = urlHelper,
        };

        // Act
        await result.ExecuteResultAsync(actionContext);

        // Assert
        httpResponse.Verify(r => r.Redirect(expectedUrl, permanentRedirect), Times.Exactly(1));
    }
Example #2
0
        public void OnGet_AlreadyInitialzed_Redirect()
        {
            const string userName = "******";

            var Context = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseSqlite(CreateInMemoryDatabase())
                          .Options;

            IdentityUser user = new IdentityUser(userName);

            UserManager.CreateAsync(user);



            var tempBalance = new BalanceModel {
                BalanceAmount = 2000, OwnerID = UserID, OwnerName = "Test"
            };

            Context.BalanceModel.Add(tempBalance);

            //arrange
            var pageModel = new IndexModel(Context, AuthorizationService, UserManager);

            //act
            var result = pageModel.OnGet();

            //assert
            RedirectToPageResult redirect = result as RedirectToPageResult; //<--cast here

            Assert.Equal("/Dashbaord", redirect.PageName);
        }
Example #3
0
 public void ControllerPageTester_TestRedirectToPage_should_not_throw_exception_for_expected_PageName()
 {
     AssertExceptionNotThrown.WhenExecuting(() =>
     {
         RedirectToPageResult result =
             _pageTester.Action(x => x.RedirectToPageAction).TestRedirectToPage("testPageName");
         Assert.IsNotNull(result);
     });
 }
Example #4
0
    public async Task RedirectToPage_DoesNotUseAmbientHandler()
    {
        // Arrange
        var expected     = "path/to/this-page";
        var httpContext  = new Mock <HttpContext>();
        var httpResponse = new Mock <HttpResponse>();

        httpContext.SetupGet(c => c.Response)
        .Returns(httpResponse.Object);
        httpContext.SetupGet(c => c.RequestServices)
        .Returns(CreateServices());
        var routeData = new RouteData
        {
            Values =
            {
                ["page"]    = expected,
                ["handler"] = "delete",
            }
        };

        var actionContext = new ActionContext(
            httpContext.Object,
            routeData,
            new ActionDescriptor());

        UrlRouteContext context   = null;
        var             urlHelper = new Mock <IUrlHelper>();

        urlHelper.Setup(h => h.RouteUrl(It.IsAny <UrlRouteContext>()))
        .Callback((UrlRouteContext c) => context = c)
        .Returns("some-value");
        urlHelper.SetupGet(h => h.ActionContext)
        .Returns(actionContext);
        var pageName = (string)null;
        var result   = new RedirectToPageResult(pageName)
        {
            UrlHelper = urlHelper.Object,
        };

        // Act
        await result.ExecuteResultAsync(actionContext);

        // Assert
        Assert.NotNull(context);
        Assert.Collection(Assert.IsType <RouteValueDictionary>(context.Values),
                          value =>
        {
            Assert.Equal("page", value.Key);
            Assert.Equal(expected, value.Value);
        },
                          value =>
        {
            Assert.Equal("handler", value.Key);
            Assert.Null(value.Value);
        });
    }
Example #5
0
    public async Task ExecuteResultAsync_LocalRelativePaths()
    {
        // Arrange
        var httpContext = new DefaultHttpContext
        {
            RequestServices = CreateServices(),
        };

        var pageContext = new ActionContext
        {
            HttpContext      = httpContext,
            RouteData        = new RouteData(),
            ActionDescriptor = new ActionDescriptor(),
        };

        pageContext.RouteData.Values.Add("page", "/A/Redirecting/Page");

        UrlRouteContext context   = null;
        var             urlHelper = new Mock <IUrlHelper>();

        urlHelper.SetupGet(h => h.ActionContext).Returns(pageContext);
        urlHelper.Setup(h => h.RouteUrl(It.IsAny <UrlRouteContext>()))
        .Callback((UrlRouteContext c) => context = c)
        .Returns("some-value");
        var values = new { test = "test-value" };
        var result = new RedirectToPageResult("./", "page-handler", values, true, "test-fragment")
        {
            UrlHelper = urlHelper.Object,
            Protocol  = "ftp",
        };

        // Act
        await result.ExecuteResultAsync(pageContext);

        // Assert
        Assert.NotNull(context);
        Assert.Null(context.RouteName);
        Assert.Collection(Assert.IsType <RouteValueDictionary>(context.Values),
                          value =>
        {
            Assert.Equal("test", value.Key);
            Assert.Equal("test-value", value.Value);
        },
                          value =>
        {
            Assert.Equal("page", value.Key);
            Assert.Equal("/A/Redirecting", value.Value);
        },
                          value =>
        {
            Assert.Equal("handler", value.Key);
            Assert.Equal("page-handler", value.Value);
        });
        Assert.Equal("ftp", context.Protocol);
        Assert.Equal("test-fragment", context.Fragment);
    }
Example #6
0
 public void TestDetailsPageOnGetWithoutIDValue()
 {
     using (var context = new UserDbContext(MockRSVPUserDb.TestRSVPDbContextOptions()))
     {
         DetailsModel         dm    = new DetailsModel(context);
         var                  page  = dm.OnGet(null);
         RedirectToPageResult check = (RedirectToPageResult)page;
         Assert.Equal("/Dashboard", check.PageName);
     }
 }
Example #7
0
        public void DeleteAnAuthor_RedirectToPage_POST()
        {
            // arrange
            var mock2 = new Mock <IConfiguration>();
            var mock  = new Mock <ILibService>();
            AuthorController controller = new AuthorController(mock.Object, mock2.Object);
            // act
            RedirectToPageResult result = controller.RedirectToPage("DeleteAnAuthor");

            //assert
            Assert.IsNotNull(result);
            Assert.That(result.PageName, Is.EqualTo("DeleteAnAuthor"));
        }
        public void LogOutFunctionsProperly()
        {
            MockStoreContexts mock = new MockStoreContexts();
            LogoutModel       lm   = new LogoutModel(mock.SignInManager.Object);

            mock.SignInManager.Setup(x => x.SignOutAsync())
            .Returns(Task.CompletedTask);

            var result = lm.OnGet().Result;
            RedirectToPageResult check = (RedirectToPageResult)result;

            Assert.Equal("/", check.PageName);
        }
Example #9
0
        public void UpdateProgress_RedirectToPage_POST()
        {
            // arrange
            var            mock2      = new Mock <IConfiguration>();
            var            mock       = new Mock <ILibService>();
            BookController controller = new BookController(mock.Object, mock2.Object);
            // act
            RedirectToPageResult result = controller.RedirectToPage("UpdateProgress");

            //assert
            Assert.IsNotNull(result);
            Assert.That(result.PageName, Is.EqualTo("UpdateProgress"));
        }
Example #10
0
        public void Results_NoResults_WhenSearchStringIsNull()
        {
            using (var db = new ArtDbContext(TestingDbContextOptions.TestDbContextOptions()))
            {
                var controller = new SearchController(db);

                string searchTag = null;

                RedirectToPageResult result = (RedirectToPageResult)controller.Results(searchTag);


                Assert.AreEqual(result.PageName, "/Index");
            }
        }
Example #11
0
        public void Can_Checkout_And_Submit_Order()
        {
            Mock<IOrderRepository> mock = new Mock<IOrderRepository>();

            Cart cart = new Cart();
            cart.AddItem(new Article(), 1);

            OrderController target = new OrderController(mock.Object, cart);

            RedirectToPageResult result = target.Checkout(new Order())
                as RedirectToPageResult;

            Assert.Equal("/Completed", result.PageName);
        }
        public void Can_Checkout_And_Sumit_Order()
        {
            Mock <IOrderRepository> mock = new Mock <IOrderRepository>();
            Cart cart = new Cart();

            cart.AddItem(new Product(), 1);
            OrderController target = new OrderController(mock.Object, cart);

            RedirectToPageResult result = target.CheckOut(new Order()) as RedirectToPageResult;

            mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once);

            Assert.Equal("/Completed", result.PageName);
        }
        public void Can_Checkout_And_Submit_Order()
        {
            // Arrange:
            Mock <IOrderRepository> mock = new Mock <IOrderRepository>();
            Cart cart = new Cart();

            cart.AddItem(new Product(), 1);
            OrderController target = new OrderController(mock.Object, cart);
            // Act:
            RedirectToPageResult result = target.Checkout(new Order()) as RedirectToPageResult;

            // Assert - check that the order has been stored
            mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once);
            // Assert - check that the method is redirecting to the Completed action
            Assert.Equal("/Completed", result.PageName);
        }
        public void OnPageHandlerExecuting(PageHandlerExecutingContext context)
        {
            if (!context.HttpContext.Session.SessionExists(SessionKeys.SessionKey(SessionKeys.UserLoginModel)))
            {
                var result  = new RedirectToPageResult("/account/login");
                var request = context.HttpContext.Request;
                var url     = context.HttpContext.Request.Path + context.HttpContext.Request.QueryString.Value;
                var query   = context.HttpContext.Request.Query;
                var dict    = new Microsoft.AspNetCore.Routing.RouteValueDictionary(new { returnUrl = url });
                //foreach (var item in query.Keys)
                //{
                //    dict.Add(item, query[item]);
                //}

                result.RouteValues = dict;
                context.Result     = result;
            }
        }
        public void Can_Checkout_And_Submit_Order()
        {
            // arrange
            // create mock repository, create cart with one item, create instance of orderController
            Mock <IOrderRepository> mockOrderRepo = new Mock <IOrderRepository>();
            Cart cart = new Cart();

            cart.AddItem(new Product(), 1);
            OrderController target = new OrderController(mockOrderRepo.Object, cart);

            // act
            // try to check out - Checkout() fills the new order object from cart, then saves order to order repository, then redirects to "Completed" Razor page
            RedirectToPageResult result = target.Checkout(new Order()) as RedirectToPageResult;

            // assert
            // check order has been stored
            mockOrderRepo.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once);

            Assert.Equal("/Completed", result.PageName);
        }
Example #16
0
        public void Can_Checkout_And_Submit_Order()
        {
            // Arrange - create a mock order repository    
            Mock <IOrderRepository> mock = new Mock <IOrderRepository>();     

            // Arrange - create a cart with one item    
            Cart cart = new Cart();     

            cart.AddItem(new Product(), 1);     
            // Arrange - create an instance of the controller    
            OrderController target = new OrderController(mock.Object, cart);     

            // Act - try to checkout    
            RedirectToPageResult result = target.Checkout(new Order()) as RedirectToPageResult;     

            // Assert - check that the order has been stored    
            mock.Verify(m => m.SaveOrder(It.IsAny <Order>()), Times.Once);     
            // Assert - check that the method is redirecting to the Completed action    
            Assert.Equal("/Completed", result.PageName);
        }
        public void ContactModelOnPostValidModelState()
        {
            var EmailSender = new MockEmailSender();

            ContactModel contact = new ContactModel(EmailSender)
            {
                FirstName         = "Test Name",
                Email             = "*****@*****.**",
                Phone             = 1234567890,
                Reason            = EmailMessages.ContactType.Donate,
                AdditionalRemarks = "Additional Remarks"
            };

            //Check validity of the model
            MockValidation.CheckValidation(contact);
            var result = contact.OnPost().Result;
            RedirectToPageResult check = (RedirectToPageResult)result;

            Assert.Equal("/", check.PageName);
        }
Example #18
0
    public async Task ExecuteResultAsync_ThrowsOnNullUrl()
    {
        // Arrange
        var httpContext = new DefaultHttpContext
        {
            RequestServices = CreateServices(),
        };

        var actionContext = new ActionContext(httpContext, new RouteData(), new ActionDescriptor());

        var urlHelper = GetUrlHelper(actionContext, returnValue: null);
        var result    = new RedirectToPageResult("/some-page", new Dictionary <string, object>())
        {
            UrlHelper = urlHelper,
        };

        // Act & Assert
        await ExceptionAssert.ThrowsAsync <InvalidOperationException>(
            () => result.ExecuteResultAsync(actionContext),
            "No page named '/some-page' matches the supplied values.");
    }
        public virtual void Execute(ActionContext context, RedirectToPageResult result)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            var urlHelper      = result.UrlHelper ?? _urlHelperFactory.GetUrlHelper(context);
            var destinationUrl = urlHelper.Page(
                result.PageName,
                result.PageHandler,
                result.RouteValues,
                result.Protocol,
                result.Host,
                fragment: result.Fragment);

            if (string.IsNullOrEmpty(destinationUrl))
            {
                throw new InvalidOperationException(Resources.FormatNoRoutesMatchedForPage(result.PageName));
            }

            _logger.RedirectToPageResultExecuting(result.PageName);

            if (result.PreserveMethod)
            {
                context.HttpContext.Response.StatusCode = result.Permanent ?
                                                          StatusCodes.Status308PermanentRedirect : StatusCodes.Status307TemporaryRedirect;
                context.HttpContext.Response.Headers[HeaderNames.Location] = destinationUrl;
            }
            else
            {
                context.HttpContext.Response.Redirect(destinationUrl, result.Permanent);
            }
        }
Example #20
0
        public async void TestAdminLoginValidStateAndAdminUsesDefaultPassword()
        {
            MockStoreContexts mocks = new MockStoreContexts();

            mocks.UserManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>()))
            .ReturnsAsync(IdentityResult.Success);
            mocks.UserManager.Setup(x => x.FindByEmailAsync(It.IsAny <string>()))
            .ReturnsAsync(mocks.User);
            mocks.UserManager.Setup(x => x.IsInRoleAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>()))
            .ReturnsAsync(true);
            mocks.UserManager.Setup(x => x.AddToRoleAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>()))
            .ReturnsAsync(IdentityResult.Success);

            mocks.SignInManager.Setup(x => x.PasswordSignInAsync(
                                          It.IsAny <string>(), It.IsAny <string>(),
                                          It.IsAny <bool>(), It.IsAny <bool>()))
            .ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success);

            mocks.Configuration.Setup(x => x[It.IsAny <string>()])
            .Returns("Test2!");
            await mocks.UserManager.Object.CreateAsync(mocks.User, "Test2!");

            await mocks.UserManager.Object.AddToRoleAsync(mocks.User, ApplicationRoles.Admin);

            AdminLoginModel alm = new AdminLoginModel(mocks.UserManager.Object,
                                                      mocks.SignInManager.Object,
                                                      mocks.Configuration.Object)
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            MockValidation.CheckValidation(alm);
            var result = alm.OnPost().Result;
            RedirectToPageResult check = (RedirectToPageResult)result;

            Assert.Equal("/Change_Password", check.PageName);
        }
        public async void TestAddUserPageAddingAUserWithValidModelState()
        {
            using (var context = new UserDbContext(MockRSVPUserDb.TestRSVPDbContextOptions()))
            {
                Add_UserModel aum = new Add_UserModel(context)
                {
                    Agree                = true,
                    Name                 = "Test User",
                    Email                = "*****@*****.**",
                    PhoneNumber          = "0123456789",
                    IsVeteran            = true,
                    PreferredTime        = false,
                    IsWashingtonResident = true,
                    ChooseMaritalStatus  = MaritalStatus.SingleAndNeverDivorced,
                    SpouseName           = "N/A",
                    HasChildren          = false,
                    IsCurrentlyPregnant  = false,
                    MinorChildName       = "N/A",
                    ContRemBeneficiary   = WhoToInheritEstate.OtherPerson,
                    PersonToInherit      = WhoToInheritEstate.OtherPerson,
                    PersonalRep          = WhoToInheritEstate.OtherPerson,
                };

                //Checking DB is actually empty
                var result = await context.Users.ToListAsync();

                Assert.Empty(result);

                MockValidation.CheckValidation(aum);
                var page = await aum.OnPost();

                RedirectToPageResult check = (RedirectToPageResult)page;
                result = await context.Users.ToListAsync();

                Assert.Single(result);
                Assert.Equal("/Dashboard", check.PageName);
            }
        }
Example #22
0
        public void TestPasswordMatchingAndValidModelStateAndUserAndUpdates()
        {
            MockStoreContexts    mocks = new MockStoreContexts();
            Change_PasswordModel cpm   = new Change_PasswordModel(mocks.UserManager.Object, mocks.SignInManager.Object)
            {
                Name            = "*****@*****.**",
                Password        = "******",
                ConfirmPassword = "******"
            };

            mocks.UserManager.Setup(x => x.FindByNameAsync(It.IsAny <string>()))
            .ReturnsAsync(new ApplicationUser {
                PasswordHash = "abcdefg"
            });
            mocks.UserManager.Setup(x => x.UpdateAsync(It.IsAny <ApplicationUser>()))
            .ReturnsAsync(IdentityResult.Success);

            MockValidation.CheckValidation(cpm);
            var result = cpm.OnPostAsync().Result;
            RedirectToPageResult check = (RedirectToPageResult)result;

            Assert.Equal("/Dashboard", check.PageName);
        }
Example #23
0
        private async Task <ActionResult> LoadViewModelAsync(RedirectToPageResult redirectToPageResult = null)
        {
            if (CustomerId == Guid.Empty || ExcursionId == Guid.Empty)
            {
                return(RedirectToPage("/NotFound"));
            }

            Customer = await _customersQueryComponent.CustomerAsync(CustomerId);

            ExcursionDetail = await _productQueryComponent.ExcursionItemAsync(ExcursionId);

            if (Customer == null || ExcursionDetail == null)
            {
                return(RedirectToPage("/NotFound"));
            }

            if (redirectToPageResult != null)
            {
                return(redirectToPageResult);
            }

            return(Page());
        }
Example #24
0
        public void OnGet_IfFirstTime_Redirect()
        {
            const string userName = "******";

            var Context = new DbContextOptionsBuilder <ApplicationDbContext>()
                          .UseSqlite(CreateInMemoryDatabase())
                          .Options;

            IdentityUser user = new IdentityUser(userName);

            UserManager.CreateAsync(user);

            //arrange
            var pageModel = new IndexModel(Context, AuthorizationService, UserManager);

            //act
            var result = pageModel.OnGet();

            //assert
            RedirectToPageResult redirect = result as RedirectToPageResult; //<--cast here

            Assert.Equal("/Account/Balance/Create", redirect.PageName);
        }