Exemple #1
0
        public void Should_execute_all_cleanup_steps_despite_sync_exception_in_cleanup_and_complete_with_exception()
        {
            CleanupGuard guard = new CleanupGuard();
            List <int>   steps = new List <int>();
            Func <int, Exception, Task> doStepAsync = delegate(int i, Exception e)
            {
                steps.Add(i);
                if (e != null)
                {
                    throw e;
                }

                return(Task.FromResult(false));
            };

            InvalidTimeZoneException expectedException = new InvalidTimeZoneException("Expected.");

            guard.Register(() => doStepAsync(1, null));
            guard.Register(() => doStepAsync(2, expectedException));

            Task task = guard.RunAsync(g => Task.FromResult(false));

            Assert.Equal(TaskStatus.Faulted, task.Status);
            Assert.NotNull(task.Exception);
            AggregateException ae = Assert.IsType <AggregateException>(task.Exception).Flatten();

            Assert.Equal(1, ae.InnerExceptions.Count);
            Assert.Same(expectedException, ae.InnerExceptions[0]);
            Assert.Equal(new int[] { 2, 1 }, steps.ToArray());
        }
Exemple #2
0
        public void Should_execute_cleanup_steps_on_async_exception_in_delegate_and_complete_with_exception()
        {
            CleanupGuard     guard       = new CleanupGuard();
            List <int>       steps       = new List <int>();
            Func <int, Task> doStepAsync = delegate(int i)
            {
                steps.Add(i);
                return(Task.FromResult(false));
            };

            guard.Register(() => doStepAsync(1));
            guard.Register(() => doStepAsync(2));

            TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>();
            Task task = guard.RunAsync(g => tcs.Task);

            Assert.False(task.IsCompleted);

            InvalidTimeZoneException expectedException = new InvalidTimeZoneException("Expected.");

            tcs.SetException(expectedException);

            Assert.Equal(TaskStatus.Faulted, task.Status);
            Assert.NotNull(task.Exception);
            AggregateException ae = Assert.IsType <AggregateException>(task.Exception).Flatten();

            Assert.Equal(1, ae.InnerExceptions.Count);
            Assert.Same(expectedException, ae.InnerExceptions[0]);
            Assert.Equal(new int[] { 2, 1 }, steps.ToArray());
        }
        public void Open_with_events_traces_start_and_end_error()
        {
            ConnectionStub <IMyProxy> inner       = new ConnectionStub <IMyProxy>(true);
            ClientEventSource         eventSource = ClientEventSource.Instance;
            Guid id = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 5);
            ConnectionWithEvents <IMyProxy> outer = new ConnectionWithEvents <IMyProxy>(inner, eventSource, id);

            using (ClientEventListener listener = new ClientEventListener(eventSource, EventLevel.Informational, ClientEventSource.Keywords.Connection))
            {
                Task task = outer.OpenAsync();

                Assert.False(task.IsCompleted);
                listener.VerifyEvent(ClientEventId.ConnectionOpening, EventLevel.Informational, ClientEventSource.Keywords.Connection, EventOpcode.Start, id);
                listener.Events.Clear();

                InvalidTimeZoneException expectedException = new InvalidTimeZoneException("Expected.");
                inner.OpenCall.SetException(expectedException);
                Assert.True(task.IsFaulted);
                AggregateException ae = Assert.IsType <AggregateException>(task.Exception);
                Assert.Equal(1, ae.InnerExceptions.Count);
                Assert.Same(expectedException, ae.InnerException);

                listener.VerifyEvent(ClientEventId.ConnectionError, EventLevel.Informational, ClientEventSource.Keywords.Connection, EventOpcode.Stop, id, "System.InvalidTimeZoneException", "Expected.");
                listener.Events.Clear();
            }
        }
        public void ReportException_ExceptionIsNotNull_CallsWrapper()
        {
            Exception expectedException = new InvalidTimeZoneException("blah");
            Dictionary <string, string> expectedContextProperties = new Dictionary <string, string>
            {
                { "key 1", "value 1" },
                { "key 2", "value 2" },
            };

            Dictionary <string, string> actualContextProperties = null;

            Mock <ITelemetryClientWrapper> wrapperMock = new Mock <ITelemetryClientWrapper>(MockBehavior.Strict);

            wrapperMock.Setup(x => x.TrackException(expectedException, It.IsAny <Dictionary <string, string> >()))
            .Callback <Exception, Dictionary <string, string> >((e, d) => actualContextProperties = d);

            var aiTelemetry = new AITelemetry(wrapperMock.Object);

            foreach (KeyValuePair <string, string> pair in expectedContextProperties)
            {
                aiTelemetry.AddOrUpdateContextProperty(pair.Key, pair.Value);
            }

            aiTelemetry.ReportException(expectedException);

            Assert.IsNotNull(actualContextProperties);
            Assert.IsTrue(expectedContextProperties.SequenceEqual(actualContextProperties));

            wrapperMock.VerifyAll();
        }
        public async Task InvokeMessageHandlersForEventMessageAsync_ShouldInvokeAllRegisteredPerformanceMonitorsWithAppropriateErrorInfoWhenAHandlerBlows()
        {
            var performanceMonitor = new Mock <IEventStreamSubscriberPerformanceMonitor>();


            var expectedException = new InvalidTimeZoneException("Summat");
            var handler           = new Mock <IHandleEventsOf <object> >();

            handler.Setup(x => x.Handle(It.IsAny <object>())).Throws(expectedException);

            var called = false;

            performanceMonitor.Setup(x => x.Accept(StreamName, typeof(object).FullName, EventDate, 1, It.IsAny <IEnumerable <KeyValuePair <Type, Exception> > >())).Callback <string, string, DateTime, int, IEnumerable <KeyValuePair <Type, Exception> > >(
                (stream, type, createdDate, handlerCount, exceptions) =>
            {
                called = true;
                exceptions.Should().BeEquivalentTo(new[] { new KeyValuePair <Type, Exception>(handler.Object.GetType(), expectedException) });
            });

            var builder = new EventStreamSubscriberSettingsBuilder(_eventStoreHttpConnectionMock.Object, _eventHandlerResolverMock.Object, _streamPositionRepositoryMock.Object).WithCustomEventTypeResolver(_eventTypeResolverMock.Object).AddPerformanceMonitor(performanceMonitor.Object);

            _subscriber = (EventStreamSubscriber)EventStreamSubscriber.Create(builder);

            await _subscriber.InvokeMessageHandlersForEventMessageAsync(StreamName, typeof(object), new[] { handler.Object }, new object(), EventInfo);

            called.Should().BeTrue();
        }
        public async Task GetOrAdd_CachesCompilationExceptions()
        {
            // Arrange
            var path         = "/Views/Home/Index.cshtml";
            var fileProvider = new TestFileProvider();

            fileProvider.AddFile(path, "some content");
            var exception = new InvalidTimeZoneException();
            var compiler  = GetViewCompiler(fileProvider);

            compiler.Compile = _ => throw exception;

            // Act and Assert - 1
            var actual = await Assert.ThrowsAsync <InvalidTimeZoneException>(
                () => compiler.CompileAsync(path));

            Assert.Same(exception, actual);

            // Act and Assert - 2
            compiler.Compile = _ => throw new Exception("Shouldn't be called");

            actual = await Assert.ThrowsAsync <InvalidTimeZoneException>(
                () => compiler.CompileAsync(path));

            Assert.Same(exception, actual);
        }
