Пример #1
0
        public void Setup()
        {
            this.HttpContext = new Mock <HttpContextBase>();

            var request  = new Mock <HttpRequestBase>();
            var response = new Mock <HttpResponseBase>();
            var session  = new MockHttpSession();
            var server   = new Mock <HttpServerUtilityBase>();

            this.HttpContext.Setup(ctx => ctx.Request).Returns(request.Object);
            this.HttpContext.Setup(ctx => ctx.Response).Returns(response.Object);
            this.HttpContext.Setup(ctx => ctx.Session).Returns(session);
            this.HttpContext.Setup(ctx => ctx.Server).Returns(server.Object);
            this.HttpContext.Setup(ctx => ctx.Items).Returns(new Dictionary <string, object>());

            var defaultCollection = new List <KeyValuePair <string, object> >
            {
                new KeyValuePair <string, object>("default-1", new TestEntry {
                    Name = "Test Entry 1"
                }),
                new KeyValuePair <string, object>("default-2", new TestEntry {
                    Name = "Test Entry 2"
                }),
                new KeyValuePair <string, object>("default-3", new TestEntry {
                    Name = "Test Entry 3"
                })
            };

            this.SessionCache = new SessionCache(this.HttpContext.Object, defaultCollection);
        }
        public void TestDecreaseAmountOnProductLine()
        {
            // Arrange
            var context = new Mock <ControllerContext>();
            var session = new MockHttpSession();

            List <ProductLine> productLineList = new List <ProductLine>();

            ShoppingCartController cartController = new ShoppingCartController();

            cartController.ControllerContext = context.Object;

            Product product = new Product();

            product.ProductId = 1;
            product.Price     = 100;

            ProductLine productLine = new ProductLine();

            productLine.Amount  = 1;
            productLine.Product = product;

            productLineList.Add(productLine);
            session.insertIntoDictionary("shoppingCart", productLineList);

            context.Setup(m => m.HttpContext.Session).Returns(session);

            // Act
            cartController.Add(product);
            cartController.DecreaseAmount(productLine.Product.ProductId);

            // Assert
            Assert.AreEqual(1, productLine.Amount);
        }
Пример #3
0
        public void HasSessionExpired_throws_expection_when_session_is_null()
        {
            //Arrange
            //Mocking a session
            MockHttpSession mockSession = new MockHttpSession();

            mockSession["Key"] = "KeySession";

            HttpContext httpContext = new DefaultHttpContext()
            {
                Session = mockSession
            };

            _contextAccessor.HttpContext = httpContext;

            var controller = new AuthController(_configuration, _contextAccessor, multitenantService)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        Session = mockSession
                    }
                }
            };

            //Act and Assert
            Assert.Throws <KeyNotFoundException>(() => controller.HasSessionExpired()); //Asserting that the expection thrown is KeyNotFound
        }
Пример #4
0
        public void HasSessionExpired_returns_false_when_session_found()
        {
            //Arrange
            //Mocking a session
            MockHttpSession mockSession = new MockHttpSession();

            mockSession["ModuleOperations"] = JsonConvert.SerializeObject("modules");

            var controller = new AuthController(_configuration, _contextAccessor, multitenantService)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        Session = mockSession
                    }
                }
            };

            //Act
            var result = controller.HasSessionExpired();

            //Assert
            var viewResult = Assert.IsType <bool>(result);

            Assert.False(viewResult);
        }
        private DashboardController ConfigureController()
        {
            //Mocking the user claims
            var claims = new List <Claim> {
                new Claim("CreatedOn", DateTime.UtcNow.ToString()),
                new Claim("Email", "*****@*****.**"),
                new Claim("Initials", "JD"),
                new Claim("Name", "John Doe"),
                new Claim("Role", "Admin"),
                new Claim("UserId", Guid.NewGuid().ToString()),
                new Claim("Username", "SomeUserName"),
                new Claim("IsAuthenticated", "True")
            };
            var             userIdentity = new ClaimsIdentity(claims, "Auth");
            ClaimsPrincipal principal    = new ClaimsPrincipal(userIdentity);

            //Mocking a session
            MockHttpSession mockSession = new MockHttpSession();

            mockSession["Key"] = "KeySession";

            var controller = new DashboardController()
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        User = principal, Session = mockSession
                    }
                }
            };

            return(controller);
        }
