Exemplo n.º 1
0
        public void SetUp()
        {
            HttpContext.Current = HttpContextFactory.CreateHttpContext();

            routeValues = HttpContext.Current.Request.RequestContext.RouteData.Values;
            provider    = new MvcSiteMapProvider(siteMapPath, parser);
        }
Exemplo n.º 2
0
        public static MockHttpContext CreateMockHttpContext()
        {
            var mock = new MockHttpContext();

            HttpContextFactory.SetCurrentContext(mock.Object);
            return(mock);
        }
Exemplo n.º 3
0
        public DatabaseFixture()
        {
            Items = new Dictionary <string, object>();
            var c = FakeHttpContext();

            HttpContextFactory.SetCurrentContext(c);
            if (BuildDb)
            {
                var csMaster   = Util.GetConnectionString2("master");
                var csElmah    = Util.GetConnectionString2("elmah");
                var scriptsDir = ScriptsDirectory();
                if (DropDb)
                {
                    var cn = new SqlConnection(csMaster);
                    cn.Execute(@"drop database if exists CMS_test");
                }
                DbUtil.CreateDatabase(
                    Util.Host,
                    scriptsDir,
                    csMaster,
                    Util.ConnectionStringImage,
                    csElmah,
                    Util.ConnectionString);
            }
        }
        public void OnAuthorization_NotAuthenticated_RedirectsToLogin()
        {
            AuthorizationContext action = new AuthorizationContext();

            action.ActionDescriptor = Substitute.For <ActionDescriptor>();
            HttpContextBase context = HttpContextFactory.CreateHttpContextBase();
            AuthorizationFilterAttribute attribute = new AuthorizationFilterAttribute {
                Users = "None"
            };

            action.RouteData = context.Request.RequestContext.RouteData;
            action.RouteData.Values["test"] = "Test";
            action.HttpContext = context;

            attribute.OnAuthorization(action);

            RouteValueDictionary actual = (action.Result as RedirectToRouteResult).RouteValues;

            Assert.Equal(action.RouteData.Values["language"], actual["language"]);
            Assert.Equal(action.HttpContext.Request.RawUrl, actual["returnUrl"]);
            Assert.Equal("Auth", actual["controller"]);
            Assert.Equal("Login", actual["action"]);
            Assert.Equal("", actual["area"]);
            Assert.Equal(5, actual.Count);
        }
Exemplo n.º 5
0
        public async Task Write_400_Response_If_ValidationException_Is_Thrown()
        {
            var failures = new List <ValidationFailure>
            {
                new ValidationFailure("name", "name can not be empty")
            };

            var exception = new ValidationException(failures);

            Task next(HttpContext context)
            {
                throw exception;
            }

            var middleware = new ExceptionHandlingMiddleware(next);
            var context    = HttpContextFactory.Create();

            await middleware.Invoke(context);

            Assert.AreEqual("application/json", context.Response.ContentType);
            Assert.AreEqual(400, context.Response.StatusCode);

            var failuresResponse = await context.Response.ReadAsAsync <List <ValidationFailure> >();

            Assert.AreEqual(exception.Errors.ToList()[0].ErrorMessage, failuresResponse[0].ErrorMessage);
        }
Exemplo n.º 6
0
        public BaseDatalistTests()
        {
            HttpContext.Current = HttpContextFactory.CreateHttpContext();
            urlHelper           = new UrlHelper(HttpContext.Current.Request.RequestContext);

            datalist = new BaseDatalistProxy <Role, RoleView>(urlHelper);
        }
