Exemplo n.º 1
0
        public void ReturnsTrueWhenCancellationThunkIsFalse()
        {
            var sink = new DelegatingExecutionSummarySink(innerSink, () => false);

            var result = sink.OnMessage(testMessage);

            Assert.True(result);
        }
Exemplo n.º 2
0
    private async Task <XElement> Run(Assembly assembly, string assemblyPath)
    {
        using (var frontController = new XunitFrontController(AppDomainSupport, assemblyPath, null, false))
        {
            using (var discoverySink = new TestDiscoverySink())
            {
                var configuration = GetConfiguration(assembly) ?? new TestAssemblyConfiguration()
                {
                    PreEnumerateTheories = false
                };
                ITestFrameworkDiscoveryOptions discoveryOptions = GetFrameworkOptionsForDiscovery(configuration);
                discoveryOptions.SetSynchronousMessageReporting(true);
                Logger.OnDebug($"Starting test discovery in the '{assembly}' assembly");
                frontController.Find(false, discoverySink, discoveryOptions);
                Logger.OnDebug($"Test discovery in assembly '{assembly}' completed");
                discoverySink.Finished.WaitOne();

                if (discoverySink.TestCases == null || discoverySink.TestCases.Count == 0)
                {
                    Logger.Info("No test cases discovered");
                    return(null);
                }

                TotalTests += discoverySink.TestCases.Count;
                List <ITestCase> testCases;
                if (_filters != null && _filters.TestCaseFilters.Any())
                {
                    Action <string> log = LogExcludedTests ? (s) => do_log(s) : (Action <string>)null;
                    testCases = discoverySink.TestCases.Where(
                        tc => !_filters.IsExcluded(tc, log)).ToList();
                    FilteredTests += discoverySink.TestCases.Count - testCases.Count;
                }
                else
                {
                    testCases = discoverySink.TestCases;
                }

                var            assemblyElement = new XElement("assembly");
                IExecutionSink resultsSink     = new DelegatingExecutionSummarySink(_messageSink, null, null);
                resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                ITestFrameworkExecutionOptions executionOptions = GetFrameworkOptionsForExecution(configuration);
                executionOptions.SetDisableParallelization(!RunInParallel);
                executionOptions.SetSynchronousMessageReporting(true);
                executionOptions.SetMaxParallelThreads(MaxParallelThreads);

                // set the wait for event cb first, then execute the tests
                var resultTask = WaitForEvent(resultsSink.Finished, TimeSpan.FromDays(10)).ConfigureAwait(false);
                frontController.RunTests(testCases, resultsSink, executionOptions);
                await resultTask;

                return(assemblyElement);
            }
        }
    }
Exemplo n.º 3
0
        XElement Run(Assembly assembly, string assemblyPath)
        {
            using (var frontController = new XunitFrontController(AppDomainSupport, assemblyPath, null, false))
            {
                using (var discoverySink = new TestDiscoverySink())
                {
                    var configuration = GetConfiguration(assembly) ?? new TestAssemblyConfiguration();
                    ITestFrameworkDiscoveryOptions discoveryOptions = GetFrameworkOptionsForDiscovery(configuration);
                    discoveryOptions.SetSynchronousMessageReporting(true);
                    Logger.OnInfo(LogTag, $"Starting test discovery in the '{assembly}' assembly");
                    frontController.Find(false, discoverySink, discoveryOptions);
                    Logger.OnInfo(LogTag, $"Test discovery in assembly '{assembly}' completed");
                    discoverySink.Finished.WaitOne();

                    if (discoverySink.TestCases == null || discoverySink.TestCases.Count == 0)
                    {
                        Logger.OnInfo(LogTag, "No test cases discovered");
                        return(null);
                    }

                    TotalTests += discoverySink.TestCases.Count;
                    List <ITestCase> testCases;
                    if (filters != null && filters.Count > 0)
                    {
                        testCases      = discoverySink.TestCases.Where(tc => IsIncluded(tc)).ToList();
                        FilteredTests += discoverySink.TestCases.Count - testCases.Count;
                    }
                    else
                    {
                        testCases = discoverySink.TestCases;
                    }

                    var            assemblyElement = new XElement("assembly");
                    IExecutionSink resultsSink     = new DelegatingExecutionSummarySink(messageSink, null, null);
                    resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                    ITestFrameworkExecutionOptions executionOptions = GetFrameworkOptionsForExecution(configuration);
                    executionOptions.SetDisableParallelization(!RunInParallel);
                    executionOptions.SetSynchronousMessageReporting(true);

                    try
                    {
                        frontController.RunTests(testCases, resultsSink, executionOptions);
                        resultsSink.Finished.WaitOne();
                    }
                    finally
                    {
                        resultsSink.Dispose();
                    }

                    return(assemblyElement);
                }
            }
        }
Exemplo n.º 4
0
        void RunTestsInAssembly(List <IDisposable> toDispose, AssemblyRunInfo runInfo)
        {
            if (cancelled)
            {
                return;
            }

            var assemblyFileName = runInfo.AssemblyFileName;

            var longRunningSeconds = runInfo.Configuration.LongRunningTestSecondsOrDefault;

            var controller = new XunitFrontController(AppDomainSupport.Denied, assemblyFileName);

            lock (toDispose)
                toDispose.Add(controller);


            var xunitTestCases = runInfo.TestCases.Select(tc => new { vm = tc, tc = tc.TestCase })
                                 .Where(tc => tc.tc.UniqueID != null)
                                 .ToDictionary(tc => tc.tc, tc => tc.vm);

            var executionOptions = TestFrameworkOptions.ForExecution(runInfo.Configuration);

            var diagSink = new DiagnosticMessageSink(d => context.Post(_ => OnDiagnosticMessage?.Invoke(d), null), runInfo.AssemblyFileName, executionOptions.GetDiagnosticMessagesOrDefault());


            var deviceExecSink = new DeviceExecutionSink(xunitTestCases, this, context);

            IExecutionSink resultsSink = new DelegatingExecutionSummarySink(deviceExecSink, () => cancelled);

            if (longRunningSeconds > 0)
            {
                resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), diagSink);
            }


            var assm = new XunitProjectAssembly()
            {
                AssemblyFilename = runInfo.AssemblyFileName
            };

            deviceExecSink.OnMessage(new TestAssemblyExecutionStarting(assm, executionOptions));

            controller.RunTests(xunitTestCases.Select(tc => tc.Value.TestCase).ToList(), resultsSink, executionOptions);
            resultsSink.Finished.WaitOne();


            deviceExecSink.OnMessage(new TestAssemblyExecutionFinished(assm, executionOptions, resultsSink.ExecutionSummary));
        }
Exemplo n.º 5
0
    public static int Main(string[] args)
    {
        var asm = typeof(SingleFileTestRunner).Assembly;

        Console.WriteLine("Running assembly:" + asm.FullName);

        var diagnosticSink = new ConsoleDiagnosticMessageSink();
        var testsFinished  = new TaskCompletionSource();
        var testSink       = new TestMessageSink();
        var summarySink    = new DelegatingExecutionSummarySink(testSink,
                                                                () => false,
                                                                (completed, summary) => Console.WriteLine($"Tests run: {summary.Total}, Errors: {summary.Errors}, Failures: {summary.Failed}, Skipped: {summary.Skipped}. Time: {TimeSpan.FromSeconds((double)summary.Time).TotalSeconds}s"));
        var resultsXmlAssembly = new XElement("assembly");
        var resultsSink        = new DelegatingXmlCreationSink(summarySink, resultsXmlAssembly);

        testSink.Execution.TestSkippedEvent += args => { Console.WriteLine($"[SKIP] {args.Message.Test.DisplayName}"); };
        testSink.Execution.TestFailedEvent  += args => { Console.WriteLine($"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{Xunit.ExceptionUtility.CombineMessages(args.Message)}{Environment.NewLine}{Xunit.ExceptionUtility.CombineStackTraces(args.Message)}"); };

        testSink.Execution.TestAssemblyFinishedEvent += args =>
        {
            Console.WriteLine($"Finished {args.Message.TestAssembly.Assembly}{Environment.NewLine}");
            testsFinished.SetResult();
        };

        var xunitTestFx = new SingleFileTestRunner(diagnosticSink);
        var asmInfo     = Reflector.Wrap(asm);
        var asmName     = asm.GetName();

        var discoverySink = new TestDiscoverySink();
        var discoverer    = xunitTestFx.CreateDiscoverer(asmInfo);

        discoverer.Find(false, discoverySink, TestFrameworkOptions.ForDiscovery());
        discoverySink.Finished.WaitOne();
        XunitFilters filters = new XunitFilters();

        filters.ExcludedTraits.Add("category", new List <string> {
            "failing"
        });
        var filteredTestCases = discoverySink.TestCases.Where(filters.Filter).ToList();
        var executor          = xunitTestFx.CreateExecutor(asmName);

        executor.RunTests(filteredTestCases, resultsSink, TestFrameworkOptions.ForExecution());

        resultsSink.Finished.WaitOne();

        var failed = resultsSink.ExecutionSummary.Failed > 0 || resultsSink.ExecutionSummary.Errors > 0;

        return(failed ? 1 : 0);
    }