Exemple #7
0
        public void Dequeue_with_events_traces_event_on_error()
        {
            InputQueueStub <string> inner       = new InputQueueStub <string>();
            QueueEventSource        eventSource = QueueEventSource.Instance;
            Guid id = new Guid(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1);
            InputQueueWithEvents <string> queue = new InputQueueWithEvents <string>(inner, id, eventSource);

            using (QueueEventListener listener = new QueueEventListener(eventSource, EventLevel.Informational, EventKeywords.None))
            {
                Task <string> task = queue.DequeueAsync();

                Assert.False(task.IsCompleted);

                listener.VerifyEvent(QueueEventId.Dequeue, EventLevel.Informational, EventKeywords.None, id);
                listener.Events.Clear();

                InvalidTimeZoneException expectedException = new InvalidTimeZoneException("Expected.");
                inner.PendingDequeue.SetException(expectedException);

                Assert.Equal(TaskStatus.Faulted, task.Status);
                Assert.NotNull(task.Exception);
                AggregateException ae = task.Exception;
                Assert.Equal(1, ae.InnerExceptions.Count);
                Assert.Same(expectedException, ae.InnerExceptions[0]);

                listener.VerifyEvent(QueueEventId.DequeueCompleted, EventLevel.Informational, EventKeywords.None, id);
            }
        }