Exemplo n.º 7
0
        public static MockHttpContext CreateMockHttpContext(bool isAuthenticated = true)
        {
            var mock = new MockHttpContext(isAuthenticated);

            HttpContextFactory.SetCurrentContext(mock.Object);
            return(mock);
        }
        public HttpClientContextTest()
        {
            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.Bind(new IPEndPoint(IPAddress.Any, 14862));
            _listenSocket.Listen(0);
            IAsyncResult res = _listenSocket.BeginAccept(null, null);

            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _client.Connect("localhost", 14862);
            _remoteSocket = _listenSocket.EndAccept(res);

            _disconnectEvent.Reset();
            _event.Reset();
            _counter = 0;

            var requestParserFactory = new RequestParserFactory();

            _factory = new HttpContextFactory(NullLogWriter.Instance, 8192, requestParserFactory);
            _factory.RequestReceived += OnRequest;
            _context = _factory.CreateContext(_client);
            _context.Disconnected += OnDisconnect;
            //_context = new HttpClientContext(false, new IPEndPoint(IPAddress.Loopback, 21111), OnRequest, OnDisconnect, _client.GetStream(), ConsoleLogWriter.Instance);

            _request      = null;
            _disconnected = false;
        }
Exemplo n.º 9
0
        public void AddActionLink_OnNullAuthorizationProviderRendersActionLink()
        {
            String actionLink = "";

            Authorization.Provider = null;
            AllTypesView view = new AllTypesView();

            columns.Grid.HttpContext = HttpContextFactory.CreateHttpContextBase();
            UrlHelper urlHelper = new UrlHelper(columns.Grid.HttpContext.Request.RequestContext);

            columns
            .Add(Arg.Any <Expression <Func <AllTypesView, String> > >()).Returns(column)
            .AndDoes(info => { actionLink = info.Arg <Expression <Func <AllTypesView, String> > >().Compile().Invoke(view); });

            columns.AddActionLink("Details", "fa fa-info");

            String actual   = actionLink;
            String expected = String.Format(
                "<a class=\"details-action\" href=\"{0}\">" +
                "<i class=\"fa fa-info\"></i>" +
                "</a>",
                urlHelper.Action("Details", new { id = view.Id }));

            Assert.Equal(expected, actual);
        }
Exemplo n.º 10
0
        public MvcDatalistTests()
        {
            HttpContext.Current = HttpContextFactory.CreateHttpContext();
            url = new UrlHelper(HttpContext.Current.Request.RequestContext);

            datalist = new MvcDatalist <Role, RoleView>(url);
            using (TestingContext context = new TestingContext()) context.DropData();
        }
Exemplo n.º 11
0
        public UtilSessionTests()
        {
            var mockContext = new Mock <HttpContextBase>();
            var mockSession = new MockHttpSessionState(MockSessionDictionary);

            mockContext.Setup(c => c.Session).Returns(mockSession);
            HttpContextFactory.SetCurrentContext(mockContext.Object);
        }
        public DatalistControllerTests()
        {
            unitOfWork = Substitute.For <IUnitOfWork>();
            controller = Substitute.ForPartsOf <DatalistController>(unitOfWork);

            HttpContext.Current = HttpContextFactory.CreateHttpContext();
            datalist            = Substitute.For <AbstractDatalist>();
            filter = new DatalistFilter();
        }
Exemplo n.º 13
0
        public void Log_DoesNotSaveChanges()
        {
            entry.State         = EntityState.Added;
            HttpContext.Current = HttpContextFactory.CreateHttpContext();

            logger.Log(new[] { entry });

            Assert.Empty(context.Set <AuditLog>());
        }
Exemplo n.º 14
0
        public void HtmlGrid_DoesNotChangeExistingHttpContext()
        {
            HttpContextBase httpContext = grid.HttpContext = HttpContextFactory.CreateHttpContextBase();

            Object actual   = new HtmlGrid <GridModel>(htmlHelper, grid).Grid.HttpContext;
            Object expected = httpContext;

            Assert.Same(expected, actual);
        }
        public FeatureSetBuilderWithDiscoveredFeatures()
        {
            var httpSessionMock = new Mock <HttpContextBase>();
            var session         = new Mock <HttpSessionStateBase>();

            httpSessionMock.Setup(b => b.Session).Returns(() => session.Object);

            HttpContextFactory.SetCurrentContext(httpSessionMock.Object);
        }
        private static HttpContextFactory CreateHttpContextFactory()
        {
            var ctxFacOptions = Options.Create(new FormOptions
            {
            });
            var ctxFactory = new HttpContextFactory(ctxFacOptions, new HttpContextAccessor());

            return(ctxFactory);
        }
