public void ShouldLogAnErrorWhenUpgradeFails() { var ex = new InvalidOperationException(); ScriptProvider.GetScripts(Arg.Any<Func<IDbConnection>>()).Returns(provider => { throw ex; }); DbUpgrader.PerformUpgrade(); Log.Received().WriteError("Upgrade failed due to an unexpected exception:\r\n{0}", ex.ToString()); }
public void WhenExceptionMessageHasOnlyException_ThenMessageContainsExceptionMessageAndStacktrace() { var exception = new InvalidOperationException("Foo"); var traceEvent = new ExceptionTraceEvent(TraceEventType.Error, 0, exception); Assert.Contains("Foo", traceEvent.MessageOrFormat); Assert.Contains(exception.ToString(), traceEvent.MessageOrFormat); }
public void WhenExceptionMessageHasMessageFormat_ThenMessageContainsFormattedMessageAndExceptionMessageAndStacktrace() { var exception = new InvalidOperationException("Foo"); var traceEvent = new ExceptionTraceEvent(TraceEventType.Error, 0, exception, "Hello {0}", "World"); Assert.Contains("Hello World", traceEvent.MessageOrFormat); Assert.Contains("Foo", traceEvent.MessageOrFormat); Assert.Contains(exception.ToString(), traceEvent.MessageOrFormat); }
public void WhenAddingMessageAndThrowsShouldLogError() { var message = new Message(new Uri("http://www.google.com"), string.Empty); var exception = new InvalidOperationException("Error"); this.PersistentStore.Setup(s => s.Add(message)).Throws(exception); this.StoreService.Put(message); this.PersistentStore.Verify(r => r.Add(message), Times.AtLeast(1)); this.Logger.Verify(l => l.Err("StoreService.ThreadStart. Error {0}", exception.ToString()), Times.AtLeast(1)); }
public void SerializesProperties() { var exception = new InvalidOperationException("Some message") { HelpLink = "http://example.com" }; var errors = new ErrorSerializer().Serialize(new ApiError(exception))["errors"][0]; Assert.Equal(exception.Message, errors.Value<string>("title")); Assert.Equal(exception.HelpLink, errors["links"].Value<string>("about")); Assert.Equal(exception.GetType().FullName, errors.Value<string>("code")); Assert.Equal(exception.ToString(), errors.Value<string>("detail")); }
public void ScenarioOptionThrowingException() { var injector = new MockInjector(); var program = injector.Create<Program>(); var runner = injector.GetMock<IRunner>(); var output = injector.GetMock<IOutput>(); var options = new Options { Scenario = "s" }; var exception = new InvalidOperationException("moo"); runner.Setup(r => r.Run(It.IsAny<string>(), It.IsAny<string[]>(), null)) .Throws(exception); program.Run(options) .Should().Be(1); output.Verify(o => o.Display(It.Is<ResultModel>(r => r.Result == Result.Fail && r.Message == exception.ToString()))); }
public void MainPresenter_VersionChecker_Logs_Exceptions() { _Presenter.Initialise(_View.Object); var exception = new InvalidOperationException("Exception text here"); _Log.Verify(o => o.WriteLine(It.IsAny<string>(), It.IsAny<string>()), Times.Never()); _NewVersionChecker.Setup(c => c.CheckForNewVersion()).Callback(() => { throw exception; }); _HeartbeatService.Raise(h => h.SlowTick += null, EventArgs.Empty); _Log.Verify(o => o.WriteLine(It.IsAny<string>(), exception.ToString()), Times.Once()); }
public void Plugin_Shutdown_Logs_Exceptions_Raised_During_Session_Shutdown() { var exception = new InvalidOperationException(); _BaseStationDatabase.Setup(d => d.UpdateSession(It.IsAny<BaseStationSession>())).Callback(() => { throw exception; }); SetEnabledOption(true); _Plugin.Startup(_StartupParameters); _Plugin.Shutdown(); _Log.Verify(g => g.WriteLine(It.IsAny<string>(), exception.ToString()), Times.Once()); }
public void Plugin_Startup_Records_Exception_In_Log_If_Session_Start_Throws() { var exception = new InvalidOperationException(); SetEnabledOption(true); _BaseStationDatabase.Setup(d => d.InsertSession(It.IsAny<BaseStationSession>())).Callback(() => { throw exception; }); _Plugin.Startup(_StartupParameters); _Log.Verify(g => g.WriteLine(It.IsAny<string>(), exception.ToString()), Times.Once()); }
public void Plugin_Reports_Exceptions_During_Flight_Update() { var exception = new InvalidOperationException(); SetEnabledOption(true); _BaseStationDatabase.Setup(d => d.UpdateFlight(It.IsAny<BaseStationFlight>())).Callback(() => { throw exception; }); var startTime = SetProviderTimes(DateTime.Now); _Plugin.Startup(_StartupParameters); _Plugin.StatusChanged += _StatusChangedEvent.Handler; _StatusChangedEvent.EventRaised += (s, a) => { Assert.AreEqual(String.Format("Exception caught: {0}", exception.Message), _Plugin.StatusDescription); }; var message = new BaseStationMessage() { AircraftId = 99, Icao24 = "X", MessageType = BaseStationMessageType.Transmission, TransmissionType = BaseStationTransmissionType.AirToAir }; _Listener.Raise(r => r.Port30003MessageReceived += null, new BaseStationMessageEventArgs(message)); var endTime = SetProviderTimes(startTime.AddMinutes(MinutesBeforeFlightClosed)); _HeartbeatService.Raise(s => s.SlowTick += null, EventArgs.Empty); Assert.AreEqual(1, _StatusChangedEvent.CallCount); Assert.AreSame(_Plugin, _StatusChangedEvent.Sender); _Log.Verify(g => g.WriteLine(It.IsAny<string>(), exception.ToString()), Times.Once()); }
public void Plugin_Reports_Exceptions_During_Database_EndTransaction() { var exception = new InvalidOperationException(); SetEnabledOption(true); _BaseStationDatabase.Setup(d => d.EndTransaction()).Callback(() => { throw exception; }); _Plugin.Startup(_StartupParameters); _Plugin.StatusChanged += _StatusChangedEvent.Handler; _StatusChangedEvent.EventRaised += (s, a) => { Assert.AreEqual(String.Format("Exception caught: {0}", exception.Message), _Plugin.StatusDescription); }; var message = new BaseStationMessage() { AircraftId = 99, Icao24 = "X", MessageType = BaseStationMessageType.Transmission, TransmissionType = BaseStationTransmissionType.AirToAir }; _Listener.Raise(r => r.Port30003MessageReceived += null, new BaseStationMessageEventArgs(message)); Assert.AreEqual(1, _StatusChangedEvent.CallCount); Assert.AreSame(_Plugin, _StatusChangedEvent.Sender); _Log.Verify(g => g.WriteLine(It.IsAny<string>(), exception.ToString()), Times.Once()); }
public void ShutdownPresenter_ShutdownApplication_Logs_Exceptions_Raised_By_Plugins() { var log = TestUtilities.CreateMockSingleton<ILog>(); var exception = new InvalidOperationException(); var plugin = new Mock<IPlugin>(); plugin.Setup(p => p.Shutdown()).Callback(() => { throw exception; }); _Plugins.Add(plugin.Object); _Presenter.Initialise(_View.Object); _Presenter.ShutdownApplication(); log.Verify(g => g.WriteLine(It.IsAny<string>(), It.IsAny<string>(), exception.ToString()), Times.Once()); }
public void SplashPresenter_StartApplication_Reports_Exceptions_Raised_During_Load_Of_Standing_Data() { var exception = new InvalidOperationException("oops"); _StandingDataManager.Setup(m => m.Load()).Callback(() => { throw exception; }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Exception caught during load of standing data: {0}", exception.ToString()), Times.Once()); _View.Verify(v => v.ReportProblem(String.Format(Strings.CannotLoadFlightRouteDataFull, exception.Message), Strings.CannotLoadFlightRouteDataTitle, false), Times.Once()); }
private bool ValidateForHtmlContent(InvalidOperationException exp) { return exp.ToString().Contains("<html xmlns=''> was not expected"); }
public void MessageWithExceptionTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "a"); var ex = new InvalidOperationException("Exception message."); logger.DebugException("Foo", ex); #if !SILVERLIGHT && !NET_CF string newline = Environment.NewLine; #else string newline = "\r\n"; #endif AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString()); }
public void BackgroundDataDownloader_Heartbeat_Tick_Logs_Exceptions_From_Updater() { SetUtcNow(DateTime.Now); var exception = new InvalidOperationException(); _StandingDataUpdater.Setup(u => u.Update()).Callback(() => { throw exception; }); _BackgroundDataDownloader.Start(); _HeartbeatService.Raise(h => h.SlowTick += null, EventArgs.Empty); _Log.Verify(g => g.WriteLine("Exception caught during data download: {0}", exception.ToString()), Times.Once()); }
public void WritesException_WhenNoMessageIsProvided() { // Arrange var t = SetUp(null); var logger = (ILogger)t.Item1; var sink = t.Item2; var exception = new InvalidOperationException("Invalid value"); var expectedMessage = exception.ToString(); // Act logger.LogCritical(state: null, error: exception); logger.LogCritical(10, state: null, error: exception); // Assert Assert.Equal(2, sink.Writes.Count); Assert.Equal($"critical: [{_name}] {expectedMessage}", sink.Writes[0].Message); Assert.Equal($"critical: [{_name}] {expectedMessage}", sink.Writes[1].Message); }
public void WhenAddingMessageFailShouldRetry() { var message = new Message(new Uri("http://www.google.com"), string.Empty); var exception = new InvalidOperationException("Error"); var count = 0; this.PersistentStore.Setup(s => s.Add(message)) .Callback(() => { count++; if (count % 10 != 0) { throw exception; } }); this.StoreService.Put(message); this.PersistentStore.Verify(r => r.Add(message), Times.Exactly(10)); this.Logger.Verify(l => l.Err("StoreService.ThreadStart. Error {0}", exception.ToString()), Times.Exactly(9)); }
public void write_log_exception() { var ex = new InvalidOperationException("Fake Exception"); //Act Logger.ErrorException(UniqueMessage, ex); //Assert var logItem = Db.Fetch<Log>().Single(); VerifyLog(logItem, LogLevel.Error); logItem.Message.Should().Be(UniqueMessage + ": " + ex.Message); logItem.ExceptionType.Should().Be(ex.GetType().ToString()); logItem.Exception.Should().Be(ex.ToString()); ExceptionVerification.ExpectedErrors(1); }
public void MessageWithExceptionAndCustomSeparatorTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true:exceptionSeparator=,}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); Logger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "a"); var ex = new InvalidOperationException("Exception message."); logger.DebugException("Foo", ex); AssertDebugLastMessage("debug", "Foo," + ex.ToString()); }
public void MessageWithExceptionTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog exceptionLoggingOldStyle='true'> <targets><target name='debug' type='Debug' layout='${message:withException=true}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "a"); var ex = new InvalidOperationException("Exception message."); #if !SILVERLIGHT string newline = Environment.NewLine; #else string newline = "\r\n"; #endif #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.DebugException("Foo", ex); AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString()); #pragma warning restore 0618 logger.Debug(ex, "Foo"); AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString()); logger.Debug( "Foo", ex); AssertDebugLastMessage("debug", "Foo" + newline + ex.ToString()); }
public void MessageWithExceptionAndCustomSeparatorTest() { LogManager.Configuration = CreateConfigurationFromString(@" <nlog> <targets><target name='debug' type='Debug' layout='${message:withException=true:exceptionSeparator=,}' /></targets> <rules> <logger name='*' minlevel='Debug' writeTo='debug' /> </rules> </nlog>"); ILogger logger = LogManager.GetLogger("A"); logger.Debug("a"); AssertDebugLastMessage("debug", "a"); var ex = new InvalidOperationException("Exception message."); #pragma warning disable 0618 // Obsolete method requires testing until completely removed. logger.DebugException("Foo", ex); AssertDebugLastMessage("debug", "Foo," + ex.ToString()); #pragma warning restore 0618 logger.Debug(ex, "Foo"); AssertDebugLastMessage("debug", "Foo," + ex.ToString()); }
public void Writes_NewLine_WhenExceptionIsProvided(string message) { // Arrange var t = SetUp(null); var logger = (ILogger)t.Item1; var sink = t.Item2; var eventId = 10; var exception = new InvalidOperationException("Invalid value"); var expectedMessage = _paddingString + message + Environment.NewLine + _paddingString + ReplaceMessageNewLinesWithPadding(exception.ToString()) + Environment.NewLine; // Act logger.LogCritical(message, exception); logger.LogCritical(eventId, message, exception); // Assert Assert.Equal(6, sink.Writes.Count); Assert.Equal(expectedMessage, sink.Writes[2].Message); Assert.Equal(expectedMessage, sink.Writes[5].Message); }
public void SplashPresenter_StartApplication_Reports_Problems_Starting_A_Plugin_To_User() { var plugin1 = new Mock<IPlugin>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); var plugin2 = new Mock<IPlugin>() { DefaultValue = DefaultValue.Mock }.SetupAllProperties(); plugin1.Setup(p => p.Name).Returns("P1"); plugin2.Setup(p => p.Name).Returns("P2"); _PluginManager.Setup(p => p.LoadedPlugins).Returns(new IPlugin[] { plugin1.Object, plugin2.Object }); var exception = new InvalidOperationException(); plugin1.Setup(p => p.Startup(It.IsAny<PluginStartupParameters>())).Callback(() => { throw exception; }); _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); plugin1.Verify(p => p.Startup(It.IsAny<PluginStartupParameters>()), Times.Once()); plugin2.Verify(p => p.Startup(It.IsAny<PluginStartupParameters>()), Times.Once()); _View.Verify(v => v.ReportProblem(String.Format(Strings.PluginThrewExceptionFull, "P1", exception.Message), Strings.PluginThrewExceptionTitle, false), Times.Once()); _View.Verify(v => v.ReportProblem(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<bool>()), Times.Once()); _Log.Verify(g => g.WriteLine("Caught exception when starting {0}: {1}", new object[] { "P1", exception.ToString() }), Times.Once()); }
public void WritesException_WhenNoMessageIsProvided() { // Arrange var t = SetUp(null); var logger = (ILogger)t.Item1; var sink = t.Item2; var exception = new InvalidOperationException("Invalid value"); var expectedMessage = _paddingString + ReplaceMessageNewLinesWithPadding(exception.ToString()) + Environment.NewLine; // Act logger.LogCritical(state: null, error: exception); logger.LogCritical(10, state: null, error: exception); // Assert Assert.Equal(6, sink.Writes.Count); Assert.Equal(expectedMessage, sink.Writes[2].Message); Assert.Equal(expectedMessage, sink.Writes[5].Message); }
public void SplashPresenter_StartApplication_Logs_Failure_To_Connect_To_Data_Feed_Regardless_Of_AutoReconnect_Setting() { var exception = new InvalidOperationException("msg here"); _Listener.Setup(b => b.Connect(true)).Callback(() => { throw exception; }); _Configuration.BaseStationSettings.AutoReconnectAtStartup = true; _Presenter.Initialise(_View.Object); _Presenter.StartApplication(); _Log.Verify(g => g.WriteLine("Could not connect to data feed: {0}", exception.ToString()), Times.Once()); }
public void WhenThrowsWhileForwardingMessagesShouldNotStopThreadAndContinueSending() { this.HttpClient.Setup(c => c.Post(It.IsAny<IMessage>())) .Returns(Result.Ok); var store = new Mock<IRepository>(); var waitHandle = new AutoResetEventAdapter(false); var messageProvider = new Mock<IMessageProvider>(); messageProvider.SetupGet(m => m.CanSend).Returns(true); messageProvider.Setup(s => s.GetNext()).Returns(this.CreateMessage()); var exception = new InvalidOperationException("Error"); var callCount = 0; messageProvider.Setup(s => s.Delete(It.IsAny<IMessage>())) .Callback(() => { callCount++; if (callCount % 2 == 0) { throw exception; } }); var forwardService = new ForwardService(store.Object, this.HttpClient.Object, this.NetworkStateService.Object, waitHandle, 1000, 0, false, this.Logger.Object); forwardService.MessageProvider = messageProvider.Object; this.ForwardService.PeriodicBackoutCheck = this.PeriodicBackoutCheck.Object; forwardService.Start(); Thread.Sleep(3000); forwardService.Stop(); messageProvider.Verify(m => m.CanSend, Times.AtLeast(1)); messageProvider.Verify(m => m.GetNext(), Times.AtLeast(1)); messageProvider.Verify(m => m.Delete(It.IsAny<IMessage>()), Times.AtLeast(1)); messageProvider.Verify(m => m.Close(), Times.AtLeast(1)); this.Logger.Verify(l => l.Err("ForwardService.ThreadStart. Error {0}", exception.ToString()), Times.AtLeast(1)); }