Exemplo n.º 6
0
        protected virtual XElement ExecuteAssembly(XunitProjectAssembly assembly)
        {
            if (cancel)
            {
                return(null);
            }

            var assemblyElement = NeedsXml ? new XElement("assembly") : null;

            try
            {
                // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner
                assembly.Configuration.PreEnumerateTheories = false;
                assembly.Configuration.DiagnosticMessages  |= DiagnosticMessages;

                if (appDomains.HasValue)
                {
                    assembly.Configuration.AppDomain = appDomains.GetValueOrDefault() ? AppDomainSupport.Required : AppDomainSupport.Denied;
                }

                // Setup discovery and execution options with command-line overrides
                var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration);
                var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration);
                if (maxThreadCount.HasValue && maxThreadCount.Value > -1)
                {
                    executionOptions.SetMaxParallelThreads(maxThreadCount);
                }
                if (parallelizeTestCollections.HasValue)
                {
                    executionOptions.SetDisableParallelization(!parallelizeTestCollections);
                }

                var assemblyDisplayName   = Path.GetFileNameWithoutExtension(assembly.AssemblyFilename);
                var diagnosticMessageSink = new DiagnosticMessageSink(Log, assemblyDisplayName, assembly.Configuration.DiagnosticMessagesOrDefault);
                var appDomainSupport      = assembly.Configuration.AppDomainOrDefault;
                var shadowCopy            = assembly.Configuration.ShadowCopyOrDefault;
                var longRunningSeconds    = assembly.Configuration.LongRunningTestSecondsOrDefault;

                using (var controller = new XunitFrontController(appDomainSupport, assembly.AssemblyFilename, assembly.ConfigFilename, shadowCopy, diagnosticMessageSink: diagnosticMessageSink))
                    using (var discoverySink = new TestDiscoverySink(() => cancel))
                    {
                        // Discover & filter the tests
                        reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryStarting(assembly, controller.CanUseAppDomains && appDomainSupport != AppDomainSupport.Denied, shadowCopy, discoveryOptions));

                        controller.Find(false, discoverySink, discoveryOptions);
                        discoverySink.Finished.WaitOne();

                        var testCasesDiscovered = discoverySink.TestCases.Count;
                        var filteredTestCases   = discoverySink.TestCases.Where(Filters.Filter).ToList();
                        var testCasesToRun      = filteredTestCases.Count;

                        reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryFinished(assembly, discoveryOptions, testCasesDiscovered, testCasesToRun));

                        // Run the filtered tests
                        if (testCasesToRun == 0)
                        {
                            completionMessages.TryAdd(Path.GetFileName(assembly.AssemblyFilename), new ExecutionSummary());
                        }
                        else
                        {
                            if (SerializeTestCases)
                            {
                                filteredTestCases = filteredTestCases.Select(controller.Serialize).Select(controller.Deserialize).ToList();
                            }

                            IExecutionSink resultsSink = new DelegatingExecutionSummarySink(reporterMessageHandler, () => cancel, (path, summary) => completionMessages.TryAdd(path, summary));
                            if (assemblyElement != null)
                            {
                                resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                            }
                            if (longRunningSeconds > 0)
                            {
                                resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), diagnosticMessageSink);
                            }
                            if (FailSkips)
                            {
                                resultsSink = new DelegatingFailSkipSink(resultsSink);
                            }

                            reporterMessageHandler.OnMessage(new TestAssemblyExecutionStarting(assembly, executionOptions));

                            controller.RunTests(filteredTestCases, resultsSink, executionOptions);
                            resultsSink.Finished.WaitOne();

                            reporterMessageHandler.OnMessage(new TestAssemblyExecutionFinished(assembly, executionOptions, resultsSink.ExecutionSummary));

                            if (resultsSink.ExecutionSummary.Failed != 0)
                            {
                                ExitCode = 1;
                            }
                        }
                    }
            }
            catch (Exception ex)
            {
                var e = ex;

                while (e != null)
                {
                    Log.LogError("{0}: {1}", e.GetType().FullName, e.Message);

                    foreach (var stackLine in e.StackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        Log.LogError(stackLine);
                    }

                    e = e.InnerException;
                }

                ExitCode = -1;
            }

            return(assemblyElement);
        }
Exemplo n.º 7
0
        protected virtual XElement ExecuteAssembly(XunitProjectAssembly assembly)
        {
            if (cancel)
                return null;

            var assemblyElement = NeedsXml ? new XElement("assembly") : null;

            try
            {
                // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner
                assembly.Configuration.PreEnumerateTheories = false;
                assembly.Configuration.DiagnosticMessages |= DiagnosticMessages;

                if (appDomains.HasValue)
                    assembly.Configuration.AppDomain = appDomains.GetValueOrDefault() ? AppDomainSupport.Required : AppDomainSupport.Denied;

                // Setup discovery and execution options with command-line overrides
                var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration);
                var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration);
                if (maxThreadCount.HasValue && maxThreadCount.Value > -1)
                    executionOptions.SetMaxParallelThreads(maxThreadCount);
                if (parallelizeTestCollections.HasValue)
                    executionOptions.SetDisableParallelization(!parallelizeTestCollections);

                var assemblyDisplayName = Path.GetFileNameWithoutExtension(assembly.AssemblyFilename);
                var diagnosticMessageSink = new DiagnosticMessageSink(Log, assemblyDisplayName, assembly.Configuration.DiagnosticMessagesOrDefault);
                var appDomainSupport = assembly.Configuration.AppDomainOrDefault;
                var shadowCopy = assembly.Configuration.ShadowCopyOrDefault;
                var longRunningSeconds = assembly.Configuration.LongRunningTestSecondsOrDefault;

                using (var controller = new XunitFrontController(appDomainSupport, assembly.AssemblyFilename, assembly.ConfigFilename, shadowCopy, diagnosticMessageSink: diagnosticMessageSink))
                using (var discoverySink = new TestDiscoverySink(() => cancel))
                {
                    // Discover & filter the tests
                    reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryStarting(assembly, controller.CanUseAppDomains && appDomainSupport != AppDomainSupport.Denied, shadowCopy, discoveryOptions));

                    controller.Find(false, discoverySink, discoveryOptions);
                    discoverySink.Finished.WaitOne();

                    var testCasesDiscovered = discoverySink.TestCases.Count;
                    var filteredTestCases = discoverySink.TestCases.Where(Filters.Filter).ToList();
                    var testCasesToRun = filteredTestCases.Count;

                    reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryFinished(assembly, discoveryOptions, testCasesDiscovered, testCasesToRun));

                    // Run the filtered tests
                    if (testCasesToRun == 0)
                        completionMessages.TryAdd(Path.GetFileName(assembly.AssemblyFilename), new ExecutionSummary());
                    else
                    {
                        if (SerializeTestCases)
                            filteredTestCases = filteredTestCases.Select(controller.Serialize).Select(controller.Deserialize).ToList();

                        IExecutionSink resultsSink = new DelegatingExecutionSummarySink(reporterMessageHandler, () => cancel, (path, summary) => completionMessages.TryAdd(path, summary));
                        if (assemblyElement != null)
                            resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                        if (longRunningSeconds > 0)
                            resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), diagnosticMessageSink);
                        if (FailSkips)
                            resultsSink = new DelegatingFailSkipSink(resultsSink);

                        reporterMessageHandler.OnMessage(new TestAssemblyExecutionStarting(assembly, executionOptions));

                        controller.RunTests(filteredTestCases, resultsSink, executionOptions);
                        resultsSink.Finished.WaitOne();

                        reporterMessageHandler.OnMessage(new TestAssemblyExecutionFinished(assembly, executionOptions, resultsSink.ExecutionSummary));

                        if (resultsSink.ExecutionSummary.Failed != 0)
                            ExitCode = 1;
                    }
                }
            }
            catch (Exception ex)
            {
                var e = ex;

                while (e != null)
                {
                    Log.LogError("{0}: {1}", e.GetType().FullName, e.Message);

                    foreach (var stackLine in e.StackTrace.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
                        Log.LogError(stackLine);

                    e = e.InnerException;
                }

                ExitCode = -1;
            }

            return assemblyElement;
        }