Exemplo n.º 17
0
        public HttpSessionStrategyTests()
        {
            var httpSessionMock = new Mock <HttpContextBase>();
            var session         = new Mock <HttpSessionStateBase>();

            httpSessionMock.Setup(b => b.Session).Returns(() => session.Object);

            HttpContextFactory.SetCurrentContext(httpSessionMock.Object);
        }
Exemplo n.º 18
0
        public void DisposeContextDoesNotThrowWhenContextScopeIsNull()
        {
            // Arrange
            var httpContextFactory = new HttpContextFactory(new DefaultObjectPoolProvider(), Options.Create(new FormOptions()), new HttpContextAccessor());
            var hostingApplication = new HostingApplication(ctx => Task.FromResult(0), new NullScopeLogger(), new NoopDiagnosticSource(), httpContextFactory);
            var context            = hostingApplication.CreateContext(new FeatureCollection());

            // Act/Assert
            hostingApplication.DisposeContext(context, null);
        }
Exemplo n.º 19
0
        public void GetListInValidMachineNameReturnsEmptyList()
        {
            // Mock the request object now
            HttpContextFactory.SetCurrentContext(GetMockedHttpContext());
            XmlsDataFactory.SetXmlData(GetXmlData());
            var sb = new SupportedBrowser();
            var l  = sb.GetList("Wrong Data");

            Assert.IsTrue(l.Count == 0);
        }
Exemplo n.º 20
0
        public void AddActionLink_OnUnauthorizedActionLinkDoesNotAddColumn()
        {
            Authorization.Provider   = Substitute.For <IAuthorizationProvider>();
            columns.Grid.HttpContext = HttpContextFactory.CreateHttpContextBase();

            columns.AddActionLink("Edit", "fa fa-pencil");

            columns.DidNotReceive().Add(Arg.Any <Expression <Func <AllTypesView, String> > >());
            columns.DidNotReceive().Insert(Arg.Any <Int32>(), Arg.Any <Expression <Func <AllTypesView, String> > >());
        }
Exemplo n.º 21
0
        public void AddActionLink_OnUnauthorizedActionLinkReturnsGridColumn()
        {
            Authorization.Provider   = Substitute.For <IAuthorizationProvider>();
            columns.Grid.HttpContext = HttpContextFactory.CreateHttpContextBase();

            IGridColumn <AllTypesView> column = columns.AddActionLink("Edit", "fa fa-pencil");

            Assert.IsType <GridColumn <AllTypesView, String> >(column);
            Assert.NotNull(column);
        }
Exemplo n.º 22
0
        public void Mutable_FeatureCollection_Wrapped_For_OwinFeatureCollection()
        {
            var env            = new Dictionary <string, object>();
            var contextFactory = new HttpContextFactory();
            var context        = contextFactory.CreateHttpContext(new OwinFeatureCollection(env));

            // Setting a feature will throw if the above feature collection is not wrapped in a mutable feature collection.
            context.Features.Set <ICustomFeature>(new CustomFeature(100));
            Assert.Equal(100, context.Features.Get <ICustomFeature>().Value);
        }
        public void AddActionLink_Unauthorized_Empty()
        {
            Authorization.Provider   = Substitute.For <IAuthorizationProvider>();
            columns.Grid.HttpContext = HttpContextFactory.CreateHttpContextBase();

            IGridColumn <AllTypesView> actual = columns.AddActionLink("Edit", "fa fa-pencil");

            Assert.Empty(actual.ValueFor(null).ToString());
            Assert.Empty(columns);
        }
Exemplo n.º 24
0
        public void IsValidForRequest_Ajax(String headerValue, Boolean expected)
        {
            ControllerContext context = new ControllerContext();

            context.HttpContext = HttpContextFactory.CreateHttpContextBase();
            context.HttpContext.Request["X-Requested-With"].Returns(headerValue);

            Boolean actual = new AjaxOnlyAttribute().IsValidForRequest(context, null);

            Assert.Equal(expected, actual);
        }
