public bool PosTest2()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest2: Call GetBaseException when InnerException property is not null reference");

        try
        {
            TestException desired = new TestException();
            Exception ex = new Exception(
                TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH),
                desired);
            Exception actual = ex.GetBaseException();

            if (!desired.Equals(actual))
            {
                TestLibrary.TestFramework.LogError("002.1", "Calling GetBaseException when InnerException property is not null reference does not return current exception instance");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] desired = " + desired + ", actual = " + actual);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
 public void TestExceptionFromExceptionTestJSONMessageToDotNetIsTestExceptionType()
 {
     TestException testException = new TestException();
     testException.Test1 = testString;
     String jsonMessage = marshaller.MarshallObject(testException);
     Assert.IsTrue(marshaller.UnmarshallObject<TestException>(jsonMessage) is IJavaException);
 }
        public void A_FlattenMerge_must_propagate_early_failure_from_main_stream()
        {
            var ex = new TestException("buh");
            var future = Source.Failed<Source<int, NotUsed>>(ex)
                .MergeMany(1, x => x)
                .RunWith(Sink.First<int>(), Materializer);

            future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow<TestException>().And.Should().Be(ex);
        }
Example #4
0
 public void A_Scan_must_Scan_empty_failed()
 {
     this.AssertAllStagesStopped(() =>
     {
         var error = new TestException("fail!");
         Action fail = () => Scan(Source.Failed<int>(error));
         fail.ShouldThrow<TestException>();
     }, Materializer);
 }
        public void When_Passed_A_Translatable_Exception_ToFaultException_Returns_A_Typed_Exception()
        {
            var exception = new TestException("This is an exception");
            var translator = new ExceptionTranslator();

            var result = translator.ToFaultException(exception);

            Assert.That(result, Is.TypeOf(typeof(FaultException<TestFault>)));
        }
 public void TestExceptionFromExceptionTestJSONMessageWithMessageFieldAddedToDotNetIsTestExceptionType()
 {
     TestException testException = new TestException();
     testException.Test1 = testString;
     String jsonMessage = marshaller.MarshallObject(testException);
     jsonMessage = jsonMessage.Substring(0, jsonMessage.LastIndexOf("}"));
     jsonMessage += ",\"message\":\"" + testString + "\"}";
     IJavaException exception = marshaller.UnmarshallObject<TestException>(jsonMessage) as IJavaException;
     Assert.AreEqual(exception.Message, testString);
 }
Example #7
0
 public static void ThrowTestException()
 {
     try
     {
         foo();
     }
     catch( System.Exception ex )
     {
         var e = new TestException( ex, TranslationMessages.Message2, "Parameter 1", DateTime.Now )
                         .AddData( "Console", Console.Out );
         throw e;
     }
 }
Example #8
0
 public void A_Flow_based_on_a_Task_must_produce_error_from_already_failed_Task()
 {
     this.AssertAllStagesStopped(() =>
     {
         var ex = new TestException("test");
         var c = this.CreateManualSubscriberProbe<int>();
         var p =
             Source.FromTask(Task.Run(new Func<int>(() => { throw ex; })))
                 .RunWith(Sink.AsPublisher<int>(false), Materializer);
         p.Subscribe(c);
         c.ExpectSubscriptionAndError().Should().Be(ex);
     }, Materializer);
 }
Example #9
0
        /* bool HandleException(TestException e)
         * return true if we can just ignore the exception.
         */
        public bool HandleException(TestException e)
        {
            _currentException = e;

            if (e is ItemNotFoundException)
            {
                return true;
            }
            else
            {

            }

            return false;
        }