Exemplo n.º 8
0
    public static int Main(string[] args)
    {
        string host = null;
        int    port = 0;

        // First argument is the connection string
        if (args [0].StartsWith("tcp:"))
        {
            var parts = args [0].Split(':');
            if (parts.Length != 3)
            {
                throw new Exception();
            }
            host = parts [1];
            port = Int32.Parse(parts [2]);
            args = args.Skip(1).ToArray();
        }

        // Make sure the TLS subsystem including the DependencyInjector is initialized.
        // This would normally happen on system startup in
        // `xamarin-macios/src/ObjcRuntime/Runtime.cs`.
        MonoTlsProviderFactory.Initialize();

#if XUNIT_RUNNER
        var writer           = new TcpWriter(host, port);
        var assemblyFileName = args[0];
        var configuration    = new TestAssemblyConfiguration()
        {
            ShadowCopy = false
        };
        var discoveryOptions = TestFrameworkOptions.ForDiscovery(configuration);
        var discoverySink    = new TestDiscoverySink();
        var diagnosticSink   = new DiagnosticTextWriterMessageSink(writer);
        var testOptions      = TestFrameworkOptions.ForExecution(configuration);
        var testSink         = new TestMessageSink();
        var controller       = new XunitFrontController(AppDomainSupport.Denied, assemblyFileName, configFileName: null, shadowCopy: false, diagnosticMessageSink: diagnosticSink);

        writer.WriteLine($"Discovering tests for {assemblyFileName}");
        controller.Find(includeSourceInformation: false, discoverySink, discoveryOptions);
        discoverySink.Finished.WaitOne();
        writer.WriteLine($"Discovery finished.");

        var summarySink        = new DelegatingExecutionSummarySink(testSink, () => false, (completed, summary) => { writer.WriteLine($"Tests run: {summary.Total}, Errors: 0, Failures: {summary.Failed}, Skipped: {summary.Skipped}{Environment.NewLine}Time: {TimeSpan.FromSeconds ((double)summary.Time).TotalSeconds}s"); });
        var resultsXmlAssembly = new XElement("assembly");
        var resultsSink        = new DelegatingXmlCreationSink(summarySink, resultsXmlAssembly);

        testSink.Execution.TestPassedEvent  += args => { writer.WriteLine($"[PASS] {args.Message.Test.DisplayName}"); Interop.mono_sdks_ui_increment_testcase_result(0); };
        testSink.Execution.TestSkippedEvent += args => { writer.WriteLine($"[SKIP] {args.Message.Test.DisplayName}"); Interop.mono_sdks_ui_increment_testcase_result(1); };
        testSink.Execution.TestFailedEvent  += args => { writer.WriteLine($"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{ExceptionUtility.CombineMessages (args.Message)}{Environment.NewLine}{ExceptionUtility.CombineStackTraces (args.Message)}"); Interop.mono_sdks_ui_increment_testcase_result(2); };

        testSink.Execution.TestAssemblyStartingEvent += args => { writer.WriteLine($"Running tests for {args.Message.TestAssembly.Assembly}"); };
        testSink.Execution.TestAssemblyFinishedEvent += args => { writer.WriteLine($"Finished {args.Message.TestAssembly.Assembly}{Environment.NewLine}"); };

        controller.RunTests(discoverySink.TestCases, resultsSink, testOptions);
        resultsSink.Finished.WaitOne();

        writer.WriteLine($"STARTRESULTXML");
        var resultsXml = new XElement("assemblies");
        resultsXml.Add(resultsXmlAssembly);
        resultsXml.Save(writer.RawStream);
        writer.WriteLine();
        writer.WriteLine($"ENDRESULTXML");

        var failed = resultsSink.ExecutionSummary.Failed > 0 || resultsSink.ExecutionSummary.Errors > 0;
        return(failed ? 1 : 0);
#else
        MonoSdksTextUI runner;
        TcpWriter      writer     = null;
        string         resultsXml = null;

        if (host != null)
        {
            Console.WriteLine($"Connecting to harness at {host}:{port}.");
            resultsXml = Path.GetTempFileName();
            args       = args.Concat(new string[] { "-format:xunit", $"-result:{resultsXml}" }).ToArray();
            writer     = new TcpWriter(host, port);
            runner     = new MonoSdksTextUI(writer);
        }
        else
        {
            runner = new MonoSdksTextUI();
        }

        runner.Execute(args);

        if (resultsXml != null)
        {
            writer.WriteLine($"STARTRESULTXML");
            using (var resultsXmlStream = File.OpenRead(resultsXml)) resultsXmlStream.CopyTo(writer.RawStream);
            writer.WriteLine();
            writer.WriteLine($"ENDRESULTXML");
        }

        return(runner.Failure ? 1 : 0);
#endif
    }
Exemplo n.º 9
0
        public int Run(string assemblyFileName, bool printXml, XunitFilters filters)
        {
            var configuration = new TestAssemblyConfiguration()
            {
                ShadowCopy = false, ParallelizeAssembly = false, ParallelizeTestCollections = false, MaxParallelThreads = 1, PreEnumerateTheories = false
            };
            var discoveryOptions = TestFrameworkOptions.ForDiscovery(configuration);
            var discoverySink    = new TestDiscoverySink();
            var diagnosticSink   = new ConsoleDiagnosticMessageSink();
            var testOptions      = TestFrameworkOptions.ForExecution(configuration);
            var testSink         = new TestMessageSink();
            var controller       = new Xunit2(AppDomainSupport.Denied, new NullSourceInformationProvider(), assemblyFileName, configFileName: null, shadowCopy: false, shadowCopyFolder: null, diagnosticMessageSink: diagnosticSink, verifyTestAssemblyExists: false);

            discoveryOptions.SetSynchronousMessageReporting(true);
            testOptions.SetSynchronousMessageReporting(true);

            Console.WriteLine($"Discovering tests for {assemblyFileName}");
            var assembly     = Assembly.LoadFrom(assemblyFileName);
            var assemblyInfo = new global::Xunit.Sdk.ReflectionAssemblyInfo(assembly);
            var discoverer   = new ThreadlessXunitDiscoverer(assemblyInfo, new NullSourceInformationProvider(), discoverySink);

            discoverer.FindWithoutThreads(includeSourceInformation: false, discoverySink, discoveryOptions);
            discoverySink.Finished.WaitOne();
            var testCasesToRun = discoverySink.TestCases.Where(filters.Filter).ToList();

            Console.WriteLine($"Discovery finished.");

            var summarySink        = new DelegatingExecutionSummarySink(testSink, () => false, (completed, summary) => { Console.WriteLine($"Tests run: {summary.Total}, Errors: 0, Failures: {summary.Failed}, Skipped: {summary.Skipped}. Time: {TimeSpan.FromSeconds((double)summary.Time).TotalSeconds}s"); });
            var resultsXmlAssembly = new XElement("assembly");
            var resultsSink        = new DelegatingXmlCreationSink(summarySink, resultsXmlAssembly);

            testSink.Execution.TestPassedEvent  += args => { Console.WriteLine($"[PASS] {args.Message.Test.DisplayName}"); };
            testSink.Execution.TestSkippedEvent += args => { Console.WriteLine($"[SKIP] {args.Message.Test.DisplayName}"); };
            testSink.Execution.TestFailedEvent  += args => { Console.WriteLine($"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{ExceptionUtility.CombineMessages(args.Message)}{Environment.NewLine}{ExceptionUtility.CombineStackTraces(args.Message)}"); };

            testSink.Execution.TestAssemblyStartingEvent += args => { Console.WriteLine($"Running tests for {args.Message.TestAssembly.Assembly}"); };
            testSink.Execution.TestAssemblyFinishedEvent += args => { Console.WriteLine($"Finished {args.Message.TestAssembly.Assembly}{Environment.NewLine}"); };

            controller.RunTests(testCasesToRun, resultsSink, testOptions);
            var threadpoolPump = typeof(ThreadPool).GetMethod("PumpThreadPool", BindingFlags.NonPublic | BindingFlags.Static);

            if (threadpoolPump != null)
            {
                while (!resultsSink.Finished.WaitOne(0))
                {
                    threadpoolPump.Invoke(this, null);
                }
            }
            else
            {
                resultsSink.Finished.WaitOne();
            }

            if (printXml)
            {
                Console.WriteLine($"STARTRESULTXML");
                var resultsXml = new XElement("assemblies");
                resultsXml.Add(resultsXmlAssembly);
                resultsXml.Save(Console.OpenStandardOutput());
                Console.WriteLine();
                Console.WriteLine($"ENDRESULTXML");
            }

            var failed = resultsSink.ExecutionSummary.Failed > 0 || resultsSink.ExecutionSummary.Errors > 0;

            return(failed ? 1 : 0);
        }
Exemplo n.º 10
0
    public static int Main(string[] args)
    {
        var asm = typeof(SingleFileTestRunner).Assembly;

        Console.WriteLine("Running assembly:" + asm.FullName);

        var diagnosticSink = new ConsoleDiagnosticMessageSink();
        var testsFinished  = new TaskCompletionSource();
        var testSink       = new TestMessageSink();
        var summarySink    = new DelegatingExecutionSummarySink(testSink,
                                                                () => false,
                                                                (completed, summary) => Console.WriteLine($"Tests run: {summary.Total}, Errors: {summary.Errors}, Failures: {summary.Failed}, Skipped: {summary.Skipped}. Time: {TimeSpan.FromSeconds((double)summary.Time).TotalSeconds}s"));
        var resultsXmlAssembly = new XElement("assembly");
        var resultsSink        = new DelegatingXmlCreationSink(summarySink, resultsXmlAssembly);

        testSink.Execution.TestSkippedEvent += args => { Console.WriteLine($"[SKIP] {args.Message.Test.DisplayName}"); };
        testSink.Execution.TestFailedEvent  += args => { Console.WriteLine($"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{Xunit.ExceptionUtility.CombineMessages(args.Message)}{Environment.NewLine}{Xunit.ExceptionUtility.CombineStackTraces(args.Message)}"); };

        testSink.Execution.TestAssemblyFinishedEvent += args =>
        {
            Console.WriteLine($"Finished {args.Message.TestAssembly.Assembly}{Environment.NewLine}");
            testsFinished.SetResult();
        };

        var assemblyConfig = new TestAssemblyConfiguration()
        {
            // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner
            PreEnumerateTheories = false,
        };

        var xunitTestFx = new SingleFileTestRunner(diagnosticSink);
        var asmInfo     = Reflector.Wrap(asm);
        var asmName     = asm.GetName();

        var discoverySink = new TestDiscoverySink();
        var discoverer    = xunitTestFx.CreateDiscoverer(asmInfo);

        discoverer.Find(false, discoverySink, TestFrameworkOptions.ForDiscovery(assemblyConfig));
        discoverySink.Finished.WaitOne();

        string       xmlResultFileName = null;
        XunitFilters filters           = new XunitFilters();
        // Quick hack wo much validation to get args that are passed (notrait, xml)
        Dictionary <string, List <string> > noTraits = new Dictionary <string, List <string> >();

        for (int i = 0; i < args.Length; i++)
        {
            if (args[i].Equals("-notrait", StringComparison.OrdinalIgnoreCase))
            {
                var traitKeyValue = args[i + 1].Split("=", StringSplitOptions.TrimEntries);
                if (!noTraits.TryGetValue(traitKeyValue[0], out List <string> values))
                {
                    noTraits.Add(traitKeyValue[0], values = new List <string>());
                }
                values.Add(traitKeyValue[1]);
            }
            if (args[i].Equals("-xml", StringComparison.OrdinalIgnoreCase))
            {
                xmlResultFileName = args[i + 1].Trim();
            }
        }

        foreach (KeyValuePair <string, List <string> > kvp in noTraits)
        {
            filters.ExcludedTraits.Add(kvp.Key, kvp.Value);
        }

        var filteredTestCases = discoverySink.TestCases.Where(filters.Filter).ToList();
        var executor          = xunitTestFx.CreateExecutor(asmName);

        executor.RunTests(filteredTestCases, resultsSink, TestFrameworkOptions.ForExecution(assemblyConfig));

        resultsSink.Finished.WaitOne();

        // Helix need to see results file in the drive to detect if the test has failed or not
        if (xmlResultFileName != null)
        {
            resultsXmlAssembly.Save(xmlResultFileName);
        }

        var failed = resultsSink.ExecutionSummary.Failed > 0 || resultsSink.ExecutionSummary.Errors > 0;

        return(failed ? 1 : 0);
    }
