示例#1
0
        public void TestExtractAllInnerExceptions()
        {
            // the implementation only concatenates exception type and message (no stacktrace)
            // format is: excp.GetType().Name + " : " + excp.Message + "\n" and this same is repeated as long there are innerexceptions

            ArgumentNullException nex   = new ArgumentNullException("nex", "Parameter cannot be null.");
            ArgumentException     argEx = new ArgumentException("Invalid argument supplied.", nex);
            Exception             ex    = new Exception("An error occured when calling typography service.", argEx);

            string extractedMessage = CoreExtensions.ExtractAllInnerExceptions(ex);

            extractedMessage.Should().NotBeNullOrWhiteSpace();

            // create the expected message parts separated with the \n
            // remove \r\n so that we can split with \n easily
            string partOne   = $"{ex.GetType().Name} : {ex.Message}".Replace("\r\n", string.Empty);
            string partTwo   = $"{argEx.GetType().Name} : {argEx.Message}".Replace("\r\n", string.Empty);
            string partThree = $"{nex.GetType().Name} : {nex.Message}".Replace("\r\n", string.Empty);

            // remove \r\n also from the result (when parameter name is given it will be part of the ex.Message)
            extractedMessage = extractedMessage.Replace("\r\n", string.Empty);

            // don't remove empty entries
            var splittedMsgs = extractedMessage.Split(new string[] { "\n" }, StringSplitOptions.None);

            splittedMsgs.Length.Should().Be(4, "Count should be 4 because there are 3 exceptions and after last exception there will be '\n' which will produce the extra string in the array.");

            splittedMsgs[0].Should().Be(partOne);
            splittedMsgs[1].Should().Be(partTwo);
            splittedMsgs[2].Should().Be(partThree);
        }
        [Fact] // OpenExeConfiguration (String)
        public void OpenExeConfiguration2_ExePath_DoesNotExist()
        {
            using (var temp = new TempDirectory())
            {
                string exePath = Path.Combine(temp.Path, "DoesNotExist.exe");

                ConfigurationErrorsException ex = Assert.Throws <ConfigurationErrorsException>(
                    () => ConfigurationManager.OpenExeConfiguration(exePath));

                // An error occurred loading a configuration file:
                // The parameter 'exePath' is invalid
                Assert.Equal(typeof(ConfigurationErrorsException), ex.GetType());
                Assert.Null(ex.Filename);
                Assert.NotNull(ex.InnerException);
                Assert.Equal(0, ex.Line);
                Assert.NotNull(ex.Message);

                // The parameter 'exePath' is invalid
                ArgumentException inner = ex.InnerException as ArgumentException;
                Assert.NotNull(inner);
                Assert.Equal(typeof(ArgumentException), inner.GetType());
                Assert.Null(inner.InnerException);
                Assert.NotNull(inner.Message);
                Assert.Equal("exePath", inner.ParamName);
            }
        }
