Esempio n. 1
0
        public async Task DiagnosticsObserversInitializer_InvokedProperly()
        {
            string     name   = nameof(DiagnosticsObserversInitializer_InvokedProperly);
            MockLogger logger = new();
            DiagnosticsObserversInitializer diagnosticsInitializer = new(logger);

            try
            {
                await diagnosticsInitializer.StartAsync(CancellationToken.None).ConfigureAwait(false);

                using DiagnosticListener listener = new DiagnosticListener(name);

                AssertEnabledFor(listener, HttpClientListenerName);
                AssertEnabledFor(listener, HttpRequestOutEventName);
                AssertEnabledFor(listener, HttpRequestInEventName);
                AssertEnabledFor(listener, ExceptionEventName);

                Assert.IsFalse(listener.IsEnabled(name, "Should be disabled for other events"));

                Exception exception = new ArithmeticException();
                listener.Write(ExceptionEventName, exception);
                Assert.IsTrue(logger.Exceptions.Contains(exception), "Should log exception event");
            }
            catch
            {
                await diagnosticsInitializer.StopAsync(CancellationToken.None).ConfigureAwait(false);

                throw;
            }
        }
Esempio n. 2
0
        public async Task FireAndForgetInvokesTheExceptionActionWhenAnExceptionOccurs()
        {
            var expectedException = new ArithmeticException();
            var observedException = default(Exception);
            var completionSource  = new TaskCompletionSource <byte>(TaskCreationOptions.RunContinuationsAsynchronously);
            var invoked           = false;

            Action <Exception> exceptionAction = ex =>
            {
                invoked           = true;
                observedException = ex;

                completionSource.TrySetResult(0);
            };

            Task.Factory.StartNew(() =>
            {
                throw expectedException;
            }).FireAndForget(exceptionAction);

            // Wait for completion with timeout, just in case something goes wrong.

            var tokenSource = new CancellationTokenSource();

            if (completionSource.Task != await Task.WhenAny(completionSource.Task, Task.Delay(500, tokenSource.Token)))
            {
                tokenSource.Cancel();
            }

            // Verify the results.

            invoked.Should().BeTrue("because the exception action should have been invoked");
            observedException.Should().BeEquivalentTo(expectedException, "because the exception should have been passed to the handler");
        }
Esempio n. 3
0
        public static void Ctor_String()
        {
            string message   = "arithmetic operation error";
            var    exception = new ArithmeticException(message);

            ExceptionHelpers.ValidateExceptionProperties(exception, hResult: COR_E_ARITHMETIC, message: message);
        }
        public void Constructor3_Message_Null()
        {
            ArithmeticException   ame = new ArithmeticException("something");
            FileNotFoundException fnf = new FileNotFoundException((string)null, ame);

#if NET_2_0
            Assert.IsNotNull(fnf.Data, "#1");
#endif
            Assert.IsNull(fnf.FileName, "#2");
            Assert.IsNotNull(fnf.InnerException, "#3");
            Assert.AreSame(ame, fnf.InnerException, "#4");
#if NET_2_0
            Assert.IsNull(fnf.Message, "#5");
#else
            Assert.IsNotNull(fnf.Message, "#5");              // File or assembly name (null), or ...
#endif
            Assert.IsNull(fnf.FusionLog, "#6");
#if NET_2_0
            Assert.AreEqual(fnf.GetType().FullName + ":  ---> "
                            + ame.GetType().FullName + ": something", fnf.ToString(), "#7");
#else
            Assert.IsTrue(fnf.ToString().StartsWith(fnf.GetType().FullName), "#7");
            Assert.IsFalse(fnf.ToString().IndexOf(Environment.NewLine) != -1, "#9");
#endif
        }
        public void Constructor3_Message_Null()
        {
            ArithmeticException     ame = new ArithmeticException("something");
            BadImageFormatException bif = new BadImageFormatException((string)null, ame);

#if NET_2_0
            Assert.IsNotNull(bif.Data, "#1");
#endif
            Assert.IsNull(bif.FileName, "#2");
            Assert.IsNotNull(bif.InnerException, "#3");
            Assert.AreSame(ame, bif.InnerException, "#4");
#if NET_2_0
            Assert.IsNotNull(bif.Message, "#5"); // Could not load file or assembly '' ...
            Assert.IsTrue(bif.Message.IndexOf("''") != -1, "#6");
#else
            Assert.IsNotNull(bif.Message, "#5"); // Format of the executable (.exe) or library ...
            Assert.IsFalse(bif.Message.IndexOf("''") != -1, "#6");
#endif
            Assert.IsNull(bif.FusionLog, "#7");
            Assert.IsTrue(bif.ToString().StartsWith(bif.GetType().FullName), "#8");
            Assert.IsTrue(bif.ToString().IndexOf("---> " + ame.GetType().FullName) != -1, "#9");
#if !TARGET_JVM // ToString always has a stack trace under TARGET_JVM
            Assert.IsFalse(bif.ToString().IndexOf(Environment.NewLine) != -1, "#10");
#endif // TARGET_JVM
        }