Exemplo n.º 11
0
        static XElement ExecuteAssembly(object consoleLock,
                                        XunitProjectAssembly assembly,
                                        bool serialize,
                                        bool needsXml,
                                        bool? parallelizeTestCollections,
                                        int? maxThreadCount,
                                        bool diagnosticMessages,
                                        bool noColor,
                                        bool noAppDomain,
                                        bool failSkips,
                                        XunitFilters filters)
        {
            if (cancel)
                return null;

            var assemblyElement = needsXml ? new XElement("assembly") : null;

            try
            {
                if (!ValidateFileExists(consoleLock, assembly.AssemblyFilename) || !ValidateFileExists(consoleLock, assembly.ConfigFilename))
                    return null;

                // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner
                assembly.Configuration.PreEnumerateTheories = false;
                assembly.Configuration.DiagnosticMessages |= diagnosticMessages;

                if (noAppDomain)
                    assembly.Configuration.AppDomain = AppDomainSupport.Denied;

                // Setup discovery and execution options with command-line overrides
                var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration);
                var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration);
                if (maxThreadCount.HasValue)
                    executionOptions.SetMaxParallelThreads(maxThreadCount);
                if (parallelizeTestCollections.HasValue)
                    executionOptions.SetDisableParallelization(!parallelizeTestCollections.GetValueOrDefault());

                var assemblyDisplayName = Path.GetFileNameWithoutExtension(assembly.AssemblyFilename);
                var diagnosticMessageSink = new DiagnosticMessageSink(consoleLock, assemblyDisplayName, assembly.Configuration.DiagnosticMessagesOrDefault, noColor);
                var appDomainSupport = assembly.Configuration.AppDomainOrDefault;
                var shadowCopy = assembly.Configuration.ShadowCopyOrDefault;
                var longRunningSeconds = assembly.Configuration.LongRunningTestSecondsOrDefault;

                using (var controller = new XunitFrontController(appDomainSupport, assembly.AssemblyFilename, assembly.ConfigFilename, shadowCopy, diagnosticMessageSink: diagnosticMessageSink))
                using (var discoverySink = new TestDiscoverySink(() => cancel))
                {
                    // Discover & filter the tests
                    reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryStarting(assembly, controller.CanUseAppDomains && appDomainSupport != AppDomainSupport.Denied, shadowCopy, discoveryOptions));

                    controller.Find(false, discoverySink, discoveryOptions);
                    discoverySink.Finished.WaitOne();

                    var testCasesDiscovered = discoverySink.TestCases.Count;
                    var filteredTestCases = discoverySink.TestCases.Where(filters.Filter).ToList();
                    var testCasesToRun = filteredTestCases.Count;

                    reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryFinished(assembly, discoveryOptions, testCasesDiscovered, testCasesToRun));

                    // Run the filtered tests
                    if (testCasesToRun == 0)
                        completionMessages.TryAdd(Path.GetFileName(assembly.AssemblyFilename), new ExecutionSummary());
                    else
                    {
                        if (serialize)
                            filteredTestCases = filteredTestCases.Select(controller.Serialize).Select(controller.Deserialize).ToList();

                        reporterMessageHandler.OnMessage(new TestAssemblyExecutionStarting(assembly, executionOptions));

                        IExecutionSink resultsSink = new DelegatingExecutionSummarySink(reporterMessageHandler, () => cancel, (path, summary) => completionMessages.TryAdd(path, summary));
                        if (assemblyElement != null)
                            resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                        if (longRunningSeconds > 0)
                            resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), diagnosticMessageSink);
                        if (failSkips)
                            resultsSink = new DelegatingFailSkipSink(resultsSink);

                        controller.RunTests(filteredTestCases, resultsSink, executionOptions);
                        resultsSink.Finished.WaitOne();

                        reporterMessageHandler.OnMessage(new TestAssemblyExecutionFinished(assembly, executionOptions, resultsSink.ExecutionSummary));
                    }
                }
            }
            catch (Exception ex)
            {
                failed = true;

                var e = ex;
                while (e != null)
                {
                    Console.WriteLine($"{e.GetType().FullName}: {e.Message}");
                    e = e.InnerException;
                }
            }

            return assemblyElement;
        }
