Beispiel #1
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 void When_cast_from_func_creates_a_pipeline_with_one_item()
        {
            var castPipeline = new AfterPipeline();
            castPipeline += r => { };

            Assert.Equal(1, castPipeline.PipelineDelegates.Count());
        }
Beispiel #3
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 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()));
        }
        public void PlusEquals_with_func_add_item_to_end_of_pipeline()
        {
            pipeline += r => { };

            pipeline.PipelineDelegates.ShouldHaveCount(1);
            Assert.Equal(1, pipeline.PipelineDelegates.Count());
        }
        public void Pipeline_containing_another_pipeline_will_invoke_items_in_both_pipelines()
        {
            var item1Called             = false;
            Action <NancyContext> item1 = (r) => { item1Called = true; };
            var item2Called             = false;
            Action <NancyContext> item2 = (r) => { item2Called = true; };
            var item3Called             = false;
            Action <NancyContext> item3 = (r) => { item3Called = true; };
            var item4Called             = false;
            Action <NancyContext> item4 = (r) => { item4Called = true; };

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

            subPipeline += item3;
            subPipeline += item4;

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

            Assert.True(item1Called);
            Assert.True(item2Called);
            Assert.True(item3Called);
            Assert.True(item4Called);
        }
        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 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);
        }
        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 PlusEquals_with_func_add_item_to_end_of_pipeline()
        {
            pipeline += r => { };

            pipeline.PipelineDelegates.ShouldHaveCount(1);
            Assert.Equal(1, pipeline.PipelineDelegates.Count());
        }
        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();
        }
Beispiel #12
0
        public void When_cast_from_func_creates_a_pipeline_with_one_item()
        {
            var castPipeline = new AfterPipeline();

            castPipeline += r => { };

            Assert.Equal(1, castPipeline.PipelineDelegates.Count());
        }
Beispiel #13
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;
 }
Beispiel #14
0
        public void When_cast_from_func_creates_a_pipeline_with_one_item()
        {
            Action <NancyContext> item1 = (r) => { };

            AfterPipeline castPipeline = item1;

            Assert.Equal(1, castPipeline.PipelineDelegates.Count());
            Assert.Same(item1, castPipeline.PipelineDelegates.First());
        }
Beispiel #15
0
        public void PlusEquals_with_func_add_item_to_end_of_pipeline()
        {
            Action<NancyContext> item1 = (r) => { };
            Action<NancyContext> item2 = (r) => { };
            pipeline.AddItemToEndOfPipeline(item2);

            pipeline += item1;

            Assert.Equal(2, pipeline.PipelineDelegates.Count());
            Assert.Same(item1, pipeline.PipelineDelegates.Last());
        }
        /// <summary>
        /// Use Response XFrame-Options Pipelines
        /// </summary>
        /// <param name="pipelines"></param>
        /// <param name="type"></param>
        /// <param name="domain"></param>
        /// <returns></returns>
        public static AfterPipeline UseResponseFrameOptions(this AfterPipeline pipelines, ResponseFrameOptionsType type, string domain)
        {
            if (pipelines == null)
            {
                throw new ArgumentNullException(nameof(pipelines));
            }

            pipelines.AddItemToEndOfPipeline(ctx => Internal.ResponseHelper.UpdateHeader(ctx, type, domain));

            return(pipelines);
        }
        public void PlusEquals_with_func_add_item_to_end_of_pipeline()
        {
            Action<NancyContext> item1 = (r) => { };
            Action<NancyContext> item2 = (r) => { };
            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());
    }
        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 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);
        }
        private static void ExecutePost(NancyContext context, CancellationToken cancellationToken, AfterPipeline postHook, Func<NancyContext, Exception, Response> onError, TaskCompletionSource<Response> tcs)
        {
            if (postHook == null)
            {
                tcs.SetResult(context.Response);
                return;
            }

            postHook.Invoke(context, cancellationToken).WhenCompleted(
                completedTask => tcs.SetResult(context.Response),
                completedTask => HandlePostHookFaultedTask(context, onError, completedTask, tcs),
                false);
        }
        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);
        }
        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()
        {
            pipeline.AddItemToEndOfPipeline(r => { });
            pipeline.AddItemToEndOfPipeline(r => { });
            var pipeline2 = new AfterPipeline();
            pipeline2.AddItemToEndOfPipeline(r => { });
            pipeline2.AddItemToEndOfPipeline(r => { });

            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());
        }
