示例#1
0
        public async Task ExecuteAsync_RemovesInnerControllerFromReleaseListAndAddsItselfInstead()
        {
            // Arrange
            var request        = new HttpRequestMessage();
            var context        = ContextUtil.CreateControllerContext(request: request);
            var mockController = new Mock <IHttpController>();
            var mockDisposable = mockController.As <IDisposable>();

            mockController.Setup(c => c.ExecuteAsync(context, CancellationToken.None))
            .Callback <HttpControllerContext, CancellationToken>((cc, ct) => cc.Request.RegisterForDispose(mockDisposable.Object))
            .Returns(() => Task.FromResult(new HttpResponseMessage()))
            .Verifiable();
            context.ControllerDescriptor = _controllerDescriptor;
            context.Controller           = mockController.Object;
            var traceWriter = new TestTraceWriter();
            var tracer      = new HttpControllerTracer(request, mockController.Object, traceWriter);

            // Act
            var controller = (IHttpController)tracer;
            await controller.ExecuteAsync(context, CancellationToken.None);

            // Assert
            IEnumerable <IDisposable> disposables = (IEnumerable <IDisposable>)request.Properties[HttpPropertyKeys.DisposableRequestResourcesKey];

            Assert.Contains(tracer, disposables);
            Assert.DoesNotContain(mockDisposable.Object, disposables);
        }
        public void TestInit()
        {
            userService = new Mock <IUserService>();
            controller  = new UsersController(userService.Object);
            controller.ControllerContext = ContextUtil.CreateControllerContext();

            userService.Setup(x => x.GetUsersAsync(It.IsAny <QueryableOperator <UserDTO> >()))
            .ReturnsAsync(new PagedQueryResults <UserDTO>(0, new List <UserDTO>()));
        }
        protected override void Given()
        {
            var ac = ContextUtil.CreateActionContext();
            var cc = ContextUtil.CreateControllerContext(request: GivenRequest());

            ac.SetPrivateFieldValue("_controllerContext", cc);
            Context = ContextUtil.CreateActionExecutedConected(GivenException(), ac);
            base.Given();
        }
        protected override void Given()
        {
            Context = ContextUtil.CreateActionContext();
            Context.SetPrivateFieldValue("_modelState", GivenModelState());
            var cc = ContextUtil.CreateControllerContext(request: GivenRequest());

            Context.SetPrivateFieldValue("_controllerContext", cc);
            base.Given();
        }
        private HttpControllerContext CreateControllerContext(string controllerName, Type controllerType)
        {
            ComplexTypeAwareActionSelector actionSelector       = new ComplexTypeAwareActionSelector();
            HttpControllerContext          controllerContext    = ContextUtil.CreateControllerContext();
            HttpControllerDescriptor       controllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, controllerName, controllerType);

            controllerDescriptor.Configuration.Services.Replace(typeof(IHttpActionSelector), actionSelector);
            controllerContext.ControllerDescriptor = controllerDescriptor;

            return(controllerContext);
        }
        private HttpResponseMessage RequestSingleProject(string name)
        {
            var uri    = "http://localhost/api/projects/" + name;
            var ctrler = new ProjectsController
            {
                Configuration = new HttpConfiguration(),
                Request       = new HttpRequestMessage(),
                ActionContext = ContextUtil.CreateActionContext(ContextUtil.CreateControllerContext(request: new HttpRequestMessage(HttpMethod.Get, uri)))
            };

            return(ctrler.FindSingleProject(name).Result);
        }
        private static HttpActionExecutedContext GetActionExecutedContext <TResponse>(string uri, TResponse result)
        {
            var request               = new HttpRequestMessage(HttpMethod.Get, uri);
            var actionContext         = ContextUtil.CreateActionContext(ContextUtil.CreateControllerContext(request: request));
            var response              = request.CreateResponse <TResponse>(HttpStatusCode.OK, result);
            var actionExecutedContext = new HttpActionExecutedContext {
                ActionContext = actionContext, Response = response
            };

            actionContext.ActionDescriptor.Configuration = request.GetConfiguration();
            return(actionExecutedContext);
        }