Пример #6
0
        public void Initialize()
        {
            controller = new LoginControllerMock();
            userTest   = new LoginViewModel()
            {
                UserName = userName, Password = password
            };
            response = new User()
            {
                UserName = userName, Password = password, Roles = new List <RolesEnum>()
                {
                    RolesEnum.PAGE_1
                }
            };
            invalidResponse = new User()
            {
                UserName = null, Password = null
            };
            sessionMock     = new MockHttpSession();
            contextMock     = new Mock <ControllerContext>();
            httpServiceMock = new Mock <IHttpService>();

            contextMock.Setup(m => m.HttpContext.Session).Returns(sessionMock);
            controller.ControllerContext = contextMock.Object;
            controller.http = httpServiceMock.Object;
        }
Пример #7
0
        public AuthControllerTests()
        {
            authClient            = A.Fake <IOpenIdConnectClient>();
            log                   = A.Fake <ILogger <AuthController> >();
            defaultVersionedFiles = A.Fake <IVersionedFiles>();
            defaultConfiguration  = A.Fake <IConfiguration>();
            var requestServices = A.Fake <IServiceProvider>();

            defaultAuthService = A.Fake <IAuthenticationService>();
            session            = new MockHttpSession();
            baseUrlService     = A.Fake <IBaseUrlService>();
            defaultUrlHelper   = A.Fake <IUrlHelper>();
            A.CallTo(() => defaultAuthService.SignInAsync(A <HttpContext> .Ignored, A <string> .Ignored, A <ClaimsPrincipal> .Ignored, A <AuthenticationProperties> .Ignored)).Returns(Task.CompletedTask);

            A.CallTo(() => requestServices.GetService(typeof(IAuthenticationService))).Returns(defaultAuthService);

            A.CallTo(() => baseUrlService.GetBaseUrl(A <HttpRequest> .Ignored, A <IUrlHelper> .Ignored))
            .Returns(baseAddress);

            defaultContext = new DefaultHttpContext
            {
                RequestServices = requestServices,
                Session         = session,
                Request         = { Headers = { new KeyValuePair <string, StringValues>("Referer", refererUrl) } },
            };

            defaultsettings = Options.Create(new AuthSettings
            {
                Audience           = "audience",
                ClientSecret       = "clientSecret123456",
                Issuer             = "issuer",
                DefaultRedirectUrl = "test",
                AuthDssEndpoint    = "test/{url}",
            });

            defaultSettings = Options.Create(new OpenIDConnectSettings
            {
                RedirectUrl        = "test/",
                SignOutRedirectUrl = "test/",
                Issuer             = "issuer",
                AuthdUrl           = "auth",
                AuthorizeUrl       = "AuthorizeUrl",
                ClientId           = "clientid",
                EndSessionUrl      = "Endsesison",
                JWK      = "jjjjjjfhfjjfjfjfjfhfjkhdfkhdfkjhskfhsldkjhfskdljfhsdlkfhsdflksdhsdlkfh",
                Exponent = "AQAB",
            });

            tokenHandler         = A.Fake <SecurityTokenHandler>();
            configurationManager = A.Fake <IConfigurationManager <OpenIdConnectConfiguration> >();
            A.CallTo(() => configurationManager.GetConfigurationAsync(CancellationToken.None)).Returns(
                new OpenIdConnectConfiguration
            {
                AuthorizationEndpoint = "auth",
                EndSessionEndpoint    = "end",
                Issuer = "issuer",
            });

            _urlHelper = A.Fake <IUrlHelper>();
        }
Пример #8
0
            //Arrange Controller...
            public MyControllerTesting()
            {
                var session = new MockHttpSession();
                var context = new Mock <ControllerContext>();

                context.Setup(m => m.HttpContext.Session).Returns(session);
                ControllerContext = context.Object;
            }
