public TAttribute HasAttribute <TAttribute>() where TAttribute : Attribute { TAttribute?attribute = null; try { attribute = assembly.GetCustomAttribute <TAttribute>(); } catch (AmbiguousMatchException ex) { string expectedMessage = $"{typeof(TAttribute)}"; string actualMessage = $"(Multiple custom attributes of the same specified type are applied to assembly '{assembly.FullName}')"; AssertionFailedException.Throw(nameof(HasAttribute), expectedMessage, actualMessage, ex); } if (attribute is null) { string expectedMessage = $"{typeof(TAttribute)}"; string actualMessage = $"(A custom attribute of the specified type is not applied to assembly '{assembly.FullName}')"; AssertionFailedException.Throw(nameof(HasAttribute), expectedMessage, actualMessage); } return(attribute); }
public async Task <TException> ThrowsDeferredAsync <TException>() where TException : Exception { IAsyncEnumerable <T>?asyncIterator; try { asyncIterator = asyncEnumerableMethod(); } catch (Exception e) { asyncIterator = null; AssertionFailedException.Throw(nameof(ThrowsDeferredAsync), typeof(TException).FullName !, $"(An exception was thrown before iteration over the asynchronous stream: '{e.GetType()}')"); } Exception?exception = await CaptureExceptionAsync(asyncIterator); if (exception is null) { AssertionFailedException.Throw(nameof(ThrowsDeferredAsync), typeof(TException).FullName !, "(No exception was thrown during iteration over the asynchronous stream)"); } else if (exception.GetType() != typeof(TException)) { AssertionFailedException.Throw(nameof(ThrowsDeferredAsync), typeof(TException).FullName !, exception.GetType().FullName !); } return((exception as TException) !); }
private void Write(ref TransactionToken token, OperationCode operation, TKey key, TValue value) { AssertionFailedException.Assert(token.State == StateOpen); MemoryStream buffer = token.Object as MemoryStream; if (buffer == null) { token.Object = buffer = new MemoryStream(); PrimitiveSerializer.Int32.WriteTo(0, buffer); PrimitiveSerializer.Int32.WriteTo(unchecked ((int)token.Handle), buffer); PrimitiveSerializer.Int16.WriteTo(0, buffer); } PrimitiveSerializer.Int16.WriteTo((short)operation, buffer); _options.KeySerializer.WriteTo(key, buffer); if (operation != OperationCode.Remove) { _options.ValueSerializer.WriteTo(value, buffer); } //Increment the operation counter at offset 8 long pos = buffer.Position; buffer.Position = 8; short count = PrimitiveSerializer.Int16.ReadFrom(buffer); buffer.Position = 8; PrimitiveSerializer.Int16.WriteTo(++count, buffer); buffer.Position = pos; }
public async Task <TException> ThrowsAsynchronously <TException>() where TException : Exception { Task?task; try { task = asyncMethod(); } catch (Exception e) { task = null; AssertionFailedException.Throw(nameof(ThrowsAsynchronously), typeof(TException).FullName !, $"(An exception was thrown synchronously: '{e.GetType()}')"); } Exception?exception = await CaptureExceptionAsynchronously(task); if (exception is null) { AssertionFailedException.Throw(nameof(ThrowsAsynchronously), typeof(TException).FullName !, "(No exception was observed asynchronously)"); } else if (exception.GetType() != typeof(TException)) { AssertionFailedException.Throw(nameof(ThrowsAsynchronously), typeof(TException).FullName !, exception.GetType().FullName !); } return((exception as TException) !); }
public static void MessageTest() { Exception e = new AssertionFailedException("bla"); Assert.Null(e.InnerException); Assert.Equal("bla", e.Message); }
public static void NormalTest() { Exception e = new AssertionFailedException(); Assert.Null(e.InnerException); Assert.Equal("Exception of type 'AssertNet.FailureHandlers.AssertionFailedException' was thrown.", e.Message); }
public TException ThrowsDeferred <TException>() where TException : Exception { IEnumerable <T>?iterator; try { iterator = enumerableMethod(); } catch (Exception e) { iterator = null; AssertionFailedException.Throw(nameof(ThrowsDeferred), typeof(TException).FullName !, $"(An exception was thrown before iteration over the sequence: '{e.GetType()}')"); } Exception?exception = CaptureException(iterator); if (exception is null) { AssertionFailedException.Throw(nameof(ThrowsDeferred), typeof(TException).FullName !, "(No exception was thrown during iteration over the sequence)"); } else if (exception.GetType() != typeof(TException)) { AssertionFailedException.Throw(nameof(ThrowsDeferred), typeof(TException).FullName !, exception.GetType().FullName !); } return((exception as TException) !); }
/// <summary> /// Commits the provided transaction /// </summary> public void CommitTransaction(ref TransactionToken token) { AssertionFailedException.Assert(token.State == StateOpen); token.State = StateCommitted; MemoryStream buffer = token.Object as MemoryStream; if (buffer == null) { return; // nothing to commit } byte[] bytes = buffer.GetBuffer(); Crc32 crc = new Crc32(); crc.Add(bytes, 4, (int)buffer.Position - 4); PrimitiveSerializer.Int32.WriteTo(crc.Value, buffer); int len = (int)buffer.Position; PrimitiveSerializer.Int32.WriteTo((0xee << 24) + len, buffer); buffer.Position = 0; PrimitiveSerializer.Int32.WriteTo((0xbb << 24) + len, buffer); bytes = buffer.GetBuffer(); WriteBytes(bytes, 0, len + 4); }
public static void InnerTest() { Exception inner = new ArgumentException(string.Empty); Exception e = new AssertionFailedException("blu", inner); Assert.Same(inner, e.InnerException); Assert.Equal("blu", e.Message); }
public void TestObjectProperties() { TestsObject.AssertNull(TestTestsObject, "TestTestsObject"); TestTestsObject = TestsObject; if (TestTestsObject != TestsObject) { throw AssertionFailedException.Create(TestTestsObject, TestsObject, "TestTestsObject-Write"); } }
#pragma warning disable SYSLIB0011 // Type or member is obsolete private static AssertionFailedException RoundTrip(AssertionFailedException exception) { using Stream stream = new MemoryStream(); IFormatter formatter = new BinaryFormatter(); formatter.Serialize(stream, exception); stream.Seek(0, SeekOrigin.Begin); return((AssertionFailedException)formatter.Deserialize(stream)); }
private static void AssertExceptionCause(AssertionFailedException e, string expected) { string actual = e.Message; if (actual.Length - expected.Length < 0) { Assert.Fail($"length of '{actual}' is less than length of '{expected}'"); } string end = actual[^ expected.Length..];
public static FulcrumException ToFulcrumException(FulcrumError error) { if (error == null) { return(null); } FulcrumException exception; switch (error.TypeId) { case BusinessRuleException.ExceptionTypeId: exception = new BusinessRuleException(error.TechnicalMessage, ToFulcrumException(error.InnerError)); break; case ConflictException.ExceptionTypeId: exception = new ConflictException(error.TechnicalMessage, ToFulcrumException(error.InnerError)); break; case ServerContractException.ExceptionTypeId: exception = new ServerContractException(error.TechnicalMessage, ToFulcrumException(error.InnerError)); break; case NotFoundException.ExceptionTypeId: exception = new NotFoundException(error.TechnicalMessage, ToFulcrumException(error.InnerError)); break; case UnauthorizedException.ExceptionTypeId: exception = new UnauthorizedException(error.TechnicalMessage, ToFulcrumException(error.InnerError)); break; case AssertionFailedException.ExceptionTypeId: exception = new AssertionFailedException(error.TechnicalMessage, ToFulcrumException(error.InnerError)); break; case NotImplementedException.ExceptionTypeId: exception = new NotImplementedException(error.TechnicalMessage, ToFulcrumException(error.InnerError)); break; case TryAgainException.ExceptionTypeId: exception = new TryAgainException(error.TechnicalMessage, ToFulcrumException(error.InnerError)); break; default: exception = null; break; } if (exception == null) { var message = $"The TypeId ({error.TypeId}) was not recognized: {error.ToJsonString(Formatting.Indented)}"; return(new AssertionFailedException(message, ToFulcrumException(error.InnerError))); } exception.CopyFrom(error); return(exception); }
public void Constructor_Deserialization_And_TypeIsMarkedAsSerializable() { AssertionFailedException original = new("240", new ArgumentException("F0")); AssertionFailedException roundtrip = RoundTrip(original); Assert.NotSame(original, roundtrip); Assert.Equal("240", roundtrip.Message); Assert.IsType <ArgumentException>(roundtrip.InnerException); Assert.Equal("F0", roundtrip.InnerException.Message); }
public void Throw_WithoutInnerException() { Exception exception = Assert.Throws <AssertionFailedException>(() => AssertionFailedException.Throw("1", "2", "3")); string message = "'1' failed." + Environment.NewLine + " Expected: 2" + Environment.NewLine + " Actual: 3"; Assert.Equal(message, exception.Message); Assert.Null(exception.InnerException); }
public void SecondThenActionIsInvokedEvenIfFirstAssertFailed() { var exception = new AssertionFailedException("Assertion failed"); FirstThenActionThrows(exception); var scenarioTest = CreateScenarioWithResultsCheck().Test; var testResult = scenarioTest.Run(); TestShouldFailWithExceptions(testResult, exception); AllThenActionsShouldBeExecutedOnce(); }
private Ticket GetTicketWithExceptions(string ticketId, ExpectedResultEnum expectedFacadeResult) { FulcrumException fulcrumException = null; switch (expectedFacadeResult) { case ExpectedResultEnum.Ok: return(new Ticket { Id = ticketId }); case ExpectedResultEnum.BusinessRuleException: fulcrumException = new BusinessRuleException("Business rule exception"); break; case ExpectedResultEnum.ConflictException: fulcrumException = new ConflictException("Conflict exception"); break; case ExpectedResultEnum.ServerContractException: fulcrumException = new ServerContractException("Contract exception"); break; case ExpectedResultEnum.NotFoundException: fulcrumException = new NotFoundException("Not found exception"); break; case ExpectedResultEnum.UnauthorizedException: fulcrumException = new UnauthorizedException("Unauthorized exception"); break; case ExpectedResultEnum.AssertionFailedException: fulcrumException = new AssertionFailedException("Assertion failed exception"); break; case ExpectedResultEnum.NotImplementedException: fulcrumException = new NotImplementedException("Not implemented exception"); break; case ExpectedResultEnum.TryAgainException: fulcrumException = new TryAgainException("Try again exception"); break; default: fulcrumException = new AssertionFailedException($"Unexpected switch value: {expectedFacadeResult}"); break; } // This is to be able to test that the properties are copied all the way back to the test case. fulcrumException.Code = fulcrumException.InstanceId; throw fulcrumException; }
public Version?HasAssemblyVersion(Version?expected) { Version?actual = assembly.GetName().Version; if (!EqualityComparer <Version?> .Default.Equals(expected, actual)) { string expectedMessage = expected is null ? "(null)" : expected.ToString(); string actualMessage = actual is null ? "(null)" : actual.ToString(); AssertionFailedException.Throw(nameof(HasAssemblyVersion), expectedMessage, actualMessage); } return(actual); }
private void AssertTitleFails(string title) { AssertionFailedException thrown = null; try { Scenario(title); } catch (AssertionFailedException e) { thrown = e; } Assert.NotNull(thrown, "Expect assertion failed exception to be thrown"); }
public void AllExceptionsFromThenActionsAreReportedInTestResult() { var exception1 = new AssertionFailedException("Assertion 1 failed"); FirstThenActionThrows(exception1); var exception2 = new AssertionFailedException("Assertion 2 failed"); SecondThenActionThrows(exception2); var scenarioTest = CreateScenarioWithResultsCheck().Test; var testResult = scenarioTest.Run(); TestShouldFailWithExceptions(testResult, exception1, exception2); }
protected void AssertFails(Action action) { AssertionFailedException exception = null; try { action.Invoke(); } catch (AssertionFailedException e) { exception = e; } Assert.IsNotNull(exception, "Expect exception to be thrown"); }
public TException ThrowsSynchronously <TException>() where TException : Exception { Exception?exception = CaptureExceptionSynchronously(); if (exception is null) { AssertionFailedException.Throw(nameof(ThrowsSynchronously), typeof(TException).FullName !, "(No exception was observed synchronously)"); } else if (exception.GetType() != typeof(TException)) { AssertionFailedException.Throw(nameof(ThrowsSynchronously), typeof(TException).FullName !, exception.GetType().FullName !); } return((exception as TException) !); }
public TException ThrowsImmediately <TException>() where TException : Exception { Exception?exception = CaptureException(); if (exception is null) { AssertionFailedException.Throw(nameof(ThrowsImmediately), typeof(TException).FullName !, "(No exception was thrown when retrieving the asynchronous iterator)"); } else if (exception.GetType() != typeof(TException)) { AssertionFailedException.Throw(nameof(ThrowsImmediately), typeof(TException).FullName !, exception.GetType().FullName !); } return((exception as TException) !); }
protected void AssertFails(Action action, String errorMsg = null) { AssertionFailedException thrownAssertion = null; Exception thrown = null; try { action(); } catch (AssertionFailedException e) { thrownAssertion = e; } catch (Exception e) { thrown = e; } Assert.IsNotNull(thrownAssertion, "expected assertion failure " + appendMsg(errorMsg)); Assert.IsNull(thrown, errorMsg, "expected assertion failure not this exception" + appendMsg(errorMsg)); }
/// <summary> /// Abandons the provided transaction /// </summary> public void RollbackTransaction(ref TransactionToken token) { if (token.State == StateRolledback) { return; } AssertionFailedException.Assert(token.State == StateOpen); token.State = StateRolledback; MemoryStream buffer = token.Object as MemoryStream; if (buffer != null) { buffer.Dispose(); } token.Object = null; token.Handle = 0; }
public static HttpResponseMessage ToHttpResponseMessage(Exception e, bool mustMatchCoreExceptions = false) { bool firstTime = true; while (true) { var error = ToFulcrumError(e); if (error == null) { var message = $"The exception {e.GetType().FullName} was not recognized as a Fulcrum Exception. Message: {e.Message}"; if (!firstTime) { throw new ApplicationException(message); } firstTime = false; e = new AssertionFailedException(message, e); continue; } var statusCode = ToHttpStatusCode(error); if (statusCode == null) { var message = $"The TypeId of the following error could not be converted to an HTTP status code: {error.ToJsonString(Formatting.Indented)}."; if (!firstTime) { throw new ApplicationException(message); } firstTime = false; if (!mustMatchCoreExceptions) { return(null); } e = new AssertionFailedException(message, e); continue; } var content = error.ToJsonString(Formatting.Indented); var stringContent = new StringContent(content); var response = new HttpResponseMessage(statusCode.Value) { Content = stringContent }; return(response); } }
public IEnumerable <TAttribute> HasAttributes <TAttribute>() where TAttribute : Attribute { IEnumerable <TAttribute> attributes = assembly.GetCustomAttributes <TAttribute>(); if (!attributes.Any()) { string expectedMessage = $"{typeof(TAttribute)}"; string actualMessage = $"(No custom attributes of the specified type are applied to assembly '{assembly.FullName}')"; AssertionFailedException.Throw(nameof(HasAttributes), expectedMessage, actualMessage); } if (attributes.HasExactlyOne()) { string expectedMessage = $"{typeof(TAttribute)}"; string actualMessage = $"(Only one custom attribute of the specified type is applied to assembly '{assembly.FullName}')"; AssertionFailedException.Throw(nameof(HasAttributes), expectedMessage, actualMessage); } return(attributes); }
public TAttribute[] HasAttributes <TAttribute>(long expectedLongCount) where TAttribute : Attribute { if (expectedLongCount < 0) { throw new ArgumentOutOfRangeException(nameof(expectedLongCount), expectedLongCount, $"The {nameof(expectedLongCount)} argument cannot be a negative number."); } IEnumerable <TAttribute> attributes = assembly.GetCustomAttributes <TAttribute>(); TAttribute[] array = attributes.ToArray(); long actualLongLength = array.LongLength; if (expectedLongCount != actualLongLength) { string expectedMessage = $"Total number of {typeof(TAttribute)}: {expectedLongCount} (Target: '{assembly.FullName}')"; string actualMessage = $"Total number of {typeof(TAttribute)}: {actualLongLength} (Target: '{assembly.FullName}')"; AssertionFailedException.Throw($"{nameof(HasAttributes)}({nameof(Int64)})", expectedMessage, actualMessage); } return(array); }
public void When_the_fallback_assertion_exception_crosses_appdomain_boundaries_it_should_be_deserializable() { //----------------------------------------------------------------------------------------------------------- // Arrange //---------------------------------------------------------------------------------------------------------- Exception exception = new AssertionFailedException("Message"); //----------------------------------------------------------------------------------------------------------- // Act //----------------------------------------------------------------------------------------------------------- // Save the full ToString() value, including the exception message and stack trace. string exceptionToString = exception.ToString(); // Round-trip the exception: Serialize and de-serialize with a BinaryFormatter BinaryFormatter formatter = new BinaryFormatter(); using (MemoryStream memoryStream = new MemoryStream()) { // "Save" object state formatter.Serialize(memoryStream, exception); // Re-use the same stream for de-serialization memoryStream.Seek(0, 0); // Replace the original exception with de-serialized one exception = (AssertionFailedException)formatter.Deserialize(memoryStream); } //----------------------------------------------------------------------------------------------------------- // Assert //----------------------------------------------------------------------------------------------------------- // Double-check that the exception message and stack trace (owned by the base Exception) are preserved Assert.AreEqual(exceptionToString, exception.ToString(), "exception.ToString()"); }
public void Throw_WithInnerException() { Exception innerException = new InvalidOperationException("Inner Message"); Exception exception = Assert.Throws <AssertionFailedException>(() => AssertionFailedException.Throw("1", "2", "3", innerException)); string message = "'1' failed. (Inner Message)" + Environment.NewLine + " Expected: 2" + Environment.NewLine + " Actual: 3" + Environment.NewLine + " Inner --> System.InvalidOperationException: Inner Message"; Assert.Equal(message, exception.Message); Assert.NotNull(exception.InnerException); Assert.Same(innerException, exception.InnerException); }