Beispiel #1
0
 public void CreateMesh(ChunkCell[,] cells)
 {
     using (Instrumenter.Start())
     {
         GenerateMesh(cells);
     }
 }
Beispiel #2
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);
                    }
                }
            }
        }
Beispiel #3
0
        private bool IsEnabled(object thing)
        {
            var payload = new InstrumentationPayload {
                FeatureName = Name,
                Operation   = "enabled?",
            };

            if (thing != null)
            {
                payload.Thing = thing;
            }
            using (Instrumenter.InstrumentFeature(payload))
            {
                var  values   = GateValues;
                var  openGate = Gates.FirstOrDefault(gate => InstrumentGate(gate, "open?", thing, x => x.IsOpen(thing, values[x.Key], Name)));
                bool result;
                if (openGate != null)
                {
                    payload.GateName = openGate.Name;
                    result           = true;
                }
                else
                {
                    result = false;
                }
                payload.Result = result;
                return(result);
            }
        }
Beispiel #4
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);
                    }
                }
            }
        }
Beispiel #5
0
        public void Generate()
        {
            using (Instrumenter.Start())
            {
                _missCounter = 0;

                MapGenerationData.Instance = MapGenerationData;

                var seed = MapGenerationData.Instance.Seed.GetHashCode();
                _size = MapGenerationData.Instance.MapSize * MapGenerationData.Instance.ChunkSize;

                _heightMap      = GetHeightMap(seed);
                _temperatureMap = GetTemperatureMap();
                _moistureMap    = GetMoistureMap(seed);

                _cells = GetCells();

                DrawChunks();

                Debug.Log($"Miss: {_missCounter}/{_size * _size}");

                Camera.ConfigureMinMax(0, _size, 0, (int)(_size * 1.5f));
                Camera.MoveToWorldCenter();
            }
        }
        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);
        }
        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;
        }
Beispiel #8
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();
        }
        public List <ChunkCell> Resolve()
        {
            using (Instrumenter.Start())
            {
                Reset();
                AddCellToFrontier(_origin);

                while (_searchFrontier.Count > 0)
                {
                    _iterations++;
                    if (_iterations > _maxIterations)
                    {
                        throw new OverflowException($"Search area too large > {_maxIterations} reached!");
                    }

                    var cell = _searchFrontier.Dequeue();
                    if (_search(cell))
                    {
                        _matches.Add(cell);
                        AddNeighboursToSearchFrontier(cell);
                    }
                }
            }

            return(_matches.ToList());
        }
Beispiel #10
0
        public static Texture2D CreateTextureFromColorMap(int width, int height, Color[,] color)
        {
            using (Instrumenter.Start())
            {
                var texture = new Texture2D(width, height)
                {
                    filterMode = FilterMode.Point,
                    wrapMode   = TextureWrapMode.Clamp
                };
                var pixels = new Color[width * height];

                var i = 0;
                for (var y = 0; y < height; y++)
                {
                    for (var x = 0; x < width; x++)
                    {
                        pixels[i] = color[x, y];
                        i++;
                    }
                }
                texture.SetPixels(pixels);
                texture.Apply();
                File.WriteAllBytes($@"C:\ext\tex\{DateTime.Now.Ticks}.png", texture.EncodeToPNG());

                return(texture);
            }
        }
        private InstrumenterTest CreateInstrumentor(bool fakeCoreLibModule = false, string[] attributesToIgnore = null, string[] excludedFiles = null, bool singleHit = false)
        {
            string module     = GetType().Assembly.Location;
            string pdb        = Path.Combine(Path.GetDirectoryName(module), Path.GetFileNameWithoutExtension(module) + ".pdb");
            string identifier = Guid.NewGuid().ToString();

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

            string destModule, destPdb;

            if (fakeCoreLibModule)
            {
                destModule = "System.Private.CoreLib.dll";
                destPdb    = "System.Private.CoreLib.pdb";
            }
            else
            {
                destModule = Path.GetFileName(module);
                destPdb    = Path.GetFileName(pdb);
            }

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

            module = Path.Combine(directory.FullName, destModule);
            Instrumenter instrumenter = new Instrumenter(module, identifier, Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), attributesToIgnore, false, _mockLogger.Object, _instrumentationHelper);

            return(new InstrumenterTest
            {
                Instrumenter = instrumenter,
                Module = module,
                Identifier = identifier,
                Directory = directory
            });
        }
Beispiel #12
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()
            });
        }