Exemple #8
0
        public void EventManagerTests_FireEvent_FoundEvent_ValidArguments()
        {
            LogUtility.SetLogToConsole();
            InvalidTimeZoneException workaroundStuff = new InvalidTimeZoneException();
            var mockAggregator = new MockEventAggregator(new List <Type> {
                typeof(EntityMoveEvent)
            });

            EventManager._aggregator = mockAggregator;

            try
            {
                var result = EventManager.FireEvent("EntityMoveEvent", new object[]
                {
                    false,
                    new UnityEngine.Vector3(),
                    new UnityEngine.Vector3(),
                    null,                     //new World(),
                    new {
                        pos = 12,
                        rot = 241
                    }
                });
            }
            catch (SurvivalKitPluginException exception)
            {
                // exception should not- be thrown. constructor arguments are correct.
                Assert.IsNotNull(exception);
                Assert.Fail("Code should not reach this part.");
            }
        }
Exemple #9
0
        public void Throws_sync_all_handlers_return_false_on_sync_exception()
        {
            InvalidTimeZoneException         expected = new InvalidTimeZoneException("Expected.");
            ReturnFalseHandlersSyncOperation op       = new ReturnFalseHandlersSyncOperation(expected);
            InvalidTimeZoneException         actual   = Assert.Throws <InvalidTimeZoneException>(() => op.Start(null, null));

            Assert.Same(expected, actual);
        }
Exemple #10
0
        public void Throws_sync_no_matching_exception_handler_on_sync_exception()
        {
            InvalidTimeZoneException       expected = new InvalidTimeZoneException("Expected.");
            NoMatchingHandlerSyncOperation op       = new NoMatchingHandlerSyncOperation(expected);
            InvalidTimeZoneException       actual   = Assert.Throws <InvalidTimeZoneException>(() => op.Start(null, null));

            Assert.Same(expected, actual);
        }
Exemple #11
0
        public void Throws_sync_on_throw_from_handler_on_sync_exception()
        {
            InvalidTimeZoneException      expected = new InvalidTimeZoneException("Expected.");
            ThrowFromHandlerSyncOperation op       = new ThrowFromHandlerSyncOperation(expected);
            InvalidTimeZoneException      actual   = Assert.Throws <InvalidTimeZoneException>(() => op.Start(null, null));

            Assert.Same(expected, actual);
        }
Exemple #12
0
        public void Throw_in_finally_throws_sync_exception()
        {
            InvalidTimeZoneException expected = new InvalidTimeZoneException("Expected.");
            ThrowInFinallyOperation  op       = new ThrowInFinallyOperation(expected);
            InvalidTimeZoneException actual   = Assert.Throws <InvalidTimeZoneException>(() => op.Start(null, null));

            Assert.Same(expected, actual);
        }
Exemple #13
0
        public void Throw_before_yield_throws_sync_exception()
        {
            InvalidTimeZoneException  expected = new InvalidTimeZoneException("Expected.");
            ThrowBeforeYieldOperation op       = new ThrowBeforeYieldOperation(expected);
            InvalidTimeZoneException  actual   = Assert.Throws <InvalidTimeZoneException>(() => op.Start(null, null));

            Assert.Same(expected, actual);
        }