示例#8
0
        public void Decorator_GetInner_On_HttpActionDescriptorTracer_Returns_HttpActionDescriptor()
        {
            // Arrange
            HttpActionDescriptor       expectedInner     = new Mock <HttpActionDescriptor>().Object;
            HttpControllerContext      controllerContext = ContextUtil.CreateControllerContext();
            HttpActionDescriptorTracer productUnderTest  = new HttpActionDescriptorTracer(controllerContext, expectedInner, new TestTraceWriter());

            // Act
            HttpActionDescriptor actualInner = Decorator.GetInner(productUnderTest as HttpActionDescriptor);

            // Assert
            Assert.Same(expectedInner, actualInner);
        }
        public Task ApiControllerBase_InvokesOnControllerExecuted()
        {
            //Arrange
            var fakeController    = new FakeOKController();
            var controllerContext = ContextUtil.CreateControllerContext(fakeController, "FakeOk", typeof(FakeOKController));

            //Act
            return(fakeController.ExecuteAsync(controllerContext, CancellationToken.None)

                   //Assert
                   .ContinueWith(task => {
                Assert.True(fakeController.OnControllerExecutedInvoked);
            }));
        }
        public Task ApiControllerBase_InvokesActionIfOnControllerExecutingDoesNotTerminate()
        {
            //Arrange
            var fakeController    = new FakeOKController();
            var controllerContext = ContextUtil.CreateControllerContext(fakeController, "FakeOk", typeof(FakeOKController));

            //Act
            return(fakeController.ExecuteAsync(controllerContext, CancellationToken.None)

                   //Assert
                   .ContinueWith(task => {
                Assert.Equal(HttpStatusCode.OK, task.Result.StatusCode);
                Assert.Equal("Hello World", ((StringContent)task.Result.Content).ReadAsStringAsync().Result);
            }));
        }
        public HttpActionSelectorTracerTest()
        {
            _mockActionDescriptor = new Mock <HttpActionDescriptor>()
            {
                CallBase = true
            };
            _mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            _mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection <HttpParameterDescriptor>(new HttpParameterDescriptor[0]));

            _controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "controller", typeof(ApiController));

            _controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());
            _controllerContext.ControllerDescriptor = _controllerDescriptor;

            _actionContext = ContextUtil.CreateActionContext(_controllerContext, actionDescriptor: _mockActionDescriptor.Object);
        }
        public void ExecuteAsync_Invokes_Inner_ExecuteAsync()
        {
            // Arrange
            var cts = new CancellationTokenSource();
            var mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            var controllerContext = ContextUtil.CreateControllerContext();
            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(ApiController));
            var arguments = new Dictionary<string, object>();
            var tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, new TestTraceWriter());

            // Act
            tracer.ExecuteAsync(controllerContext, arguments, cts.Token);

            // Assert
            mockActionDescriptor.Verify(a => a.ExecuteAsync(controllerContext, arguments, cts.Token), Times.Once());
        }
        private HttpResponseMessage RequestAllProjects()
        {
            var uri    = "http://localhost/api/projects/";
            var ctrler = new ProjectsController
            {
                Configuration     = new HttpConfiguration(),
                Request           = new HttpRequestMessage(),
                ControllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage(HttpMethod.Get, uri))
            };

            //configuração para a lib DRUM
            ctrler.Configuration.MapHttpAttributeRoutesAndUseUriMaker(new DefaultDirectRouteProvider());
            ctrler.Configuration.EnsureInitialized();

            //ctrler.Request.SetConfiguration(new HttpConfiguration());
            return(ctrler.GetProjects(0).Result);
        }
        public Task ApiControllerBase_DoesNotInvokeActionIfOnControllerExecutingThrowsException()
        {
            //Arrange
            var fakeController    = new FakeExceptionController();
            var controllerContext = ContextUtil.CreateControllerContext(fakeController, "FakeException", typeof(FakeExceptionController));

            //Act
            return(fakeController.ExecuteAsync(controllerContext, CancellationToken.None)

                   //Assert
                   .ContinueWith(task => {
                Assert.True(fakeController.OnControllerExecutingInvoked);
                Assert.True(fakeController.OnControllerExecutedInvoked);
                Assert.False(fakeController.IsActionInvoked);
                Assert.Equal(TaskStatus.Faulted, task.Status);
            }));
        }
        public Task ApiControllerBase_DoesNotInvokeActionIfOnControllerExecutingTerminates()
        {
            //Arrange
            var fakeController    = new FakeTerminatedController();
            var controllerContext = ContextUtil.CreateControllerContext(fakeController, "FakeTerminated", typeof(FakeTerminatedController));

            //Act
            return(fakeController.ExecuteAsync(controllerContext, CancellationToken.None)

                   //Assert
                   .ContinueWith(task => {
                Assert.True(fakeController.OnControllerExecutingInvoked);
                Assert.True(fakeController.OnControllerExecutedInvoked);
                Assert.False(fakeController.IsActionInvoked);
                Assert.Equal(HttpStatusCode.NotAcceptable, task.Result.StatusCode);
            }));
        }
