Exemplo n.º 1
0
        private void InstrumentSampleProject()
        {
            var tempPath = Path.Combine(Path.GetTempPath(), "SG.CodeCoverage");

            if (Directory.Exists(tempPath))
            {
                CleanDirectory(tempPath);
            }
            else
            {
                Directory.CreateDirectory(tempPath);
            }

            var oridgAssemblyFileName = typeof(SampleProjectForTest.PrimeCalculator).Assembly.Location;
            var origPdbFileName       = Path.ChangeExtension(oridgAssemblyFileName, "pdb");

            var assemblyFileName = Path.Combine(tempPath, Path.GetFileName(oridgAssemblyFileName));
            var mapFileName      = Path.Combine(tempPath, "map.json");

            File.Copy(oridgAssemblyFileName, assemblyFileName);
            File.Copy(origPdbFileName, Path.Combine(tempPath, Path.GetFileName(origPdbFileName)));

            Instrumenter instrumenter = new Instrumenter(new[] { assemblyFileName },
                                                         tempPath, mapFileName, PortNumber, new ConsoleLogger());

            instrumenter.Instrument();
        }
Exemplo n.º 2
0
        public void TestCoreLibInstrumentation()
        {
            // Attention: to run this test adjust the paths and copy the IL only version of corelib
            const string OriginalFilesDir = @"c:\s\tmp\Coverlet-CoreLib\Original\";
            const string TestFilesDir     = @"c:\s\tmp\Coverlet-CoreLib\Test\";

            Directory.CreateDirectory(TestFilesDir);

            string[] files = new[]
            {
                "System.Private.CoreLib.dll",
                "System.Private.CoreLib.pdb"
            };

            foreach (var file in files)
            {
                File.Copy(Path.Combine(OriginalFilesDir, file), Path.Combine(TestFilesDir, file), overwrite: true);
            }

            Instrumenter instrumenter = new Instrumenter(Path.Combine(TestFilesDir, files[0]), "_coverlet_instrumented", Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), false, _mockLogger.Object, _instrumentationHelper);

            Assert.True(instrumenter.CanInstrument());
            var result = instrumenter.Instrument();

            Assert.NotNull(result);
        }
Exemplo n.º 3
0
        public void PrepareModules()
        {
            string[] modules  = InstrumentationHelper.GetCoverableModules(_module, _includeDirectories);
            string[] excludes = InstrumentationHelper.GetExcludedFiles(_excludedSourceFiles);
            _excludeFilters = _excludeFilters?.Where(f => InstrumentationHelper.IsValidFilterExpression(f)).ToArray();
            _includeFilters = _includeFilters?.Where(f => InstrumentationHelper.IsValidFilterExpression(f)).ToArray();

            foreach (var module in modules)
            {
                if (InstrumentationHelper.IsModuleExcluded(module, _excludeFilters) ||
                    !InstrumentationHelper.IsModuleIncluded(module, _includeFilters))
                {
                    continue;
                }

                var instrumenter = new Instrumenter(module, _identifier, _excludeFilters, _includeFilters, excludes, _excludeAttributes);
                if (instrumenter.CanInstrument())
                {
                    InstrumentationHelper.BackupOriginalModule(module, _identifier);

                    // Guard code path and restore if instrumentation fails.
                    try
                    {
                        var result = instrumenter.Instrument();
                        _results.Add(result);
                    }
                    catch (Exception)
                    {
                        // TODO: With verbose logging we should note that instrumentation failed.
                        InstrumentationHelper.RestoreOriginalModule(module, _identifier);
                    }
                }
            }
        }
        public void InstrumentSampleProject()
        {
            if (Directory.Exists(OutputPath))
            {
                CleanDirectory(OutputPath);
            }
            else
            {
                Directory.CreateDirectory(OutputPath);
            }

            var oridgAssemblyFileName = typeof(PrimeCalculator).Assembly.Location;
            var origPdbFileName       = Path.ChangeExtension(oridgAssemblyFileName, "pdb");

            var assemblyFileName = Path.Combine(OutputPath, Path.GetFileName(oridgAssemblyFileName));

            File.Copy(oridgAssemblyFileName, assemblyFileName);
            File.Copy(origPdbFileName, Path.Combine(OutputPath, Path.GetFileName(origPdbFileName)));

            var options = new InstrumentationOptions(
                new[] { assemblyFileName },
                Array.Empty <string>(), OutputPath, PortNumber);
            Instrumenter instrumenter = new Instrumenter(options, _logger);

            instrumenter.BackupFolder = Path.Combine(OutputPath, "backup");
            Directory.CreateDirectory(instrumenter.BackupFolder);
            RecordingController      = instrumenter.Instrument();
            InstrumentedAssemblyPath = assemblyFileName;
        }
