예제 #1
0
        public void Pipeline_containing_another_pipeline_will_invoke_items_in_both_pipelines()
        {
            // Given
            var item1Called = false;
            Func<NancyContext, Response> item1 = (r) => { item1Called = true; return null; };
            var item2Called = false;
            Func<NancyContext, Response> item2 = (r) => { item2Called = true; return null; };
            var item3Called = false;
            Func<NancyContext, Response> item3 = (r) => { item3Called = true; return null; };
            var item4Called = false;
            Func<NancyContext, Response> item4 = (r) => { item4Called = true; return null; };
            pipeline += item1;
            pipeline += item2;
            var subPipeline = new BeforePipeline();
            subPipeline += item3;
            subPipeline += item4;

            // When
            pipeline.AddItemToEndOfPipeline(subPipeline);
            pipeline.Invoke(CreateContext(), new CancellationToken());

            // Then
            Assert.True(item1Called);
            Assert.True(item2Called);
            Assert.True(item3Called);
            Assert.True(item4Called);
        }
예제 #2
0
        public void Should_add_response_cookie_if_it_has_changed()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IApplicationPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            CookieBasedSessions.Enable(hooks, encryptionProvider, hmacProvider, "this passphrase", "this is a salt", "hmac passphrase").WithFormatter(new Fakes.FakeSessionObjectFormatter());
            var request = CreateRequest("encryptedkey1=value1");

            A.CallTo(() => this.encryptionProvider.Decrypt("encryptedkey1=value1", A <string> .Ignored, A <byte[]> .Ignored)).Returns("key1=value1;");
            var response     = A.Fake <Response>();
            var nancyContext = new NancyContext()
            {
                Request = request, Response = response
            };

            beforePipeline.Invoke(nancyContext);
            request.Session["Testing"] = "Test";

            afterPipeline.Invoke(nancyContext);

            response.Cookies.Count.ShouldEqual(1);
        }
        public async Task Pipeline_containing_another_pipeline_will_invoke_items_in_both_pipelines()
        {
            // Given
            var item1Called = false;
            Func <NancyContext, Response> item1 = (r) => { item1Called = true; return(null); };
            var item2Called = false;
            Func <NancyContext, Response> item2 = (r) => { item2Called = true; return(null); };
            var item3Called = false;
            Func <NancyContext, Response> item3 = (r) => { item3Called = true; return(null); };
            var item4Called = false;
            Func <NancyContext, Response> item4 = (r) => { item4Called = true; return(null); };

            pipeline += item1;
            pipeline += item2;
            var subPipeline = new BeforePipeline();

            subPipeline += item3;
            subPipeline += item4;

            // When
            pipeline.AddItemToEndOfPipeline(subPipeline);
            await pipeline.Invoke(CreateContext(), new CancellationToken());

            // Then
            Assert.True(item1Called);
            Assert.True(item2Called);
            Assert.True(item3Called);
            Assert.True(item4Called);
        }
        public void HandleRequest_should_allow_module_after_hook_to_add_items_to_context()
        {
            // Given
            var route = new FakeRoute();

            var before = new BeforePipeline();
            before += ctx => null;

            var after = new AfterPipeline();
            after += ctx => ctx.Items.Add("RoutePostReq", new object());

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                null);

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            // When
            this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            context.Items.ContainsKey("RoutePostReq").ShouldBeTrue();
        }
        public void Should_not_rethrow_exception_when_onerror_hook_returns_response()
        {
            // Given
            var route = new FakeRoute
            {
                Action = (parameters, ct) => TaskHelpers.GetFaultedTask <dynamic>(new Exception())
            };

            var before = new BeforePipeline();

            before += ctx => null;

            var after = new AfterPipeline();

            after += ctx => { };

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                (ctx, ex) => new Response());

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            //When

            // Then
            Assert.DoesNotThrow(() => this.requestDispatcher.Dispatch(context, new CancellationToken()));
        }
