public void TestNoDieNoAbort() { var executor = new Executor(1) { AbortPipelineOnError = false, DieOnException = false }; var collector = new EventCollector <ExecutorLifeCycleEventArgs>(); CreatePipelineWithException(executor); executor.LifeCycleEvent += collector.Collect; executor.ExecuteBlocking(new MockFileSource(), true); AnalyzeCollector(collector, out int _, out int failedCount); // both pipelines are executed, and both fail Assert.AreEqual(2, failedCount); // due to no die, new file sources can be added executor.ExecuteBlocking(new MockFileSource(), true); AnalyzeCollector(collector, out int _, out failedCount); // with a second execution, two more should have failed Assert.AreEqual(4, failedCount); executor.Stop(); executor.LifeCycleEvent -= collector.Collect; }
public void TestDieAndAbort() { var executor = new Executor(1) { AbortPipelineOnError = true, DieOnException = true }; var collector = new EventCollector <ExecutorLifeCycleEventArgs>(); CreatePipelineWithException(executor); executor.LifeCycleEvent += collector.Collect; executor.ExecuteBlocking(new MockFileSource(), true); AnalyzeCollector(collector, out int _, out int failedCount); // after the first pipeline, the second (which also throws an exception) should not be executed Assert.AreEqual(1, failedCount); // due to die, new sources are not accepted anymore Assert.IsFalse(executor.Add(new MockFileSource())); Assert.IsTrue(collector.WaitFor(arg => arg.EventType == ExecutorLifeCycleEventType.Stop, 5000), "The executor did not stop in time (it should have died)."); executor.LifeCycleEvent -= collector.Collect; }
public async Task WatcherRaisesTheChangedEventOnStart() { using var watcher = new BindingsWatcher(_gif, _gof); var evs = new EventCollector <BindingPreset>(h => watcher.Changed += h, h => watcher.Changed -= h, nameof(WatcherRaisesTheChangedEventOnStart)); var binds = await evs.WaitAsync(() => { watcher.Start(); watcher.Stop(); }).ConfigureAwait(false); Assert.Null(binds.PresetName); // "Custom" and "Custom2" get merged to null. Assert.Equal(new Version(3, 0), binds.Version); Assert.Equal("es-ES", binds.KeyboardLayout); var k = binds.Bindings["Supercruise"].Primary; Assert.Equal("Keyboard", k.Device); Assert.Equal("Key_H", k.Key); Assert.Equal(2, k.Modifiers.Count); var modifiers = k.Modifiers.OrderBy(x => x.Key).ToList(); Assert.Equal("Keyboard", modifiers[0].Device); Assert.Equal("Key_LeftAlt", modifiers[0].Key); Assert.Equal("Keyboard", modifiers[1].Device); Assert.Equal("Key_LeftShift", modifiers[1].Key); }
private static bool HasConcurrency(EventCollector <ExecutorLifeCycleEventArgs> collector) { int runningSimultaneously = 0; foreach (var collectedEvent in collector.Events) { var currentEvent = collectedEvent.EventType; switch (currentEvent) { case ExecutorLifeCycleEventType.SourceExecutionStart: runningSimultaneously++; break; case ExecutorLifeCycleEventType.SourceExecutionFailed: case ExecutorLifeCycleEventType.SourceExecutionFinished: runningSimultaneously--; break; } if (runningSimultaneously > 1) { return(true); } } return(false); }
public async Task WatchesForChangesInTheGraphicsConfigurationFiles() { using var dirMain = new TestFolder(_gif.FullName); using var dirOpts = new TestFolder(_gof.FullName); using var watcher = new GraphicsConfigWatcher(new GameInstallFolder(dirMain.Name), new GameOptionsFolder(dirOpts.Name)); watcher.Start(); var evs = new EventCollector <GraphicsConfig>(h => watcher.Changed += h, h => watcher.Changed -= h); var xmlMain = dirMain.ReadText(_mainFile); var config = await evs.WaitAsync(() => dirMain.WriteText(_mainFile, string.Empty), 100).ConfigureAwait(false); Assert.Null(config); config = await evs.WaitAsync(() => dirMain.WriteText(_mainFile, xmlMain)).ConfigureAwait(false); Assert.Equal(0, config.GuiColour.Default[0, 0]); config = await evs.WaitAsync(() => dirOpts.WriteText(_overrideFile, string.Empty), 100).ConfigureAwait(false); Assert.Null(config); config = await evs.WaitAsync(() => dirOpts.WriteText(_overrideFile, _minimalConfig)).ConfigureAwait(false); Assert.Equal(1, config.GuiColour.Default[0, 0]); }
public int Execute() { EventCollector collector = new EventCollector(); Console.WriteLine(); ConsoleWriter outStream = new ConsoleWriter(Console.Out); ConsoleWriter errorStream = new ConsoleWriter(Console.Error); if (!options.noSummary) { TestResult result = testDomain.Run(collector, outStream, errorStream); Console.WriteLine("\n"); XmlResultVisitor resultVisitor = new XmlResultVisitor(outputFile, result); result.Accept(resultVisitor); resultVisitor.Write(); CreateSummaryDocument(); return(result.IsFailure ? 1 : 0); } else { testDomain.Run(collector, outStream, errorStream); return(0); } }
// case 5 or 6. public async Task FailedTransactionWillBeRetriedOnNewEvent() { var persistentCollector = new TestPersistentCollectorFailure(); var persistentCollectors = new List <IPersistentCollector>() { persistentCollector }; var eventCollector = new EventCollector(persistentCollectors); var partitionId = new Guid(); persistentCollector.DontAcceptChangesNow(); await Assert.ThrowsAnyAsync <Exception>(async() => await eventCollector.TransactionApplied(partitionId, 0, 1, this.Data)); persistentCollector.AcceptChangesNow(); await eventCollector.TransactionApplied(partitionId, 1, 2, this.Data); var changes = persistentCollector.Changes; Assert.True(1 == changes.Count); Assert.Equal(2, changes[0].Transactions.Count); Assert.Equal(1, changes[0].Transactions[0].Lsn); Assert.Equal(2, changes[0].Transactions[1].Lsn); }
public async Task WatcherRaisesEventsForNewJournalEntries() { using var dir = new TestFolder(_jf.FullName); using var watcher = new JournalWatcher(new JournalFolder(dir.Name)); var ecEntries = new EventCollector <JournalEntry>(h => watcher.EntryAdded += h, h => watcher.EntryAdded -= h, nameof(WatcherRaisesEventsForNewJournalEntries)); var ecReady = new EventCollector <EventArgs>(h => watcher.Started += h, h => watcher.Started -= h, nameof(WatcherRaisesEventsForNewJournalEntries)); var ev = await ecReady.WaitAsync(watcher.Start).ConfigureAwait(false); Assert.NotNull(ev); Assert.True(watcher.IsWatching); ev = await ecReady.WaitAsync(watcher.Start, 100).ConfigureAwait(false); Assert.Null(ev); var entry = await ecEntries.WaitAsync(() => dir.WriteText(_journalFile1, "{ \"event\":\"One\" }\r\n", true)).ConfigureAwait(false); Assert.Equal("One", entry.Event); var file2 = _journalFile1.Replace(".01.log", ".02.log", StringComparison.Ordinal); entry = await ecEntries.WaitAsync(() => dir.WriteText(file2, "{ \"event\":\"Two\" }\r\n")).ConfigureAwait(false); Assert.Equal("Two", entry.Event); watcher.Stop(); Assert.False(watcher.IsWatching); }
public async Task WatcherRaisesEventsForHistoricalEntriesOnStart() { using var watcher = new JournalWatcher(_jf); var ecEntries = new EventCollector <JournalEntry>(h => watcher.EntryAdded += h, h => watcher.EntryAdded -= h, nameof(WatcherRaisesEventsForHistoricalEntriesOnStart)); var ecReady = new EventCollector <EventArgs>(h => watcher.Started += h, h => watcher.Started -= h, nameof(WatcherRaisesEventsForHistoricalEntriesOnStart)); var readyTask = ecReady.WaitAsync(() => { }); var entries = new Queue <JournalEntry>(await ecEntries.WaitAsync(_journalFile1Count, () => { watcher.Start(); Assert.False(watcher.IsWatching); }).ConfigureAwait(false)); var ready = await readyTask.ConfigureAwait(false); Assert.NotNull(ready); Assert.True(watcher.IsWatching); watcher.Stop(); Assert.False(watcher.IsWatching); Assert.Equal(_journalFile1Count, entries.Count); Assert.IsType <FileHeader>(entries.Dequeue()); Assert.IsType <Music>(entries.Dequeue()); Assert.IsType <UnderAttack>(entries.Dequeue()); Assert.IsType <StartJump>(entries.Dequeue()); Assert.IsType <JournalEntry>(entries.Dequeue()); Assert.IsType <Shutdown>(entries.Dequeue()); }
private static void StopScheduler(IScheduler scheduler, EventCollector <SchedulerLifeCycleEventArgs> collector) { scheduler.Stop(); scheduler.Join(); scheduler.LifeCycleEvent -= collector.Collect; }
public void WatchesForGameProcessChanges() { var nm = new NativeMethodsMock() { Processes = { [0] = "System", [1000] = "Process 1000", [2000] = _gif.MainExecutable.FullName, }, }; using var gpw = new GameProcessWatcher(_gif, nm); var evs = new EventCollector <GameProcessState>(h => gpw.Changed += h, h => gpw.Changed -= h, nameof(WatchesForGameProcessChanges)); var pss = evs.Wait(3, () => { InvokeTimerElapsed(gpw); nm.ForegroundWindow = new IntPtr(2000); InvokeTimerElapsed(gpw); nm.ForegroundWindow = new IntPtr(1000); InvokeTimerElapsed(gpw); }); Assert.Equal(GameProcessState.NotRunning, pss[0]); Assert.Equal(GameProcessState.InForeground, pss[1]); Assert.Equal(GameProcessState.InBackground, pss[2]); }
public void RaisesEventsForEachGameStateChange() { var expected = new[] { ChangeType.StatusEntry, ChangeType.BindingPreset, ChangeType.GraphicsConfig, ChangeType.DeviceKeySet, ChangeType.GameProcessState, ChangeType.JournalEntry, ChangeType.JournalEntry, ChangeType.JournalEntry, ChangeType.JournalDrain, }; using var watcher = new GameStateWatcher(_gameRootFolder, _gameOptionsFolder, _journalFolder) { RaisePreStartupEvents = true, }; var evs = new EventCollector <ChangeType>(h => watcher.Changed += h, h => watcher.Changed -= h, nameof(RaisesEventsForEachGameStateChange)); var events = evs.Wait(expected.Length, watcher.Start, 5000); watcher.Stop(); var mismatches = expected.Except(events); Assert.Empty(mismatches); }
TestResult RunNUnitAssembly( IPNUnitServices services, ConsoleWriter outStream, TestRunner testRunner, string assemblyName) { ITestFilter testFilter = TestFilter.Empty; string excludeFilterString = GetExcludeFilter(); if (!string.IsNullOrEmpty(excludeFilterString)) { testFilter = new NotFilter( new CategoryExpression(excludeFilterString).Filter); } int testCount = testRunner.CountTestCases(testFilter); EventCollector collector = new EventCollector(outStream, testCount, services, assemblyName); TestResult result = testRunner.Run( collector, testFilter, true, LoggingThreshold.All); collector.NotifyProgress(); return(result); }
protected Domain(EventEmitter emitter, EventCollector collector, EventStore store) { Current = this; Emitter = emitter; Collector = collector; Store = store; TransactionTracker = new TransactionTracker(emitter); }
// case 7 and more :) public async Task RandomizedRealWorldTest() { var persistentCollector = new TestPersistentCollectorFailure(); var persistentCollectors = new List <IPersistentCollector>() { persistentCollector }; var eventCollector = new EventCollector(persistentCollectors); var partitionId = new Guid(); var rand = new Random(); const int MaxTimeToWaitInMs = 1000 * 20; // 20 seconds of test Func <Task> randomPCFailureFunc = async() => { var watch = Stopwatch.StartNew(); while (watch.ElapsedMilliseconds < MaxTimeToWaitInMs) { if (rand.Next(0, 10) < 3) // fail upload 30% time. { persistentCollector.DontAcceptChangesNow(); } else { persistentCollector.AcceptChangesNow(); } await Task.Delay(rand.Next(3, 20)); } }; var lsnTaskDict = new Dictionary <long, Task>(); var lsn = 0; Func <Task> addEvents = async() => { var watch = Stopwatch.StartNew(); while (watch.ElapsedMilliseconds < MaxTimeToWaitInMs) { var t = eventCollector.TransactionApplied(partitionId, lsn - 1, lsn, this.Data); lsnTaskDict.Add(lsn, t); lsn += 1; if (rand.Next(0, 10) < 4) // sleep 40% time. { await Task.Delay(rand.Next(0, 10)); } } }; Task.WaitAll(new Task[] { randomPCFailureFunc(), addEvents() }); persistentCollector.AcceptChangesNow(); await eventCollector.TransactionApplied(partitionId, lsn - 1, lsn, this.Data); var changes = persistentCollector.Changes; var allTransactions = changes.SelectMany((pc) => pc.Transactions).ToList(); var monotinicallyIncreasingLsns = allTransactions.Zip(allTransactions.Skip(1), (t1, t2) => t1.Lsn + 1 == t2.Lsn) .All(b => b == true); Assert.True(monotinicallyIncreasingLsns, "Some transaction is lost."); Assert.True(allTransactions[0].Lsn == 0, "First lsn is not right"); Assert.True(allTransactions.Last().Lsn == lsn, "Last lsn is not right"); }
public async Task RaisesEventsForEachGameStateChange() { using var watcher = new GameStateWatcher(_gameRootFolder, _gameOptionsFolder, _journalFolder); var evs = new EventCollector <EventArgs>(h => watcher.Changed += h, h => watcher.Changed -= h); await evs.WaitAsync(10, watcher.Start, 5000).ConfigureAwait(false); watcher.Stop(); }
static void Main(string[] args) { //Common.Logging.LogManager.Adapter //log4net.Config.XmlConfigurator.Configure(); ServiceManager.Services.AddService(new SettingsService()); ServiceManager.Services.AddService(new DomainManager()); ServiceManager.Services.AddService(new ProjectService()); ServiceManager.Services.InitializeServices(); TextReader inReader = Console.In; TextWriter outWriter = Console.Out; TextWriter errorWriter = Console.Error; EventListener testListener = new EventCollector(inReader, outWriter, errorWriter); try { var assembly = typeof(com.espertech.esper.client.TestConfiguration).Assembly.Location; var framework = RuntimeFramework.CurrentFramework; var testPackage = new TestPackage(assembly); testPackage.TestName = null; testPackage.Settings["DomainUsage"] = DomainUsage.Single; testPackage.Settings["ProcessModel"] = ProcessModel.Single; testPackage.Settings["ShadowCopyFiles"] = false; testPackage.Settings["UseThreadedRunner"] = true; testPackage.Settings["DefaultTimeout"] = 0; testPackage.Settings["RuntimeFramework"] = framework; var testFilter = TestFilter.Empty; if (args.Length > 0) { var nameFilter = new SimpleNameFilter(); nameFilter.Add(args[0]); testFilter = nameFilter; Console.WriteLine("Using SimpleNameFilter"); } using (var testRunner = new DefaultTestRunnerFactory().MakeTestRunner(testPackage)) { testRunner.Load(testPackage); Console.Error.WriteLine("{0}: Testing begins", DateTime.Now.Ticks); testRunner.Run(testListener, testFilter, true, LoggingThreshold.Off); Console.Error.WriteLine("{0}: Testing ends", DateTime.Now.Ticks); } } catch (Exception e) { Console.WriteLine(">> Error"); Console.WriteLine(e); } //Console.ReadLine(); }
public void AddUniqueCollector(EventCollector collector) { var collectorName = collector.Name; var existingCollector = _collectors.Find(col => col.Name == collectorName); if (existingCollector == null) { _collectors.Add(collector); } }
public void TestMultiThreadedExecution() { var executor = new Executor(4, new ReferenceFileSourceComparer()); var collector = new EventCollector <ExecutorLifeCycleEventArgs>(e => e.FileSource != null); CreateAndExecuteSimplePipeline(executor, collector, 8); Assert.IsTrue(HasConcurrency(collector), "It could not be observed, that two threads run concurrently. " + "It is very unlikely, that this was just a coincidence."); }
public static EventCollectorDescriptor GetDescriptor(this EventCollector collector) { var d = new EventCollectorDescriptor(); d.BufferSize = collector.BufferSize; d.MinimumBuffers = collector.MinimumBuffers; d.MaximumBuffers = collector.MaximumBuffers; d.LogFileName = collector.LogFileName; d.FlushPeriod = collector.FlushPeriod; d.Providers.AddRange(collector.Providers.Where(x => x.IsEnabled).Select(GetDescriptor)); return(d); }
public void RaisesEventsForEachGameStateChange() { using var watcher = new GameStateWatcher(_gameRootFolder, _gameOptionsFolder, _journalFolder) { RaisePreStartupEvents = true, }; var evs = new EventCollector <EventArgs>(h => watcher.Changed += h, h => watcher.Changed -= h); evs.Wait(8, watcher.Start, 5000); watcher.Stop(); }
private TestResult RunTest(ConsoleWriter outStream, TestDomain testDomain) { EventListener collector = new EventCollector(outStream); ITestFilter filter = new NUnit.Core.Filters.SimpleNameFilter(mPNUnitTestInfo.TestToRun); TestResult result = FindResult( mPNUnitTestInfo.TestToRun, testDomain.Run(collector, filter, false, LoggingThreshold.Off)); return(result); }
public async Task WatcherRaisesTheChangedEventOnStart() { using var watcher = new StatusWatcher(_jf); var ecs = new EventCollector <StatusEntry>(h => watcher.Changed += h, h => watcher.Changed -= h, nameof(WatcherRaisesTheChangedEventOnStart)); var status = await ecs.WaitAsync(() => { watcher.Start(); watcher.Stop(); }).ConfigureAwait(false); Assert.Equal("Status", status.Event); }
public async Task WatcherRaisesTheChangedEventOnStart() { using var watcher = new GraphicsConfigWatcher(_gif, _gof); var evs = new EventCollector <GraphicsConfig>(h => watcher.Changed += h, h => watcher.Changed -= h); var config = await evs.WaitAsync(() => { watcher.Start(); watcher.Stop(); }).ConfigureAwait(false); Assert.Null(config.GuiColour.Default.LocalisationName); }
private static BaseSchedulerImpl StartScheduler(out EventCollector <SchedulerLifeCycleEventArgs> collector) { var scheduler = new BaseSchedulerImpl() { SourceConditionDelay = 200 }; collector = new EventCollector <SchedulerLifeCycleEventArgs>(); scheduler.LifeCycleEvent += collector.Collect; scheduler.Start(); return(scheduler); }
public void TestDelayConflictingSources() { var executor = new Executor(3, new AlwaysEqualFileSourceComparer()); var collector = new EventCollector <ExecutorLifeCycleEventArgs>(e => e.FileSource != null); CreateAndExecuteSimplePipeline(executor, collector, 4); Assert.AreEqual(4, collector.Events.Count(e => e.EventType == ExecutorLifeCycleEventType.SourceExecutionFinished), "Not all file sources have been execute successfully."); Assert.IsFalse(HasConcurrency(collector), "Two threads executed simultaneously that were not allowed to (conflicting file sources)."); }
private void VerifyEqual(EventCollector expected, EventCollectorDescriptor actual) { // "expected.Name" is not mapped Assert.Equal(expected.BufferSize, actual.BufferSize); Assert.Equal(expected.MinimumBuffers, actual.MinimumBuffers); Assert.Equal(expected.MaximumBuffers, actual.MaximumBuffers); Assert.Equal(expected.LogFileName, actual.LogFileName); Assert.Equal(expected.FlushPeriod, actual.FlushPeriod); Assert.Equal(expected.Providers.Count, actual.Providers.Count); for (int i = 0; i < expected.Providers.Count; ++i) { VerifyEqual(expected.Providers[i], actual.Providers[i]); } }
public async Task WatcherToleratesEmptyGraphicsConfigurationOverrideFiles() { using var dirOpts = new TestFolder(_gof.FullName); dirOpts.WriteText(_overrideFile, string.Empty); using var watcher = new GraphicsConfigWatcher(_gif, new GameOptionsFolder(dirOpts.Name)); var evs = new EventCollector <GraphicsConfig>(h => watcher.Changed += h, h => watcher.Changed -= h, nameof(WatcherRaisesTheChangedEventOnStart)); var config = await evs.WaitAsync(() => { watcher.Start(); watcher.Stop(); }).ConfigureAwait(false); Assert.Equal("Standard", config.GuiColour.Default.LocalisationName); }
private void Update() { int count = Random.Range(10, 100); for (int i = 0; i < count; i++) { int stream = Random.Range(0, 3); int val = lastValue[stream] + Random.Range(-3, 3); if (val < 0) { val = 0; } EventCollector.PostEvent(new DiagnosticEvent(graphName, "", Random.Range(0, 250).ToString(), stream, Time.frameCount, val, null)); lastValue[stream] = val; } }
private void OnTransactionChangedHandler(object sender, NotifyTransactionChangedEventArgs e) { if (e.Action == NotifyTransactionChangedAction.Commit) { var allEvents = changeCollector.GetAllChanges(); var transactionMock = new TransactionMock(e.Transaction.TransactionId, e.Transaction.CommitSequenceNumber); var trAppliedEvent = new NotifyTransactionAppliedEvent(transactionMock, allEvents); Byte[] byteStream = messageConverter.Serialize(trAppliedEvent); long currentLsn = e.Transaction.CommitSequenceNumber; // handle the failure of Task here. EventCollector.TransactionApplied(this.partitionId, previousLsn, currentLsn, byteStream); previousLsn = currentLsn; // Flush previous items. this.changeCollector.CreateNew(); } }
TestResult RunTest( PNUnitTestInfo testInfo, ConsoleWriter outStream, TestRunner testRunner) { EventListener collector = new EventCollector(outStream); ITestFilter filter = new NUnit.Core.Filters.SimpleNameFilter( testInfo.TestToRun); TestResult result = testRunner.Run( collector, filter, true, LoggingThreshold.All); result = FindResult(testInfo.TestToRun, result); return(result); }
private void ThreadProc() { PNUnitTestResult result = null; TestDomain testDomain = new TestDomain(); try { log.InfoFormat("Thread entered for Test {0}:{1} Assembly {2}", mTestInfo.TestName, mTestInfo.TestToRun, mTestInfo.AssemblyName); ConsoleWriter outStream = new ConsoleWriter(Console.Out); // ConsoleWriter errorStream = new ConsoleWriter(Console.Error); #if NUNIT_2_5 ITest test = MakeTest(testDomain, Path.Combine(mConfig.PathToAssemblies, mTestInfo.AssemblyName)); #else testDomain.ShadowCopyFiles = false; Test test = MakeTest(testDomain, Path.Combine(mConfig.PathToAssemblies, mTestInfo.AssemblyName)); #endif if (test == null) { Console.Error.WriteLine("Unable to locate tests"); mTestInfo.Services.NotifyResult( mTestInfo.TestName, null); return; } Directory.SetCurrentDirectory(mConfig.PathToAssemblies); // test directory ? EventListener collector = new EventCollector( outStream ); // string savedDirectory = Environment.CurrentDirectory; log.Info("Creating PNUnitServices in the AppDomain of the test"); object[] param = { mTestInfo, (ITestConsoleAccess)this }; testDomain.AppDomain.CreateInstanceAndUnwrap( typeof(PNUnitServices).Assembly.FullName, typeof(PNUnitServices).FullName, false, BindingFlags.Default, null, param, null, null, null); log.Info("Running tests"); try { #if NUNIT_2_5 TestFilter filter = new NUnit.Core.Filters.SimpleNameFilter(mTestInfo.TestToRun); result = new PNUnitTestResult(testDomain.Run(collector, filter)); #else result = new PNUnitTestResult(testDomain.Run(collector, new string[1] { mTestInfo.TestToRun })[0]); #endif } catch( Exception e ) { result = new PNUnitTestResult(e); } } finally { log.Info("Notifying the results"); mTestInfo.Services.NotifyResult( mTestInfo.TestName, result); //Bug with framework if (IsWindows()) { lock(obj) { log.Info("Unloading test appdomain"); testDomain.Unload(); log.Info("Unloaded test appdomain"); } } } }
private TestResult RunTest(ConsoleWriter outStream, TestDomain testDomain) { EventListener collector = new EventCollector( outStream ); ITestFilter filter = new NUnit.Core.Filters.SimpleNameFilter(mPNUnitTestInfo.TestToRun); TestResult result = FindResult( mPNUnitTestInfo.TestToRun, testDomain.Run(collector, filter, false, LoggingThreshold.Off) ); return result; }
public TestableDomain(EventEmitter emitter, EventCollector collector, EventStore store) : base(emitter, collector, store) { }
private void ThreadProc() { TestResult result = null; TestDomain testDomain = new TestDomain(); TestConsoleAccess consoleAccess = new TestConsoleAccess(); try { log.InfoFormat("Thread entered for Test {0}:{1} Assembly {2}", mPNUnitTestInfo.TestName, mPNUnitTestInfo.TestToRun, mPNUnitTestInfo.AssemblyName); ConsoleWriter outStream = new ConsoleWriter(Console.Out); ConsoleWriter errorStream = new ConsoleWriter(Console.Error); bool testLoaded = MakeTest(testDomain, Path.Combine(mConfig.PathToAssemblies, mPNUnitTestInfo.AssemblyName), GetShadowCopyCacheConfig()); if (!testLoaded) { log.InfoFormat("Unable to locate test {0}", mPNUnitTestInfo.TestName); result = BuildError("Unable to locate tests", consoleAccess); mPNUnitTestInfo.Services.NotifyResult( mPNUnitTestInfo.TestName, result); return; } Directory.SetCurrentDirectory(mConfig.PathToAssemblies); // test directory ? EventListener collector = new EventCollector( outStream ); string savedDirectory = Environment.CurrentDirectory; log.Info("Creating PNUnitServices in the AppDomain of the test"); object[] param = { mPNUnitTestInfo, (ITestConsoleAccess) consoleAccess }; try { System.Runtime.Remoting.ObjectHandle obj #if NET_2_0 = Activator.CreateInstance( testDomain.AppDomain, #else = testDomain.AppDomain.CreateInstance( #endif typeof(PNUnitServices).Assembly.FullName, typeof(PNUnitServices).FullName, false, BindingFlags.Default, null, param, null, null, null); obj.Unwrap(); } catch( Exception e ) { result = BuildError(e, consoleAccess); log.ErrorFormat("Error running test {0}", e.Message); return; } log.Info("Running tests"); try { ITestFilter filter = new NUnit.Core.Filters.SimpleNameFilter(mPNUnitTestInfo.TestToRun); result = FindResult( mPNUnitTestInfo.TestToRun, testDomain.Run(collector, filter) ); filter = null; } catch( Exception e ) { result = BuildError(e, consoleAccess); log.ErrorFormat("Error running test {0}", e.Message); } } finally { log.Info("Notifying the results"); mPNUnitTestInfo.Services.NotifyResult( mPNUnitTestInfo.TestName, BuildResult(result, consoleAccess)); result = null; //Bug with framework if( IsWindows() ) { #if !NET_2_0 lock(obj) #endif { testDomain.Unload(); } } } }
public int Execute() { EventCollector collector = new EventCollector(); Console.WriteLine (); ConsoleWriter outStream = new ConsoleWriter(Console.Out); ConsoleWriter errorStream = new ConsoleWriter(Console.Error); if (!options.noSummary) { TestResult result = testDomain.Run(collector, outStream, errorStream); Console.WriteLine("\n"); XmlResultVisitor resultVisitor = new XmlResultVisitor(outputFile, result); result.Accept(resultVisitor); resultVisitor.Write(); CreateSummaryDocument(); return result.IsFailure ? 1 : 0; } else { testDomain.Run (collector, outStream, errorStream); return 0; } }
/// <summary> /// Runs the tests and sets up the formatters. /// </summary> protected override void ExecuteTask() { if (FormatterElements.Count == 0) { FormatterElement defaultFormatter = new FormatterElement(); defaultFormatter.Project = Project; defaultFormatter.NamespaceManager = NamespaceManager; defaultFormatter.Type = FormatterType.Plain; defaultFormatter.UseFile = false; FormatterElements.Add(defaultFormatter); Log(Level.Warning, "No <formatter .../> element was specified." + " A plain-text formatter was added to prevent losing output of the" + " test results."); Log(Level.Warning, "Add a <formatter .../> element to the" + " <nunit2> task to prevent this warning from being output and" + " to ensure forward compatibility with future revisions of NAnt."); } LogWriter logWriter = new LogWriter(this, Level.Info, CultureInfo.InvariantCulture); EventListener listener = new EventCollector(logWriter, logWriter); foreach (NUnit2Test testElement in Tests) { IFilter categoryFilter = null; // include or exclude specific categories string categories = testElement.Categories.Includes.ToString(); if (!StringUtils.IsNullOrEmpty(categories)) { categoryFilter = new CategoryFilter(categories.Split(','), false); } else { categories = testElement.Categories.Excludes.ToString(); if (!StringUtils.IsNullOrEmpty(categories)) { categoryFilter = new CategoryFilter(categories.Split(','), true); } } foreach (string testAssembly in testElement.TestAssemblies) { NUnit2TestDomain domain = new NUnit2TestDomain(); try { TestRunner runner = domain.CreateRunner( new FileInfo(testAssembly), testElement.AppConfigFile, testElement.References.FileNames); Test test = null; if (testElement.TestName != null) { test = runner.Load(testAssembly, testElement.TestName); } else { test = runner.Load(testAssembly); } if (test == null) { Log(Level.Warning, "Assembly \"{0}\" contains no tests.", testAssembly); continue; } // set category filter if (categoryFilter != null) { runner.Filter = categoryFilter; } // run test TestResult result = runner.Run(listener); // flush test output to log logWriter.Flush(); // format test results using specified formatters FormatResult(testElement, result); if (result.IsFailure && (testElement.HaltOnFailure || HaltOnFailure)) { throw new BuildException("Tests Failed.", Location); } } catch (BuildException) { // re-throw build exceptions throw; } catch (Exception ex) { if (!FailOnError) { // just log error and continue with next test Log(Level.Error, LogPrefix + "NUnit Error: " + ex.ToString()); continue; } Version nunitVersion = typeof(TestResult).Assembly.GetName().Version; throw new BuildException(string.Format(CultureInfo.InvariantCulture, "Failure executing test(s). If you assembly is not built using" + " NUnit version {0}, then ensure you have redirected assembly" + " bindings. Consult the documentation of the <nunit2> task" + " for more information.", nunitVersion), Location, ex); } finally { domain.Unload(); // flush test output to log logWriter.Flush(); } } } }
public int Execute( ConsoleOptions options ) { XmlTextReader transformReader = GetTransformReader(options); if(transformReader == null) return 3; ConsoleWriter outStream = options.isOut ? new ConsoleWriter( new StreamWriter( options.output ) ) : new ConsoleWriter(Console.Out); ConsoleWriter errorStream = options.isErr ? new ConsoleWriter( new StreamWriter( options.err ) ) : new ConsoleWriter(Console.Error); TestDomain testDomain = new TestDomain(outStream, errorStream); if ( options.noshadow ) testDomain.ShadowCopyFiles = false; Test test = MakeTestFromCommandLine(testDomain, options); if(test == null) { Console.Error.WriteLine("Unable to locate fixture {0}", options.fixture); return 2; } Directory.SetCurrentDirectory(new FileInfo((string)options.Parameters[0]).DirectoryName); EventCollector collector = new EventCollector( options, outStream ); string savedDirectory = Environment.CurrentDirectory; if (options.HasInclude) { Console.WriteLine( "Included categories: " + options.include ); testDomain.SetFilter( new CategoryFilter( options.IncludedCategories ) ); } else if ( options.HasExclude ) { Console.WriteLine( "Excluded categories: " + options.exclude ); testDomain.SetFilter( new CategoryFilter( options.ExcludedCategories, true ) ); } TestResult result = null; if ( options.thread ) { testDomain.RunTest( collector ); testDomain.Wait(); result = testDomain.Result; } else { result = testDomain.Run( collector ); } Directory.SetCurrentDirectory( savedDirectory ); Console.WriteLine(); Console.WriteLine(); collector.PrintSummary( result ); Console.WriteLine(); string xmlOutput = CreateXmlOutput( result ); if (options.xmlConsole) Console.WriteLine(xmlOutput); else CreateSummaryDocument(xmlOutput, transformReader, outStream); // Write xml output here string xmlResultFile = options.IsXml ? options.xml : "TestResult.xml"; using ( StreamWriter writer = new StreamWriter( xmlResultFile ) ) { writer.Write(xmlOutput); } outStream.Flush(); errorStream.Flush(); if ( testDomain != null ) testDomain.Unload(); return result.IsFailure ? 1 : 0; }