Exemplo n.º 12
0
        async ValueTask <XElement?> ExecuteAssembly(
            XunitProjectAssembly assembly,
            bool needsXml,
            _IMessageSink reporterMessageHandler)
        {
            if (cancel)
            {
                return(null);
            }

            var assemblyElement = needsXml ? new XElement("assembly") : null;

            try
            {
                // Setup discovery and execution options with command-line overrides
                var discoveryOptions = _TestFrameworkOptions.ForDiscovery(assembly.Configuration);
                var executionOptions = _TestFrameworkOptions.ForExecution(assembly.Configuration);

                // The normal default is true here, but we want it to be false for us by default
                if (!assembly.Configuration.PreEnumerateTheories.HasValue)
                {
                    discoveryOptions.SetPreEnumerateTheories(false);
                }

                var assemblyDisplayName            = assembly.AssemblyDisplayName;
                var noColor                        = assembly.Project.Configuration.NoColorOrDefault;
                var diagnosticMessageSink          = ConsoleDiagnosticMessageSink.ForDiagnostics(consoleLock, assemblyDisplayName, assembly.Configuration.DiagnosticMessagesOrDefault, noColor);
                var internalDiagnosticsMessageSink = ConsoleDiagnosticMessageSink.ForInternalDiagnostics(consoleLock, assemblyDisplayName, assembly.Configuration.InternalDiagnosticMessagesOrDefault, noColor);
                var longRunningSeconds             = assembly.Configuration.LongRunningTestSecondsOrDefault;

                var assemblyInfo = new ReflectionAssemblyInfo(testAssembly);

                await using var disposalTracker = new DisposalTracker();
                var testFramework = ExtensibilityPointFactory.GetTestFramework(diagnosticMessageSink, assemblyInfo);
                disposalTracker.Add(testFramework);

                var discoverySink = new TestDiscoverySink(() => cancel);

                // Discover & filter the tests
                var testDiscoverer    = testFramework.GetDiscoverer(assemblyInfo);
                var discoveryStarting = new TestAssemblyDiscoveryStarting
                {
                    AppDomain        = AppDomainOption.NotAvailable,
                    Assembly         = assembly,
                    DiscoveryOptions = discoveryOptions,
                    ShadowCopy       = false
                };
                reporterMessageHandler.OnMessage(discoveryStarting);

                testDiscoverer.Find(discoverySink, discoveryOptions);
                discoverySink.Finished.WaitOne();

                var testCasesDiscovered = discoverySink.TestCases.Count;
                var filteredTestCases   = discoverySink.TestCases.Where(assembly.Configuration.Filters.Filter).ToList();
                var testCasesToRun      = filteredTestCases.Count;

                var discoveryFinished = new TestAssemblyDiscoveryFinished
                {
                    Assembly            = assembly,
                    DiscoveryOptions    = discoveryOptions,
                    TestCasesDiscovered = testCasesDiscovered,
                    TestCasesToRun      = testCasesToRun
                };
                reporterMessageHandler.OnMessage(discoveryFinished);

                // Run the filtered tests
                if (testCasesToRun == 0)
                {
                    testExecutionSummaries.Add(testDiscoverer.TestAssemblyUniqueID, new ExecutionSummary());
                }
                else
                {
                    var executionStarting = new TestAssemblyExecutionStarting
                    {
                        Assembly         = assembly,
                        ExecutionOptions = executionOptions
                    };
                    reporterMessageHandler.OnMessage(executionStarting);

                    IExecutionSink resultsSink = new DelegatingExecutionSummarySink(reporterMessageHandler, () => cancel);
                    if (assemblyElement != null)
                    {
                        resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                    }
                    if (longRunningSeconds > 0)
                    {
                        resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), diagnosticMessageSink);
                    }
                    if (assembly.Configuration.FailSkipsOrDefault)
                    {
                        resultsSink = new DelegatingFailSkipSink(resultsSink);
                    }

                    using (resultsSink)
                    {
                        var executor = testFramework.GetExecutor(assemblyInfo);

                        executor.RunTests(filteredTestCases, resultsSink, executionOptions);
                        resultsSink.Finished.WaitOne();

                        testExecutionSummaries.Add(testDiscoverer.TestAssemblyUniqueID, resultsSink.ExecutionSummary);

                        var executionFinished = new TestAssemblyExecutionFinished
                        {
                            Assembly         = assembly,
                            ExecutionOptions = executionOptions,
                            ExecutionSummary = resultsSink.ExecutionSummary
                        };
                        reporterMessageHandler.OnMessage(executionFinished);

                        if (assembly.Configuration.StopOnFailOrDefault && resultsSink.ExecutionSummary.Failed != 0)
                        {
                            Console.WriteLine("Canceling due to test failure...");
                            cancel = true;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                failed = true;

                var e = ex;
                while (e != null)
                {
                    Console.WriteLine($"{e.GetType().FullName}: {e.Message}");

                    if (assembly.Configuration.InternalDiagnosticMessagesOrDefault)
                    {
                        Console.WriteLine(e.StackTrace);
                    }

                    e = e.InnerException;
                }
            }

            return(assemblyElement);
        }
Exemplo n.º 13
0
        private void ExecuteTests(
            [NotNull] XunitProjectAssembly assembly,
            [NotNull] TestRunOptions options,
            [NotNull] XunitFilters filters,
            [NotNull] XunitFrontController controller,
            [NotNull] TestDiscoverySink discoverySink,
            [NotNull] ITestFrameworkExecutionOptions executionOptions,
            [CanBeNull] XElement assemblyElement,
            [NotNull] DiagnosticMessageSink diagnosticMessageSink)
        {
            var appDomainSupport = assembly.Configuration.AppDomainOrDefault;
            var shadowCopy       = assembly.Configuration.ShadowCopyOrDefault;
            var serialize        = options.Serialize;
            var failSkips        = options.FailSkips;
            var stopOnFail       = options.StopOnFail;

            var longRunningSeconds = assembly.Configuration.LongRunningTestSecondsOrDefault;

            var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration);

            // Discover & filter the tests
            _reporterMessageHandler.OnMessage(
                new TestAssemblyDiscoveryStarting(
                    assembly,
                    controller.CanUseAppDomains && appDomainSupport != AppDomainSupport.Denied,
                    shadowCopy,
                    discoveryOptions));

            controller.Find(false, discoverySink, discoveryOptions);
            discoverySink.Finished.WaitOne();

            var testCasesDiscovered = discoverySink.TestCases.Count;
            var filteredTestCases   = discoverySink.TestCases.Where(filters.Filter).ToList();
            var testCasesToRun      = filteredTestCases.Count;

            _reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryFinished(assembly, discoveryOptions, testCasesDiscovered, testCasesToRun));

            // Run the filtered tests
            if (testCasesToRun == 0)
            {
                _completionMessages.TryAdd(assembly.GetFileName().ThrowIfNull(), new ExecutionSummary());
            }
            else
            {
                if (serialize)
                {
                    filteredTestCases = filteredTestCases.Select(controller.Serialize).Select(controller.Deserialize).ToList();
                }

                _reporterMessageHandler.OnMessage(new TestAssemblyExecutionStarting(assembly, executionOptions));

                IExecutionSink resultsSink = new DelegatingExecutionSummarySink(
                    _reporterMessageHandler,
                    () => _cancel,
                    (path, summary) => _completionMessages.TryAdd(path, summary));
                if (assemblyElement != null)
                {
                    resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                }

                if (longRunningSeconds > 0)
                {
                    resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), diagnosticMessageSink);
                }

                if (failSkips)
                {
                    resultsSink = new DelegatingFailSkipSink(resultsSink);
                }

                controller.RunTests(filteredTestCases, resultsSink, executionOptions);
                resultsSink.Finished.WaitOne();

                _reporterMessageHandler.OnMessage(new TestAssemblyExecutionFinished(assembly, executionOptions, resultsSink.ExecutionSummary));

                if (!stopOnFail || resultsSink.ExecutionSummary.Failed == 0)
                {
                    return;
                }

                Console.WriteLine("Canceling due to test failure...");
                _cancel = true;
            }
        }
Exemplo n.º 14
0
        public bool Run(string assemblyFileName, IEnumerable <string> excludedTraits)
        {
            WebAssembly.Runtime.InvokeJS($"if (document) document.body.innerHTML = ''");

            Log("Starting tests...");

            var filters = new XunitFilters();

            foreach (var trait in excludedTraits ?? Array.Empty <string>())
            {
                ParseEqualSeparatedArgument(filters.ExcludedTraits, trait);
            }

            var configuration = new TestAssemblyConfiguration
            {
                ShadowCopy                 = false,
                ParallelizeAssembly        = false,
                ParallelizeTestCollections = false,
                MaxParallelThreads         = 1,
                PreEnumerateTheories       = false
            };
            var discoveryOptions = TestFrameworkOptions.ForDiscovery(configuration);
            var discoverySink    = new TestDiscoverySink();
            var diagnosticSink   = new ConsoleDiagnosticMessageSink();
            var testOptions      = TestFrameworkOptions.ForExecution(configuration);
            var testSink         = new TestMessageSink();
            var controller       = new Xunit2(
                AppDomainSupport.Denied,
                new NullSourceInformationProvider(),
                assemblyFileName,
                configFileName: null,
                shadowCopy: false,
                shadowCopyFolder: null,
                diagnosticMessageSink: diagnosticSink,
                verifyTestAssemblyExists: false);

            discoveryOptions.SetSynchronousMessageReporting(true);
            testOptions.SetSynchronousMessageReporting(true);

            Log($"Discovering tests for {assemblyFileName}...");
            var assembly     = Assembly.LoadFrom(assemblyFileName);
            var assemblyInfo = new Xunit.Sdk.ReflectionAssemblyInfo(assembly);
            var discoverer   = new ThreadlessXunitDiscoverer(assemblyInfo, new NullSourceInformationProvider(), discoverySink);

            discoverer.FindWithoutThreads(includeSourceInformation: false, discoverySink, discoveryOptions);
            discoverySink.Finished.WaitOne();
            var testCasesToRun = discoverySink.TestCases.Where(filters.Filter).ToList();

            Log($"Discovery finished.");
            Log("");

            var summarySink = new DelegatingExecutionSummarySink(
                testSink,
                () => false,
                (completed, summary) => { Log($"Tests run: {summary.Total}, Errors: 0, Failures: {summary.Failed}, Skipped: {summary.Skipped}. Time: {TimeSpan.FromSeconds((double)summary.Time).TotalSeconds}s"); });

            var resultsXmlAssembly = new XElement("assembly");
            var resultsSink        = new DelegatingXmlCreationSink(summarySink, resultsXmlAssembly);

            testSink.Execution.TestPassedEvent  += args => { Log($"[PASS] {args.Message.Test.DisplayName}", color: "green"); };
            testSink.Execution.TestSkippedEvent += args => { Log($"[SKIP] {args.Message.Test.DisplayName}", color: "orange"); };
            testSink.Execution.TestFailedEvent  += args => { Log($"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{ExceptionUtility.CombineMessages(args.Message)}{Environment.NewLine}{ExceptionUtility.CombineStackTraces(args.Message)}", color: "red"); };

            testSink.Execution.TestAssemblyStartingEvent += args => { Log($"Running tests for {args.Message.TestAssembly.Assembly}"); };
            testSink.Execution.TestAssemblyFinishedEvent += args => { Log($"Finished {args.Message.TestAssembly.Assembly}{Environment.NewLine}"); };

            controller.RunTests(testCasesToRun, resultsSink, testOptions);
            resultsSink.Finished.WaitOne();

            var resultsXml = new XElement("assemblies");

            resultsXml.Add(resultsXmlAssembly);

            Console.WriteLine(resultsXml.ToString());

            Log("");
            Log("Test results (Base64 encoded):");
            var base64 = Convert.ToBase64String(Encoding.UTF8.GetBytes(resultsXml.ToString()));

            Log(base64, id: "results");

            return(resultsSink.ExecutionSummary.Failed > 0 || resultsSink.ExecutionSummary.Errors > 0);
        }