예제 #6
0
        public void Should_add_response_cookie_if_it_has_changed()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer);
            var request = CreateRequest("encryptedkey1=value1");

            A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
            var response     = A.Fake <Response>();
            var nancyContext = new NancyContext()
            {
                Request = request, Response = response
            };

            beforePipeline.Invoke(nancyContext, new CancellationToken());
            request.Session["Testing"] = "Test";

            afterPipeline.Invoke(nancyContext, new CancellationToken());

            response.Cookies.Count.ShouldEqual(1);
        }
        public async Task HandleRequest_should_allow_module_after_hook_to_add_items_to_context()
        {
            // Given
            var route = new FakeRoute();

            var before = new BeforePipeline();

            before += ctx => null;

            var after = new AfterPipeline();

            after += ctx => ctx.Items.Add("RoutePostReq", new object());

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                null);

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            context.Items.ContainsKey("RoutePostReq").ShouldBeTrue();
        }
        public async Task should_preserve_stacktrace_when_rethrowing_the_excption()
        {
            // Given
            var route = new FakeRoute
            {
                Action = (o, ct) => BrokenMethod()
            };

            var before = new BeforePipeline();

            before += ctx => null;

            var after = new AfterPipeline();

            after += ctx => { };

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                (ctx, ex) => null);

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            var exception = await RecordAsync.Exception(async() => await this.requestDispatcher.Dispatch(context, new CancellationToken()));

            exception.StackTrace.ShouldContain("BrokenMethod");
        }
        public void Should_return_response_from_module_before_hook_when_not_null()
        {
            // Given
            Func <NancyContext, Response> moduleBeforeHookResponse = ctx => new Response();

            var before = new BeforePipeline();

            before += moduleBeforeHookResponse;

            var after = new AfterPipeline();

            after += ctx => { };

            var route = new FakeRoute();

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                null);

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            // When
            this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            context.Response.ShouldBeSameAs(moduleBeforeHookResponse);
        }
예제 #10
0
        public void Pipeline_containing_another_pipeline_will_invoke_items_in_both_pipelines()
        {
            var item1Called = false;
            Func <NancyContext, Response> item1 = (r) => { item1Called = true; return(null); };
            var item2Called = false;
            Func <NancyContext, Response> item2 = (r) => { item2Called = true; return(null); };
            var item3Called = false;
            Func <NancyContext, Response> item3 = (r) => { item3Called = true; return(null); };
            var item4Called = false;
            Func <NancyContext, Response> item4 = (r) => { item4Called = true; return(null); };

            pipeline += item1;
            pipeline += item2;
            var subPipeline = new BeforePipeline();

            subPipeline += item3;
            subPipeline += item4;

            pipeline.AddItemToEndOfPipeline(subPipeline);
            pipeline.Invoke(CreateContext());

            Assert.True(item1Called);
            Assert.True(item2Called);
            Assert.True(item3Called);
            Assert.True(item4Called);
        }
        public void PlusEquals_with_func_add_item_to_end_of_pipeline()
        {
            pipeline.AddItemToEndOfPipeline(r => CreateResponse());

            pipeline += r => null;

            Assert.Equal(2, pipeline.PipelineDelegates.Count());
        }
예제 #12
0
        public void PlusEquals_with_func_add_item_to_end_of_pipeline()
        {
            pipeline.AddItemToEndOfPipeline(r => CreateResponse());

            pipeline += r => null;

            Assert.Equal(2, pipeline.PipelineDelegates.Count());
        }
 public ResolveResult(Route route, DynamicDictionary parameters, BeforePipeline before, AfterPipeline after, Func <NancyContext, Exception, dynamic> onError)
 {
     this.Route      = route;
     this.Parameters = parameters;
     this.Before     = before;
     this.After      = after;
     this.OnError    = onError;
 }
예제 #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ResolveResult"/> class, with
 /// the provided <paramref name="route"/>, <paramref name="parameters"/>, <paramref name="before"/>, 
 /// <paramref name="after"/> and <paramref name="onError"/>.
 /// </summary>
 /// <param name="route">The request route instance.</param>
 /// <param name="parameters">The parameters.</param>
 /// <param name="before">The before pipeline instance</param>
 /// <param name="after">The after pipeline instace.</param>
 /// <param name="onError">The on error interceptor instance.</param>
 public ResolveResult(Route route, DynamicDictionary parameters, BeforePipeline before, AfterPipeline after, Func<NancyContext, Exception, dynamic> onError)
 {
     this.Route = route;
     this.Parameters = parameters;
     this.Before = before;
     this.After = after;
     this.OnError = onError;
 }
예제 #15
0
        public void When_cast_from_func_creates_a_pipeline_with_one_item()
        {
            Func <NancyContext, Response> item1 = (r) => null;

            BeforePipeline castPipeline = item1;

            Assert.Equal(1, castPipeline.PipelineItems.Count());
            Assert.Same(item1, castPipeline.PipelineItems.First());
        }
