<commit_before>﻿using Microsoft.Win32;
using OpenCover.UI.Helpers;
using OpenCover.UI.Model;
using OpenCover.UI.Model.Test;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Linq;

namespace OpenCover.UI.Processors
{
    internal class XUnitTestExecutor : TestExecutor
    {
        private string _runListFile;
        private string _xUnitPath;

        /// <summary>
        /// Initializes a new instance of the <see cref="XUnitTestExecutor"/> class.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="selectedTests">The selected tests.</param>
        internal XUnitTestExecutor(OpenCoverUIPackage package, Tuple<IEnumerable<String>, IEnumerable<String>, IEnumerable<String>> selectedTests)
            : base(package, selectedTests)
        {
            SetXUnitPath();

            _executionStatus = new Dictionary<string, IEnumerable<TestResult>>();
        }

        /// <summary>
        /// Sets the OpenCover commandline arguments.
        /// </summary>
        protected override void SetOpenCoverCommandlineArguments()
        {
            var fileFormat = DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss_ms");
            var dllPaths = BuildDLLPath();

            SetOpenCoverResultsFilePath();

            _testResultsFile = Path.Combine(_currentWorkingDirectory.FullName, String.Format("{0}.xml", fileFormat));
            _runListFile = Path.Combine(_currentWorkingDirectory.FullName, String.Format("{0}.txt", fileFormat));

            _commandLineArguments = String.Format(CommandlineStringFormat,
                                                    _xUnitPath,
                                                    String.Format("{0} -nologo -noshadow -xml {1}", dllPaths, _testResultsFile),
                                                    _openCoverResultsFile);            
        }

        /// <summary>
        /// Reads the test results file.
        /// </summary>
        protected override void ReadTestResults()
        {
            try
            {
                if (File.Exists(_testResultsFile))
                {
                    var testResultsFile = XDocument.Load(_testResultsFile);
                    
                    _executionStatus.Clear();

                    var rootAssemblies = testResultsFile.Elements("assemblies");
                    var assemblies = rootAssemblies.Elements().Where(e => e.Name == "assembly");

                    foreach (var assembly in assemblies)
                    {
                        var testCases = assembly.Elements("collection");
                        var testMethods = testCases.Elements("test").Select(tc => GetTestResult(tc, null));                        
                        _executionStatus.Add(assembly.Attribute("name").Value.ToLower(), testMethods);
                    }
                }
                else
                {
                    IDEHelper.WriteToOutputWindow("Test Results File does not exist: {0}", _testResultsFile);
                }
            }
            catch (Exception ex)
            {
                IDEHelper.WriteToOutputWindow(ex.Message);
                IDEHelper.WriteToOutputWindow(ex.StackTrace);
            }
        }

        /// <summary>
        /// Updates the test methods execution.
        /// </summary>
        internal override void UpdateTestMethodsExecution(IEnumerable<TestClass> tests)
        {
            var execution = _executionStatus.SelectMany(t => t.Value.Select(tm => new { dll = t.Key, result = tm }));

            var executedTests = tests.SelectMany(t => t.TestMethods)
                                        .Join(execution,
                                                t => new { d = t.Class.DLLPath.ToUpperInvariant(), n = t.FullyQualifiedName },
                                                t => new { d = t.dll.ToUpperInvariant(), n = t.result.MethodName },
                                                (testMethod, result) => new { TestMethod = testMethod, Result = result });

            foreach (var test in executedTests)
            {
                test.TestMethod.ExecutionResult = test.Result.result;
            }
        }


        /// <summary>
        /// Delete temporary files created.
        /// </summary>
        internal override void Cleanup()
        {
            base.Cleanup();

            if (File.Exists(_runListFile))
            {
                File.Delete(_runListFile);
            }
        }

        private IEnumerable<DirectoryInfo> ProgramFilesFolders()
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
            if (Environment.Is64BitOperatingSystem)
            {
                if (path.EndsWith(" (x86)"))
                {
                    yield return new DirectoryInfo(path.Replace(" (x86)", ""));
                }
                else
                {
                    yield return new DirectoryInfo(path + " (x86)");
                }
            }
            yield return new DirectoryInfo(path);
        }

