public void IsLocal_should_return_false_if_urlString_is_empty() { // Given when var request = new FakeRequest("GET", string.Empty, string.Empty, string.Empty); // Then Assert.False(request.IsLocal()); }
public void IsAjaxRequest_should_return_false_if_request_is_not_ajax() { // Given when var request = new FakeRequest("POST", "/"); // Then Assert.False(request.IsAjaxRequest()); }
public void IsLocal_should_return_true_if_userHostAddr_is_localhost_IPV4() { // Given when var request = new FakeRequest("POST", "/", string.Empty, "127.0.0.1"); request.Url.HostName = "localhost"; // Then Assert.True(request.IsLocal()); }
public void IsLocal_should_return_false_if_userHostAddr_is_not_localhost() { // Given when var request = new FakeRequest("GET", "/", string.Empty, "86.13.73.12"); request.Url.HostName = "anotherhost"; // Then Assert.False(request.IsLocal()); }
public void IsAjaxRequest_should_return_true_if_request_is_ajax() { // Given var headers = new Dictionary<string, IEnumerable<string>> { { "X-Requested-With", new[] { "XMLHttpRequest" } } }; // When var request = new FakeRequest("POST", "/", headers); // Then Assert.True(request.IsAjaxRequest()); }
public void StoringArbitraryData(OwinEnv owinEnironment) { var route = new Route("GET", "/customers/show/{id}", App); route.Data["CacheOptions"] = new CacheOptions(/* options */); var router = new Router(); router.AddRoute(route); var result = router.Resolve(FakeRequest.Get("/customers/show/{id}")); var cacheOptions = (CacheOptions)route.Data["CacheOptions"]; // Add Caching Options to HTTP-Header result.Route.OwinAction.Invoke(owinEnironment); }
public void Should_return_methodnotallowedroute_with_path_set_to_request_uri_when_matched_route_was_for_wrong_request_method() { // Given var request = new FakeRequest("POST", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => x.AddGetRoute("/foo/bar")); // When var route = resolver.Resolve(context).Item1; // Then route.ShouldNotBeNull(); route.ShouldBeOfType <MethodNotAllowedRoute>(); route.Description.Path.ShouldEqual(request.Path); }
public void Should_allow_head_request_when_route_is_defined_for_get() { // Given var request = new FakeRequest("HEAD", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => x.AddGetRoute("/bar/foo")); // When var resolvedRoute = resolver.Resolve(context); // Then resolvedRoute.ShouldNotBeNull(); resolvedRoute.ShouldNotBeOfType <NotFoundRoute>(); resolvedRoute.ShouldNotBeOfType <MethodNotAllowedRoute>(); }
public void Should_ignore_method_casing_when_resolving_routes() { // Given var request = new FakeRequest("GeT", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => x.AddGetRoute("/foo/bar")); // When var resolvedRoute = resolver.Resolve(context); // Then resolvedRoute.ShouldNotBeNull(); resolvedRoute.ShouldNotBeOfType <NotFoundRoute>(); resolvedRoute.ShouldNotBeOfType <MethodNotAllowedRoute>(); }
public void Should_return_options_route_with_path_set_to_request_route_for_options() { // Given var request = new FakeRequest("OPTIONS", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => x.AddGetRoute("/foo/bar")); // When var resolvedRoute = resolver.Resolve(context); // Then resolvedRoute.ShouldNotBeNull(); resolvedRoute.Item1.ShouldBeOfType <OptionsRoute>(); resolvedRoute.Item1.Description.Path.ShouldEqual(request.Path); }
public void Should_not_return_a_route_if_matching_and_the_filter_returns_false() { // Given var moduleCatalog = new FakeModuleCatalog(); var routeCache = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake <INancyContextFactory>()); var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder); var request = new FakeRequest("GET", "/filtered"); var context = new NancyContext { Request = request }; // When var route = specificResolver.Resolve(context, routeCache).Item1; // Then route.ShouldBeOfType(typeof(NotFoundRoute)); }
private static async Task <bool> InvokeAsync(DateTimeOffset created, DateTimeOffset lastRun, bool debounce) { var lastRunStore = new FakeLastRunStore(lastRun); var middleware = new DebounceMiddleware(lastRunStore, NullLoggerFactory.Instance); var meta = debounce ? new[] { new DebounceAttribute() } : null; var request = new FakeRequest(created: created, meta: meta); bool executed = false; await middleware.InvokeAsync(new Context(request), ctx => { executed = true; return(Task.CompletedTask); }); return(executed); }
public void Should_return_a_route_if_matching_and_the_filter_returns_true() { // Given var moduleCatalog = new FakeModuleCatalog(); var routeCache = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake <INancyContextFactory>(), A.Fake <IRouteSegmentExtractor>(), this.routeDescriptionProvider); var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder, routeCache, null); var request = new FakeRequest("GET", "/notfiltered"); var context = new NancyContext { Request = request }; // When var route = specificResolver.Resolve(context).Item1; // Then route.ShouldBeOfType(typeof(Route)); }
public async Task ProcessAsyncTest(string scenario, IList <RuleScenario> ruleScenarios) { var fakeRequest = new FakeRequest(); var fakeResponse = new FakeResponse(); var mockRules = ruleScenarios.Select(ruleScenario => CreateMockRule(fakeRequest, fakeResponse, ruleScenario.RuleStatusType, ruleScenario.ContinueProcessing)).ToList(); var rulesEngine = new RulesEngine(); var rules = mockRules.Select(mockRule => mockRule.Object).ToList(); await rulesEngine.ProcessAsync(fakeRequest, fakeResponse, rules); for (var i = 0; i < rules.Count; i++) { VerifyMockRule(mockRules[i], fakeRequest, fakeResponse, ruleScenarios[i].ExpectedTimes); } }
public void Should_return_route_whos_filter_returns_true_when_there_is_also_a_matching_route_with_a_failing_filter() { // Given var moduleCatalog = new FakeModuleCatalog(); var routeCache = new RouteCache(moduleCatalog, new FakeModuleKeyGenerator(), A.Fake <INancyContextFactory>()); var specificResolver = new DefaultRouteResolver(moduleCatalog, this.matcher, this.moduleBuilder); var request = new FakeRequest("GET", "/filt"); var context = new NancyContext { Request = request }; // When var route = specificResolver.Resolve(context, routeCache).Item1; // Then route.Description.Condition(context).ShouldBeTrue(); }
public CsrfFixture() { this.pipelines = new MockPipelines(); this.cryptographyConfiguration = CryptographyConfiguration.Default; var csrfStartup = new CsrfApplicationStartup( this.cryptographyConfiguration, new DefaultCsrfTokenValidator(this.cryptographyConfiguration)); csrfStartup.Initialize(this.pipelines); Csrf.Enable(this.pipelines); this.request = new FakeRequest("GET", "/"); this.optionsRequest = new FakeRequest("OPTIONS", "/"); this.response = new Response(); }
public void Should_invoke_pattern_matcher_with_request_uri() { // Given var request = new FakeRequest("get", "/foo/bar"); var context = new NancyContext(); context.Request = request; var routeCache = new FakeRouteCache(x => { x.AddGetRoute("/foo/bar"); }); // When this.resolver.Resolve(context, routeCache); // Then A.CallTo(() => this.matcher.Match(request.Uri, A <string> .Ignored)).MustHaveHappened(); }
public void Endpoint_with_multiple_request_parameters() { //Arrange var fakeEndpoint = new FakeEndpoint(); var fakeRequest = new FakeRequest(); string Param2 = "Param2"; //Act var endpoint = new Endpoint(fakeEndpoint.Operation) .WithRequestParameter ( fakeRequest.Name, fakeRequest.Type, fakeRequest.Format, fakeRequest.Required, fakeRequest.Description, fakeRequest.Loc, fakeRequest.Deprecated ) .WithRequestParameter ( Param2, fakeRequest.Type, fakeRequest.Format, fakeRequest.Required, fakeRequest.Description, fakeRequest.Loc, fakeRequest.Deprecated ); //Assert Assert.Equal(fakeRequest.Description, endpoint.RequestParameters[0].Description); Assert.Null(endpoint.RequestParameters[0].Schema.Format); Assert.Equal(fakeRequest.Required, endpoint.RequestParameters[0].Required); Assert.Equal(fakeRequest.Name, endpoint.RequestParameters[0].Name); Assert.Equal(fakeRequest.Loc, endpoint.RequestParameters[0].In); Assert.Equal(fakeRequest.Type.Name.ToLowerInvariant(), endpoint.RequestParameters[0].Schema.Type); Assert.Equal(fakeRequest.Description, endpoint.RequestParameters[1].Description); Assert.Null(endpoint.RequestParameters[1].Schema.Format); Assert.Equal(fakeRequest.Required, endpoint.RequestParameters[1].Required); Assert.Equal(Param2, endpoint.RequestParameters[1].Name); Assert.Equal(fakeRequest.Loc, endpoint.RequestParameters[1].In); Assert.Equal(fakeRequest.Type.Name.ToLowerInvariant(), endpoint.RequestParameters[1].Schema.Type); }
public void UrlHashKey_Keyed_by_url() { //Arrange var keyGen = new UrlHashKeyGenerator(); var request = new FakeRequest( method: METHOD, path: PATH, headers: acceptHeader); //Act string key = keyGen.Get(request); byte[] bytekey = System.Convert.FromBase64String(key); //Assert //Validating lengths from hash created. Assert.Equal(24, key.Length); Assert.Equal(16, bytekey.Length); }
public void WhenTheBasicCredentialsHaveInvalidValues_ThenTheResultIsHttpBasicUnauthorizedResult() { userService.Setup(u => u.GetRegisteredUser()).Returns(new User { Salt = "saltsalt", Name = "name", Password = "******" }); configurationManager.Setup(c => c.AppSetting("keyphrase")).Returns("key"); var filterContext = new AuthorizationContext(); var attr = new BasicAuthorizeAttribute(); attr.UserService = userService.Object; attr.ConfigurationManager = configurationManager.Object; attr.RequireSsl = false; var request = new FakeRequest { SecureConnection = false, Local = false }; httpContext.Setup(h => h.Request).Returns(request); httpContext.Setup(h => h.Response).Returns(new FakeResponse()); httpContext.SetupProperty(h => h.User); request.Values["Authorization"] = "Basic: "; filterContext.HttpContext = httpContext.Object; attr.OnAuthorization(filterContext); filterContext.Result.Should().BeOfType<HttpBasicUnauthorizedResult>(); }
public void Should_set_parameters_on_resolved_route_to_parameteres_that_was_matched() { // Given var request = new FakeRequest("get", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => x.AddGetRoute("/foo/bar", "module-key")); // When var resolvedRoute = resolver.Resolve(context); // Then resolvedRoute.ShouldNotBeOfType <NotFoundRoute>(); resolvedRoute.ShouldNotBeOfType <MethodNotAllowedRoute>(); ((string)resolvedRoute.Item2["foo"]).ShouldEqual("bar"); }
public void Should_return_route_with_path_set_to_request_uri_when_single_route_could_be_resolved() { // Given var request = new FakeRequest("GET", "/foo/bar"); var context = new NancyContext(); context.Request = request; var routeCache = new FakeRouteCache(x => { x.AddGetRoute("/foo/bar"); }); // When var resolvedRoute = this.resolver.Resolve(context, routeCache); // Then resolvedRoute.ShouldNotBeOfType <NotFoundRoute>(); resolvedRoute.Item1.Description.Path.ShouldEqual(request.Uri); }
public void Should_ignore_method_casing_when_resolving_routes() { var request = new FakeRequest("GeT", "/foo/bar"); var context = new NancyContext(); context.Request = request; var routeCache = new FakeRouteCache(x => { x.AddGetRoute("/foo/bar"); }); // When var resolvedRoute = this.resolver.Resolve(context, routeCache); // Then resolvedRoute.ShouldNotBeNull(); resolvedRoute.ShouldNotBeOfType <NotFoundRoute>(); resolvedRoute.ShouldNotBeOfType <MethodNotAllowedRoute>(); }
public void Should_set_action_on_resolved_route() { // Given var request = new FakeRequest("get", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => x.AddGetRoute("/foo/bar", "module-key")); // When var resolvedRoute = resolver.Resolve(context).Item1; // Then resolvedRoute.ShouldNotBeOfType <NotFoundRoute>(); resolvedRoute.ShouldNotBeOfType <MethodNotAllowedRoute>(); resolvedRoute.Action.ShouldBeSameAs(this.expectedAction); }
public void Should_allow_favicon_override() { var favicon = new byte[] { 1, 2, 3 }; bootstrapper.Favicon = favicon; var favIconRequest = new FakeRequest("GET", "/favicon.ico"); var context = new NancyContext { Request = favIconRequest }; bootstrapper.Initialise(); var result = bootstrapper.PreRequest.Invoke(context); result.ShouldNotBeNull(); result.ContentType.ShouldEqual("image/vnd.microsoft.icon"); result.StatusCode = HttpStatusCode.OK; GetBodyBytes(result).SequenceEqual(favicon).ShouldBeTrue(); }
public async Task Should_invoke_route_resolver_with_passed_in_accept_headers_when_path_does_not_contain_file_extensions() { // Given var expectedAcceptHeaders = new List <Tuple <string, decimal> > { { new Tuple <string, decimal>("application/json", 0.8m) }, { new Tuple <string, decimal>("application/xml", 0.4m) } }; var requestedAcceptHeaders = new List <Tuple <string, decimal> >(); var request = new FakeRequest("GET", "/") { Headers = { Accept = expectedAcceptHeaders } }; var context = new NancyContext { Request = request }; var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => this.routeResolver.Resolve(context)) .Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList()) .Returns(resolvedRoute); // When await this.requestDispatcher.Dispatch(context, new CancellationToken()); // Then requestedAcceptHeaders.ShouldHaveCount(2); requestedAcceptHeaders[0].Item1.ShouldEqual("application/json"); requestedAcceptHeaders[0].Item2.ShouldEqual(0.8m); requestedAcceptHeaders[1].Item1.ShouldEqual("application/xml"); requestedAcceptHeaders[1].Item2.ShouldEqual(0.4m); }
public void Should_return_notfoundroute_with_path_set_to_request_uri_when_route_could_not_be_resolved() { // Given var request = new FakeRequest("GET", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => x.AddGetRoute("/bar/foo")); A.CallTo(() => this.matcher.Match("/foo/bar", "/bar/foo", null)).Returns( new FakeRoutePatternMatchResult(x => x.IsMatch(false))); // When var resolvedRoute = resolver.Resolve(context).Item1; // Then resolvedRoute.ShouldBeOfType <NotFoundRoute>(); resolvedRoute.Description.Path.ShouldEqual(request.Path); }
public void Should_return_route_with_module_returned_by_module_builder() { // Given var request = new FakeRequest("GET", "/foo/bar"); var context = new NancyContext { Request = request }; var routeCache = new FakeRouteCache(x => x.AddGetRoute("/foo/bar")); var moduleReturnedByBuilder = new FakeNancyModule(x => x.AddGetRoute("/bar/foo")); A.CallTo(() => this.moduleBuilder.BuildModule(A <NancyModule> .Ignored, A <NancyContext> .Ignored)).Returns( moduleReturnedByBuilder); // When var route = this.resolver.Resolve(context, routeCache); // Then route.Item1.Description.Path.ShouldEqual("/bar/foo"); }
public void Default_keyed_by_query() { //Arrange var keyGen = new DefaultCacheKeyGenerator(new string[] { nameof(QUERY) }); var request = new FakeRequest( method: METHOD, path: PATH, headers: acceptHeader, body: null, protocol: PROTOCOL, query: QUERY); //Act string key = keyGen.Get(request); //Assert Assert.DoesNotContain(ACCEPT, key); Assert.Contains(QUERY, key); Assert.Contains(PATH, key); }
public void Should_allow_head_request_when_route_is_defined_for_get() { // Given var request = new FakeRequest("HEAD", "/foo/bar"); var context = new NancyContext(); context.Request = request; var routeCache = new FakeRouteCache(x => { x.AddGetRoute("/foo/bar"); }); // When var resolvedRoute = this.resolver.Resolve(context, routeCache); // Then resolvedRoute.ShouldNotBeNull(); resolvedRoute.ShouldNotBeOfType <NotFoundRoute>(); resolvedRoute.ShouldNotBeOfType <MethodNotAllowedRoute>(); }
public void Should_return_user_defined_route_for_route_with_custom_options_defined() { // Given var request = new FakeRequest("OPTIONS", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => { x.AddGetRoute("/foo/bar"); x.AddOptionsRoute("/foo/bar"); }); // When var route = resolver.Resolve(context).Item1; // Then route.ShouldNotBeNull(); route.ShouldNotBeOfType <OptionsRoute>(); }
public void Default_keyed_by_url_only_with_removal_key() { //Arrange var keyGen = new DefaultCacheKeyGenerator(); var request = new FakeRequest( method: METHOD, path: PATH, headers: acceptHeader, body: null, protocol: PROTOCOL, query: string.Concat(QUERY, "?RapidCacheRemove=true")); //Act string key = keyGen.Get(request); //Assert Assert.DoesNotContain(ACCEPT, key); Assert.DoesNotContain(QUERY, key); Assert.Contains(PATH, key); }
private static KendoGridRequest SetupBinder(NameValueCollection form, NameValueCollection queryString) { var fakeRequest = new FakeRequest("POST", form, queryString ?? new NameValueCollection()); var httpContext = new FakeContext(fakeRequest); var controller = new FakeController(); var controllerContext = new ControllerContext(new RequestContext(httpContext, new RouteData()), controller); var modelBindingContext = new ModelBindingContext(); var binder = new KendoGridModelBinder(); var model = binder.BindModel(controllerContext, modelBindingContext); Assert.IsNotNull(model); var gridRequest = model as KendoGridRequest; Assert.IsNotNull(gridRequest); return(gridRequest); }
public void Should_return_methodnotallowedroute_with_allow_header_set_to_allowed_methods_matching_request_route() { // Given var request = new FakeRequest("POST", "/foo/bar"); var context = new NancyContext(); context.Request = request; var routeCache = new FakeRouteCache(x => { x.AddGetRoute("/foo/bar"); x.AddPutRoute("/foo/bar"); }); // When var route = this.resolver.Resolve(context, routeCache).Item1; // Then route.ShouldNotBeNull(); route.ShouldBeOfType <MethodNotAllowedRoute>(); route.Invoke(new DynamicDictionary()).Headers["Allow"].ShouldEqual("GET, PUT"); }
public void Should_return_optionsroute_with_allow_header_set_to_allowed_methods_matching_request_route_for_options() { // Given var request = new FakeRequest("OPTIONS", "/foo/bar"); var context = new NancyContext { Request = request }; var resolver = CreateResolver(x => { x.AddGetRoute("/foo/bar"); x.AddPutRoute("/foo/bar"); }); // When var route = resolver.Resolve(context).Item1; // Then route.ShouldNotBeNull(); route.ShouldBeOfType <OptionsRoute>(); route.Invoke(new DynamicDictionary()).Headers["Allow"].ShouldEqual("GET, PUT"); }
public void Should_invoke_pattern_matcher_for_all_entries_in_route_cache() { // Given var request = new FakeRequest("get", "/foo/bar"); var context = new NancyContext(); context.Request = request; var routeCache = new FakeRouteCache(x => { x.AddGetRoute("/foo/bar"); x.AddGetRoute("/bar/foo"); x.AddGetRoute("/foobar"); }); // When this.resolver.Resolve(context, routeCache); // Then A.CallTo(() => this.matcher.Match(A <string> .Ignored, "/foo/bar")).MustHaveHappened(); A.CallTo(() => this.matcher.Match(A <string> .Ignored, "/bar/foo")).MustHaveHappened(); A.CallTo(() => this.matcher.Match(A <string> .Ignored, "/foobar")).MustHaveHappened(); }
public void WhenThereIsNoAuthorizationHeader_ThenTheResultIsHttpBasicUnauthorizedResult() { var filterContext = new AuthorizationContext(); var attr = new BasicAuthorizeAttribute(); attr.RequireSsl = false; var request = new FakeRequest { SecureConnection = false, Local = false }; httpContext.Setup(h => h.Request).Returns(request); filterContext.HttpContext = httpContext.Object; attr.OnAuthorization(filterContext); filterContext.Result.Should().BeOfType<HttpBasicUnauthorizedResult>(); }
public void Should_invoke_route_resolver_with_passed_in_accept_headers_when_path_does_not_contain_file_extensions() { // Given var expectedAcceptHeaders = new List<Tuple<string, decimal>> { { new Tuple<string, decimal>("application/json", 0.8m) }, { new Tuple<string, decimal>("application/xml", 0.4m) } }; var requestedAcceptHeaders = new List<Tuple<string, decimal>>(); var request = new FakeRequest("GET", "/") { Headers = { Accept = expectedAcceptHeaders } }; var context = new NancyContext { Request = request }; var resolvedRoute = new ResolveResult( new FakeRoute(), DynamicDictionary.Empty, null, null, null); A.CallTo(() => this.routeResolver.Resolve(context)) .Invokes(x => requestedAcceptHeaders = ((NancyContext)x.Arguments[0]).Request.Headers.Accept.ToList()) .Returns(resolvedRoute); // When this.requestDispatcher.Dispatch(context); // Then requestedAcceptHeaders.ShouldHaveCount(2); requestedAcceptHeaders[0].Item1.ShouldEqual("application/json"); requestedAcceptHeaders[0].Item2.ShouldEqual(0.8m); requestedAcceptHeaders[1].Item1.ShouldEqual("application/xml"); requestedAcceptHeaders[1].Item2.ShouldEqual(0.4m); }
public void WhenThereIsAPrinciple_ThenTheUserIsStoredInTheContext() { userService.Setup(u => u.GetRegisteredUser()).Returns(new User { Salt = "saltsalt", Name = "name", Password = "******" }); configurationManager.Setup(c => c.AppSetting("keyphrase")).Returns("key"); var filterContext = new AuthorizationContext(); var attr = new BasicAuthorizeAttribute(); attr.UserService = userService.Object; attr.ConfigurationManager = configurationManager.Object; attr.RequireSsl = false; var request = new FakeRequest { SecureConnection = false, Local = false }; httpContext.Setup(h => h.Request).Returns(request); httpContext.Setup(h => h.Response).Returns(new FakeResponse()); httpContext.SetupProperty(h => h.User); request.Values["Authorization"] = "Basic: " + ToBase64("name", "password"); filterContext.HttpContext = httpContext.Object; attr.OnAuthorization(filterContext); filterContext.HttpContext.User.Should().BeOfType<GenericPrincipal>(); }