using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using UnitTestSharp; namespace Amphora.UnitTests { public class ExceptionReportTests : TestFixture { public class UnreadableException : Exception { public override string Message => throw new NotSupportedException(); public override string StackTrace => throw new NotSupportedException(); public override IDictionary Data => throw new NotSupportedException(); } public class SelfDescribingTarget { public override string ToString() => "okButton"; } public class UndescribableTarget { public override string ToString() => throw new NotSupportedException(); } public class PlainTarget { } public class LongTarget { public override string ToString() => new string('a', ExceptionReport.MaxTextLength); } public static ExceptionEntry Entry(Exception exception, ExceptionSeverity severity = ExceptionSeverity.Contained) { var returnMe = new ExceptionEntry(exception, frame: 3, time: TimeSpan.FromMilliseconds(50), severity); returnMe.RecordHit(new ExceptionSite(new PlainTarget(), phase: 2), notes: null, frame: 3, time: TimeSpan.FromMilliseconds(50)); return returnMe; } public static string[] Lines(ExceptionEntry entry, IEnumerable> environment = null) { return ExceptionReport.Write(entry, environment) .Split(new[] { Environment.NewLine }, StringSplitOptions.None); } public static ExceptionEntry EntryAt(object target, params Dictionary[] notes) { var returnMe = new ExceptionEntry(new InvalidOperationException(), frame: 0, time: TimeSpan.Zero); foreach (Dictionary set in notes) { returnMe.RecordHit(new ExceptionSite(target, phase: 1), set, frame: 0, time: TimeSpan.Zero); } return returnMe; } public class DescribeEnvironmentTests : TestFixture { [IgnoreTest] private string[] Labels(List> lines) { return lines.Select(line => line.Key).ToArray(); } public void NothingKnown_StillSaysTheRuntimeAndSystem() { CheckEqual(new[] { "Runtime", "System" }, Labels(ExceptionReport.DescribeEnvironment(program: null, flags: null))); } public void Runtime_SaysHowWideTheProcessIs() { string runtime = ExceptionReport.DescribeEnvironment(program: null, flags: null)[0].Value; CheckTrue(runtime.EndsWith(IntPtr.Size == 8 ? ", 64-bit" : ", 32-bit")); } public void AProgram_LeadsWithItsNameAndVersion() { Assembly program = typeof(ExceptionReport).Assembly; KeyValuePair first = ExceptionReport.DescribeEnvironment(program, flags: null)[0]; CheckEqual("Program", first.Key); CheckEqual($"Amphora {program.GetName().Version}", first.Value); } public void ANamedFlag_IsListedLast() { KeyValuePair last = ExceptionReport .DescribeEnvironment(program: null, FlagRegistryTests.Read("--seed=7")).Last(); CheckEqual("Flag seed", last.Key); CheckEqual("7", last.Value); } } public class WriteCrashTests : TestFixture { [IgnoreTest] private string[] CrashLines(Exception exception, IEnumerable> environment = null) { return ExceptionReport.WriteCrash(exception, environment) .Split(new[] { Environment.NewLine }, StringSplitOptions.None); } public void NoException_Throws() { CheckThrow(typeof(ArgumentNullException)); ExceptionReport.WriteCrash(null, environment: null); } public void HoldsTheSeverityThenTheException() { CheckEqual( new[] { "Severity: fatal", "", "System.InvalidOperationException: It broke.", " (no stack trace)", "", }, CrashLines(new InvalidOperationException("It broke."))); } public void AnInnerException_IsListedAsTheCause() { var thrown = new InvalidOperationException("outer", new ArgumentException("inner")); CheckTrue(CrashLines(thrown).Contains("Caused by: System.ArgumentException: inner")); } public void AnEnvironment_ClosesTheReport() { var environment = new[] { new KeyValuePair("System", "TestOS") }; string[] lines = CrashLines(new InvalidOperationException(), environment); CheckEqual(new[] { "Program", "System: TestOS", "" }, lines.Skip(lines.Length - 3).ToArray()); } } public class WriteTests : TestFixture { public void NoEntry_Throws() { CheckThrow(typeof(ArgumentNullException)); ExceptionReport.Write(null, environment: null); } public void Contained_OpensWithTheSeverity() { CheckEqual("Severity: contained", Lines(Entry(new InvalidOperationException()))[0]); } public void StateSuspect_OpensWithTheSeverity() { CheckEqual("Severity: state may be wrong", Lines(Entry(new InvalidOperationException(), ExceptionSeverity.StateSuspect))[0]); } public void Fatal_OpensWithTheSeverity() { CheckEqual("Severity: fatal", Lines(Entry(new InvalidOperationException(), ExceptionSeverity.Fatal))[0]); } public void ThrownOnce_SaysOnlyWhenItWasFirstThrown() { string[] lines = Lines(Entry(new InvalidOperationException())); CheckEqual("Times thrown: 1", lines[1]); CheckEqual("First: frame 3 at 0.05 s", lines[2]); CheckFalse(lines.Any(line => line.StartsWith("Last:"))); } public void ThrownAgain_SaysWhenItWasLastThrown() { ExceptionEntry entry = Entry(new InvalidOperationException()); entry.RecordHit(entry.Sites.Single(), notes: null, frame: 90, time: TimeSpan.FromSeconds(1.5)); string[] lines = Lines(entry); CheckEqual("Times thrown: 2", lines[1]); CheckEqual("Last: frame 90 at 1.5 s", lines[3]); } public void SaysTheTypeAndMessage() { CheckTrue(Lines(Entry(new InvalidOperationException("It broke."))) .Contains("System.InvalidOperationException: It broke.")); } public void AThrownException_IncludesItsStackTrace() { try { ExceptionSandboxTests.ThrowFromClientHelper(); } catch (InvalidOperationException exception) { CheckTrue(Lines(Entry(exception)) .Any(line => line.Contains(nameof(ExceptionSandboxTests.ThrowFromClientHelper)))); } } public void AnExceptionNeverThrown_SaysItHasNoStackTrace() { CheckTrue(Lines(Entry(new InvalidOperationException())).Contains(" (no stack trace)")); } public void Data_IsListed() { var thrown = new InvalidOperationException(); thrown.Data["tick"] = 12; CheckTrue(Lines(Entry(thrown)).Contains(" tick: 12")); } public void AnInnerException_IsListedAsTheCause() { var thrown = new InvalidOperationException("outer", new ArgumentException("inner")); CheckTrue(Lines(Entry(thrown)).Contains("Caused by: System.ArgumentException: inner")); } public void AnAggregate_ListsEveryCause() { var thrown = new AggregateException(new ArgumentException("one"), new FormatException("two")); string[] lines = Lines(Entry(thrown)); CheckTrue(lines.Contains("Caused by: System.ArgumentException: one")); CheckTrue(lines.Contains("Caused by: System.FormatException: two")); } public void AFailedTypeLoad_ListsWhatFailedToLoad() { var thrown = new ReflectionTypeLoadException( new Type[] { null }, new Exception[] { new TypeLoadException("missing") }); CheckTrue(Lines(Entry(thrown)).Contains("Caused by: System.TypeLoadException: missing")); } public void ATypeLoadWithAnUnknownFailure_SkipsIt() { var thrown = new ReflectionTypeLoadException( new Type[] { null, null }, new Exception[] { null, new TypeLoadException("missing") }); string[] causes = Lines(Entry(thrown)).Where(line => line.StartsWith("Caused by: ")).ToArray(); CheckEqual(new[] { "Caused by: System.TypeLoadException: missing" }, causes); } #if NETFRAMEWORK public void CausesThatCantBeRead_SaysSo() { var thrown = new ReflectionTypeLoadException(new Type[] { null }, exceptions: null); CheckTrue(Lines(Entry(thrown)) .Contains("(the cause is unreadable, since reading it threw System.ArgumentNullException)")); } #else public void ATypeLoadWithNoFailureList_ListsNoCauses() { var thrown = new ReflectionTypeLoadException(new Type[] { null }, exceptions: null); string[] lines = Lines(Entry(thrown)); CheckFalse(lines.Any(line => line.StartsWith("Caused by: ") || line.Contains("unreadable"))); } #endif public void MoreCausesThanTheMaximum_SaysSomeWereLeftOut() { Exception[] causes = Enumerable.Range(0, ExceptionReport.MaxExceptions + 1) .Select(index => (Exception)new ArgumentException($"cause {index}")) .ToArray(); string[] lines = Lines(Entry(new AggregateException(causes))); CheckEqual(ExceptionReport.MaxExceptions - 1, lines.Count(line => line.StartsWith("Caused by: "))); CheckTrue(lines.Contains("(more exceptions left out)")); } public void AnExceptionThatThrowsWhenRead_StillMakesAReport() { string[] lines = Lines(Entry(new UnreadableException())); string unreadable = "(unreadable, since reading it threw System.NotSupportedException)"; CheckTrue(lines.Contains($"{typeof(UnreadableException).FullName}: {unreadable}")); CheckTrue(lines.Contains(unreadable)); CheckTrue(lines.Contains( " (the data is unreadable, since reading it threw System.NotSupportedException)")); } public void AMessageOfTheMaximumLength_IsKeptWhole() { string message = new string('a', ExceptionReport.MaxTextLength); string[] lines = Lines(Entry(new InvalidOperationException(message))); CheckTrue(lines.Contains($"System.InvalidOperationException: {message}")); } public void ALongerMessage_IsCutShortAndSaysByHowMuch() { string kept = new string('a', ExceptionReport.MaxTextLength); string[] lines = Lines(Entry(new InvalidOperationException(kept + "bbbbb"))); CheckTrue(lines.Contains($"System.InvalidOperationException: {kept} (5 more characters left out)")); } public void ACut_DoesNotSplitACharacterPair() { string kept = new string('a', ExceptionReport.MaxTextLength - 1); string[] lines = Lines(Entry(new InvalidOperationException(kept + char.ConvertFromUtf32(0x1F600)))); CheckTrue(lines.Contains($"System.InvalidOperationException: {kept} (2 more characters left out)")); } public void ALongNote_IsCutShort() { string kept = new string('a', ExceptionReport.MaxTextLength); var notes = new Dictionary { { "path", kept + "b" } }; string[] lines = Lines(EntryAt(new PlainTarget(), notes)); CheckTrue(lines.Contains($" path: {kept} (1 more characters left out)")); } public void MoreDataThanTheMaximum_SaysSo() { var thrown = new InvalidOperationException(); for (int i = 0; i < ExceptionReport.MaxDataItems + 1; i++) { thrown.Data[$"item {i}"] = i; } string[] lines = Lines(Entry(thrown)); CheckEqual(ExceptionReport.MaxDataItems, lines.Count(line => line.StartsWith(" item "))); CheckTrue(lines.Contains(" (more data left out)")); } public void MoreSitesThanTheMaximum_SaysHowManyWereLeftOut() { var entry = new ExceptionEntry(new InvalidOperationException(), frame: 0, time: TimeSpan.Zero); for (int i = 0; i < ExceptionReport.MaxSites + 2; i++) { entry.RecordHit(new ExceptionSite(new PlainTarget(), phase: 1), notes: null, frame: 0, time: TimeSpan.Zero); } string[] lines = Lines(entry); CheckEqual(ExceptionReport.MaxSites, lines.Count(line => line.StartsWith("- "))); CheckTrue(lines.Contains("(2 more sites left out)")); } // Eight texts of the longest length reach the longest report. public void AReportAtItsMaximumLength_TakesOnNoMoreExceptions() { string message = new string('a', ExceptionReport.MaxTextLength); Exception thrown = null; for (int i = 0; i < 10; i++) { thrown = new InvalidOperationException(message, thrown); } string[] lines = Lines(Entry(thrown)); CheckEqual(7, lines.Count(line => line.StartsWith("Caused by: "))); CheckTrue(lines.Contains("(more exceptions left out)")); } public void AReportAtItsMaximumLength_TakesOnNoMoreData() { var thrown = new InvalidOperationException(); for (int i = 0; i < 10; i++) { thrown.Data[$"item {i}"] = new string('a', ExceptionReport.MaxTextLength); } string[] lines = Lines(Entry(thrown)); CheckEqual(8, lines.Count(line => line.StartsWith(" item "))); CheckTrue(lines.Contains(" (more data left out)")); } public void AReportAtItsMaximumLength_TakesOnNoMoreNotes() { Dictionary[] notes = Enumerable.Range(0, 10) .Select(index => new Dictionary { { $"item {index}", new string('a', ExceptionReport.MaxTextLength) }, }) .ToArray(); string[] lines = Lines(EntryAt(new PlainTarget(), notes)); CheckEqual(8, lines.Count(line => line.StartsWith(" item "))); CheckTrue(lines.Contains(" (more notes left out)")); } public void AReportAtItsMaximumLength_TakesOnNoMoreSites() { var thrown = new InvalidOperationException(); var entry = new ExceptionEntry(thrown, frame: 0, time: TimeSpan.Zero); for (int i = 0; i < 10; i++) { entry.RecordHit(new ExceptionSite(new LongTarget(), phase: 1), notes: null, frame: 0, time: TimeSpan.Zero); } CheckTrue(Lines(entry).Contains("(2 more sites left out)")); } public void ATargetWithNoDescription_IsNamedByItsType() { CheckTrue(Lines(Entry(new InvalidOperationException())) .Contains($"- {typeof(PlainTarget)}, phase 2")); } public void ATargetThatDescribesItself_SaysSoAfterItsType() { CheckTrue(Lines(EntryAt(new SelfDescribingTarget(), new Dictionary())) .Contains($"- {typeof(SelfDescribingTarget).FullName}, phase 1: okButton")); } public void ATargetThatThrowsWhenDescribed_IsStillListed() { CheckTrue(Lines(EntryAt(new UndescribableTarget(), new Dictionary())) .Contains($"- {typeof(UndescribableTarget).FullName}, phase 1: " + "(unreadable, since reading it threw System.NotSupportedException)")); } public void ASiteWithNoTarget_SaysSo() { CheckTrue(Lines(EntryAt(null, new Dictionary())).Contains("- no object, phase 1")); } public void EachSetOfNotes_IsOneLine() { var first = new Dictionary { { "path", "screen" }, { "phase", "update" } }; var second = new Dictionary { { "path", "dialog" } }; string[] lines = Lines(EntryAt(new PlainTarget(), first, second)); CheckTrue(lines.Contains(" path: screen, phase: update")); CheckTrue(lines.Contains(" path: dialog")); } public void EmptyNotes_AddNoLine() { string[] lines = Lines(EntryAt(new PlainTarget(), new Dictionary())); CheckFalse(lines.Any(line => line.StartsWith(" "))); } public void OmittedNotes_AreCounted() { Dictionary[] notes = Enumerable.Range(0, ExceptionEntry.MaxNotesPerSite + 2) .Select(index => new Dictionary { { "item", $"{index}" } }) .ToArray(); CheckTrue(Lines(EntryAt(new PlainTarget(), notes)).Contains("(2 more sets of notes left out)")); } public void AnEnvironment_ClosesTheReport() { var environment = new[] { new KeyValuePair("System", "TestOS") }; string[] lines = Lines(Entry(new InvalidOperationException()), environment); CheckEqual(new[] { "Program", "System: TestOS", "" }, lines.Skip(lines.Length - 3).ToArray()); } public void NoEnvironment_LeavesTheSectionOut() { CheckFalse(Lines(Entry(new InvalidOperationException())).Contains("Program")); } } } }