diff --git a/src/coverlet.collector/DataCollection/CoverageWrapper.cs b/src/coverlet.collector/DataCollection/CoverageWrapper.cs index f97471268..2854ed1d5 100644 --- a/src/coverlet.collector/DataCollection/CoverageWrapper.cs +++ b/src/coverlet.collector/DataCollection/CoverageWrapper.cs @@ -30,7 +30,8 @@ public Coverage CreateCoverage(CoverletSettings settings, ILogger coverletLogger settings.MergeWith, settings.UseSourceLink, coverletLogger, - (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper))); + (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper)), + (IFileSystem)DependencyInjection.Current.GetService(typeof(IFileSystem))); } /// diff --git a/src/coverlet.console/Program.cs b/src/coverlet.console/Program.cs index c5afa907b..e306ab6c2 100644 --- a/src/coverlet.console/Program.cs +++ b/src/coverlet.console/Program.cs @@ -59,7 +59,7 @@ static int Main(string[] args) // Adjust log level based on user input. logger.Level = verbosity.ParsedValue; } - + var fileSystem = (IFileSystem)DependencyInjection.Current.GetService(typeof(IFileSystem)); Coverage coverage = new Coverage(module.Value, includeFilters.Values.ToArray(), includeDirectories.Values.ToArray(), @@ -71,7 +71,8 @@ static int Main(string[] args) mergeWith.Value(), useSourceLink.HasValue(), logger, - (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper))); + (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper)), + fileSystem); coverage.PrepareModules(); Process process = new Process(); @@ -140,7 +141,7 @@ static int Main(string[] args) var report = Path.Combine(directory, filename); logger.LogInformation($" Generating report '{report}'", important: true); - File.WriteAllText(report, reporter.Report(result)); + fileSystem.WriteAllText(report, reporter.Report(result)); } } diff --git a/src/coverlet.core/Abstracts/IFileSystem.cs b/src/coverlet.core/Abstracts/IFileSystem.cs index 99cf8a70f..806371803 100644 --- a/src/coverlet.core/Abstracts/IFileSystem.cs +++ b/src/coverlet.core/Abstracts/IFileSystem.cs @@ -1,7 +1,23 @@ -namespace Coverlet.Core.Abstracts +using System.IO; + +namespace Coverlet.Core.Abstracts { - internal interface IFileSystem + public interface IFileSystem { bool Exists(string path); + + void WriteAllText(string path, string contents); + + string ReadAllText(string path); + + Stream OpenRead(string path); + + void Copy(string sourceFileName, string destFileName, bool overwrite); + + void Delete(string path); + + Stream NewFileStream(string path, FileMode mode); + + Stream NewFileStream(string path, FileMode mode, FileAccess access); } } diff --git a/src/coverlet.core/Coverage.cs b/src/coverlet.core/Coverage.cs index 8ce16f064..65efd576f 100644 --- a/src/coverlet.core/Coverage.cs +++ b/src/coverlet.core/Coverage.cs @@ -3,7 +3,6 @@ using System.IO; using System.Linq; using Coverlet.Core.Abstracts; -using Coverlet.Core.Helpers; using Coverlet.Core.Instrumentation; using Coverlet.Core.Logging; @@ -27,6 +26,7 @@ public class Coverage private bool _useSourceLink; private ILogger _logger; private IInstrumentationHelper _instrumentationHelper; + private IFileSystem _fileSystem; private List _results; public string Identifier @@ -45,7 +45,8 @@ public Coverage(string module, string mergeWith, bool useSourceLink, ILogger logger, - IInstrumentationHelper instrumentationHelper) + IInstrumentationHelper instrumentationHelper, + IFileSystem fileSystem) { _module = module; _includeFilters = includeFilters; @@ -59,12 +60,13 @@ public Coverage(string module, _useSourceLink = useSourceLink; _logger = logger; _instrumentationHelper = instrumentationHelper; + _fileSystem = fileSystem; _identifier = Guid.NewGuid().ToString(); _results = new List(); } - public Coverage(CoveragePrepareResult prepareResult, ILogger logger, IInstrumentationHelper instrumentationHelper) + public Coverage(CoveragePrepareResult prepareResult, ILogger logger, IInstrumentationHelper instrumentationHelper, IFileSystem fileSystem) { _identifier = prepareResult.Identifier; _module = prepareResult.Module; @@ -73,6 +75,7 @@ public Coverage(CoveragePrepareResult prepareResult, ILogger logger, IInstrument _results = new List(prepareResult.Results); _logger = logger; _instrumentationHelper = instrumentationHelper; + _fileSystem = fileSystem; } public CoveragePrepareResult PrepareModules() @@ -94,7 +97,7 @@ public CoveragePrepareResult PrepareModules() continue; } - var instrumenter = new Instrumenter(module, _identifier, _excludeFilters, _includeFilters, _excludedSourceFiles, _excludeAttributes, _singleHit, _logger, _instrumentationHelper); + var instrumenter = new Instrumenter(module, _identifier, _excludeFilters, _includeFilters, _excludedSourceFiles, _excludeAttributes, _singleHit, _logger, _instrumentationHelper, _fileSystem); if (instrumenter.CanInstrument()) { _instrumentationHelper.BackupOriginalModule(module, _identifier); @@ -215,9 +218,9 @@ public CoverageResult GetCoverageResult() var coverageResult = new CoverageResult { Identifier = _identifier, Modules = modules, InstrumentedResults = _results }; - if (!string.IsNullOrEmpty(_mergeWith) && !string.IsNullOrWhiteSpace(_mergeWith) && File.Exists(_mergeWith)) + if (!string.IsNullOrEmpty(_mergeWith) && !string.IsNullOrWhiteSpace(_mergeWith) && _fileSystem.Exists(_mergeWith)) { - string json = File.ReadAllText(_mergeWith); + string json = _fileSystem.ReadAllText(_mergeWith); coverageResult.Merge(JsonConvert.DeserializeObject(json)); } @@ -228,7 +231,7 @@ private void CalculateCoverage() { foreach (var result in _results) { - if (!File.Exists(result.HitsFilePath)) + if (!_fileSystem.Exists(result.HitsFilePath)) { // Hits file could be missed mainly for two reason // 1) Issue during module Unload() @@ -249,7 +252,7 @@ private void CalculateCoverage() } } - using (var fs = new FileStream(result.HitsFilePath, FileMode.Open)) + using (var fs = _fileSystem.NewFileStream(result.HitsFilePath, FileMode.Open)) using (var br = new BinaryReader(fs)) { int hitCandidatesCount = br.ReadInt32(); diff --git a/src/coverlet.core/Helpers/FileSystem.cs b/src/coverlet.core/Helpers/FileSystem.cs index fa0ef5b87..70ee80228 100644 --- a/src/coverlet.core/Helpers/FileSystem.cs +++ b/src/coverlet.core/Helpers/FileSystem.cs @@ -3,11 +3,47 @@ namespace Coverlet.Core.Helpers { - internal class FileSystem : IFileSystem + public class FileSystem : IFileSystem { - public bool Exists(string path) + // We need to partial mock this class on tests + public virtual bool Exists(string path) { return File.Exists(path); } + + public void WriteAllText(string path, string contents) + { + File.WriteAllText(path, contents); + } + + public string ReadAllText(string path) + { + return File.ReadAllText(path); + } + + public Stream OpenRead(string path) + { + return File.OpenRead(path); + } + + public void Copy(string sourceFileName, string destFileName, bool overwrite) + { + File.Copy(sourceFileName, destFileName, overwrite); + } + + public void Delete(string path) + { + File.Delete(path); + } + + public Stream NewFileStream(string path, FileMode mode) + { + return new FileStream(path, mode); + } + + public Stream NewFileStream(string path, FileMode mode, FileAccess access) + { + return new FileStream(path, mode, access); + } } } diff --git a/src/coverlet.core/Helpers/InstrumentationHelper.cs b/src/coverlet.core/Helpers/InstrumentationHelper.cs index e42070837..26f609d14 100644 --- a/src/coverlet.core/Helpers/InstrumentationHelper.cs +++ b/src/coverlet.core/Helpers/InstrumentationHelper.cs @@ -9,7 +9,6 @@ using System.Reflection.PortableExecutable; using System.Text.RegularExpressions; using Coverlet.Core.Abstracts; -using Coverlet.Core.Logging; namespace Coverlet.Core.Helpers { @@ -73,7 +72,7 @@ public string[] GetCoverableModules(string module, string[] directories, bool in public bool HasPdb(string module, out bool embedded) { embedded = false; - using (var moduleStream = File.OpenRead(module)) + using (var moduleStream = _fileSystem.OpenRead(module)) using (var peReader = new PEReader(moduleStream)) { foreach (var entry in peReader.ReadDebugDirectory()) @@ -88,7 +87,7 @@ public bool HasPdb(string module, out bool embedded) return true; } - return File.Exists(codeViewData.Path); + return _fileSystem.Exists(codeViewData.Path); } } @@ -99,7 +98,7 @@ public bool HasPdb(string module, out bool embedded) public bool EmbeddedPortablePdbHasLocalSource(string module, out string firstNotFoundDocument) { firstNotFoundDocument = ""; - using (FileStream moduleStream = File.OpenRead(module)) + using (Stream moduleStream = _fileSystem.OpenRead(module)) using (var peReader = new PEReader(moduleStream)) { foreach (DebugDirectoryEntry entry in peReader.ReadDebugDirectory()) @@ -117,7 +116,7 @@ public bool EmbeddedPortablePdbHasLocalSource(string module, out string firstNot // We verify all docs and return false if not all are present in local // We could have false negative if doc is not a source // Btw check for all possible extension could be weak approach - if (!File.Exists(docName)) + if (!_fileSystem.Exists(docName)) { firstNotFoundDocument = docName; return false; @@ -136,7 +135,7 @@ public bool EmbeddedPortablePdbHasLocalSource(string module, out string firstNot public bool PortablePdbHasLocalSource(string module, out string firstNotFoundDocument) { firstNotFoundDocument = ""; - using (var moduleStream = File.OpenRead(module)) + using (var moduleStream = _fileSystem.OpenRead(module)) using (var peReader = new PEReader(moduleStream)) { foreach (var entry in peReader.ReadDebugDirectory()) @@ -144,7 +143,7 @@ public bool PortablePdbHasLocalSource(string module, out string firstNotFoundDoc if (entry.Type == DebugDirectoryEntryType.CodeView) { var codeViewData = peReader.ReadCodeViewDebugDirectoryData(entry); - using FileStream pdbStream = new FileStream(codeViewData.Path, FileMode.Open); + using Stream pdbStream = _fileSystem.NewFileStream(codeViewData.Path, FileMode.Open); using MetadataReaderProvider metadataReaderProvider = MetadataReaderProvider.FromPortablePdbStream(pdbStream); MetadataReader metadataReader = metadataReaderProvider.GetMetadataReader(); foreach (DocumentHandle docHandle in metadataReader.Documents) @@ -172,16 +171,16 @@ public void BackupOriginalModule(string module, string identifier) { var backupPath = GetBackupPath(module, identifier); var backupSymbolPath = Path.ChangeExtension(backupPath, ".pdb"); - File.Copy(module, backupPath, true); + _fileSystem.Copy(module, backupPath, true); if (!_backupList.TryAdd(module, backupPath)) { throw new ArgumentException($"Key already added '{module}'"); } var symbolFile = Path.ChangeExtension(module, ".pdb"); - if (File.Exists(symbolFile)) + if (_fileSystem.Exists(symbolFile)) { - File.Copy(symbolFile, backupSymbolPath, true); + _fileSystem.Copy(symbolFile, backupSymbolPath, true); if (!_backupList.TryAdd(symbolFile, backupSymbolPath)) { throw new ArgumentException($"Key already added '{module}'"); @@ -200,18 +199,18 @@ public void RestoreOriginalModule(string module, string identifier) _retryHelper.Retry(() => { - File.Copy(backupPath, module, true); - File.Delete(backupPath); + _fileSystem.Copy(backupPath, module, true); + _fileSystem.Delete(backupPath); _backupList.TryRemove(module, out string _); }, retryStrategy, 10); _retryHelper.Retry(() => { - if (File.Exists(backupSymbolPath)) + if (_fileSystem.Exists(backupSymbolPath)) { string symbolFile = Path.ChangeExtension(module, ".pdb"); - File.Copy(backupSymbolPath, symbolFile, true); - File.Delete(backupSymbolPath); + _fileSystem.Copy(backupSymbolPath, symbolFile, true); + _fileSystem.Delete(backupSymbolPath); _backupList.TryRemove(symbolFile, out string _); } }, retryStrategy, 10); @@ -228,8 +227,8 @@ public void RestoreOriginalModules() string backupPath = _backupList[key]; _retryHelper.Retry(() => { - File.Copy(backupPath, key, true); - File.Delete(backupPath); + _fileSystem.Copy(backupPath, key, true); + _fileSystem.Delete(backupPath); _backupList.TryRemove(key, out string _); }, retryStrategy, 10); } @@ -240,7 +239,7 @@ public void DeleteHitsFile(string path) // Retry hitting the hits file - retry up to 10 times, since the file could be locked // See: https://github.com/tonerdo/coverlet/issues/25 var retryStrategy = CreateRetryStrategy(); - _retryHelper.Retry(() => File.Delete(path), retryStrategy, 10); + _retryHelper.Retry(() => _fileSystem.Delete(path), retryStrategy, 10); } public bool IsValidFilterExpression(string filter) diff --git a/src/coverlet.core/Instrumentation/Instrumenter.cs b/src/coverlet.core/Instrumentation/Instrumenter.cs index 53904252b..f8b1c26aa 100644 --- a/src/coverlet.core/Instrumentation/Instrumenter.cs +++ b/src/coverlet.core/Instrumentation/Instrumenter.cs @@ -6,7 +6,6 @@ using System.Linq; using Coverlet.Core.Abstracts; using Coverlet.Core.Attributes; -using Coverlet.Core.Helpers; using Coverlet.Core.Logging; using Coverlet.Core.Symbols; using Microsoft.Extensions.FileSystemGlobbing; @@ -28,6 +27,7 @@ internal class Instrumenter private readonly bool _isCoreLibrary; private readonly ILogger _logger; private readonly IInstrumentationHelper _instrumentationHelper; + private readonly IFileSystem _fileSystem; private InstrumenterResult _result; private FieldDefinition _customTrackerHitsArray; private FieldDefinition _customTrackerHitsFilePath; @@ -48,7 +48,8 @@ public Instrumenter( string[] excludedAttributes, bool singleHit, ILogger logger, - IInstrumentationHelper instrumentationHelper) + IInstrumentationHelper instrumentationHelper, + IFileSystem fileSystem) { _module = module; _identifier = identifier; @@ -60,6 +61,7 @@ public Instrumenter( _isCoreLibrary = Path.GetFileNameWithoutExtension(_module) == "System.Private.CoreLib"; _logger = logger; _instrumentationHelper = instrumentationHelper; + _fileSystem = fileSystem; } public bool CanInstrument() @@ -136,7 +138,7 @@ public InstrumenterResult Instrument() private void InstrumentModule() { - using (var stream = new FileStream(_module, FileMode.Open, FileAccess.ReadWrite)) + using (var stream = _fileSystem.NewFileStream(_module, FileMode.Open, FileAccess.ReadWrite)) using (var resolver = new NetstandardAwareAssemblyResolver()) { resolver.AddSearchDirectory(Path.GetDirectoryName(_module)); diff --git a/src/coverlet.msbuild.tasks/CoverageResultTask.cs b/src/coverlet.msbuild.tasks/CoverageResultTask.cs index 0e06b4078..f1a67ff7d 100644 --- a/src/coverlet.msbuild.tasks/CoverageResultTask.cs +++ b/src/coverlet.msbuild.tasks/CoverageResultTask.cs @@ -75,14 +75,20 @@ public override bool Execute() { Console.WriteLine("\nCalculating coverage result..."); - if (InstrumenterState is null || !File.Exists(InstrumenterState.ItemSpec)) + IFileSystem fileSystem = (IFileSystem)DependencyInjection.Current.GetService(typeof(IFileSystem)); + if (InstrumenterState is null || !fileSystem.Exists(InstrumenterState.ItemSpec)) { _logger.LogError("Result of instrumentation task not found"); return false; } - var coverage = new Coverage(CoveragePrepareResult.Deserialize(new FileStream(InstrumenterState.ItemSpec, FileMode.Open)), this._logger, (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper))); - var result = coverage.GetCoverageResult(); + Coverage coverage = null; + using (Stream instrumenterStateStream = fileSystem.NewFileStream(InstrumenterState.ItemSpec, FileMode.Open)) + { + coverage = new Coverage(CoveragePrepareResult.Deserialize(instrumenterStateStream), this._logger, (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper)), fileSystem); + } + + CoverageResult result = coverage.GetCoverageResult(); var directory = Path.GetDirectoryName(_output); if (directory == string.Empty) @@ -118,7 +124,7 @@ public override bool Execute() var report = Path.Combine(directory, filename); Console.WriteLine($" Generating report '{report}'"); - File.WriteAllText(report, reporter.Report(result)); + fileSystem.WriteAllText(report, reporter.Report(result)); } } diff --git a/src/coverlet.msbuild.tasks/InstrumentationTask.cs b/src/coverlet.msbuild.tasks/InstrumentationTask.cs index 0a1f50bab..b510b4aca 100644 --- a/src/coverlet.msbuild.tasks/InstrumentationTask.cs +++ b/src/coverlet.msbuild.tasks/InstrumentationTask.cs @@ -105,11 +105,25 @@ public override bool Execute() var excludeFilters = _exclude?.Split(','); var excludedSourceFiles = _excludeByFile?.Split(','); var excludeAttributes = _excludeByAttribute?.Split(','); + var fileSystem = (IFileSystem) DependencyInjection.Current.GetService(typeof(IFileSystem)); + + Coverage coverage = new Coverage(_path, + includeFilters, + includeDirectories, + excludeFilters, + excludedSourceFiles, + excludeAttributes, + _includeTestAssembly, + _singleHit, + _mergeWith, + _useSourceLink, + _logger, + (IInstrumentationHelper) DependencyInjection.Current.GetService(typeof(IInstrumentationHelper)), + fileSystem); - Coverage coverage = new Coverage(_path, includeFilters, includeDirectories, excludeFilters, excludedSourceFiles, excludeAttributes, _includeTestAssembly, _singleHit, _mergeWith, _useSourceLink, _logger, (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper))); CoveragePrepareResult prepareResult = coverage.PrepareModules(); InstrumenterState = new TaskItem(System.IO.Path.GetTempFileName()); - using (var instrumentedStateFile = new FileStream(InstrumenterState.ItemSpec, FileMode.Open, FileAccess.Write)) + using (var instrumentedStateFile = fileSystem.NewFileStream(InstrumenterState.ItemSpec, FileMode.Open, FileAccess.Write)) { using (Stream serializedState = CoveragePrepareResult.Serialize(prepareResult)) { diff --git a/test/coverlet.collector.tests/CoverletCoverageDataCollectorTests.cs b/test/coverlet.collector.tests/CoverletCoverageDataCollectorTests.cs index 306c2a5eb..07c56bd99 100644 --- a/test/coverlet.collector.tests/CoverletCoverageDataCollectorTests.cs +++ b/test/coverlet.collector.tests/CoverletCoverageDataCollectorTests.cs @@ -74,7 +74,7 @@ public void OnSessionStartShouldPrepareModulesForCoverage() null, _context); IDictionary sessionStartProperties = new Dictionary(); - Coverage coverage = new Coverage("abc.dll", null, null, null, null, null, true, true, "abc.json", true, It.IsAny(), (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper))); + Coverage coverage = new Coverage("abc.dll", null, null, null, null, null, true, true, "abc.json", true, It.IsAny(), (IInstrumentationHelper)DependencyInjection.Current.GetService(typeof(IInstrumentationHelper)), (IFileSystem)DependencyInjection.Current.GetService(typeof(IFileSystem))); sessionStartProperties.Add("TestSources", new List { "abc.dll" }); _mockCoverageWrapper.Setup(x => x.CreateCoverage(It.IsAny(), It.IsAny())).Returns(coverage); diff --git a/test/coverlet.core.tests/CoverageTests.cs b/test/coverlet.core.tests/CoverageTests.cs index 6521f9476..6db5df4c7 100644 --- a/test/coverlet.core.tests/CoverageTests.cs +++ b/test/coverlet.core.tests/CoverageTests.cs @@ -1,7 +1,7 @@ using System; using System.IO; using System.Threading.Tasks; - +using Coverlet.Core.Abstracts; using Coverlet.Core.Helpers; using Coverlet.Core.Logging; using Coverlet.Core.Samples.Tests; @@ -30,7 +30,7 @@ public void TestCoverage() // TODO: Find a way to mimick hits - var coverage = new Coverage(Path.Combine(directory.FullName, Path.GetFileName(module)), Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, false, string.Empty, false, _mockLogger.Object, _instrumentationHelper); + var coverage = new Coverage(Path.Combine(directory.FullName, Path.GetFileName(module)), Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, false, string.Empty, false, _mockLogger.Object, _instrumentationHelper, new FileSystem()); coverage.PrepareModules(); var result = coverage.GetCoverageResult(); @@ -53,7 +53,7 @@ public void TestCoverageWithTestAssembly() // TODO: Find a way to mimick hits - var coverage = new Coverage(Path.Combine(directory.FullName, Path.GetFileName(module)), Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), true, false, string.Empty, false, _mockLogger.Object, _instrumentationHelper); + var coverage = new Coverage(Path.Combine(directory.FullName, Path.GetFileName(module)), Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), true, false, string.Empty, false, _mockLogger.Object, _instrumentationHelper, new FileSystem()); coverage.PrepareModules(); var result = coverage.GetCoverageResult(); diff --git a/test/coverlet.core.tests/Instrumentation/InstrumenterTests.cs b/test/coverlet.core.tests/Instrumentation/InstrumenterTests.cs index 433999bac..b289d7362 100644 --- a/test/coverlet.core.tests/Instrumentation/InstrumenterTests.cs +++ b/test/coverlet.core.tests/Instrumentation/InstrumenterTests.cs @@ -4,8 +4,6 @@ using System.Linq; using System.Reflection; using System.Runtime.InteropServices; - -using Coverlet.Core.Abstracts; using Coverlet.Core.Helpers; using Coverlet.Core.Logging; using Coverlet.Core.Samples.Tests; @@ -42,7 +40,7 @@ public void TestCoreLibInstrumentation() 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(), Array.Empty(), Array.Empty(), Array.Empty(), false, _mockLogger.Object, _instrumentationHelper); + Instrumenter instrumenter = new Instrumenter(Path.Combine(TestFilesDir, files[0]), "_coverlet_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, _mockLogger.Object, _instrumentationHelper, new FileSystem()); Assert.True(instrumenter.CanInstrument()); var result = instrumenter.Instrument(); Assert.NotNull(result); @@ -178,7 +176,7 @@ private InstrumenterTest CreateInstrumentor(bool fakeCoreLibModule = false, stri File.Copy(pdb, Path.Combine(directory.FullName, destPdb), true); module = Path.Combine(directory.FullName, destModule); - Instrumenter instrumenter = new Instrumenter(module, identifier, Array.Empty(), Array.Empty(), Array.Empty(), attributesToIgnore, false, _mockLogger.Object, _instrumentationHelper); + Instrumenter instrumenter = new Instrumenter(module, identifier, Array.Empty(), Array.Empty(), Array.Empty(), attributesToIgnore, false, _mockLogger.Object, _instrumentationHelper, new FileSystem()); return new InstrumenterTest { Instrumenter = instrumenter, @@ -349,7 +347,7 @@ public void SkipEmbeddedPpdbWithoutLocalSource() { string xunitDll = Directory.GetFiles(Directory.GetCurrentDirectory(), "xunit.*.dll").First(); var loggerMock = new Mock(); - Instrumenter instrumenter = new Instrumenter(xunitDll, "_xunit_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, loggerMock.Object, _instrumentationHelper); + Instrumenter instrumenter = new Instrumenter(xunitDll, "_xunit_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, loggerMock.Object, _instrumentationHelper, new FileSystem()); Assert.True(_instrumentationHelper.HasPdb(xunitDll, out bool embedded)); Assert.True(embedded); Assert.False(instrumenter.CanInstrument()); @@ -357,7 +355,7 @@ public void SkipEmbeddedPpdbWithoutLocalSource() // Default case string coverletCoreDll = Directory.GetFiles(Directory.GetCurrentDirectory(), "coverlet.core.dll").First(); - instrumenter = new Instrumenter(coverletCoreDll, "_coverlet_core_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, loggerMock.Object, _instrumentationHelper); + instrumenter = new Instrumenter(coverletCoreDll, "_coverlet_core_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, loggerMock.Object, _instrumentationHelper, new FileSystem()); Assert.True(_instrumentationHelper.HasPdb(coverletCoreDll, out embedded)); Assert.False(embedded); Assert.True(instrumenter.CanInstrument()); @@ -367,16 +365,17 @@ public void SkipEmbeddedPpdbWithoutLocalSource() [Fact] public void SkipPpdbWithoutLocalSource() { - Mock mockFileSystem = new Mock(); - mockFileSystem.Setup(fs => fs.Exists(It.IsAny())).Returns((string path) => - { - return Path.GetExtension(path) != ".cs"; - }); - InstrumentationHelper instrumentationHelper = new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), mockFileSystem.Object); + Mock partialMockFileSystem = new Mock(); + partialMockFileSystem.CallBase = true; + partialMockFileSystem.Setup(fs => fs.Exists(It.IsAny())).Returns((string path) => + { + return Path.GetExtension(path) != ".cs"; + }); + InstrumentationHelper instrumentationHelper = new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), partialMockFileSystem.Object); string coverletLib = Directory.GetFiles(Directory.GetCurrentDirectory(), "coverlet.core.dll").First(); var loggerMock = new Mock(); - Instrumenter instrumenter = new Instrumenter(coverletLib, "_corelib_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, loggerMock.Object, instrumentationHelper); + Instrumenter instrumenter = new Instrumenter(coverletLib, "_corelib_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, loggerMock.Object, instrumentationHelper, partialMockFileSystem.Object); Assert.True(_instrumentationHelper.HasPdb(coverletLib, out bool embedded)); Assert.False(embedded); Assert.False(instrumenter.CanInstrument()); @@ -387,7 +386,7 @@ public void SkipPpdbWithoutLocalSource() public void TestInstrument_MissingModule() { var loggerMock = new Mock(); - var instrumenter = new Instrumenter("test", "_test_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, loggerMock.Object, _instrumentationHelper); + var instrumenter = new Instrumenter("test", "_test_instrumented", Array.Empty(), Array.Empty(), Array.Empty(), Array.Empty(), false, loggerMock.Object, _instrumentationHelper, new FileSystem()); Assert.False(instrumenter.CanInstrument()); loggerMock.Verify(l => l.LogWarning(It.IsAny())); } diff --git a/test/coverlet.core.tests/InstrumenterHelper.cs b/test/coverlet.core.tests/InstrumenterHelper.cs index 471c6a893..c64de4c19 100644 --- a/test/coverlet.core.tests/InstrumenterHelper.cs +++ b/test/coverlet.core.tests/InstrumenterHelper.cs @@ -191,7 +191,7 @@ public static CoverageResult GetCoverageResult(string filePath) using (var result = new FileStream(filePath, FileMode.Open)) { CoveragePrepareResult coveragePrepareResultLoaded = CoveragePrepareResult.Deserialize(result); - Coverage coverage = new Coverage(coveragePrepareResultLoaded, new Mock().Object, new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), new FileSystem())); + Coverage coverage = new Coverage(coveragePrepareResultLoaded, new Mock().Object, new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), new FileSystem()), new FileSystem()); return coverage.GetCoverageResult(); } } @@ -226,7 +226,7 @@ async public static Task Run(Func callM { "[xunit.*]*", "[coverlet.*]*" - }, Array.Empty(), Array.Empty(), true, false, "", false, new Logger(logFile), DependencyInjection.Current.GetService()); + }, Array.Empty(), Array.Empty(), true, false, "", false, new Logger(logFile), DependencyInjection.Current.GetService(), DependencyInjection.Current.GetService()); CoveragePrepareResult prepareResult = coverage.PrepareModules(); // Load new assembly