Esempio n. 6
0
//JAVA TO C# CONVERTER TODO TASK: Most Java annotations will not have direct .NET equivalent attributes:
//ORIGINAL LINE: @Test public void shouldCatchArithmeticExceptionsAndTryNext()
        public virtual void ShouldCatchArithmeticExceptionsAndTryNext()
        {
            // GIVEN
            NumberArrayFactory  throwingMemoryFactory = mock(typeof(NumberArrayFactory));
            ArithmeticException failure = new ArithmeticException("This is an artificial failure");

            doThrow(failure).when(throwingMemoryFactory).newByteArray(anyLong(), any(typeof(sbyte[])), anyLong());
            FailureMonitor     monitor = new FailureMonitor();
            NumberArrayFactory factory = new NumberArrayFactory_Auto(monitor, throwingMemoryFactory, NumberArrayFactory.HEAP);
            int itemSize = 4;

            // WHEN
            ByteArray array = factory.NewByteArray(KILO, new sbyte[itemSize], 0);

            array.SetInt(KILO - 10, 0, 12345);

            // THEN
            verify(throwingMemoryFactory, times(1)).newByteArray(eq(KILO), any(typeof(sbyte[])), eq(0L));
            assertTrue(array is HeapByteArray);
            assertEquals(12345, array.GetInt(KILO - 10, 0));
            assertEquals(KILO * itemSize, monitor.Memory);
            assertEquals(NumberArrayFactory.HEAP, monitor.SuccessfulFactory);
            assertEquals(throwingMemoryFactory, single(monitor.AttemptedAllocationFailures).Factory);
            assertThat(single(monitor.AttemptedAllocationFailures).Failure.Message, containsString(failure.Message));
        }
        public ExpressionEvolverResult(double parameter, ArithmeticException exception)
            : base()
        {
            exception.CheckParameterForNull("exception");

            this.Parameter = parameter;
            this.Exception = exception;
        }
        public void TypePropertiesAreCorrect()
        {
            Assert.AreEqual(typeof(ArithmeticException).GetClassName(), "Bridge.ArithmeticException", "Name");
            object d = new ArithmeticException();

            Assert.True(d is ArithmeticException, "is DivideByZeroException");
            Assert.True(d is Exception, "is Exception");
        }
Esempio n. 9
0
        public static void Ctor_String_Exception()
        {
            string message        = "arithmetic operation error";
            var    innerException = new Exception("Inner exception");
            var    exception      = new ArithmeticException(message, innerException);

            ExceptionUtility.ValidateExceptionProperties(exception, hResult: COR_E_ARITHMETIC, innerException: innerException, message: message);
        }
        public void DefaultConstructorWorks()
        {
            var ex = new ArithmeticException();

            Assert.True((object)ex is ArithmeticException, "is ArithmeticException");
            Assert.AreEqual(ex.InnerException, null, "InnerException");
            Assert.AreEqual(ex.Message, "Overflow or underflow in the arithmetic operation.");
        }
        public void ConstructorWithMessageWorks()
        {
            var ex = new ArithmeticException("The message");

            Assert.True((object)ex is ArithmeticException, "is OverflowException");
            Assert.AreEqual(ex.InnerException, null, "InnerException");
            Assert.AreEqual(ex.Message, "The message");
        }
        public void ShouldIgnoreException_ReturnsTrue_IfOuterExceptionIsIgnored()
        {
            SetupConfiguration(_exceptionsToIgnore, null, null, _statusCodesToIgnore, false, null, null, null, true);

            var exception = new ArithmeticException("OuterException", new Exception("InnerException"));

            Assert.IsTrue(_errorService.ShouldIgnoreException(exception));
        }
        public void ShouldIgnoreException_ReturnsTrue_IfExceptionIsIgnored()
        {
            SetupConfiguration(_exceptionsToIgnore, null, null, _statusCodesToIgnore, false, null, null, null, errorCollectorEnabled: true);

            var exception = new ArithmeticException();

            Assert.IsTrue(_errorService.ShouldIgnoreException(exception));
        }
