public void AutoExecute(TriggerEvent triggerEvent, GallioAction triggerAction, GallioAction cleanupAction) { if (triggerAction == null) { throw new ArgumentNullException("triggerAction"); } Finishing += (sender, e) => { if (IsTriggerEventSatisfied(triggerEvent)) { try { triggerAction(); } catch (Exception ex) { UnhandledExceptionPolicy.Report("An exception occurred while performing an auto-execute trigger action.", ex); } } if (cleanupAction != null) { try { cleanupAction(); } catch (Exception ex) { UnhandledExceptionPolicy.Report("An exception occurred while performing an auto-execute cleanup action.", ex); } } }; }
/// <summary> /// Runs isolated tasks until the server shuts down. /// </summary> public void Run() { try { var link = (IMessageExchangeLink)clientChannel.GetService(typeof(IMessageExchangeLink), TestIsolationServer.GetMessageExchangeLinkServiceName(linkId)); for (; ;) { Message message = link.Receive(PollTimeout); if (message == null) { continue; } if (message is ShutdownMessage) { break; } RunIsolatedTask(link, (RunIsolatedTaskMessage)message); } } catch (Exception ex) { UnhandledExceptionPolicy.Report("An exception occurred while processing messages. Assuming the server is no longer available.", ex); } }
private IList <PatternTestFrameworkExtensionInfo> GetExtensions(IAssemblyInfo assembly) { var testFrameworkManager = RuntimeAccessor.ServiceLocator.Resolve <ITestFrameworkManager>(); var extensions = new List <PatternTestFrameworkExtensionInfo>(); IList <AssemblyName> assemblyReferences = assembly.GetReferencedAssemblies(); foreach (var testFrameworkHandle in testFrameworkManager.TestFrameworkHandles) { if (Array.IndexOf(testFrameworkIds, testFrameworkHandle.Id) < 0) { continue; } if (testFrameworkHandle.GetTraits().IsFrameworkCompatibleWithAssemblyReferences(assemblyReferences)) { try { var testFramework = (PatternTestFramework)testFrameworkHandle.GetComponent(); extensions.AddRange(testFramework.GetExtensions(assembly)); } catch (Exception ex) { UnhandledExceptionPolicy.Report( "A pattern test framework extension threw an exception while enumerating referenced extensions for an assembly.", ex); } } } extensions.Sort((a, b) => a.Id.CompareTo(b.Id)); return(extensions); }
private void AsyncPublishLoop() { for (; ;) { Message message; lock (queue) { if (queue.Count == 0) { asyncResult = null; return; } message = queue.Dequeue(); } try { messageSink.Publish(message); } catch (Exception ex) { UnhandledExceptionPolicy.Report( "An unhandled exception occurred while asynchronously publishing a queued message.", ex); } } }
private static void UnhandledErrorPolicy() { Application.ThreadException += (sender, e) => UnhandledExceptionPolicy.Report("Error from Application.ThreadException", e.Exception); AppDomain.CurrentDomain.UnhandledException += (sender, e) => UnhandledExceptionPolicy.Report("Error from Application.ThreadException", (Exception)e.ExceptionObject); }
private static void UnhandledErrorPolicy() { BlackBoxLogger.Initialize(); UnhandledExceptionPolicy.ReportUnhandledException += (sender, e) => BlackBoxLogger.Log(e); Application.ThreadException += (sender, e) => UnhandledExceptionPolicy.Report("Error from Application.ThreadException", e.Exception); AppDomain.CurrentDomain.UnhandledException += (sender, e) => UnhandledExceptionPolicy.Report("Error from Application.ThreadException", (Exception)e.ExceptionObject); }
private static object PolicyPerformsCorrelationThenReportingCallback(object dummy) { var ex = new Exception("Some exception"); CorrelatedExceptionEventArgs finalArgs = null; UnhandledExceptionPolicy.CorrelateUnhandledException += (sender, e) => e.AddCorrelationMessage("bar"); UnhandledExceptionPolicy.ReportUnhandledException += (sender, e) => finalArgs = e; UnhandledExceptionPolicy.Report("foo", ex); return(finalArgs); }
public void Cancel() { try { remoteProgressMonitor.NotifyCanceled(); } catch (Exception ex) { UnhandledExceptionPolicy.Report("Could not locally dispatch cancelation event.", ex); } }
/// <inheritdoc /> public void Dispose() { try { Flush(); } catch (Exception ex) { UnhandledExceptionPolicy.Report("An unhandled exception occurred while flushing a queued message sink.", ex); } }
private void RemotelyRegisterDispatcher() { dispatcher = new Dispatcher(this); try { forwarder.RegisterDispatcher(dispatcher); } catch (Exception ex) { UnhandledExceptionPolicy.Report("Could not remotely register the progress monitor callback dispatcher.", ex); } }
public void RegisterDispatcher(Dispatcher dispatcher) { progressMonitor.Canceled += delegate { try { dispatcher.Cancel(); } catch (Exception ex) { UnhandledExceptionPolicy.Report("Could not remotely dispatch cancelation event.", ex); } }; }
private static void UnloadPackages() { foreach (var package in RuntimeAccessor.ServiceLocator.ResolveAll <IPackage>()) { try { package.Dispose(); } catch (Exception ex) { UnhandledExceptionPolicy.Report("Error unloading package", ex); } } }
private void CaptureFrame() { try { lastBitmap = grabber.CaptureScreenshot(lastBitmap); AddFrame(lastBitmap); } catch (ScreenshotNotAvailableException) { // Ignore the exception. } catch (Exception ex) { UnhandledExceptionPolicy.Report("Could not capture screenshot.", ex); } }
public void Dispatch(LogSeverity severity, string message, ExceptionData exceptionData) { EventHandlerPolicy.SafeInvoke(LogMessage, this, new LogEntrySubmittedEventArgs(severity, message, exceptionData)); foreach (ILogger logger in Listeners) { try { logger.Log(severity, message, exceptionData); } catch (Exception ex) { UnhandledExceptionPolicy.Report( "An exception occurred while dispatching a message to a log listener.", ex); } } }
/// <inheritdoc /> public override void Write(string value) { if (value == null) { return; } try { ITestContext context = TestContextTrackerAccessor.Instance.CurrentContext; if (context == null) { return; } Write(context, value); } catch (Exception ex) { UnhandledExceptionPolicy.Report(String.Format("Could not write to the '{0}' log stream.\nMessage: '{1}'", streamName, value), ex); } }
private PreferenceContainer LoadPreferenceContainer() { preferenceSetFile.Refresh(); if (preferenceSetFile.Exists) { try { using (var reader = new StreamReader(preferenceSetFile.Open(FileMode.Open, FileAccess.Read, FileShare.Read))) { var container = (PreferenceContainer)XmlSerializer.Deserialize(reader); container.Validate(); return(container); } } catch (Exception ex) { UnhandledExceptionPolicy.Report(string.Format("Failed to load preferences from file '{0}'.", preferenceSetFile.FullName), ex); } } return(null); }
private void Run() { try { try { try { BeforeTask(); ThreadAbortException ex = threadAbortScope.Run(invoker.Invoke); if (ex != null) { NotifyTerminated(TaskResult <object> .CreateFromException(ex)); } else { NotifyTerminated(TaskResult <object> .CreateFromValue(invoker.Result)); } } finally { AfterTask(); } } catch (Exception ex) { NotifyTerminated(TaskResult <object> .CreateFromException(ex)); } } catch (Exception ex) { UnhandledExceptionPolicy.Report("An unhandled exception occurred in a thread task.", ex); } }
private static void ReportUnhandledException(Exception ex) { UnhandledExceptionPolicy.Report("An unhandled exception occurred while running a parallelizable action.", ex); }
/// <summary> /// Runs an isolated task in a host. /// </summary> /// <typeparam name="TIsolatedTask">The isolated task type.</typeparam> /// <param name="hostSetup">The host setup which includes the test isolation option properties copied down, not null.</param> /// <param name="statusReporter">The status reporter, not null.</param> /// <param name="args">The task arguments.</param> /// <returns>The task result.</returns> protected virtual object RunIsolatedTaskInHost <TIsolatedTask>(HostSetup hostSetup, StatusReporter statusReporter, object[] args) where TIsolatedTask : IsolatedTask { IHost host = null; try { statusReporter("Creating test host."); host = hostFactory.CreateHost(hostSetup, logger); RemoteLogger remoteLogger = new RemoteLogger(logger); RuntimeSetup runtimeSetup = RuntimeAccessor.Instance.GetRuntimeSetup().Copy(); Shim shim = HostUtils.CreateInstance <Shim>(host); try { statusReporter("Initializing the runtime."); shim.Initialize(runtimeSetup, remoteLogger); statusReporter(""); var isolatedTask = HostUtils.CreateInstance <TIsolatedTask>(host); ManualResetEvent disconnectedEvent = new ManualResetEvent(false); EventHandler disconnectedEventHandler = (sender, e) => disconnectedEvent.Set(); try { host.Disconnected += disconnectedEventHandler; RunIsolatedTaskDelegate isolatedTaskDelegate = isolatedTask.Run; IAsyncResult asyncResult = isolatedTaskDelegate.BeginInvoke(args, null, null); WaitHandle.WaitAny(new[] { disconnectedEvent, asyncResult.AsyncWaitHandle }); if (asyncResult.IsCompleted) { return(isolatedTaskDelegate.EndInvoke(asyncResult)); } throw new TestIsolationException("The host disconnected or was terminated prematurely while the task was running."); } finally { host.Disconnected -= disconnectedEventHandler; } } finally { statusReporter("Shutting down the runtime."); shim.Shutdown(); GC.KeepAlive(remoteLogger); } } finally { statusReporter("Disposing test host."); try { if (host != null) { host.Dispose(); } } catch (Exception ex) { UnhandledExceptionPolicy.Report("An exception occurred while disposing the test host.", ex); } statusReporter(""); } }
private TestResult FinishStep(TestOutcome outcome, TimeSpan?actualDuration, bool isDisposing) { EventHandler cachedFinishingHandlers; lock (syncRoot) { if (!IsRunning) { if (isDisposing) { return(result ?? new TestResult(TestOutcome.Error)); } throw new InvalidOperationException("Cannot finish a step unless the test step is running."); } this.outcome = outcome; executionStatus = StatusFinishing; LifecyclePhase = LifecyclePhases.Finishing; cachedFinishingHandlers = finishingHandlers; finishingHandlers = null; } // Note: We no longer need to hold the lock because none of the state used from here on can change // since the status is now StatusFinishing. try { if (parent != null) { parent.Finishing -= HandleParentFinishedBeforeThisContext; } using (Enter()) EventHandlerPolicy.SafeInvoke(cachedFinishingHandlers, this, EventArgs.Empty); if (isDisposing) { logWriter.Failures.Write("The test step was orphaned by the test runner!\n"); } logWriter.Close(); result = new TestResult(outcome) { AssertCount = assertCount, Duration = actualDuration.GetValueOrDefault(stopwatch.Elapsed) }; MessageSink.Publish(new TestStepFinishedMessage() { StepId = testStep.Id, Result = result }); if (contextCookie != null) { if (!isDisposing) { contextCookie.Dispose(); } contextCookie = null; } return(result); } catch (Exception ex) { UnhandledExceptionPolicy.Report("An unhandled exception occurred while finishing a test step.", ex); return(new TestResult(TestOutcome.Error)); } finally { lock (syncRoot) executionStatus = StatusFinished; } }
public void ReportThrowsIfExceptionIsNull() { UnhandledExceptionPolicy.Report("blah", null); }
public void ReportThrowsIfMessageIsNull() { UnhandledExceptionPolicy.Report(null, new Exception()); }