Beispiel #24
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);
        }
Beispiel #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);

            hooks.Enable(_fakeSessionManager);

            Assert.Equal(1, beforePipeline.PipelineDelegates.Count());
            Assert.Equal(1, afterPipeline.PipelineItems.Count());
        }
Beispiel #26
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);
        }
        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();
        }
Beispiel #28
0
        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()
        {
            pipeline.AddItemToEndOfPipeline(r => { });
            pipeline.AddItemToEndOfPipeline(r => { });
            var pipeline2 = new AfterPipeline();

            pipeline2.AddItemToEndOfPipeline(r => { });
            pipeline2.AddItemToEndOfPipeline(r => { });

            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();
        }
        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();
        }
Beispiel #31
0
        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()
        {
            Action<NancyContext> item1 = (r) => { };
            Action<NancyContext> item2 = (r) => { };
            pipeline.AddItemToEndOfPipeline(item1);
            pipeline.AddItemToEndOfPipeline(item2);
            Action<NancyContext> item3 = (r) => { };
            Action<NancyContext> item4 = (r) => { };
            var pipeline2 = new AfterPipeline();
            pipeline2.AddItemToEndOfPipeline(item3);
            pipeline2.AddItemToEndOfPipeline(item4);

            pipeline += pipeline2;

            Assert.Equal(4, pipeline.PipelineItems.Count());
            Assert.Same(item3, pipeline.PipelineDelegates.ElementAt(2));
            Assert.Same(item4, pipeline.PipelineDelegates.Last());
        }
        public void PlusEquals_with_another_pipeline_adds_those_pipeline_items_to_end_of_pipeline()
        {
            Action<NancyContext> item1 = (r) => { };
            Action<NancyContext> item2 = (r) => { };
            pipeline.AddItemToEndOfPipeline(item1);
            pipeline.AddItemToEndOfPipeline(item2);
            Action<NancyContext> item3 = (r) => { };
            Action<NancyContext> item4 = (r) => { };
            var pipeline2 = new AfterPipeline();
            pipeline2.AddItemToEndOfPipeline(item3);
            pipeline2.AddItemToEndOfPipeline(item4);

            pipeline += pipeline2;

            Assert.Equal(4, pipeline.PipelineItems.Count());
            Assert.Same(item3, pipeline.PipelineDelegates.ElementAt(2));
            Assert.Same(item4, pipeline.PipelineDelegates.Last());
        }
Beispiel #33
0
 public static void AutoQueryable(this AfterPipeline afterPipeline, NancyContext context, IQueryable <dynamic> query, IAutoQueryableContext autoQueryableContext)
 {
     context.Items.Add("autoqueryable-query", query);
     afterPipeline += ctx =>
     {
         if (query == null)
         {
             throw new Exception("Unable to retrieve value of IQueryable from context result.");
         }
         ctx.Response.Contents = stream =>
         {
             using (var writer = new StreamWriter(stream))
             {
                 var result = query.AutoQueryable(autoQueryableContext).ToAutoQueryListResult(autoQueryableContext);
                 writer.Write(JsonConvert.SerializeObject(result));
             }
         };
     };
 }
        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);
        }
        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 void When_cast_to_func_and_invoked_members_are_invoked()
        {
            var item1Called = false;
            Action<NancyContext> item1 = (r) => { item1Called = true; };
            var item2Called = false;
            Action<NancyContext> item2 = (r) => { item2Called = true; };
            var item3Called = false;
            Action<NancyContext> item3 = (r) => { item3Called = true; };
            pipeline.AddItemToEndOfPipeline(item1);
            pipeline.AddItemToEndOfPipeline(item2);
            pipeline.AddItemToEndOfPipeline(item3);

            Action<NancyContext> action = context => { };
            pipeline += action;

            pipeline.Invoke(CreateContext(), CancellationToken.None);

            Assert.True(item1Called);
            Assert.True(item2Called);
            Assert.True(item3Called);
        }
        public void When_cast_to_func_and_invoked_members_are_invoked()
        {
            var item1Called = false;
            Action<NancyContext> item1 = (r) => { item1Called = true; };
            var item2Called = false;
            Action<NancyContext> item2 = (r) => { item2Called = true; };
            var item3Called = false;
            Action<NancyContext> item3 = (r) => { item3Called = true; };
            pipeline.AddItemToEndOfPipeline(item1);
            pipeline.AddItemToEndOfPipeline(item2);
            pipeline.AddItemToEndOfPipeline(item3);

            Action<NancyContext> action = context => { };
            pipeline += action;

            action.Invoke(CreateContext());

            Assert.True(item1Called);
            Assert.True(item2Called);
            Assert.True(item3Called);
        }
        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);
        }