Exemplo n.º 15
0
        /// <summary>
        ///     <see cref="StarcounterXunitRunner.Start(string, string)"/> for description.
        /// </summary>
        /// <param name="typeName"></param>
        /// <param name="testReportName"></param>
        private void ExecuteTests(string typeName = null, string testReportName = null)
        {
            ExecutionSummary executionSummary = null;

            XunitProjectAssembly assembly = new XunitProjectAssembly
            {
                AssemblyFilename = assemblyLocation,
                ConfigFilename   = null
            };

            XElement assembliesElement = new XElement("assemblies");
            XElement assemblyElement   = new XElement("assembly");

            // Logger
            var                   verboserReporter       = new XunitReporters.VerboseReporter();
            IRunnerLogger         logger                 = new ConsoleRunnerLogger(useColors: true);
            IMessageSinkWithTypes reporterMessageHandler = MessageSinkWithTypesAdapter.Wrap(verboserReporter.CreateMessageHandler(logger));

            // Option setup
            ITestFrameworkDiscoveryOptions discoveryOptions = TestFrameworkOptions.ForDiscovery(null);
            ITestFrameworkExecutionOptions executionOptions = TestFrameworkOptions.ForExecution(null);

            executionOptions.SetSynchronousMessageReporting(true);
            executionOptions.SetDisableParallelization(DeveloperMode || !RunTestsInParallel);
            executionOptions.SetDiagnosticMessages(true);

            var assemblyDisplayName = Path.GetFileNameWithoutExtension(assembly.AssemblyFilename);
            var appDomainSupport    = assembly.Configuration.AppDomainOrDefault;
            var shadowCopy          = assembly.Configuration.ShadowCopyOrDefault;

            var  clockTime = Stopwatch.StartNew();
            bool cancel    = false;

            using (var controller = new XunitFrontController(
                       appDomainSupport: AppDomainSupport.Denied,
                       assemblyFileName: assembly.AssemblyFilename,
                       configFileName: null,
                       shadowCopy: shadowCopy,
                       shadowCopyFolder: null,
                       sourceInformationProvider: null,
                       diagnosticMessageSink: null))
                using (var discoverySink = new TestDiscoverySink(() => cancel))
                {
                    // Discover & filter the tests
                    reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryStarting(
                                                         assembly: assembly,
                                                         appDomain: controller.CanUseAppDomains && appDomainSupport != AppDomainSupport.Denied,
                                                         shadowCopy: shadowCopy,
                                                         discoveryOptions: discoveryOptions));

                    if (typeName != null)
                    {
                        controller.Find(typeName, false, discoverySink, discoveryOptions);
                    }
                    else
                    {
                        controller.Find(false, discoverySink, discoveryOptions);
                    }
                    discoverySink.Finished.WaitOne();

                    var testCasesDiscovered = discoverySink.TestCases.Count;
                    var filteredTestCases   = discoverySink.TestCases.Where(TestCaseFilter).ToList();
                    var testCasesToRun      = filteredTestCases.Count;

                    reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryFinished(assembly, discoveryOptions, testCasesDiscovered, testCasesToRun));

                    // Run the filtered tests
                    if (testCasesToRun == 0)
                    {
                        executionSummary = new ExecutionSummary();
                    }
                    else
                    {
                        reporterMessageHandler.OnMessage(new TestAssemblyExecutionStarting(assembly, executionOptions));

                        IExecutionSink resultsSink = new DelegatingExecutionSummarySink(reporterMessageHandler, () => cancel, (path, summary) => { executionSummary = summary; });
                        if (assemblyElement != null)
                        {
                            resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                        }

                        controller.RunTests(filteredTestCases, resultsSink, executionOptions);
                        resultsSink.Finished.WaitOne();

                        reporterMessageHandler.OnMessage(new TestAssemblyExecutionFinished(assembly, executionOptions, resultsSink.ExecutionSummary));
                        assembliesElement.Add(assemblyElement);
                    }
                }

            clockTime.Stop();

            assembliesElement.Add(new XAttribute("timestamp", DateTime.Now.ToString(CultureInfo.InvariantCulture)));

            if (executionSummary != null)
            {
                Console.WriteLine();

                KeyValuePair <string, ExecutionSummary> kvpExecutionSummary = new KeyValuePair <string, ExecutionSummary>(this.assebmlyName, executionSummary);

                reporterMessageHandler.OnMessage(new TestExecutionSummary(clockTime.Elapsed, new List <KeyValuePair <string, ExecutionSummary> > {
                    kvpExecutionSummary
                }));

                if (testReportName != null)
                {
                    // Create folder if it does not exist
                    FileInfo      fi        = new FileInfo(testReportName);
                    DirectoryInfo directory = fi.Directory;
                    if (!directory.Exists)
                    {
                        Directory.CreateDirectory(directory.FullName);
                    }

                    CreateXmlTestReport(assembliesElement, fi);
                    CreateHtmlTestReport(assembliesElement, fi);
                }
                Console.WriteLine();
                Console.WriteLine();
            }
        }
Exemplo n.º 16
0
        async ValueTask <XElement?> ExecuteAssembly(
            XunitProjectAssembly assembly,
            bool needsXml,
            _IMessageSink reporterMessageHandler)
        {
            if (cancel)
            {
                return(null);
            }

            var assemblyElement = needsXml ? new XElement("assembly") : null;

            try
            {
                var assemblyFileName = Guard.ArgumentNotNull("assembly.AssemblyFilename", assembly.AssemblyFilename);

                // Setup discovery and execution options with command-line overrides
                var discoveryOptions = _TestFrameworkOptions.ForDiscovery(assembly.Configuration);
                var executionOptions = _TestFrameworkOptions.ForExecution(assembly.Configuration);

                // The normal default is true here, but we want it to be false for us by default
                if (!assembly.Configuration.PreEnumerateTheories.HasValue)
                {
                    discoveryOptions.SetPreEnumerateTheories(false);
                }

                var assemblyDisplayName            = Path.GetFileNameWithoutExtension(assemblyFileName);
                var noColor                        = assembly.Project.Configuration.NoColorOrDefault;
                var diagnosticMessageSink          = ConsoleDiagnosticMessageSink.ForDiagnostics(consoleLock, assemblyDisplayName, assembly.Configuration.DiagnosticMessagesOrDefault, noColor);
                var internalDiagnosticsMessageSink = ConsoleDiagnosticMessageSink.ForInternalDiagnostics(consoleLock, assemblyDisplayName, assembly.Configuration.InternalDiagnosticMessagesOrDefault, noColor);
                var appDomainSupport               = assembly.Configuration.AppDomainOrDefault;
                var shadowCopy                     = assembly.Configuration.ShadowCopyOrDefault;
                var longRunningSeconds             = assembly.Configuration.LongRunningTestSecondsOrDefault;

                using var _ = AssemblyHelper.SubscribeResolveForAssembly(assemblyFileName, internalDiagnosticsMessageSink);
                await using var controller = XunitFrontController.ForDiscoveryAndExecution(assembly, diagnosticMessageSink: diagnosticMessageSink);

                var executionStarting = new TestAssemblyExecutionStarting
                {
                    Assembly         = assembly,
                    ExecutionOptions = executionOptions
                };
                reporterMessageHandler.OnMessage(executionStarting);

                IExecutionSink resultsSink = new DelegatingExecutionSummarySink(reporterMessageHandler, () => cancel, (summary, _) => completionMessages.TryAdd(controller.TestAssemblyUniqueID, summary));
                if (assemblyElement != null)
                {
                    resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                }
                if (longRunningSeconds > 0)
                {
                    resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), diagnosticMessageSink);
                }
                if (assembly.Configuration.FailSkipsOrDefault)
                {
                    resultsSink = new DelegatingFailSkipSink(resultsSink);
                }

                using (resultsSink)
                {
                    var settings = new FrontControllerFindAndRunSettings(discoveryOptions, executionOptions, assembly.Configuration.Filters);
                    controller.FindAndRun(resultsSink, settings);
                    resultsSink.Finished.WaitOne();

                    var executionFinished = new TestAssemblyExecutionFinished
                    {
                        Assembly         = assembly,
                        ExecutionOptions = executionOptions,
                        ExecutionSummary = resultsSink.ExecutionSummary
                    };
                    reporterMessageHandler.OnMessage(executionFinished);

                    if (assembly.Configuration.StopOnFailOrDefault && resultsSink.ExecutionSummary.Failed != 0)
                    {
                        Console.WriteLine("Canceling due to test failure...");
                        cancel = true;
                    }
                }
            }
            catch (Exception ex)
            {
                failed = true;

                var e = ex;
                while (e != null)
                {
                    Console.WriteLine($"{e.GetType().FullName}: {e.Message}");

                    if (assembly.Configuration.InternalDiagnosticMessagesOrDefault)
                    {
                        Console.WriteLine(e.StackTrace);
                    }

                    e = e.InnerException;
                }
            }

            return(assemblyElement);
        }