Пример #9
0
 public void Cleanup()
 {
     httpServiceMock            = null;
     controller.Session["user"] = null;
     controller  = null;
     sessionMock = null;
     contextMock = null;
 }
        private static ISession MockHttpContext()
        {
            MockHttpSession httpcontext = new MockHttpSession();

            httpcontext.Set <string>(SessionConstants.EmailClaim, RoleGridControllerTests.UserEmail);
            httpcontext.Set <string>(SessionConstants.WebServicesUrl, RoleGridControllerTests.Endpoint);
            httpcontext.Set <string>(SessionConstants.EncodedUserId, RoleGridControllerTests._user.Id.ToString().Base64Encode());
            httpcontext.Set <UserModel>(SessionConstants.CurrentUser, RoleGridControllerTests._user);
            return(httpcontext);
        }
        public virtual void When_Using_Home_Controller()
        {
            mockHttpContext = new Mock <HttpContext>();

            mockSession  = new MockHttpSession();
            tempDataMock = new Mock <ITempDataDictionary>();

            _controller          = new HomeController();
            _controller.TempData = tempDataMock.Object;
        }
        private static ISession MockHttpContext()
        {
            MockHttpSession httpcontext = new MockHttpSession();

            httpcontext.Set <string>(SessionConstants.EmailClaim, MenuItemsViewComponentTests.UserEmail);
            httpcontext.Set <string>(SessionConstants.WebServicesUrl, MenuItemsViewComponentTests.Endpoint);
            httpcontext.Set <MainMenuModels>(SessionConstants.TopLevelMenuItems, null);
            httpcontext.Set <string>(SessionConstants.EncodedUserId, MenuItemsViewComponentTests._user.Id.ToString().Base64Encode());
            httpcontext.Set <UserModel>(SessionConstants.CurrentUser, MenuItemsViewComponentTests._user);
            return(httpcontext);
        }
        public void TestInit()
        {
            var mockTickets = new Mock<ITicketsService>();
            mockTickets.Setup(x => x.HasQuantity(It.IsAny<int>(), 1)).Returns(true);

            var mockSession = new MockHttpSession();

            var sessionAdapter = new Mock<ISessionAdapter>();
            sessionAdapter.Setup(x => x.Session).Returns(mockSession);

            this.shoppingCart = new ShoppingCartService(mockTickets.Object, sessionAdapter.Object);
        }
Пример #14
0
        public void EnglishChangesIntoUkrainian()
        {
            // lets make fake httpcontext using reflection
            var httpRequest  = new HttpRequest(string.Empty, "http://mySomething/", string.Empty);
            var stringWriter = new StringWriter();
            var httpResponce = new HttpResponse(stringWriter);
            var httpContext  = new HttpContext(httpRequest, httpResponce);

            var sessionContainer = new HttpSessionStateContainer(
                "id",
                new SessionStateItemCollection(),
                new HttpStaticObjectsCollection(),
                10,
                true,
                HttpCookieMode.AutoDetect,
                SessionStateMode.InProc,
                false);

            httpContext.Items["AspSession"] =
                typeof(HttpSessionState).GetConstructor(
                    BindingFlags.NonPublic | BindingFlags.Instance,
                    null,
                    CallingConventions.Standard,
                    new[] { typeof(HttpSessionStateContainer) },
                    null).Invoke(new object[] { sessionContainer });

            HttpContext.Current = httpContext;
            IWindsorContainer container = new WindsorContainer();

            InitializeWindsor(ref container);
            AccountController pc = null;

            try
            {
                pc = new AccountController(new DatabaseUserStorage(container.Resolve <ILmsService>()));
            }
            catch (Exception)
            {
            }

            var context = new Mock <ControllerContext>();

            var session = new MockHttpSession();

            context.Setup(m => m.HttpContext.Session).Returns(session);

            var storage = new DatabaseUserStorage(null); // returns null but we don't need it

            pc.ControllerContext = context.Object;
            var result = pc.ChangeCulture("uk-UA", "/") as ViewResult;

            Assert.AreEqual("uk-UA", pc.Session["Culture"].ToString());
        }
