using System; using System.Collections.Generic; using System.Threading; using UnitTestSharp; using Action = System.Action; namespace Foundations.UnitTests { public class DesktopCrashHandlerTests : TestFixture { public class CtorTests : TestFixture { public void NoShow_Throws() { CheckThrow(typeof(ArgumentNullException)); new DesktopCrashHandler(null, show: null, exit: () => { }); } public void NoExit_Throws() { CheckThrow(typeof(ArgumentNullException)); new DesktopCrashHandler(null, show: report => { }, exit: null); } } public class ReportTests : TestFixture { private List calls; public override void TestSetup() { calls = new List(); } [IgnoreTest] private DesktopCrashHandler Handler(Action whileShowing = null) { return new DesktopCrashHandler( new[] { new KeyValuePair("System", "TestOS") }, show: report => { calls.Add(report); whileShowing?.Invoke(); }, exit: () => calls.Add("exit")); } public void ShowsTheReportAndThenExits() { Handler().Report(new InvalidOperationException("It broke.")); CheckEqual(2, calls.Count); CheckTrue(calls[0].Contains("System.InvalidOperationException: It broke.")); CheckTrue(calls[0].Contains("System: TestOS")); CheckEqual("exit", calls[1]); } public void ASecondReport_IsIgnored() { DesktopCrashHandler handler = Handler(); handler.Report(new InvalidOperationException()); handler.Report(new InvalidOperationException()); CheckEqual(2, calls.Count); } public void AReportWhileOneShows_ReturnsAtOnceOnThatThread() { DesktopCrashHandler handler = null; handler = Handler(() => handler.Report(new InvalidOperationException())); handler.Report(new InvalidOperationException()); CheckEqual(2, calls.Count); } public void AReportFromAnotherThread_WaitsForTheOneShowing() { DesktopCrashHandler handler = null; bool returnedWhileShowing = true; Thread other = null; handler = Handler(() => { other = new Thread(() => handler.Report(new InvalidOperationException())); other.IsBackground = true; other.Start(); // Blocked or finished, whichever it comes to. while ((other.ThreadState & (ThreadState.WaitSleepJoin | ThreadState.Stopped)) == 0) { Thread.Yield(); } returnedWhileShowing = !other.IsAlive; }); handler.Report(new InvalidOperationException()); other.Join(); CheckFalse(returnedWhileShowing); CheckEqual(2, calls.Count); } public void ShowingThatThrows_StillExits() { DesktopCrashHandler handler = Handler(() => throw new NotSupportedException()); try { handler.Report(new InvalidOperationException()); } catch (NotSupportedException) { } CheckEqual("exit", calls[1]); } } } }