예제 #16
0
        public void When_cast_from_func_creates_a_pipeline_with_one_item()
        {
            Func <NancyContext, CancellationToken, Task <Response> > item2 = (token, task) => null;

            BeforePipeline castPipeline = item2;

            Assert.Equal(1, castPipeline.PipelineDelegates.Count());
            Assert.Same(item2, castPipeline.PipelineDelegates.First());
        }
        internal PipelinedDbContextProvider(IProcessBreezeRequests processBefore)
            : this()
        {
            if (processBefore == null)
            {
                throw new ArgumentException("Argument processBefore (IProcessBreezeRequests) was null.");
            }

            BeforePipeline.Add(processBefore);
        }
예제 #18
0
        public void PlusEquals_with_func_add_item_to_end_of_pipeline()
        {
            Func<NancyContext, Response> item1 = (r) => { return null; };
            Func<NancyContext, Response> item2 = (r) => { return CreateResponse(); };
            pipeline.AddItemToEndOfPipeline(item2);

            pipeline += item1;

            Assert.Equal(2, pipeline.PipelineDelegates.Count());
            Assert.Same(item1, pipeline.PipelineDelegates.Last());
        }
    public void Should_add_pre_and_post_hooks_when_enabled() {
      var beforePipeline = new BeforePipeline();
      var afterPipeline = new AfterPipeline();
      var hooks = A.Fake<IPipelines>();
      A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
      A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);

      hooks.Enable(_fakeSessionManager);

      Assert.Equal(1, beforePipeline.PipelineDelegates.Count());
      Assert.Equal(1, afterPipeline.PipelineItems.Count());
    }
예제 #20
0
        public void PlusEquals_with_func_add_item_to_end_of_pipeline()
        {
            Func <NancyContext, Response> item1 = (r) => { return(null); };
            Func <NancyContext, Response> item2 = (r) => { return(CreateResponse()); };

            pipeline.AddItemToEndOfPipeline(item2);

            pipeline += item1;

            Assert.Equal(2, pipeline.PipelineItems.Count());
            Assert.Same(item1, pipeline.PipelineItems.Last());
        }
        public async Task Should_invoke_module_before_hook_followed_by_resolved_route_followed_by_module_after_hook()
        {
            // Given
            var capturedExecutionOrder = new List <string>();
            var expectedExecutionOrder = new[] { "Prehook", "RouteInvoke", "Posthook" };

            var route = new FakeRoute
            {
                Action = (parameters, token) =>
                {
                    capturedExecutionOrder.Add("RouteInvoke");
                    return(Task.FromResult <object>(null));
                }
            };

            var before = new BeforePipeline();

            before += (ctx) =>
            {
                capturedExecutionOrder.Add("Prehook");
                return(null);
            };

            var after = new AfterPipeline();

            after += (ctx) =>
            {
                capturedExecutionOrder.Add("Posthook");
            };

            var resolvedRoute = new ResolveResult
            {
                Route      = route,
                Parameters = DynamicDictionary.Empty,
                Before     = before,
                After      = after,
                OnError    = null
            };

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            capturedExecutionOrder.Count().ShouldEqual(3);
            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
        }
예제 #22
0
        public void Should_add_pre_and_post_hooks_when_enabled()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline = new AfterPipeline();
            var hooks = A.Fake<IPipelines>();
            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);

            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider));

            beforePipeline.PipelineDelegates.Count().ShouldEqual(1);
            afterPipeline.PipelineItems.Count().ShouldEqual(1);
        }
예제 #23
0
        public void Should_add_pre_and_post_hooks_when_enabled()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline = new AfterPipeline();
            var hooks = A.Fake<IApplicationPipelines>();
            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);

            CookieBasedSessions.Enable(hooks, encryptionProvider, "this passphrase", "this is a salt");

            beforePipeline.PipelineItems.Count().ShouldEqual(1);
            afterPipeline.PipelineItems.Count().ShouldEqual(1);
        }
예제 #24
0
        private static BeforePipeline FakeOwinEnvironment()
        {
            var pipeline = new BeforePipeline();

            pipeline.AddItemToStartOfPipeline(
                context =>
            {
                context.Items.Add("OWIN_REQUEST_ENVIRONMENT", new Dictionary <string, object>());
                return(context.Response);
            });

            return(pipeline);
        }
예제 #25
0
        public void Should_add_pre_and_post_hooks_when_enabled()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);

            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider));

            beforePipeline.PipelineDelegates.Count().ShouldEqual(1);
            afterPipeline.PipelineItems.Count().ShouldEqual(1);
        }