示例#3
0
        public void ReadExceptionFile()
        {
            var expectedException = new ArgumentException("test");
            var mockFile          = Mock.Of <File>();
            var mockStream        = new System.IO.MemoryStream();

            new BinaryFormatter().Serialize(mockStream, expectedException);
            mockStream.Position = 0;
            string actualFullFileName = null;

            System.IO.FileMode?actualFileMode = null;

            Mock.Get(mockFile).Setup(f => f.FullName).Returns("test.exception");
            ErrorLogHelper.Instance.NewFileStream = (name, mode) =>
            {
                actualFullFileName = name;
                actualFileMode     = mode;
                return(mockStream);
            };

            var actualException = ErrorLogHelper.ReadExceptionFile(mockFile);

            Assert.IsInstanceOfType(actualException, expectedException.GetType());
            Assert.AreEqual(expectedException.Message, actualException.Message);
            Assert.AreEqual(mockFile.FullName, actualFullFileName);
            Assert.AreEqual(System.IO.FileMode.Open, actualFileMode);
        }
        [Test]         // OpenExeConfiguration (String)
        public void OpenExeConfiguration2_ExePath_DoesNotExist()
        {
            String exePath = Path.Combine(tempFolder, "DoesNotExist.exe");

            try {
                ConfigurationManager.OpenExeConfiguration(exePath);
                Assert.Fail("#1");
            } catch (ConfigurationErrorsException ex) {
                // An error occurred loading a configuration file:
                // The parameter 'exePath' is invalid
                Assert.AreEqual(typeof(ConfigurationErrorsException), ex.GetType(), "#2");
                Assert.IsNull(ex.Filename, "#3");
                Assert.IsNotNull(ex.InnerException, "#4");
                Assert.AreEqual(0, ex.Line, "#5");
                Assert.IsNotNull(ex.Message, "#6");

                // The parameter 'exePath' is invalid
                ArgumentException inner = ex.InnerException as ArgumentException;
                Assert.IsNotNull(inner, "#7");
                Assert.AreEqual(typeof(ArgumentException), inner.GetType(), "#8");
                Assert.IsNull(inner.InnerException, "#9");
                Assert.IsNotNull(inner.Message, "#10");
                Assert.AreEqual("exePath", inner.ParamName, "#11");
            }
        }
示例#5
0
        public void CorrectAgeTest1(int age)
        {
            var actException      = Assert.Catch(() => new Person("Name", "Surname", age));
            var expectedException = new ArgumentException();

            Assert.AreEqual(expectedException.GetType(), actException.GetType());
        }
 private static bool MapsToDateBrokenRule(ArgumentException sourceException)
 {
     return(sourceException.GetType() == typeof(ArgumentNullException) ||
            IsInvalidDateException(sourceException) ||
            IsInFututeException(sourceException) ||
            IsNotInPastException(sourceException));
 }
示例#7
0
        public void MessageTest()
        {
            const string Message            = "some message";
            var          exception          = new ArgumentException(Message);
            var          exceptionViewModel = new ExceptionViewModel(exception);

            Assert.AreEqual(exception.GetType().Name + ": " + Message, exceptionViewModel.Message);
        }
 private static bool MapsToOutOfRangeBrokenRule(ArgumentException sourceException)
 {
     return(sourceException.GetType() == typeof(ArgumentOutOfRangeException) ||
            IsGreaterThanException(sourceException) ||
            IsLessThanException(sourceException) ||
            IsGreaterThanOrEqualToException(sourceException) ||
            IsLessThanOrEqualToException(sourceException) ||
            IsInRangeException(sourceException));
 }
        public void TestReportClassifier_ShouldSetErrorClassifier_SetCorrectExceptionReportClassifier()
        {
            var exception = new ArgumentException(string.Empty);
            var report    = new BacktraceReport(
                exception: exception,
                attributes: reportAttributes,
                attachmentPaths: attachemnts);

            Assert.AreEqual(report.Classifier, exception.GetType().Name);
        }
示例#10
0
        public void Constructor0_Arguments_Mismatch()
        {
            ArgumentException ex = Assert.Throws <ArgumentException>(() => new InstanceDescriptor(ci, null));

            // Length mismatch
            Assert.Equal(typeof(ArgumentException), ex.GetType());
            Assert.Null(ex.InnerException);
            Assert.NotNull(ex.Message);
            Assert.Null(ex.ParamName);
        }
        public async Task GenericThrowsAsync_Should_ThrowAssertionException_WhenNoAnyExceptionWasThrown()
        {
            var exceptionToThrow = new ArgumentException("some_message", "some_name");

            var result = await SafelyCatchAnNUnitExceptionAsync(() => Assert.ThrowsAsync <ArgumentException>(async() => { }));

            Assert.That(result, new ExceptionTypeConstraint(typeof(AssertionException)));
            Assert.That(exceptionToThrow, Is.Not.EqualTo(result));
            Assert.That(result.Message, Is.EqualTo($"  Expected: <{exceptionToThrow.GetType().FullName}>" + Environment.NewLine +
                                                   "  But was:  null" + Environment.NewLine));
        }
        private async Task ThrowsAsyncShouldReturnCorrectExceptionBaseTest(Func <Exception, Task <Exception> > code)
        {
            var exceptionToThrow = new ArgumentException("some_message", "some_param");
            var result           = await code(exceptionToThrow) as ArgumentException;

            Assert.That(result, new ExceptionTypeConstraint(exceptionToThrow.GetType()), string.Empty, null);
            Assert.IsNotNull(result, "No ArgumentException thrown");
            Assert.That(exceptionToThrow.Message, Is.EqualTo(result.Message));
            Assert.That(exceptionToThrow.ParamName, Is.EqualTo(result.ParamName));
            Assert.That(exceptionToThrow, Is.EqualTo(result));
        }