Esempio n. 14
0
        public void TypePropertiesAreCorrect()
        {
            Assert.AreEqual("System.ArithmeticException", typeof(ArithmeticException).FullName, "Name");
            object d = new ArithmeticException();

            Assert.True(d is ArithmeticException, "is DivideByZeroException");
            Assert.True(d is Exception, "is Exception");
        }
        public void ConstructorWithMessageAndInnerExceptionWorks()
        {
            var inner = new Exception("a");
            var ex    = new ArithmeticException("The message", inner);

            Assert.True((object)ex is ArithmeticException, "is OverflowException");
            Assert.True(ReferenceEquals(ex.InnerException, inner), "InnerException");
            Assert.AreEqual(ex.Message, "The message");
        }
Esempio n. 16
0
        } // end method handleDivByZeroException


        /// <summary>
        /// Handles Arithmetic Exceptions s.a. indeterminate forms. 
        /// </summary>
        /// <param name="e">The exception with an error message. Used iff message is 0^0</param>
        private void handleArithmeticException(ArithmeticException e)
        {
            if (e.Message == "0^0")
            {
                resultLabel.Text = display.Text + " is an indeterminate form";
            } // end if

            MessageBox.Show("The expression you entered contains an invalid operation, and cannot be evaluated. Please try again.",
                            "Invalid Operation in Expression!");
        } // end method handleArithmeticException
        public static void Ctor_String_Exception(string errorMessage)
        {
            Exception innerException = new ArithmeticException();
            ValidationException ex = new ValidationException(errorMessage, innerException);
            Assert.Equal(errorMessage, ex.Message);
            Assert.Same(innerException, ex.InnerException);

            Assert.Equal(errorMessage, ex.ValidationResult.ErrorMessage);
            Assert.Null(ex.ValidationAttribute);
            Assert.Null(ex.Value);
        }
        public void HandleForwardsHandlingToConfiguredExceptionEntry()
        {
            Dictionary <string, ExceptionPolicyImpl> policies       = new Dictionary <string, ExceptionPolicyImpl>();
            Dictionary <Type, ExceptionPolicyEntry>  policy1Entries = new Dictionary <Type, ExceptionPolicyEntry>();

            policy1Entries.Add(
                typeof(ArithmeticException),
                new ExceptionPolicyEntry(PostHandlingAction.NotifyRethrow, new IExceptionHandler[] { new TestExceptionHandler("handler11") }));
            policy1Entries.Add(
                typeof(ArgumentException),
                new ExceptionPolicyEntry(PostHandlingAction.ThrowNewException, new IExceptionHandler[] { new TestExceptionHandler("handler12") }));
            policy1Entries.Add(
                typeof(ArgumentOutOfRangeException),
                new ExceptionPolicyEntry(PostHandlingAction.None, new IExceptionHandler[] { new TestExceptionHandler("handler13") }));
            policies.Add("policy1", new ExceptionPolicyImpl("policy1", policy1Entries));

            ExceptionManager manager = new ExceptionManagerImpl(policies);

            Exception thrownException;

            // is the exception rethrown?
            thrownException = new ArithmeticException();
            Assert.IsTrue(manager.HandleException(thrownException, "policy1"));
            Assert.AreEqual(1, TestExceptionHandler.HandlingNames.Count);
            Assert.AreEqual("handler11", TestExceptionHandler.HandlingNames[0]);

            // is the new exception thrown?
            TestExceptionHandler.HandlingNames.Clear();
            thrownException = new ArgumentException();
            try
            {
                manager.HandleException(thrownException, "policy1");
                Assert.Fail("should have thrown");
            }
            catch (Exception e)
            {
                Assert.AreSame(thrownException, e.InnerException);
                Assert.AreEqual(1, TestExceptionHandler.HandlingNames.Count);
                Assert.AreEqual("handler12", TestExceptionHandler.HandlingNames[0]);
            }

            // is the exception swallowed? action == None
            TestExceptionHandler.HandlingNames.Clear();
            thrownException = new ArgumentOutOfRangeException();
            Assert.IsFalse(manager.HandleException(thrownException, "policy1"));
            Assert.AreEqual(1, TestExceptionHandler.HandlingNames.Count);
            Assert.AreEqual("handler13", TestExceptionHandler.HandlingNames[0]);

            // is the unknwon exception rethrown?
            TestExceptionHandler.HandlingNames.Clear();
            thrownException = new Exception();
            Assert.IsTrue(manager.HandleException(thrownException, "policy1"));
            Assert.AreEqual(0, TestExceptionHandler.HandlingNames.Count);
        }