Beispiel #39
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);
        }
Beispiel #40
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);
        }
        public static void AutoQueryable(this AfterPipeline afterPipeline, NancyContext context, dynamic query, AutoQueryableProfile profile = null)
        {
            context.Items.Add("autoqueryable-query", query);

            afterPipeline += ctx =>
            {
                if (query == null)
                {
                    throw new Exception("Unable to retreive value of IQueryable from context result.");
                }
                Type entityType = query.GetType().GenericTypeArguments[0];

                string queryString = ctx.Request.Url.Query;

                ctx.Response.Contents = stream =>
                {
                    using (var writer = new StreamWriter(stream))
                    {
                        var result = QueryableHelper.GetAutoQuery(queryString, entityType, query, profile);
                        writer.Write(JsonConvert.SerializeObject(result));
                    }
                };
            };
        }
        public void Pipeline_containing_another_pipeline_will_invoke_items_in_both_pipelines()
        {
            var item1Called = false;
            Action<NancyContext> item1 = (r) => { item1Called = true; };
            var item2Called = false;
            Action<NancyContext> item2 = (r) => { item2Called = true; };
            var item3Called = false;
            Action<NancyContext> item3 = (r) => { item3Called = true; };
            var item4Called = false;
            Action<NancyContext> item4 = (r) => { item4Called = true; };
            pipeline += item1;
            pipeline += item2;
            var subPipeline = new AfterPipeline();
            subPipeline += item3;
            subPipeline += item4;

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

            Assert.True(item1Called);
            Assert.True(item2Called);
            Assert.True(item3Called);
            Assert.True(item4Called);
        }
        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_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();
        }
 public AfterPipelineFixture()
 {
     pipeline = new AfterPipeline();
 }
        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);
        }
        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();
        }
 public PostRequestHooksPipelineFixture()
 {
     pipeline = new AfterPipeline();
 }
            /// <summary>
            /// Adds an after-request process pipeline to the module.
            /// </summary>
            /// <param name="after">An <see cref="AfterPipeline"/> instance.</param>
            /// <returns>An instance to the current <see cref="ConfigurableNancyModuleConfigurator"/>.</returns>
            public ConfigurableNancyModuleConfigurator After(AfterPipeline after)
            {
                this.module.After = after;

                return(this);
            }
        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>
            /// Adds an after-request process pipeline to the module.
            /// </summary>
            /// <param name="after">An <see cref="AfterPipeline"/> instance.</param>
            /// <returns>An instance to the current <see cref="ConfigurableNancyModuleConfigurator"/>.</returns>
            public ConfigurableNancyModuleConfigurator After(AfterPipeline after)
            {
                this.module.After = after;

                return this;
            }
        private void ExecutePost(NancyContext context, CancellationToken cancellationToken, AfterPipeline postHook, TaskCompletionSource<Response> tcs)
        {
            if (postHook == null)
            {
                tcs.SetResult(context.Response);
                return;
            }

            postHook.Invoke(context, cancellationToken).WhenCompleted(
                                        t => tcs.SetResult(context.Response),
                                        t => tcs.SetException(t.Exception),
                                        false);
        }
        private void ExecutePost(NancyContext context, CancellationToken cancellationToken, AfterPipeline postHook, Func <NancyContext, Exception, dynamic> onError, TaskCompletionSource <Response> tcs)
        {
            if (postHook == null)
            {
                tcs.SetResult(context.Response);
                return;
            }

            postHook.Invoke(context, cancellationToken).WhenCompleted(
                completedTask => tcs.SetResult(context.Response),
                completedTask => this.HandlePostHookFaultedTask(context, onError, completedTask, tcs));
        }
 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;
 }
        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();
        }
        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);
        }
        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()));
        }
        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 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");
        }
Beispiel #60
0
        public void When_cast_from_func_creates_a_pipeline_with_one_item()
        {
            Action<NancyContext> item1 = (r) => { };

            AfterPipeline castPipeline = new AfterPipeline();
            castPipeline += item1;

            Assert.Equal(1, castPipeline.PipelineDelegates.Count());
            Assert.Same(item1, castPipeline.PipelineDelegates.First());
        }