예제 #26
0
        public void Should_add_pre_and_post_hooks_when_enabled()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IApplicationPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);

            CookieBasedSessions.Enable(hooks, encryptionProvider, hmacProvider, "this passphrase", "this is a salt", "this hmac passphrase");

            beforePipeline.PipelineItems.Count().ShouldEqual(1);
            afterPipeline.PipelineItems.Count().ShouldEqual(1);
        }
예제 #27
0
        public void Should_add_pre_and_post_hooks_when_enabled()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);

            hooks.Enable(_fakeSessionManager);

            Assert.Equal(1, beforePipeline.PipelineDelegates.Count());
            Assert.Equal(1, afterPipeline.PipelineItems.Count());
        }
        public async Task Should_invoke_module_before_hook_followed_by_resolved_route_followed_by_module_after_hook()
        {
            // Given
            var capturedExecutionOrder = new List<string>();
            var expectedExecutionOrder = new[] { "Prehook", "RouteInvoke", "Posthook" };

            var route = new FakeRoute
            {
                Action = (parameters, token) =>
                {
                    capturedExecutionOrder.Add("RouteInvoke");
                    return Task.FromResult<object>(null);
                }
            };

            var before = new BeforePipeline();
            before += (ctx) =>
            {
                capturedExecutionOrder.Add("Prehook");
                return null;
            };

            var after = new AfterPipeline();
            after += (ctx) =>
            {
                capturedExecutionOrder.Add("Posthook");
            };

            var resolvedRoute = new ResolveResult
            {
                Route = route,
                Parameters = DynamicDictionary.Empty,
                Before = before,
                After = after,
                OnError = null
            };

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            capturedExecutionOrder.Count().ShouldEqual(3);
            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
        }
        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()
        {
            pipeline.AddItemToEndOfPipeline(r => null);
            pipeline.AddItemToEndOfPipeline(r => CreateResponse());
            var pipeline2 = new BeforePipeline();

            pipeline2.AddItemToEndOfPipeline(r => null);
            pipeline2.AddItemToEndOfPipeline(r => CreateResponse());

            pipeline += pipeline2;

            Assert.Equal(4, pipeline.PipelineItems.Count());
            Assert.Same(pipeline2.PipelineDelegates.ElementAt(0), pipeline.PipelineDelegates.ElementAt(2));
            Assert.Same(pipeline2.PipelineDelegates.ElementAt(1), pipeline.PipelineDelegates.Last());
        }
        public async Task Should_not_invoke_resolved_route_if_module_before_hook_returns_response_but_should_invoke_module_after_hook()
        {
            // Given
            var capturedExecutionOrder = new List <string>();
            var expectedExecutionOrder = new[] { "Prehook", "Posthook" };

            var route = new FakeRoute
            {
                Action = (parameters, token) =>
                {
                    capturedExecutionOrder.Add("RouteInvoke");
                    return(null);
                }
            };

            var before = new BeforePipeline();

            before += ctx =>
            {
                capturedExecutionOrder.Add("Prehook");
                return(new Response());
            };

            var after = new AfterPipeline();

            after += ctx => capturedExecutionOrder.Add("Posthook");

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                null);

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            capturedExecutionOrder.Count().ShouldEqual(2);
            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
        }
예제 #31
0
        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()
        {
            // Given
            pipeline.AddItemToEndOfPipeline(r => null);
            pipeline.AddItemToEndOfPipeline(r => CreateResponse());
            var pipeline2 = new BeforePipeline();
            pipeline2.AddItemToEndOfPipeline(r => null);
            pipeline2.AddItemToEndOfPipeline(r => CreateResponse());

            // When
            pipeline += pipeline2;

            // Then
            Assert.Equal(4, pipeline.PipelineItems.Count());
            Assert.Same(pipeline2.PipelineDelegates.ElementAt(0), pipeline.PipelineDelegates.ElementAt(2));
            Assert.Same(pipeline2.PipelineDelegates.ElementAt(1), pipeline.PipelineDelegates.Last());
        }
        public void Should_invoke_module_onerror_hook_when_module_before_hook_throws_exception()
        {
            // Given
            var capturedExecutionOrder = new List <string>();
            var expectedExecutionOrder = new[] { "Prehook", "OnErrorHook" };

            var before = new BeforePipeline();

            before += ctx =>
            {
                capturedExecutionOrder.Add("Prehook");
                throw new Exception("Prehook");
            };

            var after = new AfterPipeline();

            after += ctx => capturedExecutionOrder.Add("Posthook");

            var route = new FakeRoute((parameters, ct) =>
            {
                capturedExecutionOrder.Add("RouteInvoke");
                return(CreateResponseTask(null));
            });

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                (ctx, ex) => { capturedExecutionOrder.Add("OnErrorHook"); return(new Response()); });

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            // When
            this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            capturedExecutionOrder.Count().ShouldEqual(2);
            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
        }
