CoverageData

Namespace: chutzpah
We found 10 examples in language CSharp for this search. You will see 39 fragments of code.

        public static CoverageData GetInstance()
        {
            lock (_locker)
            {
                if (_instance == null)
                {
                    _instance = new CoverageData();
                }
            }
            return _instance;
        }

        public static void SetInstance(CoverageData data)
        {
            lock (_locker)
            {
                _instance = data;
            }
        }

        // To communicate across proxy instance
        public void SetStaticInstance(CoverageData data)
        {
            SetInstance(data);
        }


        /// <summary>
        /// Merges two coverage objects together, mutating the current one
        /// </summary>
        /// <param name="coverageData"></param>
        public void Merge(CoverageData coverageData)
        {
            foreach (var pair in coverageData)
            {
                if (this.ContainsKey(pair.Key))
                {
                    this[pair.Key].Merge(pair.Value);
                }
                else
                {
                    this[pair.Key] = new CoverageFileData(pair.Value);
                }
            }

            // Since there could be multiple chutzpah.json files each setting their own success percentage
            // we take the minimum of all of them. In the future, it would be nice to e able to apply each percentage to the 
            // test files they came from.
            if (!SuccessPercentage.HasValue)
            {
                SuccessPercentage = coverageData.SuccessPercentage;
            }
            else if (coverageData.SuccessPercentage.HasValue)
            {
                SuccessPercentage = Math.Min(SuccessPercentage.Value, coverageData.SuccessPercentage.Value);
            }
        }

        private double CalculateCoveragePercentage()
        {
            if (LineExecutionCounts == null || LineExecutionCounts.Length == 0)
            {
                return 0;
            }

            var pair = GetCoveredCount();

            return pair.Item1 / pair.Item2;
        }

        public Tuple<double, double> GetCoveredCount()
        {
            if (coveredCount != null) return coveredCount;

            if (LineExecutionCounts == null || LineExecutionCounts.Length == 0)
            {
                coveredCount = Tuple.Create(0.0, 0.0);
                return coveredCount;
            }


            double sum = 0;
            double count = 0;

            for (var i = 1; i < LineExecutionCounts.Length; i++)
            {
                if (LineExecutionCounts[i].HasValue)
                {
                    count++;

                    if (LineExecutionCounts[i] > 0)
                    {
                        sum++;
                    }
                }
            }

            coveredCount = Tuple.Create(sum, count);
            return coveredCount;
        }

        public void Merge(CoverageFileData coverageFileData)
        {
            // If LineExecutionCounts is null then this class has not be merged with any coverage object yet so just take its values
            if (LineExecutionCounts == null)
            {
                LineExecutionCounts = coverageFileData.LineExecutionCounts;
                SourceLines = coverageFileData.SourceLines;
            }
            else
            {
                for (var i = 0; i < LineExecutionCounts.Length; i++)
                {
                    if (!coverageFileData.LineExecutionCounts[i].HasValue)
                    {
                        // No data to merge
                        continue;
                    }
                    else if (!this.LineExecutionCounts[i].HasValue)
                    {
                        // Just take the given data
                        this.LineExecutionCounts[i] = coverageFileData.LineExecutionCounts[i];
                    }
                    else
                    {
                        // If we both have values sum them up
                        this.LineExecutionCounts[i] += coverageFileData.LineExecutionCounts[i];
                    }
                }
            }

            // After update LineExecutionCounts we need recalculate CoveragePercentage
            this.coveragePercentage = null;
            this.coveredCount = null;
        }

// OpenCppCoverage is an open source code coverage for C++.
// Copyright (C) 2014 OpenCppCoverage
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.

using System.Collections.Generic;

namespace OpenCppCoverage.VSPackage.CoverageData
{
    class CoverageResult
    {
        public CoverageResult(
            ProtoBuff.CoverageData coverageData, 
            IEnumerable<ProtoBuff.ModuleCoverage> modules)
        {
            this.CoverageData = coverageData;
            this.Modules = modules;
        }

