Example #1
0
        public void ProcessRequestWithNormalControlFlowForAsynchronousController()
        {
            // Arrange
            Mock <HttpContextBase> mockHttpContext = new Mock <HttpContextBase>();

            mockHttpContext.Expect(c => c.Response.AppendHeader(MvcHandler.MvcVersionHeaderName, "1.0")).Verifiable();

            RequestContext  requestContext = new RequestContext(mockHttpContext.Object, GetRouteData());
            MvcAsyncHandler handler        = new MvcAsyncHandler(requestContext);

            MockAsyncResult         asyncResult    = new MockAsyncResult();
            Mock <IAsyncController> mockController = new Mock <IAsyncController>();

            mockController.Expect(c => c.BeginExecute(requestContext, It.IsAny <AsyncCallback>(), It.IsAny <object>())).Returns(asyncResult).Verifiable();
            mockController.Expect(c => c.EndExecute(asyncResult)).Verifiable();
            mockController.As <IDisposable>().Expect(c => c.Dispose()).AtMostOnce().Verifiable();

            ControllerBuilder builder = new ControllerBuilder();

            builder.SetControllerFactory(new SimpleControllerFactory(mockController.Object));
            handler.ControllerBuilder = builder;

            // Act
            IAsyncResult returnedAsyncResult = handler.BeginProcessRequest(mockHttpContext.Object, null, null);

            handler.EndProcessRequest(returnedAsyncResult);

            mockHttpContext.Verify();
            mockController.Verify();
        }