Esempio n. 19
0
 // Sqarte Root
 public double Sqrt(double a)
 {
     if (a < 0)
     {
         ArithmeticException ex = new ArithmeticException("Cannot take sqaure root of negative number.");
         throw ex;
     }
     else
     {
         return(Accumulator = Math.Sqrt(a));
     }
 }
Esempio n. 20
0
 // Power
 public double Power(double x, double exp)
 {
     if (x < 0 && exp != Math.Floor(exp))
     {
         ArithmeticException ex = new ArithmeticException("Cannot raise a negative number to a fractional exponent.");
         throw ex;
     }
     else
     {
         return(Accumulator = Math.Pow(x, exp));
     }
 }
Esempio n. 21
0
        public static void Ctor_String_Exception(string errorMessage)
        {
            Exception           innerException = new ArithmeticException();
            ValidationException ex             = new ValidationException(errorMessage, innerException);

            Assert.Equal(errorMessage, ex.Message);
            Assert.Same(innerException, ex.InnerException);

            Assert.Equal(errorMessage, ex.ValidationResult.ErrorMessage);
            Assert.Null(ex.ValidationAttribute);
            Assert.Null(ex.Value);
        }
Esempio n. 22
0
        public void Constructor_SendOneWay_ReportsException()
        {
            ArithmeticException            exception    = new ArithmeticException();
            IServiceRemotingRequestMessage messsageMock = CreateMessage();
            Mock <IServiceRemotingClient>  clientMock   = new Mock <IServiceRemotingClient>();

            clientMock.Setup(c => c.SendOneWay(messsageMock)).Throws(exception);
            (DiagnosticListener listener, MockObserver observer) = MockObserver.CreateListener();
            ServiceRemotingClientWrapper wrapper = new ServiceRemotingClientWrapper(clientMock.Object, listener);

            Assert.ThrowsException <ArithmeticException>(() => wrapper.SendOneWay(messsageMock));
            observer.AssertException(exception);
        }
Esempio n. 23
0
        static StaticData()
        {
            // Exception created but is not thrown
            TestCreatedException = new SystemException("System Test Exception");

            // Traditional created and throw exception
            try
            {
                throw new RankException("Rank Test");
            }
            catch (RankException e)
            {
                TestThrowException = e;
            }

            // Exception containing inner exceptions
            try
            {
                try
                {
                    try
                    {
                        throw new TypeAccessException("Test Type Exception");
                    }
                    catch (TypeAccessException exp1)
                    {
                        throw new DivideByZeroException("Divide By Zero Test", exp1);
                    }
                }
                catch (DivideByZeroException exp2)
                {
                    throw new ArithmeticException("Inner Exception Test", exp2);
                }
            }
            catch (ArithmeticException exp3)
            {
                TestInnerException = exp3;
            }

            // Exception with a defined stack trace
            var callClass = new TestNamespace.ClassAlpha();

            try
            {
                callClass.ThrowException();
            }
            catch (TimeoutException exp)
            {
                TestCallStackException = exp;
            }
        }
        public void Constructor3_Message_Null()
        {
            ArithmeticException   ame = new ArithmeticException("something");
            FileNotFoundException fnf = new FileNotFoundException((string)null, ame);

            Assert.IsNotNull(fnf.Data, "#1");
            Assert.IsNull(fnf.FileName, "#2");
            Assert.IsNotNull(fnf.InnerException, "#3");
            Assert.AreSame(ame, fnf.InnerException, "#4");
            Assert.IsNull(fnf.Message, "#5");
            Assert.IsNull(fnf.FusionLog, "#6");
            Assert.AreEqual(fnf.GetType().FullName + ":  ---> "
                            + ame.GetType().FullName + ": something", fnf.ToString(), "#7");
        }
        public void SutActor_ReceiveExceptionMessage_ThrowsSameException()
        {
            //arrange
            Exception message = new ArithmeticException();
            UnitTestFramework <SutActor> framework = UnitTestFrameworkSettings
                                                     .Empty
                                                     .CreateFramework <SutActor>(this);

            //act
            framework.TellMessageAndWaitForException(message);

            //assert
            framework.UnhandledExceptions.First().Should().BeSameAs(message);
        }
Esempio n. 26
0
            protected BaseWhileCondition(int totalIterations, DelegateBehavior behavior)
            {
                if (totalIterations < 0)
                {
                    throw new ArgumentOutOfRangeException("totalIterations");
                }

                TotalIterations = totalIterations;
                Behavior        = behavior;
                if (behavior == DelegateBehavior.Faulted || behavior == DelegateBehavior.SyncFaulted)
                {
                    ExpectedException = new ArithmeticException();
                }
            }