        public ProtoBuff.CoverageData CoverageData { get; }
        public IEnumerable<ProtoBuff.ModuleCoverage> Modules { get; }
    }
}


        /// <summary>
        /// Merges two coverage objects together, mutating the current one
        /// </summary>
        /// <param name="coverageData"></param>
        public void Merge(CoverageData coverageData)
        {
            foreach (var pair in coverageData)
            {
                if (this.ContainsKey(pair.Key))
                {
                    this[pair.Key].Merge(pair.Value);
                }
                else
                {
                    this[pair.Key] = new CoverageFileData(pair.Value);
                }
            }

            // Since there could be multiple chutzpah.json files each setting their own success percentage
            // we take the minimum of all of them. In the future, it would be nice to e able to apply each percentage to the 
            // test files they came from.
            if (!SuccessPercentage.HasValue)
            {
                SuccessPercentage = coverageData.SuccessPercentage;
            }
            else if (coverageData.SuccessPercentage.HasValue)
            {
                SuccessPercentage = Math.Min(SuccessPercentage.Value, coverageData.SuccessPercentage.Value);
            }
        }

        private double CalculateCoveragePercentage()
        {
            if (LineExecutionCounts == null || LineExecutionCounts.Length == 0)
            {
                return 0;
            }

            var pair = GetCoveredCount();

            return pair.Item1 / pair.Item2;
        }

        public Tuple<double, double> GetCoveredCount()
        {
            if (coveredCount != null) return coveredCount;

            if (LineExecutionCounts == null || LineExecutionCounts.Length == 0)
            {
                coveredCount = Tuple.Create(0.0, 0.0);
                return coveredCount;
            }


            double sum = 0;
            double count = 0;

            for (var i = 1; i < LineExecutionCounts.Length; i++)
            {
                if (LineExecutionCounts[i].HasValue)
                {
                    count++;

                    if (LineExecutionCounts[i] > 0)
                    {
                        sum++;
                    }
                }
            }

            coveredCount = Tuple.Create(sum, count);
            return coveredCount;
        }

        public void Merge(CoverageFileData coverageFileData)
        {
            // If LineExecutionCounts is null then this class has not be merged with any coverage object yet so just take its values
            if (LineExecutionCounts == null)
            {
                LineExecutionCounts = coverageFileData.LineExecutionCounts;
                SourceLines = coverageFileData.SourceLines;
            }
            else
            {
                for (var i = 0; i < LineExecutionCounts.Length; i++)
                {
                    if (!coverageFileData.LineExecutionCounts[i].HasValue)
                    {
                        // No data to merge
                        continue;
                    }
                    else if (!this.LineExecutionCounts[i].HasValue)
                    {
                        // Just take the given data
                        this.LineExecutionCounts[i] = coverageFileData.LineExecutionCounts[i];
                    }
                    else
                    {
                        // If we both have values sum them up
                        this.LineExecutionCounts[i] += coverageFileData.LineExecutionCounts[i];
                    }
                }
            }

            // After update LineExecutionCounts we need recalculate CoveragePercentage
            this.coveragePercentage = null;
            this.coveredCount = null;
        }


        public Dictionary<String, Dictionary<int, long>> RunTestsForCoverage(byte[] testAssemblyBytes)
        {
            // Can't pass CoverageData directly because it goes over the proxy and gets messed up during deserialization? Weird...
            //CoverageData.GetInstance().LineCounts = lineCounts;
            //CoverageData.GetInstance().LineLocatorIDs = lineLocatorIDs;
            //CoverageData.GetInstance().reverseLineLocatorIDs = reverseLineLocatorIDs;

            Assembly assembly = AppDomain.CurrentDomain.Load(testAssemblyBytes);
            {
                foreach (Module module in assembly.Modules)
                {
                    var classes = module.FindTypes(
                        (type, filterCriteria) => type.GetCustomAttributes().Any(a => a.GetType().Name.Contains("TestClass")), null);
                    foreach (
                        Type clazz in classes
                        )
                    {
                        var testMethods = clazz.GetRuntimeMethods().Where(isTestMethod).ToArray();
                        RunTestsForClassWithCoverage(testMethods, clazz, true);
                    }
                }
            }

            return _lineCountsByTests;
        }

        public bool RunTests(byte[] testAssemblyBytes, List<string> tests)
        {
            Assembly assembly = AppDomain.CurrentDomain.Load(testAssemblyBytes);
            var pairs = tests.Select((test) => test.Split(':'));
            Dictionary<Type, List<MethodInfo>> testClassesToMethods = new Dictionary<Type, List<MethodInfo>>();
            foreach (String[] pair in pairs)
            {
                Type clazz = assembly.GetType(pair[0]);
                MethodInfo testCase = clazz.GetMethod(pair[1]);
                if (testCase == null)
                {
                    throw new NullReferenceException(pair[1] + " could not be found in "+pair[0]);
                }
                if (!testClassesToMethods.ContainsKey(clazz))
                {
                    testClassesToMethods[clazz] = new List<MethodInfo>();
                }
                testClassesToMethods[clazz].Add(testCase);
            }
            bool allPassed = true;
            foreach (var pair in testClassesToMethods)
            {
                allPassed &= RunTestsForClassWithCoverage(pair.Value.ToArray(), pair.Key, false);
                if (!allPassed) break;
            }
            return allPassed;
        }

        private bool RunTestsForClassWithCoverage(MethodInfo[] testMethods, Type clazz, bool forCoverage)
        {
            bool allPassed = true;
            var classInit = clazz.GetRuntimeMethods().Where(isClassInitialize).ToArray();
            var testInit = clazz.GetRuntimeMethods().Where(isTestInitialize).ToArray();
            var testCleanup = clazz.GetRuntimeMethods().Where(isTestCleanup).ToArray();
            var classCleanup = clazz.GetRuntimeMethods().Where(isClassCleanup).ToArray();
            // FIXME: refactor out into next step of pipeline
            // run test case
            var emptyargs = new object[] {};
            // FIXME: pass in a ClassContext and TestContext
            var nullArgs = new object[] {  null};
            var testInstance = clazz.GetConstructors().First().Invoke(emptyargs);
            foreach (var methodInfo in classInit)
            {
                try
                {
                    methodInfo.Invoke(testInstance, nullArgs);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.InnerException);
                    return false;
                }
            }

            Debug.WriteLine("Running "+ testMethods.Length+" tests.");
            foreach (var testMethod in testMethods)
            {
                foreach (var methodInfo in testInit)
                {
                    try
                    {
                        methodInfo.Invoke(testInstance, emptyargs);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.InnerException);
                        if (e.InnerException is TargetInvocationException
                            || e.InnerException is MissingSatelliteAssemblyException)
                        {
                            throw e.InnerException;
                        }
                        else
                        {
                            return false;
                        }
                    }
                }
                // test MUST pass for mutation
                Debug.WriteLine("Running test " + testMethod.Name);
                bool passed = false;
                try
                {
                    testMethod.Invoke(testInstance, emptyargs);
                    passed = true;
                }
                catch (TargetInvocationException e)
                {
                    Attribute expectsException = testMethod.GetCustomAttributes()
                        .SingleOrDefault(a => a.GetType().Name.Contains("ExpectedException"));
                    IList<CustomAttributeData> data = testMethod.GetCustomAttributesData();
                    if (expectsException != null)
                    {
                        foreach (CustomAttributeData d in data)
                        {
                            if (d.AttributeType == expectsException.GetType() &&
                                d.ConstructorArguments[0].Value.Equals(e.InnerException.GetType()))
                            {
                                Debug.WriteLine("Test " + testMethod.Name + " received expected exception");
                                passed = true;
                                break;
                            }
                        }
                    }
                    else
                    {
                        Debug.WriteLine("Test " + testMethod.Name + " failed, reason: " + e.InnerException);
                    }

                }

                Debug.WriteLine(testMethod.Name + " "+ (passed? "passed":"failed"));

                allPassed &= passed;

                foreach (var methodInfo in testCleanup)
                {
                    methodInfo.Invoke(testInstance, emptyargs);
                }

                // collect coverage
                if (forCoverage)
                {
                    // only keep if tests passed
                    if (allPassed)
                    {
                        // TODO: make test object to hold test, result, coverage data instead of massive dictionary
                        String testID = clazz.FullName + ":" + testMethod.Name;
                        _lineCountsByTests[testID] = coverageData.LineCounts;
                    }
                    else
                    {
                        Debug.WriteLine(
                            "WARNING: not all tests passed during code coverage. Skipping failing tests...");
                        allPassed = true;
                    }
                    // reset coverage
                    coverageData.ResetCoverageCounters();
                }
                else if(!allPassed) // FIXME: don't put this logic here
                {
                    return false;
                }
            }
            return true;
        }

        public void SetupCoverage(Dictionary<string, int> lineLocatorIDs, Dictionary<int, string> reverseLineLocatorIDs)
        {
            coverageData = CoverageData.GetInstance();
            coverageData.LineLocatorIDs = lineLocatorIDs;
            coverageData.reverseLineLocatorIDs = reverseLineLocatorIDs;
        }

        private bool isTestMethod(MethodInfo method)
        {
            return method.GetCustomAttributes().Any(a => a.GetType().Name.Contains("TestMethod"));
        }

        private bool isTestInitialize(MethodInfo method)
        {
            return method.GetCustomAttributes().Any(a => a.GetType().Name.Contains("TestInitialize"));
        }


        //---------------------------------------------------------------------
        [TestMethod]
        public void Deserialize()
        {
            using (var stream = new MemoryStream())
            {
                WriteCoverageData(stream);

                var deserializer = new CoverageDataDeserializer();
                var coverageResult = deserializer.Deserialize(stream);

                Assert.AreEqual(coverageName, coverageResult.CoverageData.Name);
                Assert.AreEqual(exitCode, coverageResult.CoverageData.ExitCode);

                var module = coverageResult.Modules.First();
                Assert.AreEqual(modulePath, module.Path);

                var file = module.FilesList.First();
                Assert.AreEqual(filePath, file.Path);

                var line = file.LinesList.First();
                Assert.AreEqual(hasBeenExecuted, line.HasBeenExecuted);
                Assert.AreEqual(lineNumber, line.LineNumber);
            }
        }

        //---------------------------------------------------------------------
        static void WriteCoverageData(Stream stream)
        {
            var outputStream = CodedOutputStream.CreateInstance(stream);

            outputStream.WriteRawVarint32(CoverageDataDeserializer.FileTypeId);
            WriteCoverageDataOnly(outputStream);
            WriteModule(outputStream);

            outputStream.Flush();
            stream.Position = 0;
        }

        //---------------------------------------------------------------------
        static void WriteCoverageDataOnly(CodedOutputStream outputStream)
        {
            var coverageData = CoverageData.CreateBuilder();

            coverageData.SetName(coverageName);
            coverageData.SetModuleCount(moduleCount);
            coverageData.SetExitCode(exitCode);
            WriteMessage(outputStream, coverageData.Build());
        }

        //---------------------------------------------------------------------
        static void WriteModule(CodedOutputStream outputStream)
        {
            var line = LineCoverage.CreateBuilder();
            line.SetHasBeenExecuted(hasBeenExecuted);
            line.SetLineNumber(lineNumber);

            var file = FileCoverage.CreateBuilder();
            file.SetPath(filePath);
            file.AddLines(line);

            var module = ModuleCoverage.CreateBuilder();
            module.SetPath(modulePath);
            module.AddFiles(file);

            WriteMessage(outputStream, module.Build());
        }

        //---------------------------------------------------------------------
        static void WriteMessage(CodedOutputStream outputStream, IMessage message)
        {
            outputStream.WriteRawVarint32((uint)message.SerializedSize);
            message.WriteTo(outputStream);
        }


        public void Generate(FileCoverageData coverageData, DateTime timetamp)
        {
            GenerateSummaryPage(coverageData, timetamp);
            GenerateFilePages(coverageData, timetamp);
        }

        void GenerateSummaryPage(FileCoverageData coverageData, DateTime timetamp)
        {
            
        }

        void GenerateFilePages(FileCoverageData coverageData, DateTime timetamp)
        {
            
        }


        [TestMethod]
        [ExpectedException(typeof(ArgumentNullException))]
        public void ParseCoverageFileNullInputTest()
        {
            this.codeCoverageReader.ParseCoverageFile(null, null);
        }

        [TestMethod]
        [ExpectedException(typeof(ArgumentException))]
        public void ParseCoverageFileEmptyInputTest()
        {
            this.codeCoverageReader.ParseCoverageFile(new XDocument(), null);
        }

        [TestMethod]
        public void ParseCoverageFileWithOneSourceAndOneLineCovered()
        {
            var coverageFileContents = XDocument.Parse(File.ReadAllText(RelatePathToParseCoverageFileWithOneSourceAndOneLineCovered));
            var nameSpace = coverageFileContents.Root.Name.Namespace;
            var coverageData = this.codeCoverageReader.ParseCoverageFile(coverageFileContents, nameSpace);
            var expectedSourceFileNames = new List<string> { @"C:\Users\shrer\Source\Repos\CodeCoverageToLcovConverter\CodeCoverageToLcovConverter\Class1.cs" };
            var expectedRanges = new List<Range> { new Range(8, 8 , true, 0), new Range(13, 13, false, 0), new Range(14, 14, false, 0) };
            AssertUtility(coverageData, expectedSourceFileNames, expectedRanges);
        }

        [TestMethod]
        public void ParseCoverageFileWithTwoSourcesAndOneMultipleLinesCovered()
        {
            var coverageFileContents = XDocument.Parse(File.ReadAllText(RelatePathToParseCoverageFileWithTwoSourcesAndOneMultipleLinesCovered));
            var nameSpace = coverageFileContents.Root.Name.Namespace;
            var coverageData = this.codeCoverageReader.ParseCoverageFile(coverageFileContents, nameSpace);
            var expectedSourceFileNames = new List<string> { @"C:\Users\shrer\Source\Repos\CodeCoverageToLcovConverter\CodeCoverageToLcovConverter\Class1.cs",
                @"C:\Users\shrer\Source\Repos\CodeCoverageToLcovConverter\CodeCoverageToLcovConverterTests\obj\Debug\netcoreapp2.0\CodeCoverageToLcovConverterTests.Program.cs",
                @"C:\Users\shrer\Source\Repos\CodeCoverageToLcovConverter\CodeCoverageToLcovConverterTests\UnitTest1.cs" };
            var expectedRanges = new List<Range> { new Range(8, 8, true, 0), new Range(13, 13, false, 0), new Range(4, 4, false, 1), new Range(4, 4, false, 1), new Range(11, 11, true, 2), new Range(12, 12, true, 2) };
            AssertUtility(coverageData, expectedSourceFileNames, expectedRanges);
        }

        [TestMethod]
        public void ParseCoverageFileWithTwoSourcesAndOneMultipleLinesCoveredSomePartiallyCovered()
        {
            var coverageFileContents = XDocument.Parse(File.ReadAllText(RelatePathToParseCoverageFileWithTwoSourcesAndOneMultipleLinesCoveredSomePartiallyCovered));
            var nameSpace = coverageFileContents.Root.Name.Namespace;
            var coverageData = this.codeCoverageReader.ParseCoverageFile(coverageFileContents, nameSpace);
            var expectedSourceFileNames = new List<string> { @"C:\Users\shrer\Source\Repos\CodeCoverageToLcovConverter\CodeCoverageToLcovConverter\Class1.cs",
                @"C:\Users\shrer\Source\Repos\CodeCoverageToLcovConverter\CodeCoverageToLcovConverterTests\obj\Debug\netcoreapp2.0\CodeCoverageToLcovConverterTests.Program.cs",
                @"C:\Users\shrer\Source\Repos\CodeCoverageToLcovConverter\CodeCoverageToLcovConverterTests\UnitTest1.cs" };
            var expectedRanges = new List<Range> { new Range(8, 8, true, 0), new Range(13, 13, false, 0), new Range(4, 4, false, 1), new Range(4, 4, false, 1), new Range(11, 11, true, 2), new Range(12, 12, true, 2) };
            AssertUtility(coverageData, expectedSourceFileNames, expectedRanges);
        }

        private void AssertUtility(CodeCoverageDataModel coverageData, List<string> expectedSourceFileNames, List<Range> expectedRanges)
        {
            CollectionAssert.AreEqual(coverageData.Sources, expectedSourceFileNames);
            CollectionAssert.AreEqual(coverageData.Ranges, expectedRanges, Comparer<Range>.Create((Range x, Range y) => { return x.StartLine == y.StartLine && x.EndLine == y.EndLine && x.SourceFileId == y.SourceFileId && x.Covered == y.Covered ? 0 : -1; }));
        }

		public override string ToString()
		{
			return line;
		}


        public void Add(TestResult result)
        {
            result.ThrowIfNull("result");

            ResultLines.Add(result);
        }

        public void Add(NCrunchCoverageData coverageData)
        {
            coverageData.ThrowIfNull("coverageData");

            NCrunchCoverageData.Add(coverageData);
        }

        public void AddRange(IEnumerable<TestResult> results)
        {
            results.ThrowIfNull("results");

            foreach (var result in results)
                Add(result);
        }

        public void AddRange(IEnumerable<NCrunchCoverageData> coverageData)
        {
            coverageData.ThrowIfNull("coverageData");

            foreach (var cd in coverageData)
                Add(cd);
        }

        /// <summary>
        /// Summarises this instance. Call this when you have finished adding lines.
        /// </summary>
        public void Summarise()
        {
            SummariseOutcomeNames();
            SummariseByAssembly();
            SummariseByClass();
        }

        /// <summary>
        /// Summarise all the outcome names contained within a set of test results.
        /// The names are guaranteed to include "Passed" and "Failed" as the first
        /// two items and any other outcomes will be sorted by name.
        /// </summary>
        void SummariseOutcomeNames()
        {
            outcomeNames = new List<string>();
            outcomeNames.Add(KnownOutcomes.Passed);
            outcomeNames.Add(KnownOutcomes.Failed);

            var remainingOutcomes = new List<string>();
            foreach (var result in ResultLines)
            {
                string oc = result.Outcome;
                if (oc != KnownOutcomes.Passed && oc != KnownOutcomes.Failed && !remainingOutcomes.Contains(oc))
                    remainingOutcomes.Add(oc);
            }

            remainingOutcomes.Sort();
            outcomeNames.AddRange(remainingOutcomes);
        }