예제 #33
0
        protected override void ApplicationStartup(TinyIoC.TinyIoCContainer container, IPipelines pipelines)
        {
            BeforePipeline bp = new BeforePipeline();

            // Since we are including the API in the Parking.UI package (because of server constraints)
            // we need to remove the prefix folder so the routes are taken correctly.
            bp.AddItemToStartOfPipeline(ctx => {
                ctx.Request.Url.Path = ctx.Request.Url.Path.Replace("/api", "");
                return(ctx.Response);
            });

            pipelines.BeforeRequest += bp;

            // Register gzip compression
            pipelines.RegisterCompressionCheck();

            base.ApplicationStartup(container, pipelines);
        }
예제 #34
0
        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()
        {
            Func<NancyContext, Response> item1 = (r) => { return null; };
            Func<NancyContext, Response> item2 = (r) => { return CreateResponse(); };
            pipeline.AddItemToEndOfPipeline(item1);
            pipeline.AddItemToEndOfPipeline(item2);
            Func<NancyContext, Response> item3 = (r) => { return null; };
            Func<NancyContext, Response> item4 = (r) => { return CreateResponse(); };
            var pipeline2 = new BeforePipeline();
            pipeline2.AddItemToEndOfPipeline(item3);
            pipeline2.AddItemToEndOfPipeline(item4);

            pipeline += pipeline2;

            Assert.Equal(4, pipeline.PipelineDelegates.Count());
            Assert.Same(item3, pipeline.PipelineDelegates.ElementAt(2));
            Assert.Same(item4, pipeline.PipelineDelegates.Last());
        }
예제 #35
0
        public void Should_add_response_cookie_if_it_has_changed()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline = new AfterPipeline();
            var hooks = A.Fake<IPipelines>();
            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(this.fakeObjectSerializer);
            var request = CreateRequest("encryptedkey1=value1");
            A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
            var response = A.Fake<Response>();
            var nancyContext = new NancyContext() { Request = request, Response = response };
            beforePipeline.Invoke(nancyContext, new CancellationToken());
            request.Session["Testing"] = "Test";

            afterPipeline.Invoke(nancyContext, new CancellationToken());

            response.Cookies.Count.ShouldEqual(1);
        }
예제 #36
0
        public void Should_add_response_cookie_if_it_has_changed()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline = new AfterPipeline();
            var hooks = A.Fake<IApplicationPipelines>();
            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            CookieBasedSessions.Enable(hooks, encryptionProvider, "this passphrase", "this is a salt").WithFormatter(new Fakes.FakeSessionObjectFormatter());
            var request = CreateRequest("encryptedkey1=value1");
            A.CallTo(() => this.encryptionProvider.Decrypt("encryptedkey1=value1", A<string>.Ignored, A<byte[]>.Ignored)).Returns("key1=value1;");
            var response = A.Fake<Response>();
            var nancyContext = new NancyContext() { Request = request, Response = response };
            beforePipeline.Invoke(nancyContext);
            request.Session["Testing"] = "Test";

            afterPipeline.Invoke(nancyContext);

            response.Cookies.Count.ShouldEqual(1);
        }
예제 #37
0
        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()
        {
            Func <NancyContext, Response> item1 = (r) => { return(null); };
            Func <NancyContext, Response> item2 = (r) => { return(CreateResponse()); };

            pipeline.AddItemToEndOfPipeline(item1);
            pipeline.AddItemToEndOfPipeline(item2);
            Func <NancyContext, Response> item3 = (r) => { return(null); };
            Func <NancyContext, Response> item4 = (r) => { return(CreateResponse()); };
            var pipeline2 = new BeforePipeline();

            pipeline2.AddItemToEndOfPipeline(item3);
            pipeline2.AddItemToEndOfPipeline(item4);

            pipeline += pipeline2;

            Assert.Equal(4, pipeline.PipelineItems.Count());
            Assert.Same(item3, pipeline.PipelineItems.ElementAt(2));
            Assert.Same(item4, pipeline.PipelineItems.Last());
        }
        public async Task Should_allow_module_after_hook_to_change_response()
        {
            // Given
            var before = new BeforePipeline();

            before += ctx => null;

            var response = new Response();

            Func <NancyContext, Response> moduleAfterHookResponse = ctx => response;

            var after = new AfterPipeline();

            after += ctx =>
            {
                ctx.Response = moduleAfterHookResponse(ctx);
            };

            var route = new FakeRoute();

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                null);

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            context.Response.ShouldBeSameAs(response);
        }