Example #2
0
        public void ExecuteCoreWithAsynchronousInvokerAndActionCompletesSuccessfully()
        {
            // Arrange
            ControllerContext controllerContext = GetControllerContext();
            MockAsyncResult   asyncResult       = new MockAsyncResult();

            Mock <ITempDataProvider> mockTempDataProvider = new Mock <ITempDataProvider>();

            mockTempDataProvider.Expect(p => p.LoadTempData(controllerContext)).Returns(new Dictionary <string, object>()).Verifiable();
            mockTempDataProvider.Expect(p => p.SaveTempData(controllerContext, It.IsAny <IDictionary <string, object> >())).AtMostOnce().Verifiable();

            Mock <IAsyncActionInvoker> mockInvoker = new Mock <IAsyncActionInvoker>();

            mockInvoker.Expect(i => i.BeginInvokeAction(controllerContext, "SomeAction", It.IsAny <AsyncCallback>(), It.IsAny <object>())).Returns(asyncResult).Verifiable();
            mockInvoker.Expect(i => i.EndInvokeAction(asyncResult)).Returns(true).Verifiable();

            EmptyController controller = new EmptyController()
            {
                ControllerContext = controllerContext,
                TempDataProvider  = mockTempDataProvider.Object,
                ActionInvoker     = mockInvoker.Object
            };

            // Act
            IAsyncResult returnedAsyncResult = controller.BeginExecuteCore(null, null);

            controller.TempData["key"] = "value";
            controller.EndExecuteCore(returnedAsyncResult);

            // Assert
            mockInvoker.Verify();
            mockTempDataProvider.Verify();
        }
        public void RegisterTask_AsynchronousCompletion_SwallowsExceptionsThrownByEndDelegate()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            using (ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */))
            {
                Func <AsyncCallback, IAsyncResult> beginDelegate = callback =>
                {
                    MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                    ThreadPool.QueueUserWorkItem(_ =>
                    {
                        callback(asyncResult);
                        waitHandle.Set();
                    });
                    return(asyncResult);
                };
                Action <IAsyncResult> endDelegate = delegate
                {
                    endDelegateWasCalled = true;
                    throw new Exception("This is a sample exception.");
                };

                // Act
                asyncManager.RegisterTask(beginDelegate, endDelegate);
                waitHandle.WaitOne();

                // Assert
                Assert.True(endDelegateWasCalled);
                Assert.Equal(0, asyncManager.OutstandingOperations.Count);
            }
        }
        public void RegisterTask_AsynchronousCompletion() {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */);

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                ThreadPool.QueueUserWorkItem(_ => {
                    Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter shouldn't have been decremented yet.");
                    callback(asyncResult);
                    waitHandle.Set();
                });
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);
            waitHandle.WaitOne();

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsTrue(syncContext.SendWasCalled, "Asynchronous call to End() should have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
        public void ExecuteCoreWithAsynchronousInvokerAndActionCompletesSuccessfully() {
            // Arrange
            ControllerContext controllerContext = GetControllerContext();
            MockAsyncResult asyncResult = new MockAsyncResult();

            Mock<ITempDataProvider> mockTempDataProvider = new Mock<ITempDataProvider>();
            mockTempDataProvider.Expect(p => p.LoadTempData(controllerContext)).Returns(new Dictionary<string, object>()).Verifiable();
            mockTempDataProvider.Expect(p => p.SaveTempData(controllerContext, It.IsAny<IDictionary<string, object>>())).AtMostOnce().Verifiable();

            Mock<IAsyncActionInvoker> mockInvoker = new Mock<IAsyncActionInvoker>();
            mockInvoker.Expect(i => i.BeginInvokeAction(controllerContext, "SomeAction", It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(asyncResult).Verifiable();
            mockInvoker.Expect(i => i.EndInvokeAction(asyncResult)).Returns(true).Verifiable();

            EmptyController controller = new EmptyController() {
                ControllerContext = controllerContext,
                TempDataProvider = mockTempDataProvider.Object,
                ActionInvoker = mockInvoker.Object
            };

            // Act
            IAsyncResult returnedAsyncResult = controller.BeginExecuteCore(null, null);
            controller.TempData["key"] = "value";
            controller.EndExecuteCore(returnedAsyncResult);

            // Assert
            mockInvoker.Verify();
            mockTempDataProvider.Verify();
        }
        public void RegisterTask_SynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            Func <AsyncCallback, IAsyncResult> beginDelegate = callback =>
            {
                Assert.Equal(1, asyncManager.OutstandingOperations.Count);
                MockAsyncResult asyncResult = new MockAsyncResult(
                    true /* completedSynchronously */
                    );
                callback(asyncResult);
                return(asyncResult);
            };
            Action <IAsyncResult> endDelegate = delegate
            {
                endDelegateWasCalled = true;
            };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.True(endDelegateWasCalled);
            Assert.False(syncContext.SendWasCalled);
            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
        public void ExecuteCoreWithAsynchronousInvokerAndActionNotFound() {
            // Arrange
            ControllerContext controllerContext = GetControllerContext();
            MockAsyncResult asyncResult = new MockAsyncResult();

            Mock<ITempDataProvider> mockTempDataProvider = new Mock<ITempDataProvider>();
            mockTempDataProvider.Expect(p => p.LoadTempData(controllerContext)).Returns(new Dictionary<string, object>()).Verifiable();
            mockTempDataProvider.Expect(p => p.SaveTempData(controllerContext, It.IsAny<IDictionary<string, object>>())).AtMostOnce().Verifiable();

            Mock<IAsyncActionInvoker> mockInvoker = new Mock<IAsyncActionInvoker>();
            mockInvoker.Expect(i => i.BeginInvokeAction(controllerContext, "SomeAction", It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(asyncResult).Verifiable();
            mockInvoker.Expect(i => i.EndInvokeAction(asyncResult)).Returns(false).Verifiable();

            EmptyController controller = new EmptyController() {
                ControllerContext = controllerContext,
                TempDataProvider = mockTempDataProvider.Object,
                ActionInvoker = mockInvoker.Object
            };

            // Act
            IAsyncResult returnedAsyncResult = controller.BeginExecuteCore(null, null);
            controller.TempData["key"] = "value";
            ExceptionHelper.ExpectHttpException(
                delegate {
                    controller.EndExecuteCore(returnedAsyncResult);
                },
                @"A public action method 'SomeAction' was not found on controller 'Microsoft.Web.Mvc.Test.AsyncControllerTest+EmptyController'.",
                404);

            // Assert
            mockInvoker.Verify();
            mockTempDataProvider.Verify();
        }
        public void RegisterTask_AsynchronousCompletion_SwallowsExceptionsThrownByEndDelegate()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */);

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback =>
            {
                MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                ThreadPool.QueueUserWorkItem(_ =>
                {
                    callback(asyncResult);
                    waitHandle.Set();
                });
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate
            {
                endDelegateWasCalled = true;
                throw new Exception("This is a sample exception.");
            };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);
            waitHandle.WaitOne();

            // Assert
            Assert.True(endDelegateWasCalled);
            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
Example #9
0
        public void RegisterTask_AsynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            ManualResetEvent waitHandle = new ManualResetEvent(false /* initialState */);

            Func <AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(false /* completedSynchronously */);
                ThreadPool.QueueUserWorkItem(_ => {
                    Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter shouldn't have been decremented yet.");
                    callback(asyncResult);
                    waitHandle.Set();
                });
                return(asyncResult);
            };
            Action <IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);
            waitHandle.WaitOne();

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsTrue(syncContext.SendWasCalled, "Asynchronous call to End() should have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
Example #10
0
        public void ExecuteCallsInitialize()
        {
            // Arrange
            RequestContext  requestContext = new RequestContext(new Mock <HttpContextBase>().Object, new RouteData());
            MockAsyncResult asyncResult    = new MockAsyncResult();

            Mock <AsyncController> mockController = new Mock <AsyncController>()
            {
                CallBase = true
            };

            mockController.Expect(c => c.BeginExecuteCore(It.IsAny <AsyncCallback>(), It.IsAny <object>())).Returns(asyncResult).Verifiable();
            mockController.Expect(c => c.EndExecuteCore(asyncResult)).Verifiable();

            AsyncController  controller  = mockController.Object;
            IAsyncController iController = controller;

            // Act
            IAsyncResult returnedAsyncResult = iController.BeginExecute(requestContext, null, null);

            iController.EndExecute(returnedAsyncResult);

            // Assert
            Assert.AreEqual(requestContext, controller.ControllerContext.RequestContext);
            mockController.Verify();
        }
        public void ProcessRequestWithNormalControlFlowForAsynchronousController() {
            // Arrange
            Mock<HttpContextBase> mockHttpContext = new Mock<HttpContextBase>();
            mockHttpContext.ExpectMvcVersionResponseHeader().Verifiable();

            RequestContext requestContext = new RequestContext(mockHttpContext.Object, GetRouteData());
            MvcAsyncHandler handler = new MvcAsyncHandler(requestContext);

            MockAsyncResult asyncResult = new MockAsyncResult();
            Mock<IAsyncController> mockController = new Mock<IAsyncController>();
            mockController.Expect(c => c.BeginExecute(requestContext, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(asyncResult).Verifiable();
            mockController.Expect(c => c.EndExecute(asyncResult)).Verifiable();
            mockController.As<IDisposable>().Expect(c => c.Dispose()).AtMostOnce().Verifiable();

            ControllerBuilder builder = new ControllerBuilder();
            builder.SetControllerFactory(new SimpleControllerFactory(mockController.Object));
            handler.ControllerBuilder = builder;

            // Act
            IAsyncResult returnedAsyncResult = handler.BeginProcessRequest(mockHttpContext.Object, null, null);
            handler.EndProcessRequest(returnedAsyncResult);

            mockHttpContext.Verify();
            mockController.Verify();
        }
Example #12
0
        public void WrapCompletedSynchronously()
        {
            // Arrange
            IAsyncResult resultGivenToCallback = null;
            IAsyncResult innerResult           = new MockAsyncResult();

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Wrap(
                ar => { resultGivenToCallback = ar; },
                null,
                (callback, state) => {
                callback(innerResult);
                return(innerResult);
            },
                ar => { });

            // Assert
            Assert.AreEqual(outerResult, resultGivenToCallback);
        }
        public void ExecuteCallsInitialize() {
            // Arrange
            RequestContext requestContext = new RequestContext(new Mock<HttpContextBase>().Object, new RouteData());
            MockAsyncResult asyncResult = new MockAsyncResult();

            Mock<AsyncController> mockController = new Mock<AsyncController>() { CallBase = true };
            mockController.Expect(c => c.BeginExecuteCore(It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(asyncResult).Verifiable();
            mockController.Expect(c => c.EndExecuteCore(asyncResult)).Verifiable();

            AsyncController controller = mockController.Object;
            IAsyncController iController = controller;

            // Act
            IAsyncResult returnedAsyncResult = iController.BeginExecute(requestContext, null, null);
            iController.EndExecute(returnedAsyncResult);

            // Assert
            Assert.AreEqual(requestContext, controller.ControllerContext.RequestContext);
            mockController.Verify();
        }
Example #14
0
        public void WrapReturnsAsyncResultWhichWrapsInnerResult()
        {
            // Arrange
            object outerAsyncState = new object();

            IAsyncResult innerResult = new MockAsyncResult()
            {
                CompletedSynchronously = true,
                IsCompleted            = true
            };

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Wrap(null, outerAsyncState,
                                                               (callback, state) => innerResult,
                                                               ar => { });

            // Assert
            Assert.AreEqual(outerAsyncState, outerResult.AsyncState);
            Assert.AreEqual(innerResult.AsyncWaitHandle, outerResult.AsyncWaitHandle);
            Assert.AreEqual(innerResult.CompletedSynchronously, outerResult.CompletedSynchronously);
            Assert.AreEqual(innerResult.IsCompleted, outerResult.IsCompleted);
        }
Example #15
0
        public void ExecuteCoreWithAsynchronousInvokerAndActionNotFound()
        {
            // Arrange
            ControllerContext controllerContext = GetControllerContext();
            MockAsyncResult   asyncResult       = new MockAsyncResult();

            Mock <ITempDataProvider> mockTempDataProvider = new Mock <ITempDataProvider>();

            mockTempDataProvider.Expect(p => p.LoadTempData(controllerContext)).Returns(new Dictionary <string, object>()).Verifiable();
            mockTempDataProvider.Expect(p => p.SaveTempData(controllerContext, It.IsAny <IDictionary <string, object> >())).AtMostOnce().Verifiable();

            Mock <IAsyncActionInvoker> mockInvoker = new Mock <IAsyncActionInvoker>();

            mockInvoker.Expect(i => i.BeginInvokeAction(controllerContext, "SomeAction", It.IsAny <AsyncCallback>(), It.IsAny <object>())).Returns(asyncResult).Verifiable();
            mockInvoker.Expect(i => i.EndInvokeAction(asyncResult)).Returns(false).Verifiable();

            EmptyController controller = new EmptyController()
            {
                ControllerContext = controllerContext,
                TempDataProvider  = mockTempDataProvider.Object,
                ActionInvoker     = mockInvoker.Object
            };

            // Act
            IAsyncResult returnedAsyncResult = controller.BeginExecuteCore(null, null);

            controller.TempData["key"] = "value";
            ExceptionHelper.ExpectHttpException(
                delegate {
                controller.EndExecuteCore(returnedAsyncResult);
            },
                @"A public action method 'SomeAction' could not be found on controller 'Microsoft.Web.Mvc.Test.AsyncControllerTest+EmptyController'.",
                404);

            // Assert
            mockInvoker.Verify();
            mockTempDataProvider.Verify();
        }
Example #16
0
        public void ExecuteMethodWrapsAsyncExecuteMethods()
        {
            // Arrange
            IAsyncResult                asyncResult       = new MockAsyncResult();
            object                      expectedValue     = new object();
            ControllerContext           controllerContext = new Mock <ControllerContext>().Object;
            Dictionary <string, object> parameters        = new Dictionary <string, object>();

            Mock <AsyncActionDescriptor> mockDescriptor = new Mock <AsyncActionDescriptor>()
            {
                CallBase = true
            };

            mockDescriptor.Expect(d => d.BeginExecute(controllerContext, parameters, null, null)).Returns(asyncResult);
            mockDescriptor.Expect(d => d.EndExecute(asyncResult)).Returns(expectedValue);
            ActionDescriptor descriptor = mockDescriptor.Object;

            // Act
            object returnedValue = descriptor.Execute(controllerContext, parameters);

            // Assert
            Assert.AreEqual(expectedValue, returnedValue);
        }
Example #17
0
        public void RegisterTask_SynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager         = new AsyncManager(syncContext);
            bool         endDelegateWasCalled = false;

            Func <AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return(asyncResult);
            };
            Action <IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsFalse(syncContext.SendWasCalled, "Synchronous call to End() should not have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
Example #18
0
        public void ExecuteCoreWithAsynchronousInvokerAndBeginInvokeActionThrows()
        {
            // Arrange
            ControllerContext controllerContext = GetControllerContext();
            MockAsyncResult   asyncResult       = new MockAsyncResult();

            Mock <ITempDataProvider> mockTempDataProvider = new Mock <ITempDataProvider>();

            mockTempDataProvider.Expect(p => p.LoadTempData(controllerContext)).Returns(new Dictionary <string, object>()).Verifiable();
            mockTempDataProvider.Expect(p => p.SaveTempData(controllerContext, It.IsAny <IDictionary <string, object> >())).AtMostOnce().Verifiable();

            Mock <IAsyncActionInvoker> mockInvoker = new Mock <IAsyncActionInvoker>();
            EmptyController            controller  = new EmptyController()
            {
                ControllerContext = controllerContext,
                TempDataProvider  = mockTempDataProvider.Object,
                ActionInvoker     = mockInvoker.Object
            };

            mockInvoker
            .Expect(i => i.BeginInvokeAction(controllerContext, "SomeAction", It.IsAny <AsyncCallback>(), It.IsAny <object>()))
            .Callback(
                delegate(ControllerContext cc, string an, AsyncCallback cb, object s) {
                controller.TempData["key"] = "value";
                throw new InvalidOperationException("Some exception text.");
            });

            // Act
            ExceptionHelper.ExpectInvalidOperationException(
                delegate {
                controller.BeginExecuteCore(null, null);
            },
                @"Some exception text.");

            // Assert
            mockTempDataProvider.Verify();
        }
Example #19
0
        public void RegisterTaskWithFunc()
        {
            // Arrange
            Func <int>      numCallsFunc;
            AsyncManager    helper         = GetAsyncManagerForRegisterTask(out numCallsFunc);
            MockAsyncResult asyncResult    = new MockAsyncResult();
            AsyncCallback   storedCallback = null;

            int opCountDuringBeginDelegate = 0;
            int opCountDuringEndDelegate   = 0;

            Func <AsyncCallback, IAsyncResult> beginDelegate = innerCb => {
                storedCallback             = innerCb;
                opCountDuringBeginDelegate = helper.OutstandingOperations.Count;
                return(asyncResult);
            };
            AsyncCallback endDelegate = ar => {
                Assert.AreEqual(asyncResult, ar);
                opCountDuringEndDelegate = helper.OutstandingOperations.Count;
            };

            // Act
            int          opCountBeforeBeginDelegate = helper.OutstandingOperations.Count;
            IAsyncResult returnedAsyncResult        = helper.RegisterTask(beginDelegate, endDelegate);

            storedCallback(returnedAsyncResult);
            int opCountAfterEndDelegate = helper.OutstandingOperations.Count;

            // Assert
            Assert.AreEqual(asyncResult, returnedAsyncResult);
            Assert.AreEqual(0, opCountBeforeBeginDelegate);
            Assert.AreEqual(1, opCountDuringBeginDelegate);
            Assert.AreEqual(1, opCountDuringEndDelegate);
            Assert.AreEqual(0, opCountAfterEndDelegate);
            Assert.AreEqual(1, numCallsFunc(), "Send() was not called.");
        }
        public void InvokeActionMethodFilterWhereEndContinuationThrowsExceptionAndIsNotHandled() {
            // Arrange
            List<string> actions = new List<string>();
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            Exception exception = new Exception();
            ActionExecutingContext preContext = GetEmptyActionExecutingContext();
            MockAsyncResult asyncResult = new MockAsyncResult();

            ActionFilterImpl filter = new ActionFilterImpl() {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    actions.Add("OnActionExecuting");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    actions.Add("OnActionExecuted");
                    Assert.AreEqual(exception, filterContext.Exception, "Exception did not match.");
                    Assert.AreEqual(preContext.ActionDescriptor, filterContext.ActionDescriptor, "Descriptor did not match.");
                    Assert.IsFalse(filterContext.ExceptionHandled);
                }
            };

            BeginInvokeCallback beginContinuation = (innerCallback, innerState) => {
                actions.Add("BeginContinuation");
                return asyncResult;
            };

            AsyncCallback<ActionExecutedContext> endContinuation = ar => {
                Assert.AreEqual(asyncResult, ar);
                actions.Add("EndContinuation");
                throw exception;
            };

            // Act
            IAsyncResult returnedResult = AsyncControllerActionInvoker.BeginInvokeActionMethodFilter(filter, preContext, beginContinuation, endContinuation, null, null);
            Exception thrownException = ExceptionHelper.ExpectException<Exception>(
                delegate {
                    AsyncControllerActionInvoker.EndInvokeActionMethodFilter(returnedResult);
                });

            // Assert
            Assert.AreEqual(4, actions.Count);
            Assert.AreEqual("OnActionExecuting", actions[0]);
            Assert.AreEqual("BeginContinuation", actions[1]);
            Assert.AreEqual("EndContinuation", actions[2]);
            Assert.AreEqual("OnActionExecuted", actions[3]);

            Assert.AreEqual(exception, thrownException);
        }
        public void InvokeActionMethodFilterWhereEndContinuationThrowsThreadAbortException() {
            // Arrange
            List<string> actions = new List<string>();
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            ActionExecutingContext preContext = GetEmptyActionExecutingContext();
            MockAsyncResult asyncResult = new MockAsyncResult();

            ActionFilterImpl filter = new ActionFilterImpl() {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    actions.Add("OnActionExecuting");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    actions.Add("OnActionExecuted");
                    Thread.ResetAbort();
                    Assert.IsNull(filterContext.Exception, "Exception should not have shown up.");
                    Assert.AreEqual(preContext.ActionDescriptor, filterContext.ActionDescriptor, "Descriptor did not match.");
                    filterContext.ExceptionHandled = true;
                }
            };

            BeginInvokeCallback beginContinuation = (innerCallback, innerState) => {
                actions.Add("BeginContinuation");
                return asyncResult;
            };

            AsyncCallback<ActionExecutedContext> endContinuation = ar => {
                Assert.AreEqual(asyncResult, ar);
                actions.Add("EndContinuation");
                Thread.CurrentThread.Abort();
                return null;
            };

            // Act
            // Act
            IAsyncResult returnedResult = AsyncControllerActionInvoker.BeginInvokeActionMethodFilter(filter, preContext, beginContinuation, endContinuation, null, null);
            ExceptionHelper.ExpectException<ThreadAbortException>(
                delegate {
                    AsyncControllerActionInvoker.EndInvokeActionMethodFilter(returnedResult);
                },
                "Thread was being aborted.");

            // Assert
            Assert.AreEqual(4, actions.Count);
            Assert.AreEqual("OnActionExecuting", actions[0]);
            Assert.AreEqual("BeginContinuation", actions[1]);
            Assert.AreEqual("EndContinuation", actions[2]);
            Assert.AreEqual("OnActionExecuted", actions[3]);
        }
        public void ExecuteCoreWithAsynchronousInvokerAndBeginInvokeActionThrows() {
            // Arrange
            ControllerContext controllerContext = GetControllerContext();
            MockAsyncResult asyncResult = new MockAsyncResult();

            Mock<ITempDataProvider> mockTempDataProvider = new Mock<ITempDataProvider>();
            mockTempDataProvider.Expect(p => p.LoadTempData(controllerContext)).Returns(new Dictionary<string, object>()).Verifiable();
            mockTempDataProvider.Expect(p => p.SaveTempData(controllerContext, It.IsAny<IDictionary<string, object>>())).AtMostOnce().Verifiable();

            Mock<IAsyncActionInvoker> mockInvoker = new Mock<IAsyncActionInvoker>();
            EmptyController controller = new EmptyController() {
                ControllerContext = controllerContext,
                TempDataProvider = mockTempDataProvider.Object,
                ActionInvoker = mockInvoker.Object
            };

            mockInvoker
                .Expect(i => i.BeginInvokeAction(controllerContext, "SomeAction", It.IsAny<AsyncCallback>(), It.IsAny<object>()))
                .Callback(
                    delegate(ControllerContext cc, string an, AsyncCallback cb, object s) {
                        controller.TempData["key"] = "value";
                        throw new InvalidOperationException("Some exception text.");
                    });

            // Act
            ExceptionHelper.ExpectInvalidOperationException(
                delegate {
                    controller.BeginExecuteCore(null, null);
                },
                @"Some exception text.");

            // Assert
            mockTempDataProvider.Verify();
        }
        public void InvokeActionMethodFilterWithNormalControlFlow() {
            // Arrange
            List<string> actions = new List<string>();
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            ActionDescriptor action = new Mock<ActionDescriptor>().Object;
            MockAsyncResult asyncResult = new MockAsyncResult();
            object state = new object();

            ActionExecutingContext preContext = new Mock<ActionExecutingContext>().Object;
            ActionExecutedContext postContext = new Mock<ActionExecutedContext>().Object;

            ActionFilterImpl filter = new ActionFilterImpl() {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    Assert.AreEqual(preContext, filterContext);
                    Assert.IsNull(filterContext.Result);
                    actions.Add("OnActionExecuting");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    Assert.AreEqual(postContext, filterContext);
                    actions.Add("OnActionExecuted");
                }
            };

            BeginInvokeCallback beginContinuation = (innerCallback, innerState) => {
                actions.Add("BeginContinuation");
                return asyncResult;
            };

            AsyncCallback<ActionExecutedContext> endContinuation = ar => {
                Assert.AreEqual(asyncResult, ar);
                actions.Add("EndContinuation");
                return postContext;
            };

            // Act
            IAsyncResult returnedAsyncResult = AsyncControllerActionInvoker.BeginInvokeActionMethodFilter(filter, preContext, beginContinuation, endContinuation, null, state);
            ActionExecutedContext returnedPostContext = AsyncControllerActionInvoker.EndInvokeActionMethodFilter(returnedAsyncResult);

            // Assert
            Assert.AreEqual(4, actions.Count);
            Assert.AreEqual("OnActionExecuting", actions[0]);
            Assert.AreEqual("BeginContinuation", actions[1]);
            Assert.AreEqual("EndContinuation", actions[2]);
            Assert.AreEqual("OnActionExecuted", actions[3]);

            Assert.AreEqual(state, returnedAsyncResult.AsyncState);
            Assert.AreEqual(postContext, returnedPostContext);
        }
Example #24
0
        public void WrapCompletedSynchronously() {
            // Arrange
            IAsyncResult resultGivenToCallback = null;
            IAsyncResult innerResult = new MockAsyncResult();

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Wrap(
                ar => { resultGivenToCallback = ar; },
                null,
                (callback, state) => {
                    callback(innerResult);
                    return innerResult;
                },
                ar => { });

            // Assert
            Assert.AreEqual(outerResult, resultGivenToCallback);
        }
        public void InvokeActionMethodWithFiltersOrdersFiltersCorrectly() {
            // Arrange
            List<string> actions = new List<string>();
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            MockAsyncResult asyncResult = new MockAsyncResult();
            ActionResult actionResult = new ViewResult();

            ActionFilterImpl filter1 = new ActionFilterImpl() {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    actions.Add("OnActionExecuting1");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    actions.Add("OnActionExecuted1");
                }
            };
            ActionFilterImpl filter2 = new ActionFilterImpl() {
                OnActionExecutingImpl = delegate(ActionExecutingContext filterContext) {
                    actions.Add("OnActionExecuting2");
                },
                OnActionExecutedImpl = delegate(ActionExecutedContext filterContext) {
                    actions.Add("OnActionExecuted2");
                }
            };

            ControllerContext controllerContext = new ControllerContext() { Controller = new Mock<Controller>().Object };
            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;

            Mock<AsyncControllerActionInvoker> mockInvoker = new Mock<AsyncControllerActionInvoker>() { CallBase = true };
            mockInvoker.Expect(i => i.BeginInvokeActionMethod(controllerContext, ad, parameters, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(asyncResult);
            mockInvoker.Expect(i => i.EndInvokeActionMethod(asyncResult)).Returns(actionResult);

            AsyncControllerActionInvoker invoker = mockInvoker.Object;
            List<IActionFilter> filters = new List<IActionFilter>() { filter1, filter2 };

            // Act
            IAsyncResult returnedAsyncResult = invoker.BeginInvokeActionMethodWithFilters(controllerContext, filters, ad, parameters, null, null);
            ActionExecutedContext returnedPostContext = invoker.EndInvokeActionMethodWithFilters(returnedAsyncResult);

            // Assert
            Assert.AreEqual(4, actions.Count);
            Assert.AreEqual("OnActionExecuting1", actions[0]);
            Assert.AreEqual("OnActionExecuting2", actions[1]);
            Assert.AreEqual("OnActionExecuted2", actions[2]);
            Assert.AreEqual("OnActionExecuted1", actions[3]);

            Assert.AreEqual(actionResult, returnedPostContext.Result);
            Assert.IsNull(returnedPostContext.Exception);
        }
        public void RegisterTaskWithFunc() {
            // Arrange
            Func<int> numCallsFunc;
            AsyncManager helper = GetAsyncManagerForRegisterTask(out numCallsFunc);
            MockAsyncResult asyncResult = new MockAsyncResult();
            AsyncCallback storedCallback = null;

            int opCountDuringBeginDelegate = 0;
            int opCountDuringEndDelegate = 0;

            Func<AsyncCallback, IAsyncResult> beginDelegate = innerCb => {
                storedCallback = innerCb;
                opCountDuringBeginDelegate = helper.OutstandingOperations.Count;
                return asyncResult;
            };
            AsyncCallback endDelegate = ar => {
                Assert.AreEqual(asyncResult, ar);
                opCountDuringEndDelegate = helper.OutstandingOperations.Count;
            };

            // Act
            int opCountBeforeBeginDelegate = helper.OutstandingOperations.Count;
            IAsyncResult returnedAsyncResult = helper.RegisterTask(beginDelegate, endDelegate);
            storedCallback(returnedAsyncResult);
            int opCountAfterEndDelegate = helper.OutstandingOperations.Count;

            // Assert
            Assert.AreEqual(asyncResult, returnedAsyncResult);
            Assert.AreEqual(0, opCountBeforeBeginDelegate);
            Assert.AreEqual(1, opCountDuringBeginDelegate);
            Assert.AreEqual(1, opCountDuringEndDelegate);
            Assert.AreEqual(0, opCountAfterEndDelegate);
            Assert.AreEqual(1, numCallsFunc(), "Send() was not called.");
        }
        public void InvokeActionWithNormalControlFlow() {
            // Arrange
            ActionResult actionResult = new ViewResult();
            FilterInfo filters = new FilterInfo();
            ControllerDescriptor cd = new Mock<ControllerDescriptor>().Object;
            ActionDescriptor ad = new Mock<ActionDescriptor>().Object;
            Dictionary<string, object> parameterValues = new Dictionary<string, object>();
            ControllerContext controllerContext = new ControllerContext() {
                Controller = new EmptyController() { ValidateRequest = false }
            };

            MockAsyncResult asyncResult = new MockAsyncResult();

            bool invokeActionResultWasCalled = false;

            Mock<AsyncControllerActionInvokerHelper> mockHelper = new Mock<AsyncControllerActionInvokerHelper>() { CallBase = true };
            mockHelper.Expect(h => h.PublicGetControllerDescriptor(controllerContext)).Returns(cd).Verifiable();
            mockHelper.Expect(h => h.PublicFindAction(controllerContext, cd, "SomeAction")).Returns(ad).Verifiable();
            mockHelper.Expect(h => h.PublicGetFilters(controllerContext, ad)).Returns(filters).Verifiable();
            mockHelper.Expect(h => h.PublicInvokeAuthorizationFilters(controllerContext, filters.AuthorizationFilters, ad)).Returns(new AuthorizationContext()).Verifiable();
            mockHelper.Expect(h => h.PublicGetParameterValues(controllerContext, ad)).Returns(parameterValues).Verifiable();
            mockHelper.Expect(h => h.BeginInvokeActionMethodWithFilters(controllerContext, filters.ActionFilters, ad, parameterValues, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(asyncResult).Verifiable();
            mockHelper.Expect(h => h.EndInvokeActionMethodWithFilters(asyncResult)).Returns(new ActionExecutedContext() { Result = actionResult }).Verifiable();
            mockHelper
                .Expect(h => h.PublicInvokeActionResult(controllerContext, actionResult))
                .Callback(() => { invokeActionResultWasCalled = true; })
                .Verifiable();

            AsyncControllerActionInvokerHelper helper = mockHelper.Object;

            // Act & assert
            IAsyncResult returnedAsyncResult = helper.BeginInvokeAction(controllerContext, "SomeAction", null, null);
            Assert.IsFalse(invokeActionResultWasCalled, "InvokeActionResult() should not yet have been called.");
            bool retVal = helper.EndInvokeAction(returnedAsyncResult);

            Assert.IsTrue(retVal);
            mockHelper.Verify();
        }
        public void RegisterTask_SynchronousCompletion()
        {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback =>
            {
                Assert.Equal(1, asyncManager.OutstandingOperations.Count);
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.True(endDelegateWasCalled);
            Assert.False(syncContext.SendWasCalled);
            Assert.Equal(0, asyncManager.OutstandingOperations.Count);
        }
        public void RegisterTask_SynchronousCompletion() {
            // Arrange
            SimpleSynchronizationContext syncContext = new SimpleSynchronizationContext();
            AsyncManager asyncManager = new AsyncManager(syncContext);
            bool endDelegateWasCalled = false;

            Func<AsyncCallback, IAsyncResult> beginDelegate = callback => {
                Assert.AreEqual(1, asyncManager.OutstandingOperations.Count, "Counter was not incremented properly.");
                MockAsyncResult asyncResult = new MockAsyncResult(true /* completedSynchronously */);
                callback(asyncResult);
                return asyncResult;
            };
            Action<IAsyncResult> endDelegate = delegate { endDelegateWasCalled = true; };

            // Act
            asyncManager.RegisterTask(beginDelegate, endDelegate);

            // Assert
            Assert.IsTrue(endDelegateWasCalled);
            Assert.IsFalse(syncContext.SendWasCalled, "Synchronous call to End() should not have been routed through SynchronizationContext.Send()");
            Assert.AreEqual(0, asyncManager.OutstandingOperations.Count, "Counter was not decremented properly.");
        }
Example #30
0
        public void WrapReturnsAsyncResultWhichWrapsInnerResult() {
            // Arrange
            object outerAsyncState = new object();

            IAsyncResult innerResult = new MockAsyncResult() {
                CompletedSynchronously = true,
                IsCompleted = true
            };

            // Act
            IAsyncResult outerResult = AsyncResultWrapper.Wrap(null, outerAsyncState,
                (callback, state) => innerResult,
                ar => { });

            // Assert
            Assert.AreEqual(outerAsyncState, outerResult.AsyncState);
            Assert.AreEqual(innerResult.AsyncWaitHandle, outerResult.AsyncWaitHandle);
            Assert.AreEqual(innerResult.CompletedSynchronously, outerResult.CompletedSynchronously);
            Assert.AreEqual(innerResult.IsCompleted, outerResult.IsCompleted);
        }
        public void InvokeActionMethodWithAsynchronousDescriptor() {
            // Arrange
            ControllerContext controllerContext = new Mock<ControllerContext>().Object;
            Dictionary<string, object> parameters = new Dictionary<string, object>();
            ActionResult expectedResult = new ViewResult();

            IAsyncResult innerResult = new MockAsyncResult();

            Mock<ActionDescriptor> mockDescriptor = new Mock<ActionDescriptor>();
            IMock<IAsyncActionDescriptor> mockAsyncDescriptor = mockDescriptor.As<IAsyncActionDescriptor>();
            mockAsyncDescriptor.Expect(d => d.BeginExecute(controllerContext, parameters, It.IsAny<AsyncCallback>(), It.IsAny<object>())).Returns(innerResult);
            mockAsyncDescriptor.Expect(d => d.EndExecute(innerResult)).Returns(expectedResult);
            ActionDescriptor descriptor = mockDescriptor.Object;

            AsyncControllerActionInvoker invoker = new AsyncControllerActionInvoker();

            // Act
            IAsyncResult asyncResult = invoker.BeginInvokeActionMethod(controllerContext, descriptor, parameters, null, null);
            ActionResult returnedResult = invoker.EndInvokeActionMethod(asyncResult);

            // Assert
            Assert.AreEqual(expectedResult, returnedResult);
        }