Exemplo n.º 5
0
        public void PrepareModules()
        {
            string[] modules  = InstrumentationHelper.GetCoverableModules(_module, _includeDirectories);
            string[] excludes = InstrumentationHelper.GetExcludedFiles(_excludedSourceFiles);
            _excludeFilters = _excludeFilters?.Where(f => InstrumentationHelper.IsValidFilterExpression(f)).ToArray();
            _includeFilters = _includeFilters?.Where(f => InstrumentationHelper.IsValidFilterExpression(f)).ToArray();

            foreach (var module in modules)
            {
                if (InstrumentationHelper.IsModuleExcluded(module, _excludeFilters) ||
                    !InstrumentationHelper.IsModuleIncluded(module, _includeFilters))
                {
                    continue;
                }

                var instrumenter = new Instrumenter(module, _identifier, _excludeFilters, _includeFilters, excludes, _excludeAttributes, _singleHit);
                if (instrumenter.CanInstrument())
                {
                    InstrumentationHelper.BackupOriginalModule(module, _identifier);

                    // Guard code path and restore if instrumentation fails.
                    try
                    {
                        var result = instrumenter.Instrument();
                        _results.Add(result);
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning($"Unable to instrument module: {module} because : {ex.Message}");
                        InstrumentationHelper.RestoreOriginalModule(module, _identifier);
                    }
                }
            }
        }
