Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.8 kB
0
Indexable
Never
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Xml.Linq;
using OpenCover.Framework;
using OpenCover.Framework.Models;
using OpenCover.Framework.Report;

public static class OpenCoverUtil
{
    public static string GetCoverageText(string targetAssembly, string outputDirectory)
    {
        var targetDir = Path.GetDirectoryName(targetAssembly);
        var targetFileName = Path.GetFileName(targetAssembly);
        var coverageFile = Path.Combine(outputDirectory, "coverage.xml");

        // Create OpenCover configuration
        var filter = "+[*]* -[xunit.*]*";
        var configuration = new OpenCoverConfiguration
        {
            Register = true,
            Target = targetFileName,
            TargetDir = targetDir,
            Filters = filter,
            Output = coverageFile,
            OldStyle = true,
            SkipAutoProps = true,
            SkipAutoPropsOnMethods = true
        };

        // Create OpenCover framework
        var framework = new OpenCoverFramework();
        var registerProfiler = true;
        var profilerKey = Guid.NewGuid().ToString();
        var result = framework.RegisterProfiler(registerProfiler, profilerKey);

        // Create target process
        var startInfo = new ProcessStartInfo
        {
            FileName = targetAssembly,
            WorkingDirectory = targetDir,
            UseShellExecute = false
        };
        var process = Process.Start(startInfo);

        // Wait for the target process to exit
        process.WaitForExit();

        // Generate OpenCover report
        var reportGenerator = new ReportGenerator();
        var coverageFiles = new List<string> { coverageFile };
        var reportTypes = new List<ReportTypes> { ReportTypes.Html };
        var outputDirectoryInfo = new DirectoryInfo(outputDirectory);
        var reportDirectories = new List<DirectoryInfo> { outputDirectoryInfo };
        reportGenerator.GenerateReport(coverageFiles, reportTypes, outputDirectoryInfo, reportDirectories);

        // Read coverage data
        var xmlDocument = XDocument.Load(coverageFile);
        var summary = xmlDocument.Root.Element("Summary");
        var coveredSequencePoints = summary.Attribute("numSequencePointsCovered").Value;
        var totalSequencePoints = summary.Attribute("numSequencePoints").Value;
        var coveredBranchPoints = summary.Attribute("numBranchPointsCovered").Value;
        var totalBranchPoints = summary.Attribute("numBranchPoints").Value;
        var coverageText = $"{targetFileName} coverage: {coveredSequencePoints}/{totalSequencePoints} sequence points, {coveredBranchPoints}/{totalBranchPoints} branch points";

        return coverageText;
    }
}