示例#16
0
        public HttpActionInvokerTracerTest()
        {
            UsersController controller = new UsersController();

            _apiController = controller;

            Func <HttpResponseMessage> actionMethod = controller.Get;

            _actionContext = ContextUtil.CreateActionContext(
                ContextUtil.CreateControllerContext(instance: _apiController),
                new ReflectedHttpActionDescriptor {
                MethodInfo = actionMethod.Method
            });
            HttpRequestMessage request = new HttpRequestMessage();

            _actionContext.ControllerContext.Request = request;
        }
示例#17
0
        public void ExecuteAsync_Faults_And_Traces_When_Inner_Faults()
        {
            // Arrange
            InvalidOperationException exception            = new InvalidOperationException();
            TaskCompletionSource <HttpResponseMessage> tcs = new TaskCompletionSource <HttpResponseMessage>();

            tcs.TrySetException(exception);
            Mock <ApiController> mockController = new Mock <ApiController>()
            {
                CallBase = true
            };

            mockController.Setup(b => b.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <CancellationToken>())).Returns(tcs.Task);

            HttpRequestMessage    request           = new HttpRequestMessage();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);

            controllerContext.ControllerDescriptor = _controllerDescriptor;
            controllerContext.Controller           = mockController.Object;

            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);

            TestTraceWriter      traceWriter = new TestTraceWriter();
            HttpControllerTracer tracer      = new HttpControllerTracer(request, mockController.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Error)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            Exception thrown = Assert.Throws <InvalidOperationException>(() => ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None).Wait());

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, thrown);
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
        public void GetFilters_Returns_Wrapped_IFilters()
        {
            // Arrange
            Mock<IFilter> mockFilter = new Mock<IFilter>();
            Collection<IFilter> filters = new Collection<IFilter>(new IFilter[] { mockFilter.Object });
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetFilters()).Returns(filters);
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();
            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(ApiController));
            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, new TestTraceWriter());

            // Act
            IFilter[] wrappedFilters = tracer.GetFilters().ToArray();

            // Assert
            Assert.IsType<FilterTracer>(wrappedFilters[0]);
        }
        public void GetFilterPipeline_Returns_Wrapped_Filters()
        {
            // Arrange
            Mock<IFilter> mockFilter = new Mock<IFilter>();
            FilterInfo filter = new FilterInfo(mockFilter.Object, FilterScope.Global);
            Collection<FilterInfo> filterCollection = new Collection<FilterInfo>(new FilterInfo[] { filter });
            Mock<HttpActionDescriptor> mockActionDescriptor = new Mock<HttpActionDescriptor>() { CallBase = true };
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetFilterPipeline()).Returns(filterCollection);
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();
            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(ApiController));
            HttpActionDescriptorTracer tracer = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, new TestTraceWriter());

            // Act
            Collection<FilterInfo> wrappedFilterCollection = tracer.GetFilterPipeline();

            // Assert
            Assert.IsType<FilterTracer>(wrappedFilterCollection[0].Instance);
        }