Пример #15
0
        private UsersController ConfigureController(bool isClaims, bool isSession, List <Module> modules)
        {
            var             controller = new UsersController(_bosAuthClient, _bosEmailClient, _configuration);
            ClaimsPrincipal principal  = new ClaimsPrincipal();

            if (isClaims)
            {
                //Mocking the user claims
                var claims = new List <Claim> {
                    new Claim("CreatedOn", DateTime.UtcNow.ToString()),
                    new Claim("Email", "*****@*****.**"),
                    new Claim("Initials", "JD"),
                    new Claim("Name", "John Doe"),
                    new Claim("Role", "Admin"),
                    new Claim("UserId", Guid.NewGuid().ToString()),
                    new Claim("Username", "SomeUserName"),
                    new Claim("IsAuthenticated", "True")
                };

                var userIdentity = new ClaimsIdentity(claims, "Auth");
                principal = new ClaimsPrincipal(userIdentity);

                controller = new UsersController(_bosAuthClient, _bosEmailClient, _configuration)
                {
                    ControllerContext = new ControllerContext()
                    {
                        HttpContext = new DefaultHttpContext()
                        {
                            User = principal
                        }
                    }
                };
            }

            if (isSession)
            {
                //Mocking a session
                MockHttpSession mockSession = new MockHttpSession();
                mockSession["ModuleOperations"] = JsonConvert.SerializeObject(modules);

                controller = new UsersController(_bosAuthClient, _bosEmailClient, _configuration)
                {
                    ControllerContext = new ControllerContext()
                    {
                        HttpContext = new DefaultHttpContext()
                        {
                            User = principal, Session = mockSession
                        }
                    }
                };
            }
            return(controller);
        }
        public void Get_WhenCalled_ReturnsAllItems()
        {
            var cartID          = "9b3df90a-1007-4778-b614-91df990e0c95";
            var mockHttpContext = MockHttpSession.setSessionKey(cartID);

            _controller.ControllerContext.HttpContext = mockHttpContext.Object;
            // Act
            var okResult = _controller.Get().Result;
            // Assert
            var items = Assert.IsType <List <ShoppingCartDto> >(okResult.Value);

            Assert.Equal(3, items.Count);
        }
        public void Remove_ExistingGuidPassed_ReturnsOkResult()
        {
            var    cartID          = "9b3df90a-1007-4778-b614-91df990e0c95";
            string id              = "e3656e5b-23df-4ced-a7e4-4b066839f54a";
            var    mockHttpContext = MockHttpSession.setSessionKey(cartID);

            _controller.ControllerContext.HttpContext = mockHttpContext.Object;
            // Act
            var okResponse = _controller.DeleteItemFromSC(id);

            // Assert
            Assert.IsType <OkResult>(okResponse);
        }
Пример #18
0
        public static Mock <ControllerContext> GetContextBase()
        {
            var fakeHttpContext = new Mock <System.Web.HttpContextBase>();
            var session         = new MockHttpSession();

            fakeHttpContext.Setup(ctx => ctx.Session).Returns(session);

            var controllerContext = new Mock <ControllerContext>();

            controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);

            return(controllerContext);
        }
Пример #19
0
        public void Then_Url_Must_Be_CliendId()
        {
            mockSession = new MockHttpSession();
            mockHttpContext.Setup(s => s.Session).Returns(mockSession);
            _controller.ControllerContext.HttpContext = mockHttpContext.Object;

            IActionResult view       = _controller.Index();
            var           viewResult = Xunit.Assert.IsType <ViewResult>(view);
            var           result     = view as ViewResult;
            var           model      = result.Model as SessionData;

            Assert.AreEqual("No ClientId", model.ClientId);
        }