示例#13
0
        public void Property_MemberInfo_WriteOnly()
        {
            PropertyInfo pi = typeof(WriteOnlyProperty).GetProperty("Name");

            ArgumentException ex = Assert.Throws <ArgumentException>(() => new InstanceDescriptor(pi, null));

            // Parameter must be readable
            Assert.Equal(typeof(ArgumentException), ex.GetType());
            Assert.Null(ex.InnerException);
            Assert.NotNull(ex.Message);
            Assert.Null(ex.ParamName);
        }
示例#14
0
        public void Field_MemberInfo_NonStatic()
        {
            FieldInfo fi = typeof(InstanceField).GetField("Name");

            ArgumentException ex = Assert.Throws <ArgumentException>(() => new InstanceDescriptor(fi, null));

            // Parameter must be static
            Assert.Equal(typeof(ArgumentException), ex.GetType());
            Assert.Null(ex.InnerException);
            Assert.NotNull(ex.Message);
            Assert.Null(ex.ParamName);
        }
示例#15
0
        public void Field_Arguments_Mismatch()
        {
            FieldInfo fi = typeof(Uri).GetField("SchemeDelimiter");

            ArgumentException ex = Assert.Throws <ArgumentException>(() => new InstanceDescriptor(fi, new object[] { url }));

            // Parameter must be static
            Assert.Equal(typeof(ArgumentException), ex.GetType());
            Assert.Null(ex.InnerException);
            Assert.NotNull(ex.Message);
            Assert.Null(ex.ParamName);
        }
示例#16
0
        /// <summary>
        /// ArgumentException	An argument to a method was invalid.
        /// </summary>
        /// <param name="ex"></param>
        /// <returns></returns>
        private static SqlMessage SqlException(ArgumentException ex)
        {
            SqlMessage meResul = new SqlMessage
            {
                Status            = sqlMessagerType.SystemError,
                Title             = ex.GetType().FullName,
                Message           = ex.Message,
                ExceptionMesseger = ex.ToString()
            };

            return(meResul);
        }
示例#17
0
        public void Constructor0_Arguments_Mismatch()
        {
            ArgumentException ex = Assert.Throws <ArgumentException>(() => new InstanceDescriptor(ci, null));

            // Length mismatch
            Assert.Equal(typeof(ArgumentException), ex.GetType());
            Assert.Null(ex.InnerException);
            if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames.
            {
                Assert.NotNull(ex.Message);
                Assert.Null(ex.ParamName);
            }
        }
        public async Task ThrowsAsync_Should_ThrowAssertionException_WhenUnrelatedExceptionWasThrown()
        {
            var expectedExceptionType = typeof(NullReferenceException);
            var unrelatedException    = new ArgumentException("some_message", "some_name");

            var result = await SafelyCatchAnNUnitExceptionAsync(() => Assert.ThrowsAsync(expectedExceptionType,
                                                                                         async() => throw unrelatedException));

            Assert.That(result, new ExceptionTypeConstraint(typeof(AssertionException)));
            Assert.That(expectedExceptionType, Is.Not.TypeOf(result.GetType()));
            Assert.That(result.Message, Does.StartWith($"  Expected: <{expectedExceptionType.FullName}>" + Environment.NewLine +
                                                       $"  But was:  <{unrelatedException.GetType().FullName}: {unrelatedException.Message}" + Environment.NewLine));
        }