Example #10
0
        public void A_Detacher_must_pass_through_failure()
        {
            this.AssertAllStagesStopped(() =>
            {
                var ex = new TestException("buh");
                var result = Source.From(Enumerable.Range(1, 100)).Select(x =>
                {
                    if (x == 50)
                        throw ex;
                    return x;
                }).Detach().RunWith(Sink.Seq<int>(), Materializer);

                result.Invoking(r => r.Wait(TimeSpan.FromSeconds(2))).ShouldThrow<TestException>().And.Should().Be(ex);
            }, Materializer);
        }
        public async Task ShouldThrowDispatcherException_WhenDispatcherThrows_AndUpdateDetectorThrows(
            [Frozen] Mock <IMessageDispatcher> dispatcher,
            [Frozen] Mock <IUpdateDetector> updateDetector,
            TestException exception,
            ConnectionHandler sut)
        {
            dispatcher.Setup(x => x.DispatchAsync(It.IsAny <ConnectedClient>(), It.IsAny <object>(), Cts.Token))
            .Returns(new ValueTask(Task.FromException(exception)));

            updateDetector.Setup(x => x.MarkForUpdate(It.IsAny <string>()))
            .Throws(Create <Exception>());

            await AssertThrowsAsync(
                () => sut.HandleAsync(Create <IConnection>(), Cts.Token),
                exception);
        }
        public async Task HttpCodeExceptionOption(Exception exception, HttpStatusCode expected)
        {
            var repo = new Mock <IRepository <ExchangeRate2> >();

            repo.Setup(r => r.GetAsync(It.IsAny <Query <ExchangeRate2> >()))
            .Throws(exception);

            SetupServer(service =>
            {
                service.AddScoped(_ => repo.Object);
                service.Configure <ExceptionHttpStatusCodeOption>(options => options.StatusCodeMapping = e => e switch
                {
                    TestException _ => HttpStatusCode.Ambiguous,
                    _ => (HttpStatusCode?)null,
                });
            });
Example #13
0
        public void A_UnfoldResourceSource_must_fail_when_create_throws_exception()
        {
            this.AssertAllStagesStopped(() =>
            {
                var testException = new TestException("");
                var p             = Source.UnfoldResource(() =>
                {
                    throw testException;
                }, Read, Close).RunWith(Sink.AsPublisher <string>(false), Materializer);
                var c = this.CreateManualSubscriberProbe <string>();
                p.Subscribe(c);

                c.ExpectSubscription();
                c.ExpectError().Should().Be(testException);
            }, Materializer);
        }
        public void A_FlattenMerge_must_propagate_failure_from_map_function()
        {
            var ex     = new TestException("buh");
            var future = Source.From(Enumerable.Range(1, 3))
                         .MergeMany(10, x =>
            {
                if (x == 3)
                {
                    throw ex;
                }
                return(Blocked);
            })
                         .RunWith(Sink.First <int>(), Materializer);

            future.Invoking(f => f.Wait(TimeSpan.FromSeconds(1))).ShouldThrow <TestException>().And.Should().Be(ex);
        }
Example #15
0
        public void GraphStage_timer_support_must_propagate_error_if_OnTimer_throws_an_Exception()
        {
            this.AssertAllStagesStopped(() =>
            {
                var exception  = new TestException("Expected exception to the rule");
                var upstream   = this.CreatePublisherProbe <int>();
                var downstream = this.CreateSubscriberProbe <int>();

                Source.FromPublisher(upstream)
                .Via(new ThrowStage(exception))
                .RunWith(Sink.FromSubscriber(downstream), Materializer);

                downstream.Request(1);
                downstream.ExpectError().Should().Be(exception);
            }, Materializer);
        }
    //[Theory, AutoMoqData]
    public async Task ShouldThrow_WhenStoreThrows(
        [Frozen] Mock <IConnectionInitializer> initializer,
        [Frozen] Mock <IConnectedClientStore> store,
        IConnection connection,
        ConnectedClient client,
        TestException exception,
        ConnectionHandler sut)
    {
        SetupClientFromInitializer(initializer, connection, client);

        store.Setup(x => x.Add(client))
        .Throws(exception);

        await AssertThrowsAsync(
            () => sut.HandleAsync(connection, Cts.Token), exception);
    }
Example #17
0
        public void A_Foreach_must_complete_future_with_failure_when_function_throws()
        {
            this.AssertAllStagesStopped(() =>
            {
                var error  = new TestException("test");
                var future = Source.Single(1).RunForeach(_ =>
                {
                    throw error;
                }, Materializer);

                future.Invoking(f => f.Wait(TimeSpan.FromSeconds(3)))
                .Should().Throw <TestException>()
                .And.Should()
                .Be(error);
            }, Materializer);
        }
Example #18
0
 public void A_Foreach_must_yield_the_first_error()
 {
     this.AssertAllStagesStopped(() =>
     {
         var p = TestPublisher.CreateManualProbe<int>(this);
         Source.FromPublisher(p).RunForeach(i => TestActor.Tell(i), Materializer).ContinueWith(task =>
         {
             if (task.Exception != null)
                 TestActor.Tell(task.Exception.InnerException);
         });
         var proc = p.ExpectSubscription();
         var ex = new TestException("ex");
         proc.SendError(ex);
         ExpectMsg(ex);
     }, Materializer);
 }
Example #19
0
            public async Task Should_set_response_StatusCode_to_handler_StatusCode_value()
            {
                var sut       = new ExceptionTestHandler <TestException>();
                var exception = new TestException();

                await sut.ExecuteAsync(new ExceptionHandlingContext(
                                           _httpContextHelper.HttpContextMock.Object,
                                           exception,
                                           default
                                           ));

                Assert.Equal(
                    sut.StatusCode,
                    _httpContextHelper.HttpResponse.StatusCode
                    );
            }
Example #20
0
        public void A_Foreach_must_complete_future_with_failure_when_function_throws()
        {
            this.AssertAllStagesStopped(() =>
            {
                var error = new TestException("test");
                var future = Source.Single(1).RunForeach(_ =>
                {
                    throw error;
                }, Materializer);

                future.Invoking(f => f.Wait(TimeSpan.FromSeconds(3)))
                    .ShouldThrow<TestException>()
                    .And.Should()
                    .Be(error);
            }, Materializer);
        }
    //[Theory, AutoMoqData]
    public async Task ShouldThrow_WhenDispatcherThrows(
        [Frozen] Mock <IMessageDispatcher> dispatcher,
        TestException exception,
        ConnectionHandler sut)
    {
        dispatcher.Setup(x => x.DispatchAsync(It.IsAny <ConnectedClient>(), It.IsAny <object>(), Cts.Token))
        .ThrowsAsync(exception);

        var connection = Create <IConnection>();

        Mock.Get(connection).Setup(x => x.ReceiveAsync(Cts.Token))
        .ReturnsAsync(Create <MessageWithMetadata>());

        await AssertThrowsAsync(
            () => sut.HandleAsync(connection, Cts.Token),
            exception);
    }
Example #22
0
        public void A_Sum_must_propagate_an_error()
        {
            this.AssertAllStagesStopped(() =>
            {
                var error = new TestException("test");
                var task  = InputSource.Select(x =>
                {
                    if (x > 50)
                    {
                        throw error;
                    }
                    return(x);
                }).RunSum((i, i1) => 0, Materializer);

                task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow <TestException>().WithMessage("test");
            }, Materializer);
        }
Example #23
0
        public void A_Sum_must_complete_task_with_failure_when_reduce_function_throws_and_the_supervisor_strategy_decides_to_stop()
        {
            this.AssertAllStagesStopped(() =>
            {
                var error = new TestException("test");
                var task  = InputSource.RunSum((x, y) =>
                {
                    if (x > 50)
                    {
                        throw error;
                    }
                    return(x + y);
                }, Materializer);

                task.Invoking(t => t.Wait(TimeSpan.FromSeconds(3))).ShouldThrow <TestException>().WithMessage("test");
            }, Materializer);
        }
Example #24
0
        public void OnErrorObservations()
        {
            Exception error1 = null;
            Exception error2 = null;

            var subject = new Subject <int>();

            Subscribe(subject, onError: e => error1 = e);
            Subscribe(subject, onError: e => error2 = e);

            var error = new TestException();

            subject.OnError(error);

            Assert.That(error1, Is.SameAs(error));
            Assert.That(error2, Is.SameAs(error));
        }
Example #25
0
 public void A_Flow_with_OnComplete_must_yield_the_first_error()
 {
     this.AssertAllStagesStopped(() =>
     {
         var onCompleteProbe = CreateTestProbe();
         var p = this.CreateManualPublisherProbe<int>();
         Source.FromPublisher(p)
             .To(Sink.OnComplete<int>(() => {}, ex => onCompleteProbe.Ref.Tell(ex)))
             .Run(Materializer);
         var proc = p.ExpectSubscription();
         proc.ExpectRequest();
         var cause = new TestException("test");
         proc.SendError(cause);
         onCompleteProbe.ExpectMsg(cause);
         onCompleteProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
     }, Materializer);
 }
 public void A_Flow_with_OnComplete_must_yield_the_first_error()
 {
     this.AssertAllStagesStopped(() =>
     {
         var onCompleteProbe = CreateTestProbe();
         var p = this.CreateManualPublisherProbe <int>();
         Source.FromPublisher(p)
         .To(Sink.OnComplete <int>(() => { }, ex => onCompleteProbe.Ref.Tell(ex)))
         .Run(Materializer);
         var proc = p.ExpectSubscription();
         proc.ExpectRequest();
         var cause = new TestException("test");
         proc.SendError(cause);
         onCompleteProbe.ExpectMsg(cause);
         onCompleteProbe.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
     }, Materializer);
 }
        public void IfMethodThrowsExceptionInvocationRawDataShouldContainThisException()
        {
            RunTest((container, logger) =>
            {
                string testMsg = "Test";
                logger.LogInvocationOf <InvocationTestClass>(t => t.ExceptionThrowingTestMethod(Input.Param <string>()))
                .PrepareLogData((container1, data, logData) =>
                {
                    TestException exc = data.Raw.Exception as TestException;

                    Assert.IsInstanceOf <TestException>(exc);
                    Assert.AreEqual(testMsg, exc?.Message);
                });

                Assert.Catch <TestException>(() => RegisterAndResolveComponent <InvocationTestClass>(container).ExceptionThrowingTestMethod(testMsg));
            });
        }
Example #28
0
        public void A_Detacher_must_pass_through_failure()
        {
            this.AssertAllStagesStopped(() =>
            {
                var ex     = new TestException("buh");
                var result = Source.From(Enumerable.Range(1, 100)).Select(x =>
                {
                    if (x == 50)
                    {
                        throw ex;
                    }
                    return(x);
                }).Detach().RunWith(Sink.Seq <int>(), Materializer);

                result.Invoking(r => r.Wait(TimeSpan.FromSeconds(2))).ShouldThrow <TestException>().And.Should().Be(ex);
            }, Materializer);
        }
Example #29
0
        public virtual void TestSuppressedExceptions()
        {
            // test with prior exception
            try
            {
                TestException t = new TestException();
                IOUtils.DisposeWhileHandlingException(t, new BrokenIDisposable(1), new BrokenIDisposable(2));
            }
            catch (TestException e1)
            {
                assertEquals("BASE-EXCEPTION", e1.Message);
                assertEquals(2, e1.GetSuppressed().Length);
                assertEquals("TEST-IO-EXCEPTION-1", e1.GetSuppressed()[0].Message);
                assertEquals("TEST-IO-EXCEPTION-2", e1.GetSuppressed()[1].Message);
            }
#pragma warning disable 168
            catch (Exception e2)
#pragma warning restore 168
            {
                Assert.Fail("Exception should not be thrown here");
            }

            // test without prior exception
            try
            {
                IOUtils.DisposeWhileHandlingException((TestException)null, new BrokenIDisposable(1), new BrokenIDisposable(2));
            }
#pragma warning disable 168
            catch (TestException e1)
#pragma warning restore 168
            {
                fail("TestException should not be thrown here");
            }
            catch (IOException e2)
            {
                assertEquals("TEST-IO-EXCEPTION-1", e2.Message);
                assertEquals(1, e2.GetSuppressed().Length);
                assertEquals("TEST-IO-EXCEPTION-2", e2.GetSuppressed()[0].Message);
            }
#pragma warning disable 168
            catch (Exception e2)
#pragma warning restore 168
            {
                fail("Exception should not be thrown here");
            }
        }
        public async Task FilterInParallelAsync_ExceptionHandling_RespectsMaxConcurrency()
        {
            int[]       numbers = { 1, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0, 3 };
            Exception[] expectedInnerExceptions = new TestException[] {
                new TestException(1),
                new TestException(2),
                new TestException(3)
            };

            const int MAX_CONCURRENT = 3;
            int       numConcurrent  = 0;

            bool reachedMaximum  = false;
            bool exceededMaximum = false;

            Task <IEnumerable <int> > filterTask = numbers.FilterInParallelAsync(async n => {
                int concurrentTasks = Interlocked.Increment(ref numConcurrent);
                exceededMaximum    |= concurrentTasks > MAX_CONCURRENT;
                reachedMaximum     |= concurrentTasks == MAX_CONCURRENT;

                await RandomDelay(200, 500).SafeAsync();
                Interlocked.Decrement(ref numConcurrent);

                if (n != 0)
                {
                    throw new TestException(n);
                }

                return(true);
            }, MAX_CONCURRENT);

            AggregateException caughtException = null;

            try {
                await filterTask.SafeAsync();
            } catch (AggregateException exception) {
                caughtException = exception;
            }

            Interlocked.MemoryBarrier();
            Assert.IsTrue(reachedMaximum);
            Assert.IsFalse(exceededMaximum);
            Assert.IsNotNull(caughtException);
            CollectionAssert.AreEqual(expectedInnerExceptions, caughtException.InnerExceptions);
        }
Example #31
0
    public static void DoltSqlTest(MySqlConnection conn)
    {
        string[] queries = new string[] {
            "select dolt_add('-A');",
            "select dolt_commit('-m', 'my commit')",
            "select dolt_checkout('-b', 'mybranch')",
            "insert into test (pk, `value`) values (1,1)",
            "select dolt_commit('-a', '-m', 'my commit2')",
            "select dolt_checkout('main')",
            "select dolt_merge('mybranch')",
        };

        for (int i = 0; i < queries.Length; i++)
        {
            try
            {
                var cmd = new MySqlCommand(queries[i], conn);
                cmd.ExecuteScalar();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
        }

        var finalCmd = new MySqlCommand("select COUNT(*) FROM dolt_log", conn);

        try
        {
            object result = finalCmd.ExecuteScalar();
            if (result != null)
            {
                int r = Convert.ToInt32(result);
                if (r != 3)
                {
                    TestException ex = new TestException($"Expected 3, Recieved {r}");
                    throw ex;
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.ToString());
        }
    }
Example #32
0
    /**
     * Log a unit test failure to the console.
     *
     * @param Exception error, the error to log.
     */
    protected override void LogFailure(Exception error)
    {
        // If the error is valid
        if (null != error)
        {
            // If the error is a test exception
            string msg = "";
            if (typeof(TestException) == error.GetType())
            {
                // Write the summary
                TestException te = error as TestException;
                msg = te.Description;
            }

            // Log as error to the console
            Debug.LogError(msg + "\n" + error);
        }
    }
Example #33
0
            public async Task Should_call_ExecuteCoreAsync()
            {
                var sut       = new ExceptionTestHandler <TestException>();
                var exception = new TestException();

                await sut.ExecuteAsync(new ExceptionHandlingContext(
                                           _httpContextHelper.HttpContextMock.Object,
                                           exception,
                                           default
                                           ));

                Assert.True(sut.HandleCoreWasCalled);
                Assert.Same(exception, sut.Exception);
                Assert.Same(
                    _httpContextHelper.HttpContextMock.Object,
                    sut.HttpContext
                    );
            }
    //[Theory, AutoMoqData]
    public async Task ShouldNotSwallowException_WhenInitializerFailed_AndSendingDisconnectedFailed(
        [Frozen] Mock <IConnectionInitializer> initializer,
        IConnection connection,
        TestException exception,
        ConnectionHandler sut)
    {
        SetupInitializerThrows(initializer, connection, exception);

        Mock.Get(connection).Setup(x => x.SendAsync(It.IsAny <Disconnected>(), Cts.Token))
        .ThrowsAsync(Create <Exception>());

        await SwallowAnyAsync(
            sut.HandleAsync(connection, Cts.Token));

        Mock.Get(connection).Verify(x => x.SendAsync(It.IsAny <Disconnected>(), Cts.Token));
        await AssertThrowsAsync(
            () => sut.HandleAsync(connection, Cts.Token), exception);
    }
Example #35
0
 public void A_Foreach_must_yield_the_first_error()
 {
     this.AssertAllStagesStopped(() =>
     {
         var p = this.CreateManualPublisherProbe <int>();
         Source.FromPublisher(p).RunForeach(i => TestActor.Tell(i), Materializer).ContinueWith(task =>
         {
             if (task.Exception != null)
             {
                 TestActor.Tell(task.Exception.InnerException);
             }
         });
         var proc = p.ExpectSubscription();
         var ex   = new TestException("ex");
         proc.SendError(ex);
         ExpectMsg(ex);
     }, Materializer);
 }
Example #36
0
        public void A_SharedKillSwitch_must_not_affect_streams_corresponding_to_another_KillSwitch()
        {
            this.AssertAllStagesStopped(() =>
            {
                var killSwitch1 = KillSwitches.Shared("switch");
                var killSwitch2 = KillSwitches.Shared("switch");

                var t1 = this.SourceProbe <int>()
                         .Via(killSwitch1.Flow <int>())
                         .ToMaterialized(this.SinkProbe <int>(), Keep.Both)
                         .Run(Materializer);
                var t2 = this.SourceProbe <int>()
                         .Via(killSwitch2.Flow <int>())
                         .ToMaterialized(this.SinkProbe <int>(), Keep.Both)
                         .Run(Materializer);

                var upstream1   = t1.Item1;
                var downstream1 = t1.Item2;
                var upstream2   = t2.Item1;
                var downstream2 = t2.Item2;

                downstream1.Request(1);
                upstream1.SendNext(1);
                downstream1.ExpectNext(1);

                downstream2.Request(1);
                upstream2.SendNext(2);
                downstream2.ExpectNext(2);

                killSwitch1.Shutdown();
                upstream1.ExpectCancellation();
                downstream1.ExpectComplete();
                upstream2.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
                downstream2.ExpectNoMsg(TimeSpan.FromMilliseconds(100));

                var testException = new TestException("Abort");
                killSwitch2.Abort(testException);
                upstream1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
                downstream1.ExpectNoMsg(TimeSpan.FromMilliseconds(100));
                upstream2.ExpectCancellation();
                downstream2.ExpectError().InnerException.Should().Be(testException);
            }, Materializer);
        }
Example #37
0
        public void A_SharedKillSwitch_must_fail_immediately_flows_materialized_after_switch_failure()
        {
            this.AssertAllStagesStopped(() =>
            {
                var killSwitch    = KillSwitches.Shared("switch");
                var testException = new TestException("Abort");
                killSwitch.Abort(testException);

                var t = this.SourceProbe <int>()
                        .Via(killSwitch.Flow <int>())
                        .ToMaterialized(this.SinkProbe <int>(), Keep.Both)
                        .Run(Materializer);
                var upstream   = t.Item1;
                var downstream = t.Item2;

                upstream.ExpectCancellation();
                downstream.ExpectSubscriptionAndError().InnerException.Should().Be(testException);
            }, Materializer);
        }
Example #38
0
        public void A_lazy_source_must_fail_stage_when_upstream_fails()
        {
            this.AssertAllStagesStopped(() =>
            {
                var outProbe = this.CreateSubscriberProbe <int>();
                var inProbe  = this.CreatePublisherProbe <int>();

                Source.Lazily(() => Source.FromPublisher(inProbe)).RunWith(Sink.FromSubscriber(outProbe), Materializer);

                outProbe.Request(1);
                inProbe.ExpectRequest();
                inProbe.SendNext(27);
                outProbe.ExpectNext(27);

                var testException = new TestException("OMG Who set that on fire !?!");
                inProbe.SendError(testException);
                outProbe.ExpectError().Should().Be(testException);
            }, Materializer);
        }
        public void A_FlattenMerge_must_cancel_substreams_when_failing_from_substream()
        {
            var p1 = this.CreatePublisherProbe <int>();
            var p2 = this.CreatePublisherProbe <int>();
            var ex = new TestException("buh");
            var p  = new TaskCompletionSource <int>();


            Source.From(new[]
                        { Source.FromPublisher(p1), Source.FromPublisher(p2), Source.FromTask(p.Task) })
            .MergeMany(5, x => x)
            .RunWith(Sink.First <int>(), Materializer);

            p1.ExpectRequest();
            p2.ExpectRequest();
            p.SetException(ex);
            p1.ExpectCancellation();
            p2.ExpectCancellation();
        }
Example #40
0
        public void A_UnfoldResourceSource_must_fail_when_close_throws_exception()
        {
            this.AssertAllStagesStopped(() =>
            {
                var testException = new TestException("");
                var p             = Source.UnfoldResource(_open, Read, reader =>
                {
                    reader.Dispose();
                    throw testException;
                }).RunWith(Sink.AsPublisher <string>(false), Materializer);
                var c = this.CreateManualSubscriberProbe <string>();
                p.Subscribe(c);

                var sub = c.ExpectSubscription();
                sub.Request(61);
                c.ExpectNextN(60);
                c.ExpectError().Should().Be(testException);
            }, Materializer);
        }
Example #41
0
        public void A_AggregateAsync_must_propagate_an_error()
        {
            this.AssertAllStagesStopped(() =>
            {
                var error  = new TestException("buh");
                var future = InputSource.Select(x =>
                {
                    if (x > 50)
                    {
                        throw error;
                    }
                    return(x);
                }).RunAggregateAsync(NotUsed.Instance, (notused, _) => Task.FromResult(notused), Materializer);

                future.Invoking(f => f.Wait(TimeSpan.FromSeconds(3)))
                .ShouldThrow <TestException>()
                .And.Should().Be(error);
            }, Materializer);
        }
        public IEnumerator ExceptionsThrownInTaskAreLogged()
        {
            var go = new GameObject("TestGameObject");

            TestException.ExpectLog();
            go.CreateTaskRunner().StartTask(Test);

            yield return(null);

            Object.Destroy(go);

#pragma warning disable CS1998
            async Task Test()
            {
                throw new TestException();
            }

#pragma warning restore CS1998
        }
Example #43
0
        public void TestExceptionLogging()
        {
            TestException resolvedException = null;

            void logTest(LogEntry entry)
            {
                if (entry.Exception is TestException ex)
                {
                    Assert.IsNull(resolvedException, "exception was forwarded more than once");
                    resolvedException = ex;
                }
            }

            Logger.NewEntry += logTest;
            Logger.Error(new TestException(), "message");
            Logger.NewEntry -= logTest;

            Assert.IsNotNull(resolvedException, "exception wasn't forwarded by logger");
        }
Example #44
0
        public void A_Where_must_continue_if_error()
        {
            this.AssertAllStagesStopped(() =>
            {
                var ex = new TestException("Test");

                Source.From(Enumerable.Range(1, 3))
                    .Where(x =>
                    {
                        if (x == 2)
                            throw ex;
                        return true;
                    })
                    .WithAttributes(ActorAttributes.CreateSupervisionStrategy(Deciders.ResumingDecider))
                    .RunWith(this.SinkProbe<int>(), Materializer)
                    .Request(3)
                    .ExpectNext(1, 3)
                    .ExpectComplete();
            }, Materializer);
        }
Example #45
0
        public void A_FlowMonitor_must_return_Failed_when_stream_fails_and_propagate_the_error()
        {
            var t = this.SourceProbe<int>()
                .Monitor(Keep.Both)
                .ToMaterialized(this.SinkProbe<int>(), Keep.Both)
                .Run(Materializer);
            var source = t.Item1.Item1;
            var monitor = t.Item1.Item2;
            var sink = t.Item2;
            var ex = new TestException("Source failed");
            source.SendError(ex);
            AwaitAssert(() =>
            {
                var state = monitor.State as FlowMonitor.Failed;
                if(state != null && ReferenceEquals(state.Cause, ex))
                    return;

                throw new Exception();
            });
            sink.ExpectSubscriptionAndError().ShouldBe(ex);
        }
Example #46
0
        public void A_UniqueKillSwitch_must_fail_a_stream_if_requested()
        {
            var t = this.SourceProbe<int>()
                .ViaMaterialized(KillSwitches.Single<int>(), Keep.Both)
                .ToMaterialized(this.SinkProbe<int>(), Keep.Both)
                .Run(Materializer);
            var upstream = t.Item1.Item1;
            var killSwitch = t.Item1.Item2;
            var downstream = t.Item2;

            downstream.Request(1);
            upstream.SendNext(1);
            downstream.ExpectNext(1);

            var testException = new TestException("Abort");
            killSwitch.Abort(testException);

            upstream.ExpectCancellation();
            //is a AggregateException from the Task
            downstream.ExpectError().InnerException.Should().Be(testException);
        }
Example #47
0
        private void DoError()
        {
            if (NoError.IsPresent)
            {
                return;
            }

            var ex = new TestException(Message ?? "testerror");
            var err = ex.ErrorRecord;
            if (Terminating.IsPresent)
            {
                ThrowTerminatingError(err);
            }
            else if (Exception.IsPresent)
            {
                throw ex;
            }
            else
            {
                WriteError(err);
            }
        }
Example #48
0
        public void IdleTimeoutBidi_must_signal_error_to_all_outputs()
        {
            this.AssertAllStagesStopped(() =>
            {
                var upWrite = this.CreatePublisherProbe<string>();
                var upRead = this.CreateSubscriberProbe<int>();

                var downWrite = this.CreatePublisherProbe<int>();
                var downRead = this.CreateSubscriberProbe<string>();

                RunnableGraph.FromGraph(GraphDsl.Create(b =>
                {
                    var timeoutStage = b.Add(BidiFlow.BidirectionalIdleTimeout<string, int>(TimeSpan.FromSeconds(2)));

                    b.From(Source.FromPublisher(upWrite)).To(timeoutStage.Inlet1);
                    b.From(timeoutStage.Outlet1).To(Sink.FromSubscriber(downRead));
                    b.From(timeoutStage.Outlet2).To(Sink.FromSubscriber(upRead));
                    b.From(Source.FromPublisher(downWrite)).To(timeoutStage.Inlet2);

                    return ClosedShape.Instance;
                })).Run(Materializer);

                var te = new TestException("test");

                upWrite.SendError(te);

                upRead.ExpectSubscriptionAndError().ShouldBeEquivalentTo(te);
                downRead.ExpectSubscriptionAndError().ShouldBeEquivalentTo(te);
                downWrite.ExpectCancellation();
            }, Materializer);
        }
 public void A_ActorRefSource_must_fail_the_stream_when_receiving_Status_Failure()
 {
     this.AssertAllStagesStopped(() =>
     {
         var s = TestSubscriber.CreateManualProbe<int>(this);
         var actorRef = Source.ActorRef<int>(10, OverflowStrategy.Fail)
             .To(Sink.FromSubscriber(s))
             .Run(Materializer);
         s.ExpectSubscription();
         var ex = new TestException("testfailure");
         actorRef.Tell(new Status.Failure(ex));
         s.ExpectError().Should().Be(ex);
     }, Materializer);
 }
Example #50
0
        //Overloads
        public void Fail(string message, string details)
        {
            //Handle the assert, treat it as an error.
            Exception e = new TestException(TestResult.Assert, message, details, null, null);
            e.Source = "Debug.Assert";

            //Note: We don't throw the exception (by default), since we want to continue on Asserts
            //(as many of them are benign or simply a valid runtime error).
            if (this.ShouldThrow)
                throw e;

            TestLog.Error(TestResult.Assert, details, null, "Debug.Assert", message, new Exception().StackTrace, null, 0);
        }
Example #51
0
        public void GroupBy_must_abort_onError_from_upstream_when_substreams_are_running()
        {
            this.AssertAllStagesStopped(() =>
            {
                var publisherProbe = this.CreateManualPublisherProbe<int>();
                var publisher =
                    Source.FromPublisher(publisherProbe)
                        .GroupBy(2, x => x % 2)
                        .Lift(x => x % 2)
                        .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);
                var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
                publisher.Subscribe(subscriber);

                var upstreamSubscription = publisherProbe.ExpectSubscription();
                var downstreamSubscription = subscriber.ExpectSubscription();
                downstreamSubscription.Request(100);
                upstreamSubscription.SendNext(1);
                var substream = subscriber.ExpectNext().Item2;
                var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);

                substreamPuppet.Request(1);
                substreamPuppet.ExpectNext(1);

                var ex = new TestException("test");
                upstreamSubscription.SendError(ex);

                substreamPuppet.ExpectError(ex);
                subscriber.ExpectError().Should().Be(ex);
            }, Materializer);
        }
Example #52
0
    public bool PosTest4()
    {
        bool retVal = true;
        string randValue = null;

        TestLibrary.TestFramework.BeginScenario("PosTest4: Call ctor to construct a new Exception instance with InnerException is set");

        try
        {
            randValue = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LENGTH, c_MAX_STRING_LENGTH);
            TestException innerException = new TestException();
            Exception ex = new Exception(randValue, innerException);

            if (ex == null)
            {
                TestLibrary.TestFramework.LogError("004.1", "Calling ctor to construct a new Exception instance returns a null reference");
                retVal = false;
            }

            if (!ex.InnerException.Equals(innerException))
            {
                TestLibrary.TestFramework.LogError("004.2", "Calling ctor to construct a new Exception instance returns an instance with InnerException is not a instance of TestException");
                retVal = false;
            }

            if (!ex.Message.Equals(randValue))
            {
                TestLibrary.TestFramework.LogError("004.3", "Calling ctor to construct a new Exception instance returns an instance with Message is wrong");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] ex.Message = " + ex.Message + ", randValue = " + randValue);
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("004.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] randValue = " + randValue);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
Example #53
0
        public void A_Aggregate_must_complete_future_with_failure_when_folding_functions_throws()
        {
            this.AssertAllStagesStopped(() =>
            {
                var error = new TestException("buh");
                var future = InputSource.RunAggregate(0, (x,y) =>
                {
                    if (x > 50)
                        throw error;
                    return x + y;
                }, Materializer);

                future.Invoking(f => f.Wait(TimeSpan.FromSeconds(3)))
                    .ShouldThrow<TestException>()
                    .And.Should()
                    .Be(error);
            }, Materializer);
        }
		public virtual void TestDetailerMessage()
		{
			string message = "Detailed message";
			TestException e = new TestException(message, new Exception("The reason!"));
			Assert.IsGreaterOrEqual(0, e.ToString().IndexOf(message));
		}
Example #55
0
        public void GroupBy_must_fail_stream_when_GroupBy_function_throws()
        {
            this.AssertAllStagesStopped(() =>
            {
                var publisherProbe = this.CreateManualPublisherProbe<int>();
                var ex = new TestException("test");
                var publisher = Source.FromPublisher(publisherProbe).GroupBy(2, i =>
                {
                    if (i == 2)
                        throw ex;
                    return i%2;
                })
                    .Lift(x => x%2)
                    .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);


                var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
                publisher.Subscribe(subscriber);

                var upstreamSubscription = publisherProbe.ExpectSubscription();
                var downstreamSubscription = subscriber.ExpectSubscription();
                downstreamSubscription.Request(100);

                upstreamSubscription.SendNext(1);

                var substream = subscriber.ExpectNext().Item2;
                var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);

                substreamPuppet.Request(1);
                substreamPuppet.ExpectNext(1);

                upstreamSubscription.SendNext(2);
                subscriber.ExpectError().Should().Be(ex);
                substreamPuppet.ExpectError(ex);
                upstreamSubscription.ExpectCancellation();
            }, Materializer);
        }