Chutzpah.Models.CoverageData : IDictionary

Constructors :

public CoverageData()
public CoverageData(Double successPercentage = )

Methods :

public Nullable<Double> get_SuccessPercentage()
public Void set_SuccessPercentage(Nullable<Double> value = )
public Double get_CoveragePercentage()
public Void Merge(CoverageData coverageData = )
public IEqualityComparer<String> get_Comparer()
public Int32 get_Count()
public KeyCollection<String, CoverageFileData> get_Keys()
public ValueCollection<String, CoverageFileData> get_Values()
public CoverageFileData get_Item(String key = )
public Void set_Item(String key = , CoverageFileData value = )
public Void Add(String key = , CoverageFileData value = )
public Void Clear()
public Boolean ContainsKey(String key = )
public Boolean ContainsValue(CoverageFileData value = )
public Enumerator<String, CoverageFileData> GetEnumerator()
public Void GetObjectData(SerializationInfo info = , StreamingContext context = )
public Void OnDeserialization(Object sender = )
public Boolean Remove(String key = )
public Boolean Remove(String key = , CoverageFileData& value = )
public Boolean TryGetValue(String key = , CoverageFileData& value = )
public Boolean TryAdd(String key = , CoverageFileData value = )
public Int32 EnsureCapacity(Int32 capacity = )
public Void TrimExcess()
public Void TrimExcess(Int32 capacity = )
public Type GetType()
public String ToString()
public Boolean Equals(Object obj = )
public Int32 GetHashCode()