        /// <summary>
        /// Sets the XUnit path.
        /// </summary>
        private void SetXUnitPath()
        {
            _xUnitPath = OpenCoverUISettings.Default.XUnitPath;
            if (!File.Exists(_xUnitPath))
            {
                var consoleName = "xunit.console.exe";<commit_msg>Corrected bug where test execution became disabled due to previous failed build.<commit_after>﻿using Microsoft.Win32;
using OpenCover.UI.Helpers;
using OpenCover.UI.Model;
using OpenCover.UI.Model.Test;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Xml.Linq;

namespace OpenCover.UI.Processors
{
    internal class XUnitTestExecutor : TestExecutor
    {
        //private string _runListFile;
        private string _xUnitPath;

        /// <summary>
        /// Initializes a new instance of the <see cref="XUnitTestExecutor"/> class.
        /// </summary>
        /// <param name="package">The package.</param>
        /// <param name="selectedTests">The selected tests.</param>
        internal XUnitTestExecutor(OpenCoverUIPackage package, Tuple<IEnumerable<String>, IEnumerable<String>, IEnumerable<String>> selectedTests)
            : base(package, selectedTests)
        {
            SetXUnitPath();

            _executionStatus = new Dictionary<string, IEnumerable<TestResult>>();
        }

        /// <summary>
        /// Sets the OpenCover commandline arguments.
        /// </summary>
        protected override void SetOpenCoverCommandlineArguments()
        {
            var fileFormat = DateTime.Now.ToString("yyyy_MM_dd_hh_mm_ss_ms");
            var dllPaths = BuildDLLPath();

            SetOpenCoverResultsFilePath();

            _testResultsFile = Path.Combine(_currentWorkingDirectory.FullName, String.Format("{0}.xml", fileFormat));            

            _commandLineArguments = String.Format(CommandlineStringFormat,
                                                    _xUnitPath,
                                                    String.Format("{0} -nologo -noshadow -xml {1}", dllPaths, _testResultsFile),
                                                    _openCoverResultsFile);            
        }

        /// <summary>
        /// Reads the test results file.
        /// </summary>
        protected override void ReadTestResults()
        {
            try
            {
                if (File.Exists(_testResultsFile))
                {
                    var testResultsFile = XDocument.Load(_testResultsFile);
                    
                    _executionStatus.Clear();

                    var rootAssemblies = testResultsFile.Elements("assemblies");
                    var assemblies = rootAssemblies.Elements().Where(e => e.Name == "assembly");

                    foreach (var assembly in assemblies)
                    {
                        var testCases = assembly.Elements("collection");
                        var testMethods = testCases.Elements("test").Select(tc => GetTestResult(tc, null));                        
                        _executionStatus.Add(assembly.Attribute("name").Value.ToLower(), testMethods);
                    }
                }
                else
                {
                    IDEHelper.WriteToOutputWindow("Test Results File does not exist: {0}", _testResultsFile);
                }
            }
            catch (Exception ex)
            {
                IDEHelper.WriteToOutputWindow(ex.Message);
                IDEHelper.WriteToOutputWindow(ex.StackTrace);
            }
        }

        /// <summary>
        /// Updates the test methods execution.
        /// </summary>
        internal override void UpdateTestMethodsExecution(IEnumerable<TestClass> tests)
        {
            var execution = _executionStatus.SelectMany(t => t.Value.Select(tm => new { dll = t.Key, result = tm }));

            var executedTests = tests.SelectMany(t => t.TestMethods)
                                        .Join(execution,
                                                t => new { d = t.Class.DLLPath.ToUpperInvariant(), n = t.FullyQualifiedName },
                                                t => new { d = t.dll.ToUpperInvariant(), n = t.result.MethodName },
                                                (testMethod, result) => new { TestMethod = testMethod, Result = result });

            foreach (var test in executedTests)
            {
                test.TestMethod.ExecutionResult = test.Result.result;
            }
        }


        /// <summary>
        /// Delete temporary files created.
        /// </summary>
        internal override void Cleanup()
        {
            base.Cleanup();            
        }

        private IEnumerable<DirectoryInfo> ProgramFilesFolders()
        {
            var path = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
            if (Environment.Is64BitOperatingSystem)
            {
                if (path.EndsWith(" (x86)"))
                {
                    yield return new DirectoryInfo(path.Replace(" (x86)", ""));
                }
                else
                {
                    yield return new DirectoryInfo(path + " (x86)");
                }
            }
            yield return new DirectoryInfo(path);
        }

        /// <summary>
        /// Sets the XUnit path.
        /// </summary>
        private void SetXUnitPath()
        {
            _xUnitPath = OpenCoverUISettings.Default.XUnitPath;
            if (!File.Exists(_xUnitPath))
            {
                var consoleName = "xunit.console.exe";
{'fraction_non_alphanumeric': 0.0995225853837679, 'fraction_numerical': 0.002662504590525156, 'mean_word_length': 1.475681818181818, 'pattern_counts': {'":': 0, '<': 53, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3390313', 'n_tokens_mistral': 2653, 'n_tokens_neox': 2498, 'n_words': 539}