예제 #39
0
        public void Should_set_formatter_when_using_formatter_selector()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IApplicationPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            var fakeFormatter = A.Fake <ISessionObjectFormatter>();

            A.CallTo(() => this.encryptionProvider.Decrypt("encryptedkey1=value1", A <string> .Ignored, A <byte[]> .Ignored)).Returns("key1=value1;");
            CookieBasedSessions.Enable(hooks, encryptionProvider, hmacProvider, "this passphrase", "this is a salt", "hmac passphrase").WithFormatter(fakeFormatter);
            var request      = CreateRequest("encryptedkey1=value1");
            var nancyContext = new NancyContext()
            {
                Request = request
            };

            beforePipeline.Invoke(nancyContext);

            A.CallTo(() => fakeFormatter.Deserialize(A <string> .Ignored)).MustHaveHappened(Repeated.Exactly.Once);
        }
예제 #40
0
        public void Should_set_formatter_when_using_formatter_selector()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline  = new AfterPipeline();
            var hooks          = A.Fake <IPipelines>();

            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            var fakeFormatter = A.Fake <IObjectSerializer>();

            A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(fakeFormatter);
            var request      = CreateRequest("encryptedkey1=value1");
            var nancyContext = new NancyContext()
            {
                Request = request
            };

            beforePipeline.Invoke(nancyContext, new CancellationToken());

            A.CallTo(() => fakeFormatter.Deserialize(A <string> .Ignored)).MustHaveHappened(Repeated.Exactly.Once);
        }
        /// <summary>
        /// Use wechat browser filter in a NancyController/NancyModule
        /// </summary>
        /// <param name="pipeline"></param>
        /// <param name="optionAction"></param>
        /// <returns></returns>
        public static BeforePipeline UseWeChatBrowserOnly(this BeforePipeline pipeline, Action <WeChatBrowserOnlyOptions> optionAction)
        {
            if (pipeline == null)
            {
                throw new ArgumentNullException(nameof(pipeline));
            }

            var options = new WeChatBrowserOnlyOptions();

            optionAction?.Invoke(options);

            pipeline.AddItemToEndOfPipeline(ctx =>
            {
                if (!Internal.RequestHelper.IsWeChatBrowser(ctx.Request))
                {
                    return(Internal.ResponseHelper.DoWeChatBrowserOnlyOption(ctx, options));
                }

                return(null);
            });

            return(pipeline);
        }
        public async Task Should_rethrow_exception_when_onerror_hook_does_return_response()
        {
            // Given
            var route = new FakeRoute
            {
                Action = (parameters, ct) => { throw new Exception(); }
            };

            var before = new BeforePipeline();

            before += ctx => null;

            var after = new AfterPipeline();

            after += ctx => { };

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                (ctx, ex) => null);

            A.CallTo(() => this.routeResolver.Resolve(A <NancyContext> .Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext {
                Request = new Request("GET", "/", "http")
            };

            //When
            var exception = await RecordAsync.Exception(async() => await this.requestDispatcher.Dispatch(context, new CancellationToken()));

            // Then
            exception.ShouldNotBeNull();
        }
        public async Task Should_allow_module_after_hook_to_change_response()
        {
            // Given
            var before = new BeforePipeline();
            before += ctx => null;

            var response = new Response();

            Func<NancyContext, Response> moduleAfterHookResponse = ctx => response;

            var after = new AfterPipeline();
            after += ctx =>
            {
                ctx.Response = moduleAfterHookResponse(ctx);
            };

            var route = new FakeRoute();

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                null);

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            context.Response.ShouldBeSameAs(response);
        }