示例#20
0
        public void GetBinding_Returns_HttpActionBindingTracer()
        {
            // Arrange
            Mock <HttpActionDescriptor> mockActionDescriptor = new Mock <HttpActionDescriptor>()
            {
                CallBase = true
            };

            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.GetParameters()).Returns(new Collection <HttpParameterDescriptor>(new HttpParameterDescriptor[0]));

            Mock <HttpParameterDescriptor> mockParameterDescriptor = new Mock <HttpParameterDescriptor>()
            {
                CallBase = true
            };
            Mock <HttpParameterBinding> mockParameterBinding = new Mock <HttpParameterBinding>(mockParameterDescriptor.Object)
            {
                CallBase = true
            };
            HttpActionBinding actionBinding = new HttpActionBinding(mockActionDescriptor.Object, new HttpParameterBinding[] { mockParameterBinding.Object });

            HttpControllerDescriptor controllerDescriptor = new HttpControllerDescriptor(new HttpConfiguration(), "controller", typeof(ApiController));

            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: new HttpRequestMessage());

            controllerContext.ControllerDescriptor = controllerDescriptor;

            Mock <IActionValueBinder> mockBinder = new Mock <IActionValueBinder>()
            {
                CallBase = true
            };

            mockBinder.Setup(b => b.GetBinding(It.IsAny <HttpActionDescriptor>())).Returns(actionBinding);
            ActionValueBinderTracer tracer = new ActionValueBinderTracer(mockBinder.Object, new TestTraceWriter());

            // Act
            HttpActionBinding actualBinding = ((IActionValueBinder)tracer).GetBinding(mockActionDescriptor.Object);

            // Assert
            Assert.IsType <HttpActionBindingTracer>(actualBinding);
            Assert.Same(mockActionDescriptor.Object, actualBinding.ActionDescriptor);
        }
示例#21
0
        public async Task ExecuteAsync_Invokes_Inner_And_Traces()
        {
            // Arrange
            HttpResponseMessage  response       = new HttpResponseMessage();
            Mock <ApiController> mockController = new Mock <ApiController>()
            {
                CallBase = true
            };

            mockController.Setup(b => b.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <CancellationToken>())).Returns(Task.FromResult <HttpResponseMessage>(response));

            HttpRequestMessage    request           = new HttpRequestMessage();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);

            controllerContext.ControllerDescriptor = _controllerDescriptor;
            controllerContext.Controller           = mockController.Object;

            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);

            TestTraceWriter      traceWriter = new TestTraceWriter();
            HttpControllerTracer tracer      = new HttpControllerTracer(request, mockController.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            var task = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None);
            HttpResponseMessage actualResponse = await task;

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(response, actualResponse);
        }