示例#19
0
        /// <summary>
        /// simple error handler for now, could refactor to use ExceptionAttribute filter etc
        /// </summary>
        private static void HandleArgumentErrors(string extraInfo, ArgumentException argEx)
        {
            //return status 400 - BadRequest

            var msg = argEx?.Message?.Split("\r\n".ToCharArray()).FirstOrDefault();

            var resp = new HttpResponseMessage(HttpStatusCode.BadRequest)
            {
                Content      = new StringContent(argEx.Message),
                ReasonPhrase = $"{argEx.GetType().Name} ({extraInfo} - {msg})",
            };

            throw new HttpResponseException(resp);
        }
示例#20
0
        public void Property_MemberInfo_WriteOnly()
        {
            PropertyInfo pi = typeof(WriteOnlyProperty).GetProperty(nameof(WriteOnlyProperty.Name));

            ArgumentException ex = Assert.Throws <ArgumentException>(() => new InstanceDescriptor(pi, null));

            // Parameter must be readable
            Assert.Equal(typeof(ArgumentException), ex.GetType());
            Assert.Null(ex.InnerException);
            if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames.
            {
                Assert.NotNull(ex.Message);
                Assert.Null(ex.ParamName);
            }
        }
示例#21
0
        public void Field_MemberInfo_NonStatic()
        {
            FieldInfo fi = typeof(InstanceField).GetField(nameof(InstanceField.Name));

            ArgumentException ex = Assert.Throws <ArgumentException>(() => new InstanceDescriptor(fi, null));

            // Parameter must be static
            Assert.Equal(typeof(ArgumentException), ex.GetType());
            Assert.Null(ex.InnerException);
            if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames.
            {
                Assert.NotNull(ex.Message);
                Assert.Null(ex.ParamName);
            }
        }
示例#22
0
        public void SummaryOrdersErrorsFromMostOccuringDescending()
        {
            var error1 = new DllNotFoundException();
            var error2 = new ArgumentException();
            var error3 = new ArgumentException();
            var error4 = new ArgumentException();

            var exceptionsAggregated = new List <Exception> {
                error1, error2, error3, error4
            };
            var received       = exceptionsAggregated.Summary();
            var multilineRegex = new Regex($"{OpeningSequenceMultipleRegex}.?.?.?({error2.GetType().FullName}|{error2.GetType().Name}){RegexForThreeTimes}", RegexOptions.IgnoreCase | RegexOptions.Singleline);

            Assert.True(multilineRegex.IsMatch(received));
        }
示例#23
0
        public void CreatingFromException_MapsProperties_FromMostInnerException()
        {
            // Arrange
            const string InnerMessage    = "InnerMessage";
            var          innerException  = new ArgumentException(InnerMessage);
            var          middleException = new ArgumentNullException("MiddleMessage", innerException);
            var          outerException  = new Exception("OuterMessage", middleException);

            // Act
            var actualServerException = ServerException.CreateFromException(outerException);

            // Assert
            Assert.AreEqual(InnerMessage, actualServerException.Message);
            Assert.AreEqual(innerException.GetType().Name, actualServerException.TypeName);
        }
        public void Field_Arguments_Mismatch()
        {
            FieldInfo fi = typeof(StaticField).GetField(nameof(StaticField.Field));

            ArgumentException ex = AssertExtensions.Throws <ArgumentException>(null, () => new InstanceDescriptor(fi, new object[] { url }));

            // Parameter must be static
            Assert.Equal(typeof(ArgumentException), ex.GetType());
            Assert.Null(ex.InnerException);
            if (!PlatformDetection.IsNetNative) // .Net Native toolchain optimizes away exception messages and paramnames.
            {
                Assert.NotNull(ex.Message);
                Assert.Null(ex.ParamName);
            }
        }
        public void Increment_WithException_AddReadingDataForTheSpecificException()
        {
            var sensor = new ExceptionSensor();

            ArgumentException exception = new ArgumentException();

            sensor.AddError(exception);

            Reading reading = null;

            ReadingPublisher.Readings.TryDequeue(out reading); // TotalExceptions
            ReadingPublisher.Readings.TryDequeue(out reading);

            Assert.That(reading.Data.Name, Is.EqualTo(exception.GetType().Name));
        }