Beispiel #13
0
        public void TestInstrument_MissingModule()
        {
            var loggerMock   = new Mock <ILogger>();
            var instrumenter = new Instrumenter("test", "_test_instrumented", Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), false, loggerMock.Object);

            Assert.False(instrumenter.CanInstrument());
            loggerMock.Verify(l => l.LogWarning(It.IsAny <string>()));
        }
Beispiel #14
0
    public void RegenerateMap()
    {
        using (Instrumenter.Start())
        {
            var mapSize = GetMapSize();
            map = new Cell[mapSize, mapSize];

            var noise = new FastNoiseLite(Guid.NewGuid().GetHashCode());
            noise.SetNoiseType(FastNoiseLite.NoiseType.OpenSimplex2);
            noise.SetFrequency(0.01f);
            noise.SetFractalType(FastNoiseLite.FractalType.FBm);

            var height = noise.GetNoiseMap(mapSize);
            for (var x = 0; x < mapSize; x++)
            {
                for (var z = 0; z < mapSize; z++)
                {
                    var cellHeight = height[x, z] * 20f;

                    if (cellHeight <= 0)
                    {
                        cellHeight = 0;
                    }

                    Color color;
                    if (cellHeight > 9)
                    {
                        color = Color.white;
                    }
                    else if (cellHeight > 7)
                    {
                        color = Color.grey;
                    }
                    else if (cellHeight > 5)
                    {
                        color = ColorExtensions.GetColorFromHex("2d6a4f");
                    }
                    else if (cellHeight > 2)
                    {
                        color = ColorExtensions.GetColorFromHex("52b788");
                    }
                    else if (cellHeight > 0)
                    {
                        color = Color.yellow;
                    }
                    else
                    {
                        color = Color.blue;
                    }

                    map[x, z] = new Cell(x, z, cellHeight, color);
                }
            }

            Locate <ChunkManager>().RenderCells(map);
        }
    }
Beispiel #15
0
 public void InitializeServices()
 {
     foreach (var service in _services)
     {
         using (Instrumenter.Start(service.Key))
         {
             service.Value.Initialize();
         }
     }
 }
Beispiel #16
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()
            });
        }
Beispiel #17
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);
            }
        }
Beispiel #18
0
 // Start is called before the first frame update
 private void Start()
 {
     using (Instrumenter.Start())
     {
         for (int i = 0; i < Amount; i++)
         {
             var obj = Instantiate(ObjectToSpawn, transform);
             obj.transform.localPosition = new Vector3(Random.Range(1f, 100f), Random.Range(1f, 100f), Random.Range(1f, 100f));
         }
     }
 }
Beispiel #19
0
 public StormInstrumentationPass()
 {
     passName                 = "Storm instrumentation";
     pinfo                    = null;
     policy                   = null;
     vmgr                     = null;
     inst                     = null;
     tinfo_instrument         = new InsertionTrans();
     tinfo_async              = new InsertionTrans();
     blockExecutionContextMap = new Dictionary <string, int>();
 }
 public void ProcessInitializationQueue()
 {
     while (_initializationQueue.Count > 0)
     {
         var nextItem = _initializationQueue.Dequeue();
         var name     = nextItem.GetType().Name;
         using (Instrumenter.Start(name))
         {
             InitializeService(name, nextItem);
         }
     }
 }
Beispiel #21
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);
         }
     }
 }
Beispiel #22
0
        public IEnumerator ProcessServiceList()
        {
            foreach (var item in _services)
            {
                using (Instrumenter.Start(item.Key.Name))
                {
                    item.Value.Initialize();
                    _readyServices.Add(item.Key);
                    yield return(null);
                }
            }

            LogServices();
        }
Beispiel #23
0
        private bool InstrumentGate(IGate gate, string operation, object thing, Func <IGate, bool> function)
        {
            var payload = new InstrumentationPayload {
                FeatureName = Name,
                GateName    = gate.Name,
                Operation   = operation,
                Thing       = thing,
            };

            using (Instrumenter.InstrumentGate(payload))
            {
                var result = function(gate);
                payload.Result = result;
                return(result);
            }
        }