예제 #44
0
        private static BeforePipeline FakeOwinEnvironment()
        {
            var pipeline = new BeforePipeline();

            pipeline.AddItemToStartOfPipeline(
                context =>
                    {
                        context.Items.Add("OWIN_REQUEST_ENVIRONMENT", new Dictionary<string, object>());
                        return context.Response;
                    });

            return pipeline;
        }
        public async Task Should_not_invoke_resolved_route_if_module_before_hook_returns_response_but_should_invoke_module_after_hook()
        {
            // Given
            var capturedExecutionOrder = new List<string>();
            var expectedExecutionOrder = new[] { "Prehook", "Posthook" };

            var route = new FakeRoute
            {
                Action = (parameters, token) =>
                {
                    capturedExecutionOrder.Add("RouteInvoke");
                    return null;
                }
            };

            var before = new BeforePipeline();
            before += ctx =>
                          {
                              capturedExecutionOrder.Add("Prehook");
                              return new Response();
                          };

            var after = new AfterPipeline();
            after += ctx => capturedExecutionOrder.Add("Posthook");

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                null);

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            capturedExecutionOrder.Count().ShouldEqual(2);
            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
        }
예제 #46
0
            /// <summary>
            /// Adds a before-request process pipeline to the module.
            /// </summary>
            /// <param name="before">An <see cref="BeforePipeline"/> instance.</param>
            /// <returns>An instance to the current <see cref="ConfigurableNancyModuleConfigurator"/>.</returns>
            public ConfigurableNancyModuleConfigurator Before(BeforePipeline before)
            {
                this.module.Before = before;

                return(this);
            }
예제 #47
0
        private static void ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq)
        {
            if (resolveResultPreReq == null)
            {
                return;
            }

            var resolveResultPreReqResponse = resolveResultPreReq.Invoke(context, cancellationToken).Result;

            if (resolveResultPreReqResponse != null)
            {
                context.Response = resolveResultPreReqResponse;
            }
        }
        public void Should_return_response_from_module_before_hook_when_not_null()
        {
            // Given
            var expectedResponse = new Response();
            Func<NancyContext, Response> moduleBeforeHookResponse = ctx => expectedResponse;

            var before = new BeforePipeline();
            before += moduleBeforeHookResponse;

            var after = new AfterPipeline();
            after += ctx => { };

            var route = new FakeRoute();

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                null);

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            // When
            this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            context.Response.ShouldBeSameAs(expectedResponse);
        }
        public void Should_set_formatter_when_using_formatter_selector()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline = new AfterPipeline();
            var hooks = A.Fake<IPipelines>();
            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            var fakeFormatter = A.Fake<IObjectSerializer>();
            A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithSerializer(fakeFormatter);
            var request = CreateRequest("encryptedkey1=value1");
            var nancyContext = new NancyContext() { Request = request };

            beforePipeline.Invoke(nancyContext, new CancellationToken());

            A.CallTo(() => fakeFormatter.Deserialize(A<string>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
        }
예제 #50
0
        public void Should_set_formatter_when_using_formatter_selector()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline = new AfterPipeline();
            var hooks = A.Fake<IApplicationPipelines>();
            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            var fakeFormatter = A.Fake<ISessionObjectFormatter>();
            A.CallTo(() => this.encryptionProvider.Decrypt("encryptedkey1=value1", A<string>.Ignored, A<byte[]>.Ignored)).Returns("key1=value1;");
            CookieBasedSessions.Enable(hooks, encryptionProvider, "this passphrase", "this is a salt").WithFormatter(fakeFormatter);
            var request = CreateRequest("encryptedkey1=value1");
            var nancyContext = new NancyContext() { Request = request };

            beforePipeline.Invoke(nancyContext);

            A.CallTo(() => fakeFormatter.Deserialize(A<string>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
        }
예제 #51
0
 public BeforePipelineFixture()
 {
     this.pipeline = new BeforePipeline();
 }
        public async Task Should_not_rethrow_exception_when_onerror_hook_returns_response()
        {
            // Given
            var route = new FakeRoute
            {
                Action = (parameters, ct) => TaskHelpers.GetFaultedTask<dynamic>(new Exception())
            };

            var before = new BeforePipeline();
            before += ctx => null;

            var after = new AfterPipeline();
            after += ctx => { };

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                (ctx, ex) => new Response());

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            //When
            var exception = await RecordAsync.Exception(async () => await this.requestDispatcher.Dispatch(context, new CancellationToken()));

            // Then
            exception.ShouldBeNull();
        }
예제 #53
0
 public FakeHookedModule(BeforePipeline before = null, AfterPipeline after = null)
 {
     this.Before = before;
     this.After = after;
 }
        public void Should_rethrow_exception_when_onerror_hook_does_return_response()
        {
            // Given
            var route = new FakeRoute
            {
                Action = (parameters, ct) => { throw new Exception(); }
            };

            var before = new BeforePipeline();
            before += ctx => null;

            var after = new AfterPipeline();
            after += ctx => { };

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                (ctx, ex) => { return null; });

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            //When

            // Then
            Assert.Throws<Exception>(() => this.requestDispatcher.Dispatch(context, new CancellationToken()));
        }