Exemplo n.º 25
0
        public void Log_DoesNotSave()
        {
            entry.State = EntityState.Added;
            LoggableEntity entity = new LoggableEntity(entry);

            HttpContext.Current = HttpContextFactory.CreateHttpContext();

            logger.Log(entity);

            Assert.Empty(context.Set <AuditLog>());
        }
Exemplo n.º 26
0
        public void Login_IsCaseInsensitive()
        {
            HttpContext.Current = HttpContextFactory.CreateHttpContext();

            service.Login(account.Username.ToUpper());

            String actual   = FormsAuthentication.Decrypt(HttpContext.Current.Response.Cookies[0].Value).Name;
            String expected = account.Id.ToString();

            Assert.Equal(expected, actual);
        }
Exemplo n.º 27
0
        public void Logout_ExpiresCookie()
        {
            HttpContext.Current = HttpContextFactory.CreateHttpContext();

            service.Login(account.Username);
            service.Logout();

            DateTime expirationDate = HttpContext.Current.Response.Cookies[0].Expires;

            Assert.True(expirationDate < DateTime.Now);
        }
Exemplo n.º 28
0
        public void SetUp()
        {
            column  = SubstituteColumn <AllTypesView>();
            options = SubstituteOptions <AllTypesView>();
            columns = SubstituteColumns <AllTypesView, DateTime?>(column);

            HttpContext.Current = HttpContextFactory.CreateHttpContext();
            urlHelper           = new UrlHelper(HttpContext.Current.Request.RequestContext);

            Authorization.Provider = Substitute.For <IAuthorizationProvider>();
            Authorization.Provider.IsAuthorizedFor(Arg.Any <String>(), Arg.Any <String>(), Arg.Any <String>(), Arg.Any <String>()).Returns(true);
        }
Exemplo n.º 29
0
        public void Login_CreatesPersistentAuthenticationTicket()
        {
            AccountLoginView view = ObjectFactory.CreateAccountLoginView();

            HttpContext.Current = HttpContextFactory.CreateHttpContext();

            service.Login(view.Username);

            FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(HttpContext.Current.Response.Cookies[0].Value);

            Assert.True(ticket.IsPersistent);
        }
Exemplo n.º 30
0
            public async Task ShouldCreateHttpContextUsingRequest()
            {
                // Given
                var factory = new HttpContextFactory();
                var request = new HttpRequest("HTTP/1.1", "GET", Url.Blank, new Dictionary<string, string[]>(), Stream.Null, null, string.Empty);

                // When
                var context = await factory.CreateContext(request, CancellationToken.None);

                // Then
                Assert.Same(request, context.Request);
            }
Exemplo n.º 31
0
        public void Login_Account()
        {
            HttpContext.Current = HttpContextFactory.CreateHttpContext();

            service.Login(account.Username.ToUpper());

            FormsAuthenticationTicket actual   = FormsAuthentication.Decrypt(HttpContext.Current.Response.Cookies[0].Value);
            FormsAuthenticationTicket expected = new FormsAuthenticationTicket(account.Id.ToString(), true, 0);

            Assert.Equal(expected.IsPersistent, actual.IsPersistent);
            Assert.Equal(expected.Name, actual.Name);
        }
Exemplo n.º 32
0
        public HttpClientContextTest()
        {
            _listenSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _listenSocket.Bind(new IPEndPoint(IPAddress.Any, 14862));
            _listenSocket.Listen(0);
            IAsyncResult res = _listenSocket.BeginAccept(null, null);
            _client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            _client.Connect("localhost", 14862);
            _remoteSocket = _listenSocket.EndAccept(res);

            _disconnectEvent.Reset();
            _event.Reset();
            _counter = 0;

            var requestParserFactory = new RequestParserFactory();
            _factory = new HttpContextFactory(NullLogWriter.Instance, 8192, requestParserFactory);
            _factory.RequestReceived += OnRequest;
            _context = _factory.CreateContext(_client);
            _context.Disconnected += OnDisconnect;
            //_context = new HttpClientContextImp(false, new IPEndPoint(IPAddress.Loopback, 21111), OnRequest, OnDisconnect, _client.GetStream(), ConsoleLogWriter.Instance);

            _request = null;
            _disconnected = false;
        }