Exemple #14
0
        public void Throw_after_one_sync_step_throws_sync_exception()
        {
            InvalidTimeZoneException   expected = new InvalidTimeZoneException("Expected.");
            ThrowAfterOneStepOperation op       = new ThrowAfterOneStepOperation(expected);
            InvalidTimeZoneException   actual   = Assert.Throws <InvalidTimeZoneException>(() => op.Start(null, null));

            Assert.Same(expected, actual);
        }
Exemple #15
0
        public void Throws_sync_and_runs_finally_after_one_step_throws_sync()
        {
            InvalidTimeZoneException expected           = new InvalidTimeZoneException("Expected.");
            ThrowDuringAsyncStepWithFinallyOperation op = new ThrowDuringAsyncStepWithFinallyOperation(expected);
            InvalidTimeZoneException actual             = Assert.Throws <InvalidTimeZoneException>(() => op.Start(null, null));

            Assert.Same(expected, actual);
            Assert.True(op.RanFinally);
        }
Exemple #16
0
    public void T06_Exception()
    {
        var ex1 = Assert.Throws <FormatException>(() => int.Parse("invalid"));

        Write(ex1.Stringify(true));

        var ex2 = new InvalidTimeZoneException("message");

        Write(ex2.Stringify());
    }
Exemple #17
0
        public void Completes_successfully_after_catching_and_handling_exception_on_end()
        {
            InvalidTimeZoneException     expected = new InvalidTimeZoneException("Expected.");
            ThrowOnEndAndHandleOperation op       = new ThrowOnEndAndHandleOperation(1234, expected);
            IAsyncResult result = op.Start(null, null);

            Assert.True(result.IsCompleted);
            Assert.True(result.CompletedSynchronously);
            Assert.Equal(1234, ThrowOnEndAndHandleOperation.End(result));
            Assert.Same(expected, op.CaughtException);
        }
Exemple #18
0
        public void Completes_successfully_on_matching_exception_handler_on_sync_exception()
        {
            InvalidTimeZoneException           expected = new InvalidTimeZoneException("Expected.");
            SecondMatchingHandlerSyncOperation op       = new SecondMatchingHandlerSyncOperation(1234, expected);
            IAsyncResult result = op.Start(null, null);

            Assert.True(result.IsCompleted);
            Assert.True(result.CompletedSynchronously);
            Assert.Equal(1234, SecondMatchingHandlerSyncOperation.End(result));
            Assert.Same(expected, op.CaughtException);
        }
        public void ReportException_ThrowsInWrapper_EatsException()
        {
            Exception expectedException = new InvalidTimeZoneException("blah");

            Mock <ITelemetryClientWrapper> wrapperMock = new Mock <ITelemetryClientWrapper>(MockBehavior.Strict);

            wrapperMock.Setup(x => x.TrackException(expectedException, It.IsAny <Dictionary <string, string> >()))
            .Throws(new OutOfMemoryException());

            var aiTelemetry = new AITelemetry(wrapperMock.Object);

            aiTelemetry.ReportException(expectedException);

            wrapperMock.VerifyAll();
        }
Exemple #20
0
        public void Complete_ThrowsIfTaskFaulted()
        {
            TaskCompletionSource <bool> tcs            = new TaskCompletionSource <bool>();
            WorkerTask workerTask                      = new WorkerTask(tcs.Task);
            InvalidTimeZoneException expectedException = new InvalidTimeZoneException("expected");

            tcs.SetException(expectedException);

            Exception e = Record.Exception(() => workerTask.Complete());

            Assert.NotNull(e);
            AggregateException ae = Assert.IsType <AggregateException>(e);

            Assert.Equal(1, ae.InnerExceptions.Count);
            Assert.Same(expectedException, ae.InnerExceptions[0]);
        }