예제 #55
0
        public void Should_only_not_add_response_cookie_if_it_has_not_changed()
        {
            var beforePipeline = new BeforePipeline();
            var afterPipeline = new AfterPipeline();
            var hooks = A.Fake<IApplicationPipelines>();
            A.CallTo(() => hooks.BeforeRequest).Returns(beforePipeline);
            A.CallTo(() => hooks.AfterRequest).Returns(afterPipeline);
            CookieBasedSessions.Enable(hooks, new CryptographyConfiguration(this.fakeEncryptionProvider, this.fakeHmacProvider)).WithFormatter(new Fakes.FakeSessionObjectFormatter());
            var request = CreateRequest("encryptedkey1=value1");
            A.CallTo(() => this.fakeEncryptionProvider.Decrypt("encryptedkey1=value1")).Returns("key1=value1;");
            var response = A.Fake<Response>();
            var nancyContext = new NancyContext() { Request = request, Response = response };
            beforePipeline.Invoke(nancyContext);

            afterPipeline.Invoke(nancyContext);

            response.Cookies.Count.ShouldEqual(0);
        }
예제 #56
0
        private static Task<Response> ExecuteRoutePreReq(NancyContext context, CancellationToken cancellationToken, BeforePipeline resolveResultPreReq)
        {
            if (resolveResultPreReq == null)
            {
                return TaskHelpers.GetCompletedTask<Response>(null);
            }

            return resolveResultPreReq.Invoke(context, cancellationToken);
        }
        public async Task Should_invoke_module_onerror_hook_when_module_after_hook_throws_exception()
        {
            // Given
            var capturedExecutionOrder = new List<string>();
            var expectedExecutionOrder = new[] { "Posthook", "OnErrorHook" };

            var route = new FakeRoute
            {
                Action = (parameters, ct) => Task.FromResult<object>(null)
            };

            var before = new BeforePipeline();
            before += ctx => null;

            var after = new AfterPipeline();
            after += ctx =>
                         {
                             capturedExecutionOrder.Add("Posthook");
                             throw new Exception("Posthook");
                         };

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                (ctx, ex) => { capturedExecutionOrder.Add("OnErrorHook"); return new Response(); });

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            // When
            await this.requestDispatcher.Dispatch(context, new CancellationToken());

            // Then
            capturedExecutionOrder.Count().ShouldEqual(2);
            capturedExecutionOrder.SequenceEqual(expectedExecutionOrder).ShouldBeTrue();
        }
예제 #58
0
            /// <summary>
            /// Adds a before-request process pipeline to the module.
            /// </summary>
            /// <param name="before">An <see cref="BeforePipeline"/> instance.</param>
            /// <returns>An instance to the current <see cref="ConfigurableNancyModuleConfigurator"/>.</returns>
            public ConfigurableNancyModuleConfigurator Before(BeforePipeline before)
            {
                this.module.Before = before;

                return this;
            }
        public async Task should_preserve_stacktrace_when_rethrowing_the_excption()
        {
            // Given
            var route = new FakeRoute
            {
                Action = (o, ct) => BrokenMethod()
            };

            var before = new BeforePipeline();
            before += ctx => null;

            var after = new AfterPipeline();
            after += ctx => { };

            var resolvedRoute = new ResolveResult(
                route,
                DynamicDictionary.Empty,
                before,
                after,
                (ctx, ex) => null);

            A.CallTo(() => this.routeResolver.Resolve(A<NancyContext>.Ignored)).Returns(resolvedRoute);

            var context =
                new NancyContext { Request = new Request("GET", "/", "http") };

            var exception = await RecordAsync.Exception(async () => await this.requestDispatcher.Dispatch(context, new CancellationToken()));

            exception.StackTrace.ShouldContain("BrokenMethod");
        }
 public PreRequestHooksPipelineFixture()
 {
     this.pipeline = new BeforePipeline();
 }