Exemplo n.º 17
0
        XElement ExecuteAssembly(object consoleLock,
                                 XunitProjectAssembly assembly,
                                 bool needsXml,
                                 bool?parallelizeTestCollections,
                                 int?maxThreadCount,
                                 bool diagnosticMessages,
                                 bool noColor,
                                 bool failSkips,
                                 bool stopOnFail,
                                 XunitFilters filters,
                                 bool internalDiagnosticMessages)
        {
            if (cancel)
            {
                return(null);
            }

            var assemblyElement = needsXml ? new XElement("assembly") : null;

            try
            {
                if (!ValidateFileExists(consoleLock, assembly.ConfigFilename))
                {
                    return(null);
                }

                // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner
                assembly.Configuration.PreEnumerateTheories        = false;
                assembly.Configuration.DiagnosticMessages         |= diagnosticMessages;
                assembly.Configuration.InternalDiagnosticMessages |= internalDiagnosticMessages;

                // Setup discovery and execution options with command-line overrides
                var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration);
                var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration);
                executionOptions.SetStopOnTestFail(stopOnFail);
                if (maxThreadCount.HasValue)
                {
                    executionOptions.SetMaxParallelThreads(maxThreadCount);
                }
                if (parallelizeTestCollections.HasValue)
                {
                    executionOptions.SetDisableParallelization(!parallelizeTestCollections.GetValueOrDefault());
                }

                var assemblyDisplayName            = Path.GetFileNameWithoutExtension(assembly.AssemblyFilename);
                var diagnosticMessageSink          = DiagnosticMessageSink.ForDiagnostics(consoleLock, assemblyDisplayName, diagnosticMessages, noColor);
                var internalDiagnosticsMessageSink = DiagnosticMessageSink.ForInternalDiagnostics(consoleLock, assemblyDisplayName, internalDiagnosticMessages, noColor);
                var longRunningSeconds             = assembly.Configuration.LongRunningTestSecondsOrDefault;

                using var testFramework = new XunitTestFramework(diagnosticMessageSink, assembly.ConfigFilename);
                var entryAssembly = Assembly.GetEntryAssembly();
                var assemblyInfo  = new ReflectionAssemblyInfo(entryAssembly);
                var discoverySink = new TestDiscoverySink(() => cancel);

                using (var testDiscoverer = testFramework.GetDiscoverer(assemblyInfo))
                {
                    // Discover & filter the tests
                    reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryStarting(assembly, appDomain: false, shadowCopy: false, discoveryOptions));

                    testDiscoverer.Find(includeSourceInformation: false, discoverySink, discoveryOptions);
                    discoverySink.Finished.WaitOne();
                }

                var testCasesDiscovered = discoverySink.TestCases.Count;
                var filteredTestCases   = discoverySink.TestCases.Where(filters.Filter).ToList();
                var testCasesToRun      = filteredTestCases.Count;

                reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryFinished(assembly, discoveryOptions, testCasesDiscovered, testCasesToRun));

                // Run the filtered tests
                if (testCasesToRun == 0)
                {
                    executionSummary = new ExecutionSummary();
                }
                else
                {
                    reporterMessageHandler.OnMessage(new TestAssemblyExecutionStarting(assembly, executionOptions));

                    IExecutionSink resultsSink = new DelegatingExecutionSummarySink(reporterMessageHandler, () => cancel);
                    if (assemblyElement != null)
                    {
                        resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                    }
                    if (longRunningSeconds > 0)
                    {
                        resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), MessageSinkWithTypesAdapter.Wrap(diagnosticMessageSink));
                    }
                    if (failSkips)
                    {
                        resultsSink = new DelegatingFailSkipSink(resultsSink);
                    }

                    using var executor = testFramework.GetExecutor(entryAssembly.GetName());
                    executor.RunTests(filteredTestCases, resultsSink, executionOptions);
                    resultsSink.Finished.WaitOne();

                    executionSummary = resultsSink.ExecutionSummary;

                    reporterMessageHandler.OnMessage(new TestAssemblyExecutionFinished(assembly, executionOptions, resultsSink.ExecutionSummary));
                    if (stopOnFail && resultsSink.ExecutionSummary.Failed != 0)
                    {
                        Console.WriteLine("Canceling due to test failure...");
                        cancel = true;
                    }
                }
            }
            catch (Exception ex)
            {
                failed = true;

                var e = ex;
                while (e != null)
                {
                    Console.WriteLine($"{e.GetType().FullName}: {e.Message}");

                    if (internalDiagnosticMessages)
                    {
                        Console.WriteLine(e.StackTrace);
                    }

                    e = e.InnerException;
                }
            }

            return(assemblyElement);
        }
Exemplo n.º 18
0
        public async Task <int> Run(string assemblyFileName, bool printXml, XunitFilters filters)
        {
            var configuration = new TestAssemblyConfiguration()
            {
                ShadowCopy = false, ParallelizeAssembly = false, ParallelizeTestCollections = false, MaxParallelThreads = 1, PreEnumerateTheories = false
            };
            var discoveryOptions = TestFrameworkOptions.ForDiscovery(configuration);
            var discoverySink    = new TestDiscoverySink();
            var diagnosticSink   = new ConsoleDiagnosticMessageSink();
            var testOptions      = TestFrameworkOptions.ForExecution(configuration);
            var testSink         = new TestMessageSink();
            var controller       = new Xunit2(AppDomainSupport.Denied, new NullSourceInformationProvider(), assemblyFileName, configFileName: null, shadowCopy: false, shadowCopyFolder: null, diagnosticMessageSink: diagnosticSink, verifyTestAssemblyExists: false);

            discoveryOptions.SetSynchronousMessageReporting(true);
            testOptions.SetSynchronousMessageReporting(true);

            Console.WriteLine($"Discovering: {assemblyFileName} (method display = {discoveryOptions.GetMethodDisplayOrDefault()}, method display options = {discoveryOptions.GetMethodDisplayOptionsOrDefault()})");
            var assembly     = Assembly.LoadFrom(assemblyFileName);
            var assemblyInfo = new global::Xunit.Sdk.ReflectionAssemblyInfo(assembly);
            var discoverer   = new ThreadlessXunitDiscoverer(assemblyInfo, new NullSourceInformationProvider(), discoverySink);

            discoverer.FindWithoutThreads(includeSourceInformation: false, discoverySink, discoveryOptions);
            discoverySink.Finished.WaitOne();
            var testCasesToRun = discoverySink.TestCases.Where(filters.Filter).ToList();

            Console.WriteLine($"Discovered:  {assemblyFileName} (found {testCasesToRun.Count} of {discoverySink.TestCases.Count} test cases)");

            var summarySink        = new DelegatingExecutionSummarySink(testSink, () => false, (completed, summary) => { Console.WriteLine($"{Environment.NewLine}=== TEST EXECUTION SUMMARY ==={Environment.NewLine}Total: {summary.Total}, Errors: 0, Failed: {summary.Failed}, Skipped: {summary.Skipped}, Time: {TimeSpan.FromSeconds((double)summary.Time).TotalSeconds}s{Environment.NewLine}"); });
            var resultsXmlAssembly = new XElement("assembly");
            var resultsSink        = new DelegatingXmlCreationSink(summarySink, resultsXmlAssembly);

            if (Environment.GetEnvironmentVariable("XHARNESS_LOG_TEST_START") != null)
            {
                testSink.Execution.TestStartingEvent += args => { Console.WriteLine($"[STRT] {args.Message.Test.DisplayName}"); };
            }
            testSink.Execution.TestPassedEvent  += args => { Console.WriteLine($"[PASS] {args.Message.Test.DisplayName}"); };
            testSink.Execution.TestSkippedEvent += args => { Console.WriteLine($"[SKIP] {args.Message.Test.DisplayName}"); };
            testSink.Execution.TestFailedEvent  += args => { Console.WriteLine($"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{ExceptionUtility.CombineMessages(args.Message)}{Environment.NewLine}{ExceptionUtility.CombineStackTraces(args.Message)}"); };

            testSink.Execution.TestAssemblyStartingEvent += args => { Console.WriteLine($"Starting:    {assemblyFileName}"); };
            testSink.Execution.TestAssemblyFinishedEvent += args => { Console.WriteLine($"Finished:    {assemblyFileName}"); };

            controller.RunTests(testCasesToRun, resultsSink, testOptions);

            while (!resultsSink.Finished.WaitOne(0))
            {
                await Task.Delay(1);
            }

            if (printXml)
            {
                Console.WriteLine($"STARTRESULTXML");
                var resultsXml = new XElement("assemblies");
                resultsXml.Add(resultsXmlAssembly);
                resultsXml.Save(Console.OpenStandardOutput());
                Console.WriteLine();
                Console.WriteLine($"ENDRESULTXML");
            }

            var failed = resultsSink.ExecutionSummary.Failed > 0 || resultsSink.ExecutionSummary.Errors > 0;

            return(failed ? 1 : 0);
        }