Пример #20
0
        public void Setup()
        {
            _usersList = new List <User>();
            _rentList  = new List <RentOrder>();
            _broker    = new MessageBroker(new ConnectionFactory()
            {
                Uri = new Uri("amqp://*****:*****@reindeer.rmq.cloudamqp.com/zswjrhxx")
            }.CreateConnection());
            _users           = new Mock <IDataBaseRepo <User> >();
            _mockHttpContext = new Mock <HttpContext>();
            _mockSession     = new MockHttpSession();
            // mocking methods User
            _users.Setup(m => m.GetAllObjects()).ReturnsAsync(_usersList);
            _users.Setup(m => m.Insert(It.IsAny <User>()))
            .Callback <User>(item => _usersList.Add(item));
            _users.Setup(m => m.GetObjectById(It.IsAny <int>()))
            .Callback <int>(item => _usersList.Find(u => u.Id == item));
            _users.Setup(m => m.Update(It.IsAny <User>()))
            .Callback <User>(u => {
                var foundUser        = _usersList.Find(item => item.Id == u.Id);
                foundUser.RentOrders = u.RentOrders;
            });

            // mocking methods Games
            _gameList = new List <Game>();
            _games    = new Mock <IDataBaseRepo <Game> >();
            _games.Setup(m => m.GetAllObjects()).ReturnsAsync(_gameList);
            _games.Setup(m => m.Insert(It.IsAny <Game>()))
            .Callback <Game>(item => _gameList.Add(item));

            //mocking methods - RentOrder
            _rents = new Mock <IDataBaseRepo <RentOrder> >();
            _rents.Setup(m => m.GetAllObjects()).ReturnsAsync(_rentList);
            _rents.Setup(m => m.Insert(It.IsAny <RentOrder>()))
            .Callback <RentOrder>(item => _rentList.Add(item));
            _rents.Setup(m => m.GetObjectById(It.IsAny <int>()))
            .Returns <int>(id => Task.FromResult(_rentList.SingleOrDefault(r => r.Id == id)))
            .Callback <int>(item => _rentList.Find(r => r.Id == item));
            _rents.Setup(m => m.Delete(It.IsAny <int>()))
            .Callback <int>(id => _rentList.RemoveAll(r => r.Id == id));
            _rents.Setup(r => r.Update(It.IsAny <RentOrder>()))
            .Callback <RentOrder>(rent =>
            {
                var rentToUpdate          = _rentList.FirstOrDefault(r => r.Id == rent.Id);
                rentToUpdate.ExpiringDate = rent.ExpiringDate;
                rentToUpdate.RentPeriod   = rent.RentPeriod;
            });


            //mocking messageBroker
        }
Пример #21
0
        private static LoginController GetMockProviderController()
        {
            var mock    = new Mock <ControllerContext>();
            var session = new MockHttpSession();

            mock.Setup(p => p.HttpContext.Session).Returns(session);

            LoginController controller = new LoginController()
            {
                ControllerContext = mock.Object
            };

            return(controller);
        }
        public void Get_WhenCalled_ReturnsOkResult()
        {
            var cartID          = "9b3df90a-1007-4778-b614-91df990e0c95";
            var mockHttpContext = MockHttpSession.setSessionKey(cartID);

            _controller.ControllerContext.HttpContext = mockHttpContext.Object;

            // Act
            var okResult = _controller.Get();


            // Assert
            Assert.IsType <OkObjectResult>(okResult.Result);
        }
        public void Clear_ExistingGuidPassed()
        {
            var cartID          = "9b3df90a-1007-4778-b614-91df990e0c95";
            var mockHttpContext = MockHttpSession.setSessionKey(cartID);

            _controller.ControllerContext.HttpContext = mockHttpContext.Object;
            // Act
            _controller.ClearCart();
            var okResult = _controller.Get();
            var items    = Assert.IsType <List <ShoppingCartItemDto> >(okResult.Result);

            // Assert
            Assert.Empty(items);
        }
Пример #24
0
        protected void InitMocks()
        {
            var mockHttpContext = new Mock <HttpContextBase>();

            Context  = mockHttpContext.Object;
            Session  = new MockHttpSession();
            Request  = new MockHttpRequest(new MockHttpFilesCollection(null));
            Response = new MockHttpResponse();

            mockHttpContext.Setup(ctx => ctx.Session).Returns(() => Session);
            mockHttpContext.Setup(ctx => ctx.Request).Returns(() => Request);
            mockHttpContext.Setup(ctx => ctx.Response).Returns(() => Response);
            mockHttpContext.Setup(ctx => ctx.Cache).Returns(() => HttpRuntime.Cache);
        }