示例#22
0
        public void ExecuteAsync_IsCancelled_And_Traces_When_Inner_IsCancelled()
        {
            // Arrange
            Mock <ApiController> mockController = new Mock <ApiController>()
            {
                CallBase = true
            };

            mockController.Setup(b => b.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <CancellationToken>())).Returns(TaskHelpers.Canceled <HttpResponseMessage>());

            HttpRequestMessage    request           = new HttpRequestMessage();
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext(request: request);

            controllerContext.ControllerDescriptor = _controllerDescriptor;
            controllerContext.Controller           = mockController.Object;

            HttpActionContext actionContext = ContextUtil.CreateActionContext(controllerContext, actionDescriptor: _mockActionDescriptor.Object);

            TestTraceWriter      traceWriter = new TestTraceWriter();
            HttpControllerTracer tracer      = new HttpControllerTracer(request, mockController.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(actionContext.Request, TraceCategories.ControllersCategory, TraceLevel.Warn)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            Task      task   = ((IHttpController)tracer).ExecuteAsync(controllerContext, CancellationToken.None);
            Exception thrown = Assert.Throws <TaskCanceledException>(() => task.Wait());

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
        public void ExecuteAsync_Throws_What_Inner_Throws_And_Traces()
        {
            // Arrange
            Mock <HttpActionDescriptor> mockActionDescriptor = new Mock <HttpActionDescriptor>()
            {
                CallBase = true
            };
            InvalidOperationException exception = new InvalidOperationException("test");

            mockActionDescriptor.Setup(
                a => a.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <IDictionary <string, object> >())).Throws(exception);
            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();

            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(ApiController));
            IDictionary <string, object> arguments = new Dictionary <string, object>();
            TestTraceWriter            traceWriter = new TestTraceWriter();
            HttpActionDescriptorTracer tracer      = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin
                },
                new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Error)
                {
                    Kind = TraceKind.End
                }
            };

            // Act & Assert
            Assert.Throws <InvalidOperationException>(() => tracer.ExecuteAsync(controllerContext, arguments));

            // Assert
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
            Assert.Same(exception, traceWriter.Traces[1].Exception);
        }
        public void ExecuteAsync_Traces()
        {
            // Arrange
            Mock <HttpActionDescriptor> mockActionDescriptor = new Mock <HttpActionDescriptor>()
            {
                CallBase = true
            };

            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(a => a.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <IDictionary <string, object> >()))
            .Returns(TaskHelpers.FromResult <object>(null));
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();

            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(ApiController));
            IDictionary <string, object> arguments = new Dictionary <string, object>();
            TestTraceWriter            traceWriter = new TestTraceWriter();
            HttpActionDescriptorTracer tracer      = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, traceWriter);

            TraceRecord[] expectedTraces = new TraceRecord[]
            {
                new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.Begin, Operation = "ExecuteAsync"
                },
                new TraceRecord(controllerContext.Request, TraceCategories.ActionCategory, TraceLevel.Info)
                {
                    Kind = TraceKind.End
                }
            };

            // Act
            var result = tracer.ExecuteAsync(controllerContext, arguments);

            // Assert
            result.WaitUntilCompleted();
            Assert.Equal <TraceRecord>(expectedTraces, traceWriter.Traces, new TraceRecordComparer());
        }
        public void ExecuteAsync_Invokes_Inner_ExecuteAsync()
        {
            // Arrange
            bool executeCalled = false;
            Mock <HttpActionDescriptor> mockActionDescriptor = new Mock <HttpActionDescriptor>()
            {
                CallBase = true
            };

            mockActionDescriptor.Setup(a => a.ActionName).Returns("test");
            mockActionDescriptor.Setup(
                a => a.ExecuteAsync(It.IsAny <HttpControllerContext>(), It.IsAny <IDictionary <string, object> >())).Callback(() => executeCalled = true);
            HttpControllerContext controllerContext = ContextUtil.CreateControllerContext();

            controllerContext.ControllerDescriptor = new HttpControllerDescriptor(controllerContext.Configuration, "test", typeof(ApiController));
            IDictionary <string, object> arguments = new Dictionary <string, object>();
            HttpActionDescriptorTracer   tracer    = new HttpActionDescriptorTracer(controllerContext, mockActionDescriptor.Object, new TestTraceWriter());

            // Act
            tracer.ExecuteAsync(controllerContext, arguments);

            // Assert
            Assert.True(executeCalled);
        }
示例#26
0
 private static HttpControllerContext GetHttpControllerContext()
 {
     return(ContextUtil.CreateControllerContext());
 }
示例#27
0
 HttpActionContext SetupContext(string uri)
 {
     return(ContextUtil.CreateActionContext(ContextUtil.CreateControllerContext(request: new HttpRequestMessage(HttpMethod.Get, uri))));
 }