Example #56
0
        public void GroupBy_must_resume_stream_when_GroupBy_function_throws()
        {
            this.AssertAllStagesStopped(() =>
            {
                var publisherProbe = this.CreateManualPublisherProbe<int>();
                var ex = new TestException("test");
                var publisher = Source.FromPublisher(publisherProbe).GroupBy(2, i =>
                {
                    if (i == 2)
                        throw ex;
                    return i%2;
                })
                    .Lift(x => x%2)
                    .WithAttributes(ActorAttributes.CreateSupervisionStrategy(Deciders.ResumingDecider))
                    .RunWith(Sink.AsPublisher<Tuple<int, Source<int, NotUsed>>>(false), Materializer);

                var subscriber = this.CreateManualSubscriberProbe<Tuple<int, Source<int, NotUsed>>>();
                publisher.Subscribe(subscriber);

                var upstreamSubscription = publisherProbe.ExpectSubscription();
                var downstreamSubscription = subscriber.ExpectSubscription();
                downstreamSubscription.Request(100);

                upstreamSubscription.SendNext(1);

                var substream = subscriber.ExpectNext().Item2;
                var substreamPuppet1 = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);

                substreamPuppet1.Request(10);
                substreamPuppet1.ExpectNext(1);

                upstreamSubscription.SendNext(2);
                upstreamSubscription.SendNext(4);

                var substream2 = subscriber.ExpectNext().Item2;
                var substreamPuppet2 = new StreamPuppet(substream2.RunWith(Sink.AsPublisher<int>(false), Materializer), this);
                substreamPuppet2.Request(10);
                substreamPuppet2.ExpectNext(4);

                upstreamSubscription.SendNext(3);
                substreamPuppet1.ExpectNext(3);

                upstreamSubscription.SendNext(6);
                substreamPuppet2.ExpectNext(6);

                upstreamSubscription.SendComplete();
                subscriber.ExpectComplete();
                substreamPuppet1.ExpectComplete();
                substreamPuppet2.ExpectComplete();

            }, Materializer);
        }
    public bool PosTest3()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest3: Call ctor with rand message");

        try
        {
            string expected = TestLibrary.Generator.GetString(-55, false, 1, 256);
            Exception expectedException = new TestException();
            MissingManifestResourceException ex = new MissingManifestResourceException(expected, expectedException);
            if (null == ex)
            {
                TestLibrary.TestFramework.LogError("003.1", "Calling ctor will rand message returns null reference");
                retVal = false;
            }

            string message = ex.Message;
            // using default message
            if (message != expected)
            {
                TestLibrary.TestFramework.LogError("003.2", "Calling ctor will rand message returns null message");
                TestLibrary.TestFramework.LogInformation("WARNING [LOCAL VARIABLES] message = " + message + ", expected = " + expected);
                retVal = false;
            }

            Exception innerException = ex.InnerException;
            // using default message
            if (innerException != expectedException)
            {
                TestLibrary.TestFramework.LogError("003.3", "Calling ctor will string.Empty returns wrong inner exception");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("003.0", "Unexpected exception: " + e);
            TestLibrary.TestFramework.LogInformation(e.StackTrace);
            retVal = false;
        }

        return retVal;
    }
        public void SplitAfter_must_fail_stream_when_SplitAfter_function_throws()
        {
            this.AssertAllStagesStopped(() =>
            {
                var publisherProbe = TestPublisher.CreateManualProbe<int>(this);
                var ex = new TestException("test");
                var publisher = Source.FromPublisher(publisherProbe).SplitAfter(i =>
                {
                    if (i == 3)
                        throw ex;
                    return i%3 == 0;
                }).Lift().RunWith(Sink.AsPublisher<Source<int, NotUsed>>(false), Materializer);
                
                var subscriber = TestSubscriber.CreateManualProbe<Source<int, NotUsed>>(this);
                publisher.Subscribe(subscriber);

                var upstreamSubscription = publisherProbe.ExpectSubscription();
                var downstreamSubscription = subscriber.ExpectSubscription();

                downstreamSubscription.Request(100);
                upstreamSubscription.SendNext(1);

                var substream = subscriber.ExpectNext();
                var substreamPuppet = new StreamPuppet(substream.RunWith(Sink.AsPublisher<int>(false), Materializer), this);

                substreamPuppet.Request(10);
                substreamPuppet.ExpectNext(1);

                upstreamSubscription.SendNext(2);
                substreamPuppet.ExpectNext(2);

                upstreamSubscription.SendNext(3);

                subscriber.ExpectError().Should().Be(ex);
                substreamPuppet.ExpectError(ex);
                upstreamSubscription.ExpectCancellation();
            }, Materializer);
        }
        public void A_UnfoldResourceAsyncSource_must_fail_when_close_throws_exception()
        {
            this.AssertAllStagesStopped(() =>
            {
                var testException = new TestException("");
                var p = Source.UnfoldResourceAsync(_open, Read, reader =>
                {
                    reader.Close();
                    throw testException;
                }).RunWith(Sink.AsPublisher<string>(false), Materializer);
                var c = this.CreateManualSubscriberProbe<string>();
                p.Subscribe(c);

                var sub = c.ExpectSubscription();
                sub.Request(61);
                c.ExpectNextN(60);
                c.ExpectError().Should().Be(testException);

            }, Materializer);
        }
Example #60
0
        /// <summary>
        /// Run the tool
        /// </summary>
        /// <param name="exceptionOnError">Throw an exception if the expected results don't match the actual results</param>
        /// <exception cref="System.Exception">Thrown when the expected results don't match the actual results</exception>
        /// <returns>The results of the run</returns>
        public virtual Result Run(bool exceptionOnError)
        {
            Result result = base.Run(this.Arguments);

            this.errors = this.CheckResult(result);

            if (exceptionOnError && 0 < this.errors.Count)
            {
                if (this.PrintOutputToConsole)
                {
                    this.PrintErrors();
                }

                TestException e = new TestException(String.Format("Expected results did not match actual results", this.CommandLine, result.ExitCode), result);
                throw e;
            }

            return result;
        }