Пример #25
0
        // used to set the controller we are testing context's
        public static HttpContextBase FakeHttpContext()
        {
            var context  = new Mock <HttpContextBase>();
            var request  = new Mock <HttpRequestBase>();
            var response = new Mock <HttpResponseBase>();
            var session  = new MockHttpSession();
            var server   = new Mock <HttpServerUtilityBase>();

            context.Setup(ctx => ctx.Request).Returns(request.Object);
            context.Setup(ctx => ctx.Response).Returns(response.Object);
            context.Setup(ctx => ctx.Session).Returns(session);
            context.Setup(ctx => ctx.Server).Returns(server.Object);

            return(context.Object);
        }
        public void AddToCart_ExistingGuidPassed()
        {
            var    cartID = "17b37a88-c502-45a8-84be-b48ecc205a3e";
            string id     = "e3656e5b-23df-4ced-a7e4-4b066839f54a";

            var mockHttpContext = MockHttpSession.setSessionKey(cartID);

            _controller.ControllerContext.HttpContext = mockHttpContext.Object;
            // Act
            _controller.AddtoCart(id, 1);
            var okResult = _controller.Get();
            var items    = Assert.IsType <List <ShoppingCartItemDto> >(okResult.Result);

            // Assert
            Assert.Equal(2, items.Count);
        }
Пример #27
0
        //In the MVCMockHelpers I modified the FakeHttpContext() method as shown below
        public static HttpContextBase FakeHttpContext()
        {
            mockContext = new Mock <HttpContextBase>();
            var request = new Mock <HttpRequestBase>();

            response = new Mock <HttpResponseBase>();
            var session = new MockHttpSession();
            var server  = new Mock <HttpServerUtilityBase>();

            request.Setup(m => m.UrlReferrer).Returns(new Uri("http://test.com/"));
            request.Setup(m => m.QueryString).Returns(new Mock <NameValueCollection>().Object);
            mockContext.Setup(ctx => ctx.Request).Returns(request.Object);
            mockContext.Setup(ctx => ctx.Response).Returns(response.Object);
            mockContext.Setup(ctx => ctx.Session).Returns(session);
            mockContext.Setup(ctx => ctx.Server).Returns(server.Object);

            return(mockContext.Object);
        }
Пример #28
0
        public RolesControllerTests()
        {
            var config = new ConfigurationBuilder().AddJsonFile("appsettings.test.json").Build();

            bosAPIkey                       = config["BOS:APIkey"];
            _configuration                  = config;
            _contextAccessor                = new HttpContextAccessor();
            multitenantService              = new MultitenantService();
            mockSession                     = new MockHttpSession();
            tokenResponse                   = new TokenResponse();
            tokenResponse.data              = bosAPIkey;
            tokenResponse.message           = "success";
            mockSession["ApplicationToken"] = JsonConvert.SerializeObject(tokenResponse);
            _contextAccessor.HttpContext    = new DefaultHttpContext()
            {
                Session = mockSession
            };
        }