Esempio n. 27
0
        public void TypePropertiesAreCorrect()
        {
            Assert.AreEqual("System.ArithmeticException", typeof(ArithmeticException).FullName, "Name");
            Assert.True(typeof(ArithmeticException).IsClass, "IsClass");
            Assert.AreEqual(typeof(SystemException), typeof(ArithmeticException).BaseType, "BaseType");
            object d = new ArithmeticException();

            Assert.True(d is ArithmeticException, "is DivideByZeroException");
            Assert.True(d is Exception, "is Exception");

            var interfaces = typeof(ArithmeticException).GetInterfaces();

            Assert.AreEqual(0, interfaces.Length, "Interfaces length");
        }
Esempio n. 28
0
        public void Verify_ResourceStateDown_LoggedWithLevelBasedOnCritical(bool isCritical, LogLevel expectedLogLevel)
        {
            var expectedException = new ArithmeticException();

            _fixture.IsCritical = isCritical;
            _fixture.HealthCheckStrategy.Check(Arg.Any <CancellationToken>()).Throws(expectedException);
            using (var sut = _fixture.GetSut())
            {
                sut.Verify();
                _fixture.Logger
                .Received(1)
                .Log(expectedLogLevel, Arg.Any <EventId>(), Arg.Any <object>(), Arg.Any <ArithmeticException>(), Arg.Any <Func <object, Exception, string> >());
            }
        }
Esempio n. 29
0
        public async Task Constructor_RequestResponseAsync_ReportsException()
        {
            ArithmeticException            exception    = new ArithmeticException();
            IServiceRemotingRequestMessage messsageMock = CreateMessage();
            Mock <IServiceRemotingClient>  clientMock   = new Mock <IServiceRemotingClient>();

            clientMock.Setup(c => c.RequestResponseAsync(messsageMock)).Throws(exception);
            (DiagnosticListener listener, MockObserver observer) = MockObserver.CreateListener();
            ServiceRemotingClientWrapper wrapper = new ServiceRemotingClientWrapper(clientMock.Object, listener);

            await Assert.ThrowsExceptionAsync <ArithmeticException>(() => wrapper.RequestResponseAsync(messsageMock));

            observer.AssertException(exception);
        }
Esempio n. 30
0
        public void Constructor3_Message_Null()
        {
            ArithmeticException     ame = new ArithmeticException("something");
            BadImageFormatException bif = new BadImageFormatException((string)null, ame);

            Assert.IsNotNull(bif.Data, "#1");
            Assert.IsNull(bif.FileName, "#2");
            Assert.IsNotNull(bif.InnerException, "#3");
            Assert.AreSame(ame, bif.InnerException, "#4");
            Assert.IsNotNull(bif.Message, "#5");
            Assert.IsNull(bif.FusionLog, "#7");
            Assert.IsTrue(bif.ToString().StartsWith(bif.GetType().FullName), "#8");
            Assert.IsTrue(bif.ToString().IndexOf("---> " + ame.GetType().FullName) != -1, "#9");
            Assert.IsFalse(bif.ToString().IndexOf(Environment.NewLine) != -1, "#10");
        }
        public void Constructor3_Message_Empty()
        {
            ArithmeticException     ame = new ArithmeticException("something");
            BadImageFormatException bif = new BadImageFormatException(string.Empty, ame);

            Assert.IsNotNull(bif.Data, "#1");
            Assert.IsNull(bif.FileName, "#2");
            Assert.IsNotNull(bif.InnerException, "#3");
            Assert.AreSame(ame, bif.InnerException, "#4");
            Assert.IsNotNull(bif.Message, "#5");
            Assert.AreEqual(string.Empty, bif.Message, "#6");
            Assert.IsNull(bif.FusionLog, "#7");
            Assert.AreEqual(bif.GetType().FullName + ":  ---> "
                            + ame.GetType().FullName + ": something", bif.ToString(), "#8");
        }
Esempio n. 32
0
    public bool PosTest1()
    {
        bool retVal = true;

        TestLibrary.TestFramework.BeginScenario("PosTest1: Call ctor to construct a new instance");

        try
        {
            ArithmeticException arithmeticException = new ArithmeticException();
            if (arithmeticException == null)
            {
                TestLibrary.TestFramework.LogError("001", "The result is not the value as expected");
                retVal = false;
            }
        }
        catch (Exception e)
        {
            TestLibrary.TestFramework.LogError("002", "Unexpected exception: " + e);
            retVal = false;
        }

        return retVal;
    }