Exemple #21
0
        public void Throws_async_on_throw_from_handler_on_async_exception()
        {
            InvalidTimeZoneException       expected = new InvalidTimeZoneException("Expected.");
            ThrowFromHandlerAsyncOperation op       = new ThrowFromHandlerAsyncOperation(expected);
            IAsyncResult result = op.Start(null, null);

            Assert.False(result.IsCompleted);

            op.Complete();

            Assert.True(result.IsCompleted);
            Assert.False(result.CompletedSynchronously);
            InvalidTimeZoneException actual = Assert.Throws <InvalidTimeZoneException>(() => ThrowFromHandlerAsyncOperation.End(result));

            Assert.Same(expected, actual);
        }
Exemple #22
0
        public void Completes_with_async_exception_after_one_async_step_and_sync_exception()
        {
            InvalidTimeZoneException     expected = new InvalidTimeZoneException("Expected.");
            ThrowAfterAsyncStepOperation op       = new ThrowAfterAsyncStepOperation(expected);
            IAsyncResult result = op.Start(null, null);

            Assert.False(result.IsCompleted);

            op.Complete();

            Assert.True(result.IsCompleted);
            Assert.False(result.CompletedSynchronously);
            InvalidTimeZoneException actual = Assert.Throws <InvalidTimeZoneException>(() => ThrowAfterAsyncStepOperation.End(result));

            Assert.Same(expected, actual);
        }
Exemple #23
0
        public void Completes_with_async_exception_and_runs_finally_after_one_step_completes_with_async_exception()
        {
            InvalidTimeZoneException         expected = new InvalidTimeZoneException("Expected.");
            OneAsyncStepWithFinallyOperation op       = new OneAsyncStepWithFinallyOperation(1234);
            IAsyncResult result = op.Start(null, null);

            Assert.False(result.IsCompleted);

            op.Complete(expected);

            Assert.True(result.IsCompleted);
            Assert.False(result.CompletedSynchronously);
            InvalidTimeZoneException actual = Assert.Throws <InvalidTimeZoneException>(() => OneAsyncStepWithFinallyOperation.End(result));

            Assert.Same(expected, actual);
            Assert.Equal(1234, op.ResultAccessor);
        }
Exemple #24
0
        public void Completes_with_async_exception_and_runs_finally_after_one_step_completes_async_then_throws_sync_exception_on_end()
        {
            InvalidTimeZoneException expected = new InvalidTimeZoneException("Expected.");
            ThrowOnEndOfOneAsyncStepWithFinallyOperation op = new ThrowOnEndOfOneAsyncStepWithFinallyOperation(expected);
            IAsyncResult result = op.Start(null, null);

            Assert.False(result.IsCompleted);

            op.Complete();

            Assert.True(result.IsCompleted);
            Assert.False(result.CompletedSynchronously);
            InvalidTimeZoneException actual = Assert.Throws <InvalidTimeZoneException>(() => ThrowOnEndOfOneAsyncStepWithFinallyOperation.End(result));

            Assert.Same(expected, actual);
            Assert.True(op.RanFinally);
        }
        public void Returns_Valid_ArgumentWhiteSpaceException_From_Constructor_With_Message_InnerException()
        {
            // arrange
            var actualValue    = null as object;
            var innerException = new InvalidTimeZoneException();
            var message        = "message";
            var paramName      = null as string;

            // act
            var result = new ArgumentWhiteSpaceException(message, innerException);

            // assert
            Assert.IsNotNull(result);
            Assert.AreEqual(actualValue, result.ActualValue);
            Assert.AreEqual(innerException, result.InnerException);
            Assert.AreEqual(message, result.Message);
            Assert.AreEqual(paramName, result.ParamName);
        }
        public void GetOrAdd_CachesCompilationExceptions()
        {
            // Arrange
            var fileProvider = new TestFileProvider();

            fileProvider.AddFile(ViewPath, "some content");
            var cache     = new CompilerCache(fileProvider);
            var exception = new InvalidTimeZoneException();

            // Act and Assert - 1
            var actual = Assert.Throws <InvalidTimeZoneException>(() =>
                                                                  cache.GetOrAdd(ViewPath, _ => { throw exception; }));

            Assert.Same(exception, actual);

            // Act and Assert - 2
            actual = Assert.Throws <InvalidTimeZoneException>(() => cache.GetOrAdd(ViewPath, ThrowsIfCalled));
            Assert.Same(exception, actual);
        }