Exemplo n.º 6
0
        public CoveragePrepareResult PrepareModules()
        {
            string[] modules = _instrumentationHelper.GetCoverableModules(_moduleOrAppDirectory, _parameters.IncludeDirectories, _parameters.IncludeTestAssembly);

            Array.ForEach(_parameters.ExcludeFilters ?? Array.Empty <string>(), filter => _logger.LogVerbose($"Excluded module filter '{filter}'"));
            Array.ForEach(_parameters.IncludeFilters ?? Array.Empty <string>(), filter => _logger.LogVerbose($"Included module filter '{filter}'"));
            Array.ForEach(_parameters.ExcludedSourceFiles ?? Array.Empty <string>(), filter => _logger.LogVerbose($"Excluded source files filter '{FileSystem.EscapeFileName(filter)}'"));

            _parameters.ExcludeFilters = _parameters.ExcludeFilters?.Where(f => _instrumentationHelper.IsValidFilterExpression(f)).ToArray();
            _parameters.IncludeFilters = _parameters.IncludeFilters?.Where(f => _instrumentationHelper.IsValidFilterExpression(f)).ToArray();

            foreach (string module in modules)
            {
                if (_instrumentationHelper.IsModuleExcluded(module, _parameters.ExcludeFilters) ||
                    !_instrumentationHelper.IsModuleIncluded(module, _parameters.IncludeFilters))
                {
                    _logger.LogVerbose($"Excluded module: '{module}'");
                    continue;
                }

                var instrumenter = new Instrumenter(module,
                                                    Identifier,
                                                    _parameters,
                                                    _logger,
                                                    _instrumentationHelper,
                                                    _fileSystem,
                                                    _sourceRootTranslator,
                                                    _cecilSymbolHelper);

                if (instrumenter.CanInstrument())
                {
                    _instrumentationHelper.BackupOriginalModule(module, Identifier);

                    // Guard code path and restore if instrumentation fails.
                    try
                    {
                        InstrumenterResult result = instrumenter.Instrument();
                        if (!instrumenter.SkipModule)
                        {
                            _results.Add(result);
                            _logger.LogVerbose($"Instrumented module: '{module}'");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning($"Unable to instrument module: {module}\n{ex}");
                        _instrumentationHelper.RestoreOriginalModule(module, Identifier);
                    }
                }
            }

            return(new CoveragePrepareResult()
            {
                Identifier = Identifier,
                ModuleOrDirectory = _moduleOrAppDirectory,
                Parameters = _parameters,
                Results = _results.ToArray()
            });
        }
Exemplo n.º 7
0
        public CoveragePrepareResult PrepareModules()
        {
            string[] modules = _instrumentationHelper.GetCoverableModules(_module, _includeDirectories, _includeTestAssembly);

            Array.ForEach(_excludeFilters ?? Array.Empty <string>(), filter => _logger.LogVerbose($"Excluded module filter '{filter}'"));
            Array.ForEach(_includeFilters ?? Array.Empty <string>(), filter => _logger.LogVerbose($"Included module filter '{filter}'"));
            Array.ForEach(_excludedSourceFiles ?? Array.Empty <string>(), filter => _logger.LogVerbose($"Excluded source files filter '{filter}'"));

            _excludeFilters = _excludeFilters?.Where(f => _instrumentationHelper.IsValidFilterExpression(f)).ToArray();
            _includeFilters = _includeFilters?.Where(f => _instrumentationHelper.IsValidFilterExpression(f)).ToArray();

            foreach (var module in modules)
            {
                if (_instrumentationHelper.IsModuleExcluded(module, _excludeFilters) ||
                    !_instrumentationHelper.IsModuleIncluded(module, _includeFilters))
                {
                    _logger.LogVerbose($"Excluded module: '{module}'");
                    continue;
                }

                var instrumenter = new Instrumenter(module, _identifier, _excludeFilters, _includeFilters, _excludedSourceFiles, _excludeAttributes, _singleHit, _logger, _instrumentationHelper, _fileSystem, _sourceRootTranslator);

                if (instrumenter.CanInstrument())
                {
                    _instrumentationHelper.BackupOriginalModule(module, _identifier);

                    // Guard code path and restore if instrumentation fails.
                    try
                    {
                        InstrumenterResult result = instrumenter.Instrument();
                        if (!instrumenter.SkipModule)
                        {
                            _results.Add(result);
                            _logger.LogVerbose($"Instrumented module: '{module}'");
                        }
                    }
                    catch (Exception ex)
                    {
                        _logger.LogWarning($"Unable to instrument module: {module} because : {ex.Message}");
                        _instrumentationHelper.RestoreOriginalModule(module, _identifier);
                    }
                }
            }

            return(new CoveragePrepareResult()
            {
                Identifier = _identifier,
                Module = _module,
                MergeWith = _mergeWith,
                UseSourceLink = _useSourceLink,
                PathOverrides = _pathOverrides,
                Results = _results.ToArray()
            });
        }
Exemplo n.º 8
0
        public void PrepareModules()
        {
            string[] modules  = InstrumentationHelper.GetCoverableModules(_module, _includeDirectories);
            string[] excludes = InstrumentationHelper.GetExcludedFiles(_excludedSourceFiles);
            _excludeFilters = _excludeFilters?.Where(f => InstrumentationHelper.IsValidFilterExpression(f)).ToArray();
            _includeFilters = _includeFilters?.Where(f => InstrumentationHelper.IsValidFilterExpression(f)).ToArray();

            foreach (var module in modules)
            {
                if (InstrumentationHelper.IsModuleExcluded(module, _excludeFilters) ||
                    !InstrumentationHelper.IsModuleIncluded(module, _includeFilters))
                {
                    continue;
                }

                var instrumenter = new Instrumenter(module, _identifier, _excludeFilters, _includeFilters, excludes, _excludeAttributes);
                if (instrumenter.CanInstrument())
                {
                    InstrumentationHelper.BackupOriginalModule(module, _identifier);

                    // Guard code path and restore if instrumentation fails.
                    try
                    {
                        var result = instrumenter.Instrument();
                        _results.Add(result);
                    }
                    catch (Exception)
                    {
                        // TODO: With verbose logging we should note that instrumentation failed.
                        InstrumentationHelper.RestoreOriginalModule(module, _identifier);
                    }
                }
            }

            foreach (var result in _results)
            {
                var size = (result.HitCandidates.Count + ModuleTrackerTemplate.HitsResultHeaderSize) * sizeof(int);

                MemoryMappedFile mmap;

                try
                {
                    // Try using a named memory map not backed by a file (currently only supported on Windows)
                    mmap = MemoryMappedFile.CreateNew(result.HitsResultGuid, size);
                }
                catch (PlatformNotSupportedException)
                {
                    // Fall back on a file-backed memory map
                    mmap = MemoryMappedFile.CreateFromFile(result.HitsFilePath, FileMode.CreateNew, null, size);
                }

                _resultMemoryMaps.Add(result.HitsResultGuid, mmap);
            }
        }
Exemplo n.º 9
0
 public void PrepareModules()
 {
     string[] modules = InstrumentationHelper.GetDependencies(_module);
     foreach (var module in modules)
     {
         var instrumenter = new Instrumenter(module, _identifier);
         if (instrumenter.CanInstrument())
         {
             InstrumentationHelper.BackupOriginalModule(module, _identifier);
             var result = instrumenter.Instrument();
             _results.Add(result);
         }
     }
 }
Exemplo n.º 10
0
        public void TestInstrument()
        {
            string module     = typeof(InstrumenterTests).Assembly.Location;
            string pdb        = Path.Combine(Path.GetDirectoryName(module), Path.GetFileNameWithoutExtension(module) + ".pdb");
            string identifier = Guid.NewGuid().ToString();

            var directory = Directory.CreateDirectory(Path.Combine(Path.GetTempPath(), identifier));

            File.Copy(module, Path.Combine(directory.FullName, Path.GetFileName(module)), true);
            File.Copy(pdb, Path.Combine(directory.FullName, Path.GetFileName(pdb)), true);

            module = Path.Combine(directory.FullName, Path.GetFileName(module));
            Instrumenter instrumenter = new Instrumenter(module, identifier);
            var          result       = instrumenter.Instrument();

            Assert.Equal(Path.GetFileNameWithoutExtension(module), result.Module);
            Assert.Equal(module, result.ModulePath);

            directory.Delete(true);
        }
Exemplo n.º 11
0
        public void PrepareModules()
        {
            string[] modules  = InstrumentationHelper.GetCoverableModules(_module);
            string[] excludes = InstrumentationHelper.GetExcludedFiles(_excludes);
            _filters = _filters?.Where(f => InstrumentationHelper.IsValidFilterExpression(f)).ToArray();

            foreach (var module in modules)
            {
                if (InstrumentationHelper.IsModuleExcluded(module, _filters))
                {
                    continue;
                }

                var instrumenter = new Instrumenter(module, _identifier, _filters, excludes);
                if (instrumenter.CanInstrument())
                {
                    InstrumentationHelper.BackupOriginalModule(module, _identifier);
                    var result = instrumenter.Instrument();
                    _results.Add(result);
                }
            }
        }
Exemplo n.º 12
0
        public void TestCoreLibInstrumentation()
        {
            DirectoryInfo directory = Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), nameof(TestCoreLibInstrumentation)));

            string[] files = new[]
            {
                "System.Private.CoreLib.dll",
                "System.Private.CoreLib.pdb"
            };

            foreach (var file in files)
            {
                File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets", file), Path.Combine(directory.FullName, file), overwrite: true);
            }

            Mock <FileSystem> partialMockFileSystem = new Mock <FileSystem>();

            partialMockFileSystem.CallBase = true;
            partialMockFileSystem.Setup(fs => fs.OpenRead(It.IsAny <string>())).Returns((string path) =>
            {
                if (Path.GetFileName(path) == files[1])
                {
                    return(File.OpenRead(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets"), files[1])));
                }
                else
                {
                    return(File.OpenRead(path));
                }
            });
            partialMockFileSystem.Setup(fs => fs.Exists(It.IsAny <string>())).Returns((string path) =>
            {
                if (Path.GetFileName(path) == files[1])
                {
                    return(File.Exists(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets"), files[1])));
                }
                else
                {
                    if (path.Contains(@":\git\runtime"))
                    {
                        return(true);
                    }
                    else
                    {
                        return(File.Exists(path));
                    }
                }
            });
            var sourceRootTranslator                    = new SourceRootTranslator(_mockLogger.Object, new FileSystem());
            CoverageParameters    parameters            = new CoverageParameters();
            InstrumentationHelper instrumentationHelper =
                new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), partialMockFileSystem.Object, _mockLogger.Object, sourceRootTranslator);
            Instrumenter instrumenter = new Instrumenter(Path.Combine(directory.FullName, files[0]), "_coverlet_instrumented", parameters, _mockLogger.Object, instrumentationHelper, partialMockFileSystem.Object, sourceRootTranslator, new CecilSymbolHelper());

            Assert.True(instrumenter.CanInstrument());
            InstrumenterResult result = instrumenter.Instrument();

            Assert.NotNull(result);
            Assert.Equal(1052, result.Documents.Count);
            foreach ((string docName, Document _) in result.Documents)
            {
                Assert.False(docName.EndsWith(@"System.Private.CoreLib\src\System\Threading\Interlocked.cs"));
            }
            directory.Delete(true);
        }
Exemplo n.º 13
0
        public void TestCoreLibInstrumentation()
        {
            // We test only on win because sample dll/pdb were build on it
            if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
            {
                return;
            }

            DirectoryInfo directory = Directory.CreateDirectory(Path.Combine(Directory.GetCurrentDirectory(), nameof(TestCoreLibInstrumentation)));

            string[] files = new[]
            {
                "System.Private.CoreLib.dll",
                "System.Private.CoreLib.pdb"
            };

            foreach (var file in files)
            {
                File.Copy(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets", file), Path.Combine(directory.FullName, file), overwrite: true);
            }

            Mock <FileSystem> partialMockFileSystem = new Mock <FileSystem>();

            partialMockFileSystem.CallBase = true;
            partialMockFileSystem.Setup(fs => fs.OpenRead(It.IsAny <string>())).Returns((string path) =>
            {
                if (Path.GetFileName(path) == files[1])
                {
                    return(File.OpenRead(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets"), files[1])));
                }
                else
                {
                    return(File.OpenRead(path));
                }
            });
            partialMockFileSystem.Setup(fs => fs.Exists(It.IsAny <string>())).Returns((string path) =>
            {
                if (Path.GetFileName(path) == files[1])
                {
                    return(File.Exists(Path.Combine(Path.Combine(Directory.GetCurrentDirectory(), "TestAssets"), files[1])));
                }
                else
                {
                    if (path.Contains(@":\git\runtime"))
                    {
                        return(true);
                    }
                    else
                    {
                        return(File.Exists(path));
                    }
                }
            });

            InstrumentationHelper instrumentationHelper = new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), partialMockFileSystem.Object);
            Instrumenter          instrumenter          = new Instrumenter(Path.Combine(directory.FullName, files[0]), "_coverlet_instrumented", Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), false, _mockLogger.Object, instrumentationHelper, partialMockFileSystem.Object);

            Assert.True(instrumenter.CanInstrument());
            InstrumenterResult result = instrumenter.Instrument();

            Assert.NotNull(result);
            Assert.Equal(1052, result.Documents.Count);
            foreach ((string docName, Document _) in result.Documents)
            {
                Assert.False(docName.EndsWith(@"System.Private.CoreLib\src\System\Threading\Interlocked.cs"));
            }
            directory.Delete(true);
        }