Beispiel #24
0
        public List <IStructure> GetStructuresLinkedTo(IStructure structure)
        {
            var network = new List <IStructure>();

            using (Instrumenter.Start())
            {
                var frontier = new Queue <Coord>();
                frontier.Enqueue(structure.Coord);

                var closed = new List <Coord>();
                while (frontier.Count > 0)
                {
                    var current = frontier.Dequeue();
                    if (closed.Contains(current))
                    {
                        continue;
                    }
                    closed.Add(current);

                    if (TryGetStructureAtCoord(current, out IStructure linkedStructure))
                    {
                        if (!network.Contains(linkedStructure))
                        {
                            network.Add(linkedStructure);
                        }

                        if (linkedStructure.Type == StructureDefinition.StructureType.Road || linkedStructure.Type == StructureDefinition.StructureType.Core)
                        {
                            if (_mapManager.TryGetCellAtCoord(linkedStructure.Coord, out Cell cell))
                            {
                                foreach (var linkedCell in cell.GetCardinalNeighbours())
                                {
                                    if (!closed.Contains(linkedCell.Coord))
                                    {
                                        frontier.Enqueue(linkedCell.Coord);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            return(network);
        }
        private InstrumenterTest CreateInstrumentor(bool fakeCoreLibModule = false, string[] attributesToIgnore = null, string[] excludedFiles = null, bool singleHit = false)
        {
            string module     = GetType().Assembly.Location;
            string pdb        = Path.Combine(Path.GetDirectoryName(module), Path.GetFileNameWithoutExtension(module) + ".pdb");
            string identifier = Guid.NewGuid().ToString();

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

            string destModule, destPdb;

            if (fakeCoreLibModule)
            {
                destModule = "System.Private.CoreLib.dll";
                destPdb    = "System.Private.CoreLib.pdb";
            }
            else
            {
                destModule = Path.GetFileName(module);
                destPdb    = Path.GetFileName(pdb);
            }

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

            InstrumentationHelper instrumentationHelper =
                new InstrumentationHelper(new ProcessExitHandler(), new RetryHelper(), new FileSystem(), new Mock <ILogger>().Object, new SourceRootTranslator(new Mock <ILogger>().Object, new FileSystem()));

            module = Path.Combine(directory.FullName, destModule);
            CoverageParameters parameters = new()
            {
                ExcludeAttributes       = attributesToIgnore,
                DoesNotReturnAttributes = new string[] { "DoesNotReturnAttribute" }
            };
            Instrumenter instrumenter = new Instrumenter(module, identifier, parameters, _mockLogger.Object, instrumentationHelper, new FileSystem(), new SourceRootTranslator(_mockLogger.Object, new FileSystem()), new CecilSymbolHelper());

            return(new InstrumenterTest
            {
                Instrumenter = instrumenter,
                Module = module,
                Identifier = identifier,
                Directory = directory
            });
        }
Beispiel #26
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);
        }
Beispiel #27
0
        public void SkipEmbeddedPpdbWithoutLocalSource()
        {
            string       xunitDll     = Directory.GetFiles(Directory.GetCurrentDirectory(), "xunit.*.dll").First();
            var          loggerMock   = new Mock <ILogger>();
            Instrumenter instrumenter = new Instrumenter(xunitDll, "_xunit_instrumented", Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), false, loggerMock.Object);

            Assert.True(InstrumentationHelper.HasPdb(xunitDll, out bool embedded));
            Assert.True(embedded);
            Assert.False(instrumenter.CanInstrument());
            loggerMock.Verify(l => l.LogWarning(It.IsAny <string>()));

            // Default case
            string coverletCoreDll = Directory.GetFiles(Directory.GetCurrentDirectory(), "coverlet.core.dll").First();

            instrumenter = new Instrumenter(coverletCoreDll, "_coverlet_core_instrumented", Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), Array.Empty <string>(), false, loggerMock.Object);
            Assert.True(InstrumentationHelper.HasPdb(coverletCoreDll, out embedded));
            Assert.False(embedded);
            Assert.True(instrumenter.CanInstrument());
            loggerMock.VerifyNoOtherCalls();
        }
Beispiel #28
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);
                }
            }
        }
Beispiel #29
0
        private InstrumenterTest CreateInstrumentor()
        {
            string module     = GetType().Assembly.Location;
            string pdb        = Path.Combine(Path.GetDirectoryName(module), Path.GetFileNameWithoutExtension(module) + ".pdb");
            string identifier = Guid.NewGuid().ToString();

            DirectoryInfo 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, Array.Empty <string>(), Array.Empty <string>());

            return(new InstrumenterTest
            {
                Instrumenter = instrumenter,
                Module = module,
                Identifier = identifier,
                Directory = directory
            });
        }
        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);
        }