Exemplo n.º 19
0
    public static int Main(string[] args)
    {
        var    arguments = new Stack <string> ();
        string host      = null;
        int    port      = 0;
        bool   closeAfterTestRun;
        bool   failed;

        for (var i = args.Length - 1; i >= 0; i--)
        {
            arguments.Push(args[i]);
        }

        // First argument is the connection string if we're driven by harness.exe, otherwise we're driven by UITests
        if (arguments.Count > 0 && arguments.Peek().StartsWith("tcp:", StringComparison.Ordinal))
        {
            var parts = arguments.Pop().Split(':');
            if (parts.Length != 3)
            {
                throw new Exception();
            }
            host = parts [1];
            port = Int32.Parse(parts [2]);
            closeAfterTestRun = true;
        }
        else
        {
            closeAfterTestRun = false;
        }

        // Make sure the TLS subsystem including the DependencyInjector is initialized.
        // This would normally happen on system startup in
        // `xamarin-macios/src/ObjcRuntime/Runtime.cs`.
        MonoTlsProviderFactory.Initialize();

        // some tests assert having a SynchronizationContext for MONOTOUCH, provide a default one
        SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

#if XUNIT_RUNNER
        var writer           = new TcpWriter(host, port);
        var assemblyFileName = arguments.Pop();
        var filters          = XunitArgumentsParser.ParseArgumentsToFilter(arguments);
        var configuration    = new TestAssemblyConfiguration()
        {
            ShadowCopy = false
        };
        var discoveryOptions = TestFrameworkOptions.ForDiscovery(configuration);
        var discoverySink    = new TestDiscoverySink();
        var diagnosticSink   = new DiagnosticTextWriterMessageSink(writer);
        var testOptions      = TestFrameworkOptions.ForExecution(configuration);
        var testSink         = new TestMessageSink();
        var controller       = new XunitFrontController(AppDomainSupport.Denied, assemblyFileName, configFileName: null, shadowCopy: false, diagnosticMessageSink: diagnosticSink);

        Interop.mono_sdks_ui_set_test_summary_message($"Running {assemblyFileName}...");

        writer.WriteLine($"Discovering tests for {assemblyFileName}");
        controller.Find(includeSourceInformation: false, discoverySink, discoveryOptions);
        discoverySink.Finished.WaitOne();
        var testCasesToRun = discoverySink.TestCases.Where(filters.Filter).ToList();
        writer.WriteLine($"Discovery finished.");

        var summarySink        = new DelegatingExecutionSummarySink(testSink, () => false, (completed, summary) => { writer.WriteLine($"Tests run: {summary.Total}, Errors: 0, Failures: {summary.Failed}, Skipped: {summary.Skipped}{Environment.NewLine}Time: {TimeSpan.FromSeconds ((double)summary.Time).TotalSeconds}s"); });
        var resultsXmlAssembly = new XElement("assembly");
        var resultsSink        = new DelegatingXmlCreationSink(summarySink, resultsXmlAssembly);

        testSink.Execution.TestPassedEvent  += args => { writer.WriteLine($"[PASS] {args.Message.Test.DisplayName}"); Interop.mono_sdks_ui_increment_testcase_result(0); };
        testSink.Execution.TestSkippedEvent += args => { writer.WriteLine($"[SKIP] {args.Message.Test.DisplayName}"); Interop.mono_sdks_ui_increment_testcase_result(1); };
        testSink.Execution.TestFailedEvent  += args => { writer.WriteLine($"[FAIL] {args.Message.Test.DisplayName}{Environment.NewLine}{ExceptionUtility.CombineMessages (args.Message)}{Environment.NewLine}{ExceptionUtility.CombineStackTraces (args.Message)}"); Interop.mono_sdks_ui_increment_testcase_result(2); };

        testSink.Execution.TestAssemblyStartingEvent += args => { writer.WriteLine($"Running tests for {args.Message.TestAssembly.Assembly}"); };
        testSink.Execution.TestAssemblyFinishedEvent += args => { writer.WriteLine($"Finished {args.Message.TestAssembly.Assembly}{Environment.NewLine}"); };

        controller.RunTests(testCasesToRun, resultsSink, testOptions);
        resultsSink.Finished.WaitOne();

        var resultsXml = new XElement("assemblies");
        resultsXml.Add(resultsXmlAssembly);
        resultsXml.Save(resultsXmlPath);

        if (host != null)
        {
            writer.WriteLine($"STARTRESULTXML");
            resultsXml.Save(((TcpWriter)writer).RawStream);
            writer.WriteLine();
            writer.WriteLine($"ENDRESULTXML");
        }

        failed = resultsSink.ExecutionSummary.Failed > 0 || resultsSink.ExecutionSummary.Errors > 0;
#else
        MonoSdksTextUI runner;
        TextWriter     writer           = null;
        string         resultsXmlPath   = Path.GetTempFileName();
        string         assemblyFileName = arguments.Peek();

        if (File.Exists("nunit-excludes.txt"))
        {
            var excludes = File.ReadAllLines("nunit-excludes.txt");
            arguments.Push("-exclude:" + String.Join(",", excludes));
        }

        arguments.Push("-labels");
        arguments.Push("-format:xunit");
        arguments.Push($"-result:{resultsXmlPath}");

        if (host != null)
        {
            Console.WriteLine($"Connecting to harness at {host}:{port}.");
            writer = new TcpWriter(host, port);
        }
        else
        {
            writer = ConsoleWriter.Out;
        }

        Interop.mono_sdks_ui_set_test_summary_message($"Running {assemblyFileName}...");

        runner = new MonoSdksTextUI(writer);
        runner.Execute(arguments.ToArray());

        if (host != null)
        {
            writer.WriteLine($"STARTRESULTXML");
            using (var resultsXmlStream = File.OpenRead(resultsXmlPath)) resultsXmlStream.CopyTo(((TcpWriter)writer).RawStream);
            writer.WriteLine();
            writer.WriteLine($"ENDRESULTXML");
        }

        failed = runner.Failure;
#endif

        Interop.mono_sdks_ui_set_test_summary_message($"Summary: {(failed ? "Failed" : "Succeeded")} for {assemblyFileName}.");

        if (!closeAfterTestRun)
        {
            Thread.Sleep(Int32.MaxValue);
        }

        return(failed ? 1 : 0);
    }
Exemplo n.º 20
0
        static XElement ExecuteAssembly(object consoleLock,
                                        XunitProjectAssembly assembly,
                                        bool serialize,
                                        bool needsXml,
                                        bool?parallelizeTestCollections,
                                        int?maxThreadCount,
                                        bool diagnosticMessages,
                                        bool noColor,
                                        bool noAppDomain,
                                        bool failSkips,
                                        XunitFilters filters,
                                        bool internalDiagnosticMessages)
        {
            if (cancel)
            {
                return(null);
            }

            var assemblyElement = needsXml ? new XElement("assembly") : null;

            try
            {
                if (!ValidateFileExists(consoleLock, assembly.AssemblyFilename) || !ValidateFileExists(consoleLock, assembly.ConfigFilename))
                {
                    return(null);
                }

                // Turn off pre-enumeration of theories, since there is no theory selection UI in this runner
                assembly.Configuration.PreEnumerateTheories        = false;
                assembly.Configuration.DiagnosticMessages         |= diagnosticMessages;
                assembly.Configuration.InternalDiagnosticMessages |= internalDiagnosticMessages;

                if (noAppDomain)
                {
                    assembly.Configuration.AppDomain = AppDomainSupport.Denied;
                }

                // Setup discovery and execution options with command-line overrides
                var discoveryOptions = TestFrameworkOptions.ForDiscovery(assembly.Configuration);
                var executionOptions = TestFrameworkOptions.ForExecution(assembly.Configuration);
                if (maxThreadCount.HasValue)
                {
                    executionOptions.SetMaxParallelThreads(maxThreadCount);
                }
                if (parallelizeTestCollections.HasValue)
                {
                    executionOptions.SetDisableParallelization(!parallelizeTestCollections.GetValueOrDefault());
                }

                var assemblyDisplayName   = Path.GetFileNameWithoutExtension(assembly.AssemblyFilename);
                var diagnosticMessageSink = new DiagnosticMessageSink(consoleLock, assemblyDisplayName, assembly.Configuration.DiagnosticMessagesOrDefault, noColor);
                var appDomainSupport      = assembly.Configuration.AppDomainOrDefault;
                var shadowCopy            = assembly.Configuration.ShadowCopyOrDefault;
                var longRunningSeconds    = assembly.Configuration.LongRunningTestSecondsOrDefault;

                using (var controller = new XunitFrontController(appDomainSupport, assembly.AssemblyFilename, assembly.ConfigFilename, shadowCopy, diagnosticMessageSink: diagnosticMessageSink))
                    using (var discoverySink = new TestDiscoverySink(() => cancel))
                    {
                        // Discover & filter the tests
                        reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryStarting(assembly, controller.CanUseAppDomains && appDomainSupport != AppDomainSupport.Denied, shadowCopy, discoveryOptions));

                        controller.Find(false, discoverySink, discoveryOptions);
                        discoverySink.Finished.WaitOne();

                        var testCasesDiscovered = discoverySink.TestCases.Count;
                        var filteredTestCases   = discoverySink.TestCases.Where(filters.Filter).ToList();
                        var testCasesToRun      = filteredTestCases.Count;

                        reporterMessageHandler.OnMessage(new TestAssemblyDiscoveryFinished(assembly, discoveryOptions, testCasesDiscovered, testCasesToRun));

                        // Run the filtered tests
                        if (testCasesToRun == 0)
                        {
                            completionMessages.TryAdd(Path.GetFileName(assembly.AssemblyFilename), new ExecutionSummary());
                        }
                        else
                        {
                            if (serialize)
                            {
                                filteredTestCases = filteredTestCases.Select(controller.Serialize).Select(controller.Deserialize).ToList();
                            }

                            reporterMessageHandler.OnMessage(new TestAssemblyExecutionStarting(assembly, executionOptions));

                            IExecutionSink resultsSink = new DelegatingExecutionSummarySink(reporterMessageHandler, () => cancel, (path, summary) => completionMessages.TryAdd(path, summary));
                            if (assemblyElement != null)
                            {
                                resultsSink = new DelegatingXmlCreationSink(resultsSink, assemblyElement);
                            }
                            if (longRunningSeconds > 0)
                            {
                                resultsSink = new DelegatingLongRunningTestDetectionSink(resultsSink, TimeSpan.FromSeconds(longRunningSeconds), diagnosticMessageSink);
                            }
                            if (failSkips)
                            {
                                resultsSink = new DelegatingFailSkipSink(resultsSink);
                            }

                            controller.RunTests(filteredTestCases, resultsSink, executionOptions);
                            resultsSink.Finished.WaitOne();

                            reporterMessageHandler.OnMessage(new TestAssemblyExecutionFinished(assembly, executionOptions, resultsSink.ExecutionSummary));
                        }
                    }
            }
            catch (Exception ex)
            {
                failed = true;

                var e = ex;
                while (e != null)
                {
                    Console.WriteLine($"{e.GetType().FullName}: {e.Message}");
                    e = e.InnerException;
                }
            }

            return(assemblyElement);
        }
 public XmlCreationSinkDecorator(IMessageSinkWithTypes innerSink)
 {
     assemblyElement      = new XElement("assembly");
     executionSummarySink = new DelegatingExecutionSummarySink(innerSink);
     xmlCreationSink      = new DelegatingXmlCreationSink(executionSummarySink, assemblyElement);
 }