Exemple #27
0
        public void read_aggregate_exception()
        {
            var ex1 = new DivideByZeroException("Only Chuck Norris can do that");
            var ex2 = new RankException("You're last!");
            var ex3 = new InvalidTimeZoneException("You are in the wrong place!");

            var ex = new AggregateException(ex1, ex2, ex3);

            var record = new JobExecutionRecord();

            record.ReadException(ex);

            record.ExceptionText.ShouldNotBe(ex.ToString());
            record.ExceptionText.ShouldContain(ex1.ToString());
            record.ExceptionText.ShouldContain(ex2.ToString());
            record.ExceptionText.ShouldContain(ex3.ToString());

            record.ExceptionText.ShouldContain(JobExecutionRecord.ExceptionSeparator);
        }
Exemple #28
0
        public void Execute_func_throws_async_exception_caught_and_set_in_context()
        {
            InvalidTimeZoneException    exception = new InvalidTimeZoneException("Expected.");
            TaskCompletionSource <bool> tcs       = new TaskCompletionSource <bool>();

            tcs.SetException(exception);
            RetryLoop loop = new RetryLoop(r => tcs.Task);

            Task <RetryContext> task = loop.ExecuteAsync();

            Assert.Equal(TaskStatus.RanToCompletion, task.Status);
            RetryContext context = task.Result;

            Assert.Equal(1, context.Iteration);
            Assert.False(context.Succeeded);
            Assert.NotNull(context.Exception);
            Assert.Equal(1, context.Exception.InnerExceptions.Count);
            Assert.Same(exception, context.Exception.InnerExceptions[0]);
        }
Exemple #29
0
        public void RunAsync_ExceptionInFirstTask_ThrowsExceptionSkipsAction()
        {
            TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>();
            bool done = false;
            InvalidTimeZoneException expectedException = new InvalidTimeZoneException("expected");
            TaskChain chain = new TaskChain(() => tcs.Task, () => done = true);

            Task task = chain.RunAsync();

            tcs.SetException(expectedException);

            Assert.True(task.IsCompleted);
            Assert.True(task.IsFaulted);
            AggregateException ae = Assert.IsType <AggregateException>(task.Exception).Flatten();

            Assert.Equal(1, ae.InnerExceptions.Count);
            Assert.Same(expectedException, ae.InnerExceptions[0]);
            Assert.False(done);
        }
        public async Task InitializeAsync_ReportsOwnAsyncExceptions()
        {
            // Arrange
            var handler        = new Mock <CircuitHandler>(MockBehavior.Strict);
            var tcs            = new TaskCompletionSource <object>();
            var reportedErrors = new List <UnhandledExceptionEventArgs>();

            handler
            .Setup(h => h.OnCircuitOpenedAsync(It.IsAny <Circuit>(), It.IsAny <CancellationToken>()))
            .Returns(tcs.Task)
            .Verifiable();

            var circuitHost = TestCircuitHost.Create(handlers: new[] { handler.Object });

            circuitHost.UnhandledException += (sender, errorInfo) =>
            {
                Assert.Same(circuitHost, sender);
                reportedErrors.Add(errorInfo);
            };

            // Act
            var initializeAsyncTask = circuitHost.InitializeAsync(new CancellationToken());

            // Assert: No synchronous exceptions
            handler.VerifyAll();
            Assert.Empty(reportedErrors);

            // Act: Trigger async exception
            var ex = new InvalidTimeZoneException();

            tcs.SetException(ex);

            // Assert: The top-level task still succeeds, because the intended usage
            // pattern is fire-and-forget.
            await initializeAsyncTask;

            // Assert: The async exception was reported via the side-channel
            var aex = Assert.IsType <AggregateException>(reportedErrors.Single().ExceptionObject);

            Assert.Same(ex, aex.InnerExceptions.Single());
            Assert.False(reportedErrors.Single().IsTerminating);
        }