Пример #29
0
        public static Mock <HttpContextBase> MockControllerContext(string userName, bool isAjaxRequest)
        {
            var request = new Mock <HttpRequestBase>();

            request.SetupGet(r => r.HttpMethod).Returns("GET");
            //request.SetupGet(r => r.IsAuthenticated).Returns(authenticated);
            request.SetupGet(r => r.ApplicationPath).Returns("/");
            request.SetupGet(r => r.ServerVariables).Returns((NameValueCollection)null);
            request.SetupGet(r => r.Url).Returns(new Uri("http://localhost/app", UriKind.Absolute));
            //request.SetupGet(r => r.QueryString).Returns()
            if (isAjaxRequest)
            {
                request.SetupGet(x => x.Headers).Returns(new System.Net.WebHeaderCollection {
                    { "X-Requested-With", "XMLHttpRequest" }
                });
            }

            var server = new Mock <HttpServerUtilityBase>();

            server.Setup(x => x.MapPath(It.IsAny <string>())).Returns(BasePath);

            var response = new Mock <HttpResponseBase>();

            response.Setup(r => r.ApplyAppPathModifier(It.IsAny <string>())).Returns((String url) => url);

            var session = new MockHttpSession();

            var mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.Setup(c => c.Request).Returns(request.Object);
            mockHttpContext.Setup(c => c.Response).Returns(response.Object);
            mockHttpContext.Setup(c => c.Server).Returns(server.Object);
            mockHttpContext.Setup(x => x.Session).Returns(session);
            if (!String.IsNullOrEmpty(userName))
            {
                mockHttpContext.Setup(x => x.User).Returns(new GenericPrincipal(new GenericIdentity(userName), new string[0]));
            }
            else
            {
                mockHttpContext.Setup(x => x.User).Returns(new GenericPrincipal(new GenericIdentity(""), new string[0]));
            }

            return(mockHttpContext);
        }
        public void HasSessionExpired_throws_expection_when_session_is_null()
        {
            //Arrange
            //Mocking a session
            MockHttpSession mockSession = new MockHttpSession();

            mockSession["Key"] = "KeySession";

            var controller = new AuthController(_bosAuthClient, _bosIAClient, _bosEmailClient, _configuration)
            {
                ControllerContext = new ControllerContext()
                {
                    HttpContext = new DefaultHttpContext()
                    {
                        Session = mockSession
                    }
                }
            };

            //Act and Assert
            Assert.Throws <KeyNotFoundException>(() => controller.HasSessionExpired()); //Asserting that the expection thrown is KeyNotFound
        }
        public async Task WhenSignInCalledWithOutRedirectUrlAndRefererIsNotNullThenSetSessionToRefererUrl()
        {
            A.CallTo(() => authClient.GetSignInUrl()).Returns("test");
            var session     = new MockHttpSession();
            var redirectUrl = "test.com";
            var settings    = Options.Create(new AuthSettings());

            using var controller = new AuthController(authClient, log, settings, defaultVersionedFiles, defaultConfiguration, baseUrlService)
                  {
                      ControllerContext = new ControllerContext
                      {
                          HttpContext = new DefaultHttpContext
                          {
                              User    = new ClaimsPrincipal(new ClaimsIdentity(new List <Claim>())),
                              Session = session,
                              Request = { Headers = { new KeyValuePair <string, StringValues>("Referer", redirectUrl) } },
                          },
                      },
                  };
            var result = await controller.SignIn(string.Empty).ConfigureAwait(false) as RedirectResult;

            Assert.Equal(redirectUrl, session.GetString(AuthController.RedirectSessionKey));
        }
Пример #32
0
        public void EnglishChangesIntoUkrainian()
        {
            //lets make fake httpcontext using reflection
            var httpRequest = new HttpRequest("", "http://mySomething/", "");
            var stringWriter = new StringWriter();
            var httpResponce = new HttpResponse(stringWriter);
            var httpContext = new HttpContext(httpRequest, httpResponce);

            var sessionContainer = new HttpSessionStateContainer("id", new SessionStateItemCollection(),
                                                                 new HttpStaticObjectsCollection(), 10, true,
                                                                 HttpCookieMode.AutoDetect,
                                                                 SessionStateMode.InProc, false);

            httpContext.Items["AspSession"] = typeof(HttpSessionState).GetConstructor(
                                                     BindingFlags.NonPublic | BindingFlags.Instance,
                                                     null, CallingConventions.Standard,
                                                     new[] { typeof(HttpSessionStateContainer) },
                                                     null)
                                                .Invoke(new object[] { sessionContainer });
            
            HttpContext.Current = httpContext;
            IWindsorContainer container = new WindsorContainer();
            InitializeWindsor(ref container);
            AccountController pc = null;
            try
            {
                pc = new AccountController(new DatabaseUserStorage(container.Resolve<ILmsService>()));
            }
            catch (Exception e)
            {
            }
            var context = new Mock<ControllerContext>();

            var session = new MockHttpSession();

            context.Setup(m => m.HttpContext.Session).Returns(session);

            DatabaseUserStorage storage = new DatabaseUserStorage(null);//returns null but we don't need it

            pc.ControllerContext = context.Object;
            ViewResult result = pc.ChangeCulture("uk-UA", "/") as ViewResult;
            Assert.AreEqual("uk-UA", pc.Session["Culture"].ToString());

        }