示例#26
0
        public void SerializesTwoExceptions()
        {
            var exception1 = new InvalidOperationException("Some message 1");
            var exception2 = new ArgumentException("Some message 2");
            var errors     =
                new ErrorSerializer().Serialize(
                    new List <ApiError>()
            {
                new ApiError(exception1), new ApiError(exception2)
            })["errors"];

            Assert.Equal(exception1.Message, errors[0].Value <string>("title"));
            Assert.Equal(exception1.GetType().FullName, errors[0].Value <string>("code"));
            Assert.Equal(exception1.ToString(), errors[0].Value <string>("detail"));

            Assert.Equal(exception2.Message, errors[1].Value <string>("title"));
            Assert.Equal(exception2.GetType().FullName, errors[1].Value <string>("code"));
            Assert.Equal(exception2.ToString(), errors[1].Value <string>("detail"));
        }
示例#27
0
        public void Should_serialize_inner_exceptions()
        {
            var exception0 = new InvalidOperationException();
            var exception1 = new NullReferenceException();
            var exception2 = new ArgumentException();

            var aggregateException = new AggregateException(exception0, exception1, exception2);

            builder.AddExceptionData(aggregateException);

            var tags = builder.BuildTags();

            tags.ContainsKey(ExceptionTagNames.InnerExceptions).Should().BeTrue();
            var exceptions = tags[ExceptionTagNames.InnerExceptions].AsVector.AsContainerList;

            exceptions[0][ExceptionTagNames.Type].AsString.Should().Be(exception0.GetType().FullName);
            exceptions[1][ExceptionTagNames.Type].AsString.Should().Be(exception1.GetType().FullName);
            exceptions[2][ExceptionTagNames.Type].AsString.Should().Be(exception2.GetType().FullName);
        }
示例#28
0
        public void Test_TraceError_with_message()
        {
            var traceMock = new Mock <TraceListener>(MockBehavior.Loose);
            var ts        = new TraceSource(AppConstants.SignalRMagicHub, SourceLevels.All);

            ts.Listeners.Add(traceMock.Object);

            Exception ex = new ArgumentException("foo");

            ts.TraceError(ex, "bar");

            traceMock.Verify(t => t.TraceEvent(
                                 It.IsAny <TraceEventCache>(),
                                 It.IsAny <string>(),
                                 TraceEventType.Error,
                                 It.IsAny <int>(),
                                 "{3} ExceptionType=\"{0}\" ExceptionMessage=\"{1}\" StackTrace={2}",
                                 new object[]
            {
                ex.GetType().FullName, ex.Message, ex.StackTrace, "ErrorOccurred=\"bar\" "
            }),
                             Times.Exactly(1));
        }
示例#29
0
        public static void ArgumentExceptionIsThrown(Action action, string expectedArgumentName, string expectedMessage = null)
        {
            if (action == null)
            {
                throw new ArgumentNullException("method");
            }

            if (expectedArgumentName == null)
            {
                throw new ArgumentNullException("expectedArgumentName");
            }

            if (expectedArgumentName == string.Empty)
            {
                throw new ArgumentException(ValidationPredicateMessages.NullOrEmptyStringMessage, "expectedArgumentName");
            }

            ArgumentException ex = null;

            try
            {
                action();
            }
            catch (ArgumentException e)
            {
                ex = e;
            }

            Assert.AreEqual(typeof(ArgumentException), ex.GetType());
            Assert.IsNotNull(ex);
            Assert.AreEqual(expectedArgumentName, ex.ParamName);

            if (expectedMessage != null)
            {
                Assert.AreEqual(ex.Message, expectedMessage);
            }
        }
        public void PruebaConstructorConString()
        {
            #region Caso 1: Indice en rango válido.
            {
                // Preparación.
                LímiteDeVelocidad límiteDeVelocidad        = new LímiteDeVelocidad(2);
                ClaseDeRuta       claseDeRuta              = new ClaseDeRuta(3);
                string            parámetrosDeRuta         = "2,3,0,1,0,0,0,0,0,0,0,1";
                bool[]            otrosParámetrosEsperados = new bool[] { false, true, false, false, false, false, false, false, false, true };

                // Llama al constructor en prueba.
                CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(parámetrosDeRuta);

                // Prueba Propiedades.
                Assert.That(objectoEnPrueba.Identificador, Is.EqualTo(CampoParámetrosDeRuta.IdentificadorDeParámetrosDeRuta), "Identificador");
                Assert.That(objectoEnPrueba.ClaseDeRuta, Is.EqualTo(claseDeRuta), "ClaseDeRuta");
                Assert.That(objectoEnPrueba.LímiteDeVelocidad, Is.EqualTo(límiteDeVelocidad), "LímiteDeVelocidad");
                Assert.That(objectoEnPrueba.OtrosParámetros, Is.EqualTo(otrosParámetrosEsperados), "OtrosParámetros");
            }
            #endregion

            #region Caso 2: Parametros de Tuta con muy pocos elementos.
            {
                // Preparación.
                string            parametrosDeRutaInválidos = "2";
                bool              lanzóExcepción            = false;
                ArgumentException excepciónEsperada         = new ArgumentException(
                    "Los parámetros de rutas deben tener 12 elementos separados por coma, pero es: 2");

                // Llama al constructor en prueba.
                try
                {
                    CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(parametrosDeRutaInválidos);
                }
                catch (Exception e)
                {
                    // Prueba las propiedades de la excepción.
                    Assert.That(e.GetType(), Is.EqualTo(excepciónEsperada.GetType()), "Tipo de Excepción");
                    Assert.That(e.Message, Is.EqualTo(excepciónEsperada.Message), "Excepción.Message");

                    lanzóExcepción = true;
                }

                Assert.That(lanzóExcepción, Is.True, "No se lanzó la excepción.");
            }
            #endregion

            #region Caso 3: Otros Parámetros con valores diferente de 0 ó 1.
            {
                // Preparación.
                string            parametrosDeRutaInválidos = "2,3,0,5,0,0,0,0,0,0,0,1";
                bool              lanzóExcepción            = false;
                ArgumentException excepciónEsperada         = new ArgumentException(
                    "El números de los parámetros de ruta para el tercer elemento en adelante tiene que ser 0 ó 1:" +
                    " 2,3,0,5,0,0,0,0,0,0,0,1\r\nParameter name: elTextoDeParámetrosDeRuta");

                // Llama al constructor en prueba.
                try
                {
                    CampoParámetrosDeRuta objectoEnPrueba = new CampoParámetrosDeRuta(parametrosDeRutaInválidos);
                }
                catch (Exception e)
                {
                    // Prueba las propiedades de la excepción.
                    Assert.That(e.GetType(), Is.EqualTo(excepciónEsperada.GetType()), "Tipo de Excepción");
                    Assert.That(e.Message, Is.EqualTo(excepciónEsperada.Message), "Excepción.Message");

                    lanzóExcepción = true;
                }

                Assert.That(lanzóExcepción, Is.True, "No se lanzó la excepción.");
            }
            #endregion
        }