public void RequestLifetimeManagerReturnsSameObjectForSameRequest() { var context1 = new FakeHttpContext("Http://fakeUrl1.com"); var context2 = new FakeHttpContext("Http://fakeUrl2.com"); var requestltm = new RequestLifetime(); var container = new Container(); container.Register <IFoo>(c => new Foo1()) .WithLifetimeManager(requestltm); requestltm.SetContext(context1); var result1 = container.Resolve <IFoo>(); var result2 = container.Resolve <IFoo>(); requestltm.SetContext(context2); var result3 = container.Resolve <IFoo>(); Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.AreSame(result1, result2); // same request Assert.AreNotSame(result2, result3); // different request }
static public IRecognizer Create(FakeHttpContext context, PageRecognizeEnum pr) { IRecognizer recognizer = null; switch (pr) { case PageRecognizeEnum.CssStyle: recognizer = new CssRecognizer(); break; case PageRecognizeEnum.HashCode: recognizer = new HashCodeRecognizer(); break; case PageRecognizeEnum.Keyword: recognizer = new KeywordRecognizer(); break; case PageRecognizeEnum.XPath: recognizer = new XPathRecognizer(); break; default: break; } recognizer.Context = context; return(recognizer); }
public void RequestLifetimeManagerReturnsSameObjectForSameRequest() { var context1 = new FakeHttpContext("Http://fakeUrl1.com"); var context2 = new FakeHttpContext("Http://fakeUrl2.com"); var requestltm = new RequestLifetime(); var container = new IocContainer(); container.Register <IFoo>(c => new Foo1()) .WithLifetimeManager(requestltm); requestltm.SetContext(context1); var result1 = container.Resolve <IFoo>(); var result2 = container.Resolve <IFoo>(); requestltm.SetContext(context2); var result3 = container.Resolve <IFoo>(); Verify.That(result3).IsNotNull(); Verify.That(result2).IsNotNull(); Verify.That(result1).IsNotNull() .IsTheSameObjectAs(result2) .IsNotTheSameObjectAs(result3); }
public void FeatureFlagAttribute_NoFeatureFlagServiceRegistered() { // Arrange var featureFlag = new FeatureFlagAttribute("featureFlagKey"); var mockServiceProvider = new Mock <IServiceProvider>(); var context = new ActionExecutingContext(new ActionContext { HttpContext = FakeHttpContext.GetRequestHttpContext(new byte[] { }), RouteData = new RouteData(), ActionDescriptor = new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() { Name = "TestName" } } }, new List <IFilterMetadata>(), new Dictionary <string, object>() { { "id", 1 } }, new Mock <ControllerBase>().Object); context.HttpContext.RequestServices = mockServiceProvider.Object; // Act/Assert var ex = Assert.Throws <InvalidOperationException>(() => featureFlag.OnActionExecuting(context)); Assert.Equal("No feature flag service registered", ex.Message); }
private static HttpContextBase FakeHttpContext(string url, HttpVerbs?httpMethod, HttpVerbs?formMethod) { NameValueCollection form = null; if (formMethod.HasValue) { form = new NameValueCollection { { "_method", formMethod.Value.ToString().ToUpper() } } } ; if (!httpMethod.HasValue) { httpMethod = HttpVerbs.Get; } int idx = url.LastIndexOf('?'); NameValueCollection queryString = null; if (idx > -1) { queryString = new QueryString(QueryString.ExtractQuerystring(url)); url = url.Substring(0, idx); } var httpMethodStr = httpMethod.Value.ToString().ToUpper(); var context = new FakeHttpContext(url, httpMethodStr, null, form, queryString, null, null, null); return(context); }
private string ExecuteRequest(string routePath) { var httpContext = new FakeHttpContext(routePath); var sinkFilter = new MemoryStream(); httpContext.Response.Filter = sinkFilter; var routeData = new RouteData(); routeData.Values.Add("path", routePath); var requestContext = new RequestContext { RouteData = routeData, HttpContext = httpContext }; var httpHandler = _routeHandler.GetHttpHandler(requestContext) as EmbeddedResourceHttpHandler; httpHandler.ProcessRequest(httpContext); // Simulate output filtering var outputStream = httpContext.Response.OutputStream; outputStream.Seek(0, SeekOrigin.Begin); outputStream.CopyTo(httpContext.Response.Filter); sinkFilter.Seek(0, SeekOrigin.Begin); using (var reader = new StreamReader(sinkFilter)) { return(reader.ReadToEnd()); } }
public static HtmlHelper HtmlHelper(ViewDataDictionary viewData = null, HttpRequestBase request = null) { viewData = viewData ?? new ViewDataDictionary(); request = request ?? new FakeHttpRequest(); var httpContext = new FakeHttpContext { Request = request }; var controllerContext = new ControllerContext { HttpContext = httpContext, RouteData = new RouteData() }; var viewContext = new ViewContext( controllerContext, Mock.Of <IView>(), viewData, new TempDataDictionary(), new StringWriter()); var viewDataContainer = new FakeViewDataContainer { ViewData = viewData }; return(new HtmlHelper(viewContext, viewDataContainer)); }
public void SessionLifetimeReturnsSameInstanceForSameSessionAndDifferentInstanceForDifferentSession() { // Arrange using (var container = new IocContainer()) { var sessionItems1 = new SessionStateItemCollection(); var sessionItems2 = new SessionStateItemCollection(); var context1 = new FakeHttpContext("Http://fakeUrl1.com", null, null, null, null, sessionItems1); var context2 = new FakeHttpContext("Http://fakeUrl2.com", null, null, null, null, sessionItems2); HttpContextBase currentContext = null; var lifetime = new SessionLifetime(() => currentContext); // better solution for injecting HttpContext ? container.Register<IFoo>(c => new Foo1()).SetLifetime(lifetime); // Act currentContext = context1; var result1 = container.Resolve<IFoo>(); var result2 = container.Resolve<IFoo>(); currentContext = context2; var result3 = container.Resolve<IFoo>(); // Assert Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.AreSame(result1, result2); Assert.AreNotSame(result1, result3); } }
public void PrintActionResultNeedsToCreateAValidPdf() { //Arrange var httpContext = new FakeHttpContext(); var httpController = new Mock<Controller>(); var controllerContext = httpController .Object .SetFakeControllerContext(httpContext.Object, routeValues: new Dictionary<string, string> { {"action", "testaction"}, {"controller", "testcontroller"} }); var mockActionResult = PrintResult.PrintToPdf(); mockActionResult.RetrieveHtml = (viewName, masterName, model, context) => "<html><head></head><body>Test Content</body></html>"; //Act mockActionResult.ExecuteResult(controllerContext); //Assert httpContext.Response .Verify(@base => @base.BinaryWrite(It.Is<byte[]>( actualBytes => PdfReader.TestPdfFile(actualBytes) == 14))); }
public void User_can_be_authenticated_with_convenience_method() { var context = new FakeHttpContext().Authenticate(); Assert.That(context.User.Identity.IsAuthenticated, Is.True); Assert.That(context.Request.IsAuthenticated, Is.True); }
public void Test_RoleRequirementFilter_NoFeatureFlagsSupplied_ValidRoles() { // Arrange var filter = new RoleRequirementFilter(new string[] { "TestRole" }); var authContext = new AuthorizationFilterContext(new ActionContext { HttpContext = FakeHttpContext.GetRequestHttpContext(new byte[] { }), RouteData = new RouteData(), ActionDescriptor = new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() } }, new List <IFilterMetadata>()); authContext.HttpContext.User = new System.Security.Claims.ClaimsPrincipal( new ClaimsIdentity(new List <Claim> { new Claim("oid", "token"), new Claim(ClaimTypes.Role, "TestRole") }) ); // Act filter.OnAuthorization(authContext); // Assert Assert.Null(authContext.Result); }
public void PrintActionResultNeedsToCreateAValidJpeg() { //Arrange var memoryStream = new MemoryStream(); var httpContext = new FakeHttpContext(outputStream: memoryStream); var httpController = new Mock<Controller>(); var controllerContext = httpController .Object .SetFakeControllerContext(httpContext.Object, routeValues: new Dictionary<string, string> { {"action", "testaction"}, {"controller", "testcontroller"} }); var mockActionResult = PrintResult.PrintToJpeg(); mockActionResult.RetrieveHtml = (viewName, masterName, model, context) => "<html><head></head><body>Test Content</body></html>"; //Act mockActionResult.ExecuteResult(controllerContext); //Assert var actualBytes = memoryStream.ToArray(); for (var i = 0; i < actualBytes.Length; i++) { Assert.AreEqual(Resources.JpegBrowser[i], actualBytes[i]); } }
public void User_can_be_authenticated_with_convenience_method() { var context = new FakeHttpContext().Authenticate(); Assert.That(context.User.Identity.IsAuthenticated, Is.True); Assert.That(context.Request.IsAuthenticated, Is.True); }
public IResult HandleRequest(IRequest req) { context = req.HttpContext; StartJQueryAjaxMonitoring(req.Url); return(new EmptyResult()); }
public void TestInitialize() { this.logger = new Mock <ILogger <ResourceController> >(); this.telemetryClient = new TelemetryClient(new TelemetryConfiguration()); this.unitOfWork = new Mock <IUnitOfWork>(); this.resourceMapper = new Mock <IResourceMapper>(); this.usersServiceMock = new Mock <IUsersService>(); this.memberValidationService = new Mock <IMemberValidationService>(); this.accessTokenHelper = new FakeAccessTokenHelper(); this.securityGroupOptions = Options.Create(new SecurityGroupSettings()); this.resourceController = new ResourceController( this.unitOfWork.Object, this.telemetryClient, this.logger.Object, this.usersServiceMock.Object, this.resourceMapper.Object, this.memberValidationService.Object, this.securityGroupOptions) { ControllerContext = new ControllerContext(), }; this.resourceController.ControllerContext.HttpContext = FakeHttpContext.GetDefaultContextWithUserIdentity(); }
public override void ExecuteResult(ControllerContext context) { if (OverrideExecuteResult(context)) { return; } if (!string.IsNullOrEmpty(Title)) { context.Controller.ViewBag.Title = Title; } // Generate Control Form content var controlFormContent = GenerateControlFormUI(context); var faceHttpContext = new FakeHttpContext(context.HttpContext); var fakeContext = new ControllerContext(faceHttpContext, context.RouteData, context.Controller); ViewData = context.Controller.ViewData; base.ExecuteResult(fakeContext); using (var reader = new StreamReader(faceHttpContext.Response.OutputStream)) { var str = reader.ReadToEnd(); str = str.Replace("[THIS_IS_CONTENT_HOLDER_FOR_ROBO_FORM]", controlFormContent); context.HttpContext.Response.Write(str); } }
public async Task IfRequestDoesNotContainLastEventId_LastEventIdPropertyShouldBeNull() { var context = FakeHttpContext.NewHttpContext(); var sut = await HttpClient.NewClient(context); sut.LastEventId.Should().BeNull(); }
public static HtmlHelper <TModel> GetHtmlHelper <TModel>( TModel model, ControllerBase controller, bool clientValidationEnabled) { ViewEngines.Engines.Clear(); ViewEngines.Engines.Add(new FakeViewEngine()); var httpContext = new FakeHttpContext(); var viewData = new FakeViewDataContainer { ViewData = new ViewDataDictionary <TModel>(model) }; var routeData = new RouteData(); routeData.Values["controller"] = "home"; routeData.Values["action"] = "index"; ControllerContext controllerContext = new FakeControllerContext(controller); var viewContext = new FakeViewContext(controllerContext, "MyView", routeData); viewContext.HttpContext = httpContext; viewContext.ClientValidationEnabled = clientValidationEnabled; viewContext.UnobtrusiveJavaScriptEnabled = clientValidationEnabled; viewContext.FormContext = new FakeFormContext(); HtmlHelper <TModel> htmlHelper = new HtmlHelper <TModel>(viewContext, viewData); return(htmlHelper); }
public void GetAllProductsWhenOnesAreNotClear() { //Arrange var expectedList = new[] { new Good(), new Good() }; var listObjects = new List <KeyValuePair <string, IProduct> > { new KeyValuePair <string, IProduct>("cart_list_1", new Good()), new KeyValuePair <string, IProduct>("cart_list_2", new Good()) }; var map = new Dictionary <string, IProduct>(listObjects); var context = FakeHttpContext.NewFakeHttpContext(); context.SetupProperty(c => c.Session, FakeHttpContext.FakeSession(map).Object); var cart = new Cart(context.Object); //Actual var actual = cart.All(); //Assert Assert.Equal(expectedList, actual); }
public async Task ValidateHandleAsync_Failed() { // Arrange this.authContext = FakeHttpContext.GetAuthorizationHandlerContextForTeamMember(); var mockMemoryCache = new Mock <IMemoryCache>(); mockMemoryCache .Setup(x => x.CreateEntry(It.IsAny <object>())) .Returns(Mock.Of <ICacheEntry>); this.policyHandler = new MustBeTeamMemberUserPolicyHandler( mockMemoryCache.Object, this.botSettings, this.memberValidationService.Object); this.memberValidationService .Setup(svc => svc.ValidateMemberAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <string>())) .ReturnsAsync(() => false); // Act await this.policyHandler.HandleAsync(this.authContext); // Assert Assert.IsFalse(this.authContext.HasSucceeded); }
public void SessionLifetimeManagerReturnsDifferentObjectForDifferentSession() { var sessionItems1 = new SessionStateItemCollection(); var sessionItems2 = new SessionStateItemCollection(); var context1 = new FakeHttpContext("Http://fakeUrl1.com", null, null, null, null, sessionItems1); var context2 = new FakeHttpContext("Http://fakeUrl2.com", null, null, null, null, sessionItems2); var sessionltm = new SessionLifetime(); var container = new Container(); container.Register <IFoo>(c => new Foo1()) .WithLifetimeManager(sessionltm); sessionltm.SetContext(context1); var result1 = container.Resolve <IFoo>(); var result2 = container.Resolve <IFoo>(); sessionltm.SetContext(context2); var result3 = container.Resolve <IFoo>(); Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.AreSame(result1, result2); // same session Assert.AreNotSame(result2, result3); // different sessions }
public void RemoveProductWhenObjectDoesnotExistsIn() { //Arrange var targetGood = new Good() { Price = 12.2m, Supplier = new Supplier() { Name = "Maxim" } }; var map = new Dictionary <string, IProduct>(new List <KeyValuePair <string, IProduct> > { new KeyValuePair <string, IProduct>("cart_list_1", new Good()), }); var expected = map; var context = FakeHttpContext.NewFakeHttpContext(); context.SetupProperty(e => e.Session, FakeHttpContext.FakeSession(map).Object); var cart = new Cart(context.Object); //Actual cart.Remove(targetGood); //Assert NAssert.AreEqual(expected, map); }
private static HttpContextBase FakeHttpContext(string url, HttpVerbs?httpMethod, HttpVerbs?formMethod) { NameValueCollection form = null; if (formMethod.HasValue) { form = new NameValueCollection { { "_method", formMethod.Value.ToString().ToUpper() } } } ; if (!httpMethod.HasValue) { httpMethod = HttpVerbs.Get; } var request = MockRepository.GenerateStub <HttpRequestBase>(); request.Stub(x => x.AppRelativeCurrentExecutionFilePath).Return(url).Repeat.Any(); request.Stub(x => x.PathInfo).Return(string.Empty).Repeat.Any(); request.Stub(x => x.Form).Return(form).Repeat.Any(); request.Stub(x => x.HttpMethod).Return(httpMethod.Value.ToString().ToUpper()).Repeat.Any(); var context = new FakeHttpContext(url); context.SetRequest(request); return(context); }
public static T WithAuthenticatedUser <T>(this T controller, string name, string userId) where T : Controller { var claims = new List <Claim> { new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/name", name), new Claim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/nameidentifier", userId) }; var genericIdentity = new AuthenticatedGenericIdentity(name); genericIdentity.AddClaims(claims); var genericPrincipal = new GenericPrincipal(genericIdentity, new[] { "Foo" }); var context = new FakeHttpContext(); context.User = genericPrincipal; if (controller.ControllerContext == null) { controller.ControllerContext = new ControllerContext(); } controller.ControllerContext.HttpContext = context; return(controller); }
public void PrintActionResultNeedsToCreateAValidJpeg() { //Arrange var memoryStream = new MemoryStream(); var httpContext = new FakeHttpContext(outputStream: memoryStream); var httpController = new Mock <Controller>(); var controllerContext = httpController .Object .SetFakeControllerContext(httpContext.Object, routeValues: new Dictionary <string, string> { { "action", "testaction" }, { "controller", "testcontroller" } }); var mockActionResult = PrintResult.PrintToJpeg(); mockActionResult.RetrieveHtml = (viewName, masterName, model, context) => "<html><head></head><body>Test Content</body></html>"; //Act mockActionResult.ExecuteResult(controllerContext); //Assert var actualBytes = memoryStream.ToArray(); for (var i = 0; i < actualBytes.Length; i++) { Assert.AreEqual(Resources.JpegBrowser[i], actualBytes[i]); } }
public void PrintActionResultNeedsToCreateAValidPdf() { //Arrange var httpContext = new FakeHttpContext(); var httpController = new Mock <Controller>(); var controllerContext = httpController .Object .SetFakeControllerContext(httpContext.Object, routeValues: new Dictionary <string, string> { { "action", "testaction" }, { "controller", "testcontroller" } }); var mockActionResult = PrintResult.PrintToPdf(); mockActionResult.RetrieveHtml = (viewName, masterName, model, context) => "<html><head></head><body>Test Content</body></html>"; //Act mockActionResult.ExecuteResult(controllerContext); //Assert httpContext.Response .Verify(@base => @base.BinaryWrite(It.Is <byte[]>( actualBytes => PdfReader.TestPdfFile(actualBytes) == 14))); }
public void Init() { _folderPath = Path.Combine(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Media"), "Default"); _filePath = _folderPath + "\\testfile.txt"; Directory.CreateDirectory(_folderPath); File.WriteAllText(_filePath, "testfile contents"); var subfolder1 = Path.Combine(_folderPath, "Subfolder1"); Directory.CreateDirectory(subfolder1); File.WriteAllText(Path.Combine(subfolder1, "one.txt"), "one contents"); File.WriteAllText(Path.Combine(subfolder1, "two.txt"), "two contents"); var subsubfolder1 = Path.Combine(subfolder1, "SubSubfolder1"); Directory.CreateDirectory(subsubfolder1); var context = new FakeHttpContext("~/"); var webHelper = new WebHelper(context); _storageProvider = new FileSystemStorageProvider(new FileSystemSettings { DirectoryName = "Default" }, webHelper); }
public void RequestLifetimeReturnsSameInstanceForSameRequest() { // Arrange using (var container = new IocContainer()) { var context1 = new FakeHttpContext("Http://fakeUrl1.com"); var context2 = new FakeHttpContext("Http://fakeUrl2.com"); HttpContextBase currentContext = null; var lifetime = new RequestLifetime(() => currentContext); // better solution for injecting HttpContext ? container.Register<IFoo>(c => new Foo1()).SetLifetime(lifetime); // Act currentContext = context1; var result1 = container.Resolve<IFoo>(); var result2 = container.Resolve<IFoo>(); currentContext = context2; var result3 = container.Resolve<IFoo>(); // Assert Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.AreSame(result1, result2); Assert.AreNotSame(result1, result3); } }
public void AddProduct_WhenSessionIsNotClear_ResultAdd2ProductsToCart() { //Arrange var map = new Dictionary <string, IProduct>(new List <KeyValuePair <string, IProduct> > { new KeyValuePair <string, IProduct>("cart_list_0", new Good()), new KeyValuePair <string, IProduct>("cart_list_1", new Good()), new KeyValuePair <string, IProduct>("cart_list_2", new Good()), }); ICollection <IProduct> collection = new List <IProduct>((IEnumerable <IProduct>) new[] { new Good(), new Good() }); var context = FakeHttpContext.NewFakeHttpContext(); context.SetupProperty(e => e.Session, FakeHttpContext.FakeSession(map).Object); var cart = new Cart(context.Object); //Actual cart.AddProduct(collection.ToArray()); //Assert Assert.Equal(map.Count, cart.AmountProducts()); }
public void TestInitialize() { this.timesheetControllerLogger = new Mock <ILogger <TimesheetController> >(); this.telemetryClient = new TelemetryClient(new TelemetryConfiguration()); this.timesheetContext = new Mock <TimesheetContext>(); this.timesheetRepository = new Mock <ITimesheetRepository>(); this.projectRepository = new Mock <IProjectRepository>(); this.repositoryAccessors = new Mock <IRepositoryAccessors>(); this.managerDashboardHelper = new Mock <IManagerDashboardHelper>(); this.mockBotSettings = Options.Create(new BotSettings() { MicrosoftAppId = string.Empty, MicrosoftAppPassword = string.Empty, AppBaseUri = string.Empty, CardCacheDurationInHour = 12, TimesheetFreezeDayOfMonth = 12, WeeklyEffortsLimit = 44, }); this.timesheetHelper = new Mock <ITimesheetHelper>(); this.timesheetController = new TimesheetController(this.timesheetControllerLogger.Object, this.telemetryClient, this.timesheetHelper.Object, this.managerDashboardHelper.Object, this.repositoryAccessors.Object); var httpContext = FakeHttpContext.MakeFakeContext(); this.timesheetController.ControllerContext = new ControllerContext { HttpContext = httpContext, }; }
public static RouteData GetRouteDataForUrl(this RouteCollection routes, string url) { var context = new FakeHttpContext("/", url); var routeData = routes.GetRouteData(context); return(routeData); }
private static HttpContextBase FakeHttpContext(string url, HttpVerbs?httpMethod, HttpVerbs?formMethod) { NameValueCollection form = null; if (formMethod.HasValue) { form = new NameValueCollection { { "_method", formMethod.Value.ToString().ToUpper() } } } ; if (!httpMethod.HasValue) { httpMethod = HttpVerbs.Get; } var mockFactory = new FirstAvailableMockFactory(); var request = mockFactory.DynamicMock <HttpRequestBase>(); request.ReturnFor(x => x.AppRelativeCurrentExecutionFilePath, url); request.ReturnFor(x => x.PathInfo, string.Empty); request.ReturnFor(x => x.Form, form); request.ReturnFor(x => x.HttpMethod, httpMethod.Value.ToString().ToUpper()); var context = new FakeHttpContext(url); context.SetRequest(request.Object); return(context); }
public void Test_RoleRequirementFilter_FeatureFlagsSupplied_RolesAuthOff() { // Arrange var mockFeatureFlags = new Mock <IFeatureFlag>(); mockFeatureFlags.Setup(m => m.GetFeatureFlag( It.IsAny <string>(), It.IsAny <bool>() )).Returns(false); var filter = new RoleRequirementFilter(new string[] { "TestRole" }, mockFeatureFlags.Object); var authContext = new AuthorizationFilterContext(new ActionContext { HttpContext = FakeHttpContext.GetRequestHttpContext(new byte[] { }), RouteData = new RouteData(), ActionDescriptor = new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() } }, new List <IFilterMetadata>()); authContext.HttpContext.User = new ClaimsPrincipal( new ClaimsIdentity(new List <Claim> { new Claim("oid", "token"), new Claim(ClaimTypes.Role, "InvalidTestRole") })); // Act filter.OnAuthorization(authContext); // Assert Assert.Null(authContext.Result); }
public void SessionLifetimeReturnsSameInstanceForSameSessionAndDifferentInstanceForDifferentSession() { // Arrange using (var container = new IocContainer()) { var sessionItems1 = new SessionStateItemCollection(); var sessionItems2 = new SessionStateItemCollection(); var context1 = new FakeHttpContext("Http://fakeUrl1.com", null, null, null, null, sessionItems1); var context2 = new FakeHttpContext("Http://fakeUrl2.com", null, null, null, null, sessionItems2); HttpContextBase currentContext = null; var lifetime = new SessionLifetime(() => currentContext); // better solution for injecting HttpContext ? container.Register <IFoo>(c => new Foo1()).SetLifetime(lifetime); // Act currentContext = context1; var result1 = container.Resolve <IFoo>(); var result2 = container.Resolve <IFoo>(); currentContext = context2; var result3 = container.Resolve <IFoo>(); // Assert Assert.IsNotNull(result1); Assert.IsNotNull(result2); Assert.IsNotNull(result3); Assert.AreSame(result1, result2); Assert.AreNotSame(result1, result3); } }
public void Test_RoleRequirementFilter_NoFeatureFlagsSupplied() { // Arrange var mockFeatureFlags = new Mock <IFeatureFlag>(); var filter = new RoleRequirementFilter(new string[] { "" }); var authContext = new AuthorizationFilterContext(new ActionContext { HttpContext = FakeHttpContext.GetRequestHttpContext(new byte[] { }), RouteData = new RouteData(), ActionDescriptor = new ActionDescriptor() { AttributeRouteInfo = new AttributeRouteInfo() } }, new List <IFilterMetadata>()); authContext.HttpContext.User = new System.Security.Claims.ClaimsPrincipal( new ClaimsIdentity(new List <Claim> { new Claim("oid", "token") }) ); // Act filter.OnAuthorization(authContext); // Assert mockFeatureFlags.Verify(m => m.GetFeatureFlag(It.IsAny <string>(), It.IsAny <bool>()), Times.Never); }
public void Can_specify_request() { var request = new FakeHttpRequest(); var context = new FakeHttpContext(request); Assert.That(context.Request, Is.SameAs(request)); }
public void Can_initialize_context_with_existing_session() { var session = new FakeHttpSessionState(); var context = new FakeHttpContext(session: session); Assert.That(context.Session, Is.SameAs(session)); }
public void Principal_can_be_set() { var context = new FakeHttpContext { User = new GenericPrincipal(new MutableIdentity { Name = "slim" }, new string[] { }) }; Assert.That(context.User.Identity.Name, Is.EqualTo("slim")); }
public void Can_clear_all_filter_messages_with_attribute() { var filter = new ClearFlashOnAjaxAttribute(); var context = new FakeHttpContext(new NameValueCollection { { "X-Requested-With", "XMLHttpRequest" } }); Flash.Instance.Push(new SimpleMessage()); Flash.Instance.Count.Should().Be(1); filter.OnActionExecuted(new ActionExecutedContext { HttpContext = context }); Flash.Instance.Count.Should().Be(0); }
public void Should_be_possible_to_fake_http_header_if_the_property_header_is_already_initialized(string headerKey, string headerValue) { // Arrange using (var fakeContext = new FakeHttpContext()) { // ReSharper disable once UnusedVariable var touchHeaders = HttpContext.Current.Request.Headers; // Act fakeContext.Request.Add(headerKey, headerValue); // Assert HttpContext.Current.Request.Headers[headerKey].Should().Be(headerValue); } }
public void RequestLifetimeWithDisposeOnEndThrowsExceptionIfInstanceIsNotIDisposable() { // Currently throws the wrong Expection (InvalidCastException) using (var container = new IocContainer()) { // Arrange var context = new FakeHttpContext("Http://fakeUrl1.com"); var lifetime = new RequestLifetime(() => context, disposeOnEnd: true); // Should throw exception here container.Register<IFoo>(c => new Foo1()).SetLifetime(lifetime); // But currently first throws exception here var instance = container.Resolve<IFoo>(); } }
public static bool MatchesRouteWithHttpGet(this string url) { var path = VirtualPathUtility.ToAppRelative(new Uri(url).AbsolutePath); var fakeContext = new FakeHttpContext(path, "GET"); using(RouteTable.Routes.GetReadLock()) { return RouteTable.Routes.Aggregate(false, (current, route) => { if (!fakeContext.Request.AppRelativeCurrentExecutionFilePath.Equals("~/")) { var routeData = route.GetRouteData(fakeContext); var matches = routeData != null; return current | matches; } return true; }); } }
public override void SetUp() { base.SetUp(); root = CreateOneItem<RegularPage>(1, "root", null); about = CreateOneItem<AboutUsSectionPage>(2, "about", root); executives = CreateOneItem<ExecutiveTeamPage>(3, "executives", about); search = CreateOneItem<SearchPage>(4, "search", root); var typeFinder = new FakeTypeFinder2(); typeFinder.typeMap[typeof(ContentItem)] = this.NearbyTypes() .BelowNamespace("N2.Extensions.Tests.Mvc.Models").AssignableTo<ContentItem>().Union(typeof(ContentItem)).ToArray(); typeFinder.typeMap[typeof(IController)] = this.NearbyTypes() .BelowNamespace("N2.Extensions.Tests.Mvc.Controllers").AssignableTo<IController>().Except(typeof(AnotherRegularController)) .ToArray(); var changer = new StateChanger(); var definitions = new DefinitionManager(new[] { new DefinitionProvider(new DefinitionBuilder(new DefinitionMap(), typeFinder, new TransformerBase<IUniquelyNamed>[0], TestSupport.SetupEngineSection())) }, new ITemplateProvider[0], new ContentActivator(changer, null, new EmptyProxyFactory()), changer); httpContext = new FakeHttpContext(); var webContext = new FakeWebContextWrapper(httpContext); var host = new Host(webContext, root.ID, root.ID); var parser = TestSupport.Setup(persister, webContext, host); controllerMapper = new ControllerMapper(typeFinder, definitions); Url.DefaultExtension = ""; N2.Web.Url.ApplicationPath = "/"; engine = mocks.DynamicMock<IEngine>(); SetupResult.For(engine.Resolve<ITypeFinder>()).Return(typeFinder); SetupResult.For(engine.Definitions).Return(definitions); SetupResult.For(engine.UrlParser).Return(parser); SetupResult.For(engine.Persister).Return(persister); SetupResult.For(engine.Resolve<RequestPathProvider>()).Return(new RequestPathProvider(webContext, parser, new ErrorNotifier(), new HostSection())); var editUrlManager = new FakeEditUrlManager(); SetupResult.For(engine.ManagementPaths).Return(editUrlManager); engine.Replay(); route = new ContentRoute(engine, new MvcRouteHandler(), controllerMapper, null); routes = new RouteCollection { route }; }
public override void SetUp() { base.SetUp(); root = CreateOneItem<RegularPage>(1, "root", null); about = CreateOneItem<AboutUsSectionPage>(2, "about", root); executives = CreateOneItem<ExecutiveTeamPage>(3, "executives", about); search = CreateOneItem<SearchPage>(4, "search", root); var typeFinder = new FakeTypeFinder2(); typeFinder.typeMap[typeof(ContentItem)] = this.NearbyTypes() .BelowNamespace("N2.Extensions.Tests.Mvc.Models").AssignableTo<ContentItem>().Union(typeof(ContentItem)).ToArray(); typeFinder.typeMap[typeof(IController)] = this.NearbyTypes() .BelowNamespace("N2.Extensions.Tests.Mvc.Controllers").AssignableTo<IController>().Except(typeof(AnotherRegularController)) .ToArray(); var editUrlManager = new FakeEditUrlManager(); var definitions = new DefinitionManager(new DefinitionBuilder(typeFinder, new EngineSection(), editUrlManager), new N2.Edit.Workflow.StateChanger(), null, new EmptyProxyFactory()); var webContext = new ThreadContext(); var host = new Host(webContext, root.ID, root.ID); var parser = new UrlParser(persister, webContext, host, new HostSection()); controllerMapper = new ControllerMapper(typeFinder, definitions); Url.DefaultExtension = ""; engine = mocks.DynamicMock<IEngine>(); SetupResult.For(engine.Resolve<ITypeFinder>()).Return(typeFinder); SetupResult.For(engine.Definitions).Return(definitions); SetupResult.For(engine.UrlParser).Return(parser); SetupResult.For(engine.Persister).Return(persister); SetupResult.For(engine.ManagementPaths).Return(editUrlManager); engine.Replay(); route = new ContentRoute(engine, new MvcRouteHandler(), controllerMapper, null); httpContext = new FakeHttpContext(); routes = new RouteCollection { route }; }
public void Should_fake_capabilities_properties(string version, object key, object value) { // Act using (var context = new FakeHttpContext { Capabilities = new Hashtable { { "version", version } } }) { HttpContext.Current.Request.Browser.Capabilities[key] = value; // Assert HttpContext.Current.Request.Browser.Version.Should().Be(version); context.Capabilities[key].Should().Be(value); } }
public void SetUp() { context = new FakeHttpContext(); }
public static RouteData GetRouteDataForUrl(this RouteCollection routes, string url) { var context = new FakeHttpContext("/", url); var routeData = routes.GetRouteData(context); return routeData; }
public void User_should_not_be_authenticated() { var principal = new FakeHttpContext().User; Assert.That(principal.Identity.IsAuthenticated, Is.False); }
public void Identity_can_be_set_with_convenience_method() { var context = new FakeHttpContext().Set(new MutableIdentity { Name = "slim" }); Assert.That(context.User.Identity.Name, Is.EqualTo("slim")); }