diff --git a/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs b/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs index 59646e790..39fc57ecd 100644 --- a/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs +++ b/src/Microsoft.ComponentDetection.Common/CommandLineInvocationService.cs @@ -22,7 +22,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable additionalCandidateCommands = additionalCandidateCommands ?? Enumerable.Empty(); parameters = parameters ?? new string[0]; var allCommands = new[] { command }.Concat(additionalCandidateCommands); - if (!commandLocatableCache.TryGetValue(command, out string validCommand)) + if (!this.commandLocatableCache.TryGetValue(command, out string validCommand)) { foreach (var commandToTry in allCommands) { @@ -36,7 +36,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable if (result.ExitCode == 0) { - commandLocatableCache[command] = validCommand = commandToTry; + this.commandLocatableCache[command] = validCommand = commandToTry; break; } } @@ -53,7 +53,7 @@ public async Task CanCommandBeLocated(string command, IEnumerable public async Task ExecuteCommand(string command, IEnumerable additionalCandidateCommands = null, DirectoryInfo workingDirectory = null, params string[] parameters) { - var isCommandLocatable = await CanCommandBeLocated(command, additionalCandidateCommands); + var isCommandLocatable = await this.CanCommandBeLocated(command, additionalCandidateCommands); if (!isCommandLocatable) { throw new InvalidOperationException( @@ -68,7 +68,7 @@ public async Task ExecuteCommand(string command, IEn using var record = new CommandLineInvocationTelemetryRecord(); - var pathToRun = commandLocatableCache[command]; + var pathToRun = this.commandLocatableCache[command]; var joinedParameters = string.Join(" ", parameters); try { @@ -147,12 +147,12 @@ private static Task RunProcessAsync(string fileName, public async Task CanCommandBeLocated(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters) { - return await CanCommandBeLocated(command, additionalCandidateCommands, workingDirectory: null, parameters); + return await this.CanCommandBeLocated(command, additionalCandidateCommands, workingDirectory: null, parameters); } public async Task ExecuteCommand(string command, IEnumerable additionalCandidateCommands = null, params string[] parameters) { - return await ExecuteCommand(command, additionalCandidateCommands, workingDirectory: null, parameters); + return await this.ExecuteCommand(command, additionalCandidateCommands, workingDirectory: null, parameters); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs index d2009f071..82818660b 100644 --- a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs +++ b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs @@ -14,21 +14,21 @@ public class ComponentStreamEnumerable : IEnumerable public ComponentStreamEnumerable(IEnumerable fileEnumerable, ILogger logger) { - ToEnumerate = fileEnumerable; - Logger = logger; + this.ToEnumerate = fileEnumerable; + this.Logger = logger; } public IEnumerator GetEnumerator() { - foreach (var filePairing in ToEnumerate) + foreach (var filePairing in this.ToEnumerate) { if (!filePairing.File.Exists) { - Logger.LogWarning($"File {filePairing.File.FullName} does not exist on disk."); + this.Logger.LogWarning($"File {filePairing.File.FullName} does not exist on disk."); yield break; } - using var stream = SafeOpenFile(filePairing.File); + using var stream = this.SafeOpenFile(filePairing.File); if (stream == null) { @@ -41,7 +41,7 @@ public IEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator(); + return this.GetEnumerator(); } private Stream SafeOpenFile(FileInfo file) @@ -52,13 +52,13 @@ private Stream SafeOpenFile(FileInfo file) } catch (UnauthorizedAccessException) { - Logger.LogWarning($"Unauthorized access exception caught when trying to open {file.FullName}"); + this.Logger.LogWarning($"Unauthorized access exception caught when trying to open {file.FullName}"); return null; } catch (Exception e) { - Logger.LogWarning($"Unhandled exception caught when trying to open {file.FullName}"); - Logger.LogException(e, isError: false); + this.Logger.LogWarning($"Unhandled exception caught when trying to open {file.FullName}"); + this.Logger.LogException(e, isError: false); return null; } } diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs index 9f415a0e5..4949c7427 100644 --- a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs +++ b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs @@ -18,14 +18,14 @@ public class ComponentStreamEnumerableFactory : IComponentStreamEnumerableFactor public IEnumerable GetComponentStreams(DirectoryInfo directory, IEnumerable searchPatterns, ExcludeDirectoryPredicate directoryExclusionPredicate, bool recursivelyScanDirectories = true) { - SafeFileEnumerable enumerable = new SafeFileEnumerable(directory, searchPatterns, Logger, PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories); - return new ComponentStreamEnumerable(enumerable, Logger); + SafeFileEnumerable enumerable = new SafeFileEnumerable(directory, searchPatterns, this.Logger, this.PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories); + return new ComponentStreamEnumerable(enumerable, this.Logger); } public IEnumerable GetComponentStreams(DirectoryInfo directory, Func fileMatchingPredicate, ExcludeDirectoryPredicate directoryExclusionPredicate, bool recursivelyScanDirectories = true) { - SafeFileEnumerable enumerable = new SafeFileEnumerable(directory, fileMatchingPredicate, Logger, PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories); - return new ComponentStreamEnumerable(enumerable, Logger); + SafeFileEnumerable enumerable = new SafeFileEnumerable(directory, fileMatchingPredicate, this.Logger, this.PathUtilityService, directoryExclusionPredicate, recursivelyScanDirectories); + return new ComponentStreamEnumerable(enumerable, this.Logger); } } } diff --git a/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs b/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs index 3813aa4fd..b41645664 100644 --- a/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs +++ b/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs @@ -28,18 +28,18 @@ public ComponentRecorder(ILogger log = null, bool enableManualTrackingOfExplicit public TypedComponent GetComponent(string componentId) { - return singleFileRecorders.Select(x => x.GetComponent(componentId)?.Component).Where(x => x != null).FirstOrDefault(); + return this.singleFileRecorders.Select(x => x.GetComponent(componentId)?.Component).Where(x => x != null).FirstOrDefault(); } public IEnumerable GetDetectedComponents() { IEnumerable detectedComponents; - if (singleFileRecorders == null) + if (this.singleFileRecorders == null) { return Enumerable.Empty(); } - detectedComponents = singleFileRecorders + detectedComponents = this.singleFileRecorders .Select(singleFileRecorder => singleFileRecorder.GetDetectedComponents().Values) .SelectMany(x => x) .GroupBy(x => x.Component.Id) @@ -69,11 +69,11 @@ public ISingleFileComponentRecorder CreateSingleFileComponentRecorder(string loc throw new ArgumentNullException(nameof(location)); } - var matching = singleFileRecorders.FirstOrDefault(x => x.ManifestFileLocation == location); + var matching = this.singleFileRecorders.FirstOrDefault(x => x.ManifestFileLocation == location); if (matching == null) { - matching = new SingleFileComponentRecorder(location, this, enableManualTrackingOfExplicitReferences, log); - singleFileRecorders.Add(matching); + matching = new SingleFileComponentRecorder(location, this, this.enableManualTrackingOfExplicitReferences, this.log); + this.singleFileRecorders.Add(matching); } return matching; @@ -81,12 +81,12 @@ public ISingleFileComponentRecorder CreateSingleFileComponentRecorder(string loc internal DependencyGraph GetDependencyGraphForLocation(string location) { - return singleFileRecorders.Single(x => x.ManifestFileLocation == location).DependencyGraph; + return this.singleFileRecorders.Single(x => x.ManifestFileLocation == location).DependencyGraph; } public IReadOnlyDictionary GetDependencyGraphsByLocation() { - return singleFileRecorders.Where(x => x.DependencyGraph.HasComponents()) + return this.singleFileRecorders.Where(x => x.DependencyGraph.HasComponents()) .ToImmutableDictionary(x => x.ManifestFileLocation, x => x.DependencyGraph as IDependencyGraph); } @@ -98,7 +98,7 @@ public class SingleFileComponentRecorder : ISingleFileComponentRecorder internal DependencyGraph DependencyGraph { get; } - IDependencyGraph ISingleFileComponentRecorder.DependencyGraph => DependencyGraph; + IDependencyGraph ISingleFileComponentRecorder.DependencyGraph => this.DependencyGraph; private readonly ConcurrentDictionary detectedComponentsInternal = new ConcurrentDictionary(); @@ -108,15 +108,15 @@ public class SingleFileComponentRecorder : ISingleFileComponentRecorder public SingleFileComponentRecorder(string location, ComponentRecorder recorder, bool enableManualTrackingOfExplicitReferences, ILogger log) { - ManifestFileLocation = location; + this.ManifestFileLocation = location; this.recorder = recorder; this.log = log; - DependencyGraph = new DependencyGraph(enableManualTrackingOfExplicitReferences); + this.DependencyGraph = new DependencyGraph(enableManualTrackingOfExplicitReferences); } public DetectedComponent GetComponent(string componentId) { - if (detectedComponentsInternal.TryGetValue(componentId, out var detectedComponent)) + if (this.detectedComponentsInternal.TryGetValue(componentId, out var detectedComponent)) { return detectedComponent; } @@ -127,7 +127,7 @@ public DetectedComponent GetComponent(string componentId) public IReadOnlyDictionary GetDetectedComponents() { // Should this be immutable? - return detectedComponentsInternal; + return this.detectedComponentsInternal; } public void RegisterUsage( @@ -150,42 +150,42 @@ public void RegisterUsage( #if DEBUG if (detectedComponent.FilePaths?.Any() ?? false) { - log?.LogWarning("Detector should not populate DetectedComponent.FilePaths!"); + this.log?.LogWarning("Detector should not populate DetectedComponent.FilePaths!"); } if (detectedComponent.DependencyRoots?.Any() ?? false) { - log?.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!"); + this.log?.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!"); } if (detectedComponent.DevelopmentDependency.HasValue) { - log?.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!"); + this.log?.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!"); } #endif string componentId = detectedComponent.Component.Id; DetectedComponent storedComponent = null; - lock (registerUsageLock) + lock (this.registerUsageLock) { - storedComponent = detectedComponentsInternal.GetOrAdd(componentId, detectedComponent); - AddComponentToGraph(ManifestFileLocation, detectedComponent, isExplicitReferencedDependency, parentComponentId, isDevelopmentDependency, dependencyScope); + storedComponent = this.detectedComponentsInternal.GetOrAdd(componentId, detectedComponent); + this.AddComponentToGraph(this.ManifestFileLocation, detectedComponent, isExplicitReferencedDependency, parentComponentId, isDevelopmentDependency, dependencyScope); } } public void AddAdditionalRelatedFile(string relatedFilePath) { - DependencyGraph.AddAdditionalRelatedFile(relatedFilePath); + this.DependencyGraph.AddAdditionalRelatedFile(relatedFilePath); } public IList GetAdditionalRelatedFiles() { - return DependencyGraph.GetAdditionalRelatedFiles().ToImmutableList(); + return this.DependencyGraph.GetAdditionalRelatedFiles().ToImmutableList(); } public IComponentRecorder GetParentComponentRecorder() { - return recorder; + return this.recorder; } private void AddComponentToGraph( @@ -204,7 +204,7 @@ private void AddComponentToGraph( DependencyScope = dependencyScope, }; - DependencyGraph.AddComponent(componentNode, parentComponentId); + this.DependencyGraph.AddComponent(componentNode, parentComponentId); } } } diff --git a/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs b/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs index b7360c05d..0d4175a36 100644 --- a/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs +++ b/src/Microsoft.ComponentDetection.Common/DependencyGraph/DependencyGraph.cs @@ -21,7 +21,7 @@ internal class DependencyGraph : IDependencyGraph public DependencyGraph(bool enableManualTrackingOfExplicitReferences) { - componentNodes = new ConcurrentDictionary(); + this.componentNodes = new ConcurrentDictionary(); this.enableManualTrackingOfExplicitReferences = enableManualTrackingOfExplicitReferences; } @@ -37,7 +37,7 @@ public void AddComponent(ComponentRefNode componentNode, string parentComponentI throw new ArgumentNullException(nameof(componentNode.Id)); } - componentNodes.AddOrUpdate(componentNode.Id, componentNode, (key, currentNode) => + this.componentNodes.AddOrUpdate(componentNode.Id, componentNode, (key, currentNode) => { currentNode.IsExplicitReferencedDependency |= componentNode.IsExplicitReferencedDependency; @@ -55,17 +55,17 @@ public void AddComponent(ComponentRefNode componentNode, string parentComponentI return currentNode; }); - AddDependency(componentNode.Id, parentComponentId); + this.AddDependency(componentNode.Id, parentComponentId); } public bool Contains(string componentId) { - return componentNodes.ContainsKey(componentId); + return this.componentNodes.ContainsKey(componentId); } public ICollection GetDependenciesForComponent(string componentId) { - return componentNodes[componentId].DependencyIds; + return this.componentNodes[componentId].DependencyIds; } public ICollection GetExplicitReferencedDependencyIds(string componentId) @@ -75,53 +75,53 @@ public ICollection GetExplicitReferencedDependencyIds(string componentId throw new ArgumentNullException(nameof(componentId)); } - if (!componentNodes.TryGetValue(componentId, out var componentRef)) + if (!this.componentNodes.TryGetValue(componentId, out var componentRef)) { throw new ArgumentException(string.Format(Resources.MissingNodeInDependencyGraph, componentId), paramName: nameof(componentId)); } IList explicitReferencedDependencyIds = new List(); - GetExplicitReferencedDependencies(componentRef, explicitReferencedDependencyIds, new HashSet()); + this.GetExplicitReferencedDependencies(componentRef, explicitReferencedDependencyIds, new HashSet()); return explicitReferencedDependencyIds; } public void AddAdditionalRelatedFile(string additionalRelatedFile) { - AdditionalRelatedFiles.AddOrUpdate(additionalRelatedFile, 0, (notUsed, notUsed2) => 0); + this.AdditionalRelatedFiles.AddOrUpdate(additionalRelatedFile, 0, (notUsed, notUsed2) => 0); } public HashSet GetAdditionalRelatedFiles() { - return AdditionalRelatedFiles.Keys.ToImmutableHashSet().ToHashSet(); + return this.AdditionalRelatedFiles.Keys.ToImmutableHashSet().ToHashSet(); } public bool HasComponents() { - return componentNodes.Count > 0; + return this.componentNodes.Count > 0; } public bool? IsDevelopmentDependency(string componentId) { - return componentNodes[componentId].IsDevelopmentDependency; + return this.componentNodes[componentId].IsDevelopmentDependency; } public DependencyScope? GetDependencyScope(string componentId) { - return componentNodes[componentId].DependencyScope; + return this.componentNodes[componentId].DependencyScope; } public IEnumerable GetAllExplicitlyReferencedComponents() { - return componentNodes.Values - .Where(componentRefNode => IsExplicitReferencedDependency(componentRefNode)) + return this.componentNodes.Values + .Where(componentRefNode => this.IsExplicitReferencedDependency(componentRefNode)) .Select(componentRefNode => componentRefNode.Id); } private void GetExplicitReferencedDependencies(ComponentRefNode component, IList explicitReferencedDependencyIds, ISet visited) { - if (IsExplicitReferencedDependency(component)) + if (this.IsExplicitReferencedDependency(component)) { explicitReferencedDependencyIds.Add(component.Id); } @@ -132,15 +132,15 @@ private void GetExplicitReferencedDependencies(ComponentRefNode component, IList { if (!visited.Contains(parentId)) { - GetExplicitReferencedDependencies(componentNodes[parentId], explicitReferencedDependencyIds, visited); + this.GetExplicitReferencedDependencies(this.componentNodes[parentId], explicitReferencedDependencyIds, visited); } } } private bool IsExplicitReferencedDependency(ComponentRefNode component) { - return (enableManualTrackingOfExplicitReferences && component.IsExplicitReferencedDependency) || - (!enableManualTrackingOfExplicitReferences && !component.DependedOnByIds.Any()); + return (this.enableManualTrackingOfExplicitReferences && component.IsExplicitReferencedDependency) || + (!this.enableManualTrackingOfExplicitReferences && !component.DependedOnByIds.Any()); } private void AddDependency(string componentId, string parentComponentId) @@ -150,28 +150,28 @@ private void AddDependency(string componentId, string parentComponentId) return; } - if (!componentNodes.TryGetValue(parentComponentId, out var parentComponentRefNode)) + if (!this.componentNodes.TryGetValue(parentComponentId, out var parentComponentRefNode)) { throw new ArgumentException(string.Format(Resources.MissingNodeInDependencyGraph, parentComponentId), nameof(parentComponentId)); } parentComponentRefNode.DependencyIds.Add(componentId); - componentNodes[componentId].DependedOnByIds.Add(parentComponentId); + this.componentNodes[componentId].DependedOnByIds.Add(parentComponentId); } IEnumerable IDependencyGraph.GetDependenciesForComponent(string componentId) { - return GetDependenciesForComponent(componentId).ToImmutableList(); + return this.GetDependenciesForComponent(componentId).ToImmutableList(); } IEnumerable IDependencyGraph.GetComponents() { - return componentNodes.Keys.ToImmutableList(); + return this.componentNodes.Keys.ToImmutableList(); } bool IDependencyGraph.IsComponentExplicitlyReferenced(string componentId) { - return IsExplicitReferencedDependency(componentNodes[componentId]); + return this.IsExplicitReferencedDependency(this.componentNodes[componentId]); } internal class ComponentRefNode @@ -190,8 +190,8 @@ internal class ComponentRefNode internal ComponentRefNode() { - DependencyIds = new HashSet(); - DependedOnByIds = new HashSet(); + this.DependencyIds = new HashSet(); + this.DependedOnByIds = new HashSet(); } } } diff --git a/src/Microsoft.ComponentDetection.Common/DockerService.cs b/src/Microsoft.ComponentDetection.Common/DockerService.cs index 66d08276f..20c1606f8 100644 --- a/src/Microsoft.ComponentDetection.Common/DockerService.cs +++ b/src/Microsoft.ComponentDetection.Common/DockerService.cs @@ -37,7 +37,7 @@ public async Task CanPingDockerAsync(CancellationToken cancellationToken = } catch (Exception e) { - Logger.LogException(e, false); + this.Logger.LogException(e, false); return false; } } @@ -45,7 +45,7 @@ public async Task CanPingDockerAsync(CancellationToken cancellationToken = public async Task CanRunLinuxContainersAsync(CancellationToken cancellationToken = default) { using var record = new DockerServiceSystemInfoTelemetryRecord(); - if (!await CanPingDockerAsync(cancellationToken)) + if (!await this.CanPingDockerAsync(cancellationToken)) { return false; } @@ -165,7 +165,7 @@ public async Task InspectImageAsync(string image, Cancellation Image = image, Command = JsonConvert.SerializeObject(command), }; - await TryPullImageAsync(image, cancellationToken); + await this.TryPullImageAsync(image, cancellationToken); var container = await CreateContainerAsync(image, command, cancellationToken); record.Container = JsonConvert.SerializeObject(container); var stream = await AttachContainerAsync(container.ID, cancellationToken); diff --git a/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs b/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs index 223e7942b..5170c4428 100644 --- a/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs +++ b/src/Microsoft.ComponentDetection.Common/EnvironmentVariableService.cs @@ -10,7 +10,7 @@ public class EnvironmentVariableService : IEnvironmentVariableService { public bool DoesEnvironmentVariableExist(string name) { - return GetEnvironmentVariable(name) != null; + return this.GetEnvironmentVariable(name) != null; } public string GetEnvironmentVariable(string name) @@ -27,7 +27,7 @@ public string GetEnvironmentVariable(string name) public bool IsEnvironmentVariableValueTrue(string name) { - _ = bool.TryParse(GetEnvironmentVariable(name), out bool result); + _ = bool.TryParse(this.GetEnvironmentVariable(name), out bool result); return result; } } diff --git a/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs b/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs index 8ce3c554a..d7e9dacdb 100644 --- a/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs +++ b/src/Microsoft.ComponentDetection.Common/FastDirectoryWalkerFactory.cs @@ -34,7 +34,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu { if (!root.Exists) { - Logger?.LogError($"Root directory doesn't exist: {root.FullName}"); + this.Logger?.LogError($"Root directory doesn't exist: {root.FullName}"); s.OnCompleted(); return Task.CompletedTask; } @@ -52,7 +52,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu var sw = Stopwatch.StartNew(); - Logger?.LogInfo($"Starting enumeration of {root.FullName}"); + this.Logger?.LogInfo($"Starting enumeration of {root.FullName}"); var fileCount = 0; var directoryCount = 0; @@ -73,7 +73,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu if (di.Attributes.HasFlag(FileAttributes.ReparsePoint)) { - var realPath = PathUtilityService.ResolvePhysicalPath(di.FullName); + var realPath = this.PathUtilityService.ResolvePhysicalPath(di.FullName); realDirectory = new DirectoryInfo(realPath); } @@ -91,7 +91,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu return true; }); - var initialIterator = new FileSystemEnumerable(root.FullName, Transform, new EnumerationOptions() + var initialIterator = new FileSystemEnumerable(root.FullName, this.Transform, new EnumerationOptions() { RecurseSubdirectories = false, IgnoreInaccessible = true, @@ -145,7 +145,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu var scan = new ActionBlock( di => { - var enumerator = new FileSystemEnumerable(di.FullName, Transform, new EnumerationOptions() + var enumerator = new FileSystemEnumerable(di.FullName, this.Transform, new EnumerationOptions() { RecurseSubdirectories = true, IgnoreInaccessible = true, @@ -188,7 +188,7 @@ public IObservable GetDirectoryScanner(DirectoryInfo root, Concu }, () => { sw.Stop(); - Logger?.LogInfo($"Enumerated {fileCount} files and {directoryCount} directories in {sw.Elapsed}"); + this.Logger?.LogInfo($"Enumerated {fileCount} files and {directoryCount} directories in {sw.Elapsed}"); s.OnCompleted(); }); }); @@ -201,13 +201,13 @@ private FileSystemInfo Transform(ref FileSystemEntry entry) private IObservable CreateDirectoryWalker(DirectoryInfo di, ExcludeDirectoryPredicate directoryExclusionPredicate, int minimumConnectionCount, IEnumerable filePatterns) { - return GetDirectoryScanner(di, new ConcurrentDictionary(), directoryExclusionPredicate, filePatterns, true).Replay() // Returns a replay subject which will republish anything found to new subscribers. + return this.GetDirectoryScanner(di, new ConcurrentDictionary(), directoryExclusionPredicate, filePatterns, true).Replay() // Returns a replay subject which will republish anything found to new subscribers. .AutoConnect(minimumConnectionCount); // Specifies that this connectable observable should start when minimumConnectionCount subscribe. } private bool MatchesAnyPattern(FileInfo fi, params string[] searchPatterns) { - return searchPatterns != null && searchPatterns.Any(sp => PathUtilityService.MatchesPattern(sp, fi.Name)); + return searchPatterns != null && searchPatterns.Any(sp => this.PathUtilityService.MatchesPattern(sp, fi.Name)); } /// @@ -219,22 +219,22 @@ private bool MatchesAnyPattern(FileInfo fi, params string[] searchPatterns) /// Pattern used to filter files. public void Initialize(DirectoryInfo root, ExcludeDirectoryPredicate directoryExclusionPredicate, int minimumConnectionCount, IEnumerable filePatterns = null) { - pendingScans.GetOrAdd(root, new Lazy>(() => CreateDirectoryWalker(root, directoryExclusionPredicate, minimumConnectionCount, filePatterns))); + this.pendingScans.GetOrAdd(root, new Lazy>(() => this.CreateDirectoryWalker(root, directoryExclusionPredicate, minimumConnectionCount, filePatterns))); } public IObservable Subscribe(DirectoryInfo root, IEnumerable patterns) { var patternArray = patterns.ToArray(); - if (pendingScans.TryGetValue(root, out var scannerObservable)) + if (this.pendingScans.TryGetValue(root, out var scannerObservable)) { - Logger.LogVerbose(string.Join(":", patterns)); + this.Logger.LogVerbose(string.Join(":", patterns)); var inner = scannerObservable.Value.Where(fsi => { if (fsi is FileInfo fi) { - return MatchesAnyPattern(fi, patternArray); + return this.MatchesAnyPattern(fi, patternArray); } else { @@ -250,7 +250,7 @@ public IObservable Subscribe(DirectoryInfo root, IEnumerable GetFilteredComponentStreamObservable(DirectoryInfo root, IEnumerable patterns, IComponentRecorder componentRecorder) { - var observable = Subscribe(root, patterns).OfType().SelectMany(f => patterns.Select(sp => new + var observable = this.Subscribe(root, patterns).OfType().SelectMany(f => patterns.Select(sp => new { SearchPattern = sp, File = f, @@ -259,11 +259,11 @@ public IObservable GetFilteredComponentStreamObservable(Director var searchPattern = x.SearchPattern; var fileName = x.File.Name; - return PathUtilityService.MatchesPattern(searchPattern, fileName); + return this.PathUtilityService.MatchesPattern(searchPattern, fileName); }).Where(x => x.File.Exists) .Select(x => { - var lazyComponentStream = new LazyComponentStream(x.File, x.SearchPattern, Logger); + var lazyComponentStream = new LazyComponentStream(x.File, x.SearchPattern, this.Logger); return new ProcessRequest { ComponentStream = lazyComponentStream, @@ -276,7 +276,7 @@ public IObservable GetFilteredComponentStreamObservable(Director public void StartScan(DirectoryInfo root) { - if (pendingScans.TryRemove(root, out var scannerObservable)) + if (this.pendingScans.TryRemove(root, out var scannerObservable)) { // scannerObservable.Connect(); } @@ -286,7 +286,7 @@ public void StartScan(DirectoryInfo root) public void Reset() { - pendingScans.Clear(); + this.pendingScans.Clear(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/FileWritingService.cs b/src/Microsoft.ComponentDetection.Common/FileWritingService.cs index a39b47211..fc44ad6e6 100644 --- a/src/Microsoft.ComponentDetection.Common/FileWritingService.cs +++ b/src/Microsoft.ComponentDetection.Common/FileWritingService.cs @@ -23,14 +23,14 @@ public void Init(string basePath) throw new InvalidUserInputException($"The path {basePath} does not exist.", new DirectoryNotFoundException()); } - BasePath = string.IsNullOrEmpty(basePath) ? Path.GetTempPath() : basePath; + this.BasePath = string.IsNullOrEmpty(basePath) ? Path.GetTempPath() : basePath; } public void AppendToFile(string relativeFilePath, string text) { - relativeFilePath = ResolveFilePath(relativeFilePath); + relativeFilePath = this.ResolveFilePath(relativeFilePath); - lock (lockObject) + lock (this.lockObject) { File.AppendAllText(relativeFilePath, text); } @@ -38,9 +38,9 @@ public void AppendToFile(string relativeFilePath, string text) public void WriteFile(string relativeFilePath, string text) { - relativeFilePath = ResolveFilePath(relativeFilePath); + relativeFilePath = this.ResolveFilePath(relativeFilePath); - lock (lockObject) + lock (this.lockObject) { File.WriteAllText(relativeFilePath, text); } @@ -53,19 +53,19 @@ public void WriteFile(FileInfo absolutePath, string text) public string ResolveFilePath(string relativeFilePath) { - EnsureInit(); + this.EnsureInit(); if (relativeFilePath.Contains("{timestamp}")) { - relativeFilePath = relativeFilePath.Replace("{timestamp}", timestamp); + relativeFilePath = relativeFilePath.Replace("{timestamp}", this.timestamp); } - relativeFilePath = Path.Combine(BasePath, relativeFilePath); + relativeFilePath = Path.Combine(this.BasePath, relativeFilePath); return relativeFilePath; } private void EnsureInit() { - if (string.IsNullOrEmpty(BasePath)) + if (string.IsNullOrEmpty(this.BasePath)) { throw new InvalidOperationException("Base path has not yet been initialized in File Writing Service!"); } diff --git a/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs b/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs index 5b15d112d..1baae8558 100644 --- a/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs +++ b/src/Microsoft.ComponentDetection.Common/LazyComponentStream.cs @@ -14,21 +14,21 @@ private byte[] SafeOpenFile() { try { - using var fs = fileInfo.OpenRead(); + using var fs = this.fileInfo.OpenRead(); - var buffer = new byte[fileInfo.Length]; - fs.Read(buffer, 0, (int)fileInfo.Length); + var buffer = new byte[this.fileInfo.Length]; + fs.Read(buffer, 0, (int)this.fileInfo.Length); return buffer; } catch (UnauthorizedAccessException) { - logger?.LogWarning($"Unauthorized access exception caught when trying to open {fileInfo.FullName}"); + this.logger?.LogWarning($"Unauthorized access exception caught when trying to open {this.fileInfo.FullName}"); } catch (Exception e) { - logger?.LogWarning($"Unhandled exception caught when trying to open {fileInfo.FullName}"); - logger?.LogException(e, isError: false); + this.logger?.LogWarning($"Unhandled exception caught when trying to open {this.fileInfo.FullName}"); + this.logger?.LogException(e, isError: false); } return new byte[0]; @@ -36,14 +36,14 @@ private byte[] SafeOpenFile() public LazyComponentStream(FileInfo fileInfo, string pattern, ILogger logger) { - Pattern = pattern; - Location = fileInfo.FullName; + this.Pattern = pattern; + this.Location = fileInfo.FullName; this.fileInfo = fileInfo; this.logger = logger; - fileBuffer = new Lazy(SafeOpenFile); + this.fileBuffer = new Lazy(this.SafeOpenFile); } - public Stream Stream => new MemoryStream(fileBuffer.Value); + public Stream Stream => new MemoryStream(this.fileBuffer.Value); public string Pattern { get; set; } diff --git a/src/Microsoft.ComponentDetection.Common/Logger.cs b/src/Microsoft.ComponentDetection.Common/Logger.cs index fc2977e63..4fa1cb6ee 100644 --- a/src/Microsoft.ComponentDetection.Common/Logger.cs +++ b/src/Microsoft.ComponentDetection.Common/Logger.cs @@ -27,45 +27,45 @@ public class Logger : ILogger public void Init(VerbosityMode verbosity) { - WriteToFile = true; - Verbosity = verbosity; + this.WriteToFile = true; + this.Verbosity = verbosity; try { - FileWritingService.WriteFile(LogRelativePath, string.Empty); - LogInfo($"Log file: {FileWritingService.ResolveFilePath(LogRelativePath)}"); + this.FileWritingService.WriteFile(LogRelativePath, string.Empty); + this.LogInfo($"Log file: {this.FileWritingService.ResolveFilePath(LogRelativePath)}"); } catch (Exception) { - WriteToFile = false; - LogError("There was an issue writing to the log file, for the remainder of execution verbose output will be written to the console."); - Verbosity = VerbosityMode.Verbose; + this.WriteToFile = false; + this.LogError("There was an issue writing to the log file, for the remainder of execution verbose output will be written to the console."); + this.Verbosity = VerbosityMode.Verbose; } } public void LogCreateLoggingGroup() { - PrintToConsole(NewLine, VerbosityMode.Normal); - AppendToFile(NewLine); + this.PrintToConsole(NewLine, VerbosityMode.Normal); + this.AppendToFile(NewLine); } public void LogWarning(string message) { - LogInternal("WARN", message); + this.LogInternal("WARN", message); } public void LogInfo(string message) { - LogInternal("INFO", message); + this.LogInternal("INFO", message); } public void LogVerbose(string message) { - LogInternal("VERBOSE", message, VerbosityMode.Verbose); + this.LogInternal("VERBOSE", message, VerbosityMode.Verbose); } public void LogError(string message) { - LogInternal("ERROR", message, VerbosityMode.Quiet); + this.LogInternal("ERROR", message, VerbosityMode.Quiet); } private void LogInternal(string prefix, string message, VerbosityMode verbosity = VerbosityMode.Normal) @@ -73,15 +73,15 @@ private void LogInternal(string prefix, string message, VerbosityMode verbosity var formattedPrefix = string.IsNullOrWhiteSpace(prefix) ? string.Empty : $"[{prefix}] "; var text = $"{formattedPrefix}{message} {NewLine}"; - PrintToConsole(text, verbosity); - AppendToFile(text); + this.PrintToConsole(text, verbosity); + this.AppendToFile(text); } public void LogFailedReadingFile(string filePath, Exception e) { - PrintToConsole(NewLine, VerbosityMode.Verbose); - LogFailedProcessingFile(filePath); - LogException(e, isError: false); + this.PrintToConsole(NewLine, VerbosityMode.Verbose); + this.LogFailedProcessingFile(filePath); + this.LogException(e, isError: false); using var record = new FailedReadingFileRecord { FilePath = filePath, @@ -109,45 +109,45 @@ public void LogException( if (isError) { - PrintToConsole(consoleText, VerbosityMode.Quiet); + this.PrintToConsole(consoleText, VerbosityMode.Quiet); } else { - PrintToConsole(consoleText, VerbosityMode.Verbose); + this.PrintToConsole(consoleText, VerbosityMode.Verbose); } - AppendToFile(fullExceptionText); + this.AppendToFile(fullExceptionText); } // TODO: All these vso specific logs should go away public void LogBuildWarning(string message) { - PrintToConsole($"##vso[task.LogIssue type=warning;]{message}{NewLine}", VerbosityMode.Quiet); + this.PrintToConsole($"##vso[task.LogIssue type=warning;]{message}{NewLine}", VerbosityMode.Quiet); } public void LogBuildError(string message) { - PrintToConsole($"##vso[task.LogIssue type=error;]{message}{NewLine}", VerbosityMode.Quiet); + this.PrintToConsole($"##vso[task.LogIssue type=error;]{message}{NewLine}", VerbosityMode.Quiet); } private void LogFailedProcessingFile(string filePath) { - LogVerbose($"Could not read component details from file {filePath} {NewLine}"); + this.LogVerbose($"Could not read component details from file {filePath} {NewLine}"); } private void AppendToFile(string text) { - if (WriteToFile) + if (this.WriteToFile) { - FileWritingService.AppendToFile(LogRelativePath, text); + this.FileWritingService.AppendToFile(LogRelativePath, text); } } private void PrintToConsole(string text, VerbosityMode minVerbosity) { - if (Verbosity >= minVerbosity) + if (this.Verbosity >= minVerbosity) { - ConsoleWriter.Write(text); + this.ConsoleWriter.Write(text); } } } diff --git a/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs b/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs index 4a93e88ea..c507599de 100644 --- a/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs +++ b/src/Microsoft.ComponentDetection.Common/PathUtilityService.cs @@ -34,18 +34,18 @@ public bool IsRunningOnWindowsContainer { get { - if (!isRunningOnWindowsContainer.HasValue) + if (!this.isRunningOnWindowsContainer.HasValue) { - lock (isRunningOnWindowsContainerLock) + lock (this.isRunningOnWindowsContainerLock) { - if (!isRunningOnWindowsContainer.HasValue) + if (!this.isRunningOnWindowsContainer.HasValue) { - isRunningOnWindowsContainer = CheckIfRunningOnWindowsContainer(); + this.isRunningOnWindowsContainer = this.CheckIfRunningOnWindowsContainer(); } } } - return isRunningOnWindowsContainer.Value; + return this.isRunningOnWindowsContainer.Value; } } @@ -113,11 +113,11 @@ public string ResolvePhysicalPath(string path) { if (IsWindows) { - return ResolvePhysicalPathWindows(path); + return this.ResolvePhysicalPathWindows(path); } else if (IsLinux) { - return ResolvePhysicalPathLinux(path); + return this.ResolvePhysicalPathLinux(path); } return path; @@ -130,12 +130,12 @@ public string ResolvePhysicalPathWindows(string path) throw new PlatformNotSupportedException("Attempted to call a function that makes windows-only SDK calls"); } - if (IsRunningOnWindowsContainer) + if (this.IsRunningOnWindowsContainer) { return path; } - if (resolvedPaths.TryGetValue(path, out string cachedPath)) + if (this.resolvedPaths.TryGetValue(path, out string cachedPath)) { return cachedPath; } @@ -168,7 +168,7 @@ public string ResolvePhysicalPathWindows(string path) result = result.StartsWith(LongPathPrefix) ? result.Substring(LongPathPrefix.Length) : result; - resolvedPaths.TryAdd(path, result); + this.resolvedPaths.TryAdd(path, result); return result; } @@ -197,7 +197,7 @@ public string ResolvePhysicalPathLinux(string path) } catch (Exception ex) { - Logger.LogException(ex, isError: false, printException: true); + this.Logger.LogException(ex, isError: false, printException: true); return path; } finally @@ -244,7 +244,7 @@ private bool CheckIfRunningOnWindowsContainer() if (sb.ToString().Contains("Container Execution Agent")) { - Logger.LogWarning("Detected execution in a Windows container. Currently windows containers < 1809 do not support symlinks well, so disabling symlink resolution/dedupe behavior"); + this.Logger.LogWarning("Detected execution in a Windows container. Currently windows containers < 1809 do not support symlinks well, so disabling symlink resolution/dedupe behavior"); return true; } else diff --git a/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs b/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs index e299f3e00..ca9625104 100644 --- a/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs +++ b/src/Microsoft.ComponentDetection.Common/PatternMatchingUtility.cs @@ -12,11 +12,11 @@ public static class PatternMatchingUtility public static FilePatternMatcher GetFilePatternMatcher(IEnumerable patterns) { - var ordinalComparison = Expression.Constant(System.StringComparison.Ordinal, typeof(System.StringComparison)); - var asSpan = typeof(System.MemoryExtensions).GetMethod("AsSpan", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(string) }, new ParameterModifier[0]); - var equals = typeof(System.MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]); - var startsWith = typeof(System.MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]); - var endsWith = typeof(System.MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(System.StringComparison) }, new ParameterModifier[0]); + var ordinalComparison = Expression.Constant(StringComparison.Ordinal, typeof(StringComparison)); + var asSpan = typeof(MemoryExtensions).GetMethod("AsSpan", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(string) }, new ParameterModifier[0]); + var equals = typeof(MemoryExtensions).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]); + var startsWith = typeof(MemoryExtensions).GetMethod("StartsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]); + var endsWith = typeof(MemoryExtensions).GetMethod("EndsWith", BindingFlags.Public | BindingFlags.Static, null, CallingConventions.Standard, new[] { typeof(ReadOnlySpan), typeof(ReadOnlySpan), typeof(StringComparison) }, new ParameterModifier[0]); var predicates = new List(); var left = Expression.Parameter(typeof(ReadOnlySpan), "fileName"); @@ -53,4 +53,4 @@ public static FilePatternMatcher GetFilePatternMatcher(IEnumerable patte return func; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs index 3cee65b90..6e2aef8e9 100644 --- a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs +++ b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerable.cs @@ -29,9 +29,9 @@ public SafeFileEnumerable(DirectoryInfo directory, IEnumerable searchPat this.directoryExclusionPredicate = directoryExclusionPredicate; this.recursivelyScanDirectories = recursivelyScanDirectories; this.pathUtilityService = pathUtilityService; - enumeratedDirectories = previouslyEnumeratedDirectories; + this.enumeratedDirectories = previouslyEnumeratedDirectories; - enumerationOptions = new EnumerationOptions() + this.enumerationOptions = new EnumerationOptions() { IgnoreInaccessible = true, RecurseSubdirectories = this.recursivelyScanDirectories, @@ -48,9 +48,9 @@ public SafeFileEnumerable(DirectoryInfo directory, Func fileMatc public IEnumerator GetEnumerator() { - var previouslyEnumeratedDirectories = enumeratedDirectories ?? new HashSet(); + var previouslyEnumeratedDirectories = this.enumeratedDirectories ?? new HashSet(); - var fse = new FileSystemEnumerable(directory.FullName, (ref FileSystemEntry entry) => + var fse = new FileSystemEnumerable(this.directory.FullName, (ref FileSystemEntry entry) => { if (!(entry.ToFileSystemInfo() is FileInfo fi)) { @@ -58,7 +58,7 @@ public IEnumerator GetEnumerator() } var foundPattern = entry.FileName.ToString(); - foreach (var searchPattern in searchPatterns) + foreach (var searchPattern in this.searchPatterns) { if (PathUtilityService.MatchesPattern(searchPattern, ref entry)) { @@ -67,7 +67,7 @@ public IEnumerator GetEnumerator() } return new MatchedFile() { File = fi, Pattern = foundPattern }; - }, enumerationOptions) + }, this.enumerationOptions) { ShouldIncludePredicate = (ref FileSystemEntry entry) => { @@ -76,7 +76,7 @@ public IEnumerator GetEnumerator() return false; } - foreach (var searchPattern in searchPatterns) + foreach (var searchPattern in this.searchPatterns) { if (PathUtilityService.MatchesPattern(searchPattern, ref entry)) { @@ -88,7 +88,7 @@ public IEnumerator GetEnumerator() }, ShouldRecursePredicate = (ref FileSystemEntry entry) => { - if (!recursivelyScanDirectories) + if (!this.recursivelyScanDirectories) { return false; } @@ -99,7 +99,7 @@ public IEnumerator GetEnumerator() if (entry.Attributes.HasFlag(FileAttributes.ReparsePoint)) { - var realPath = pathUtilityService.ResolvePhysicalPath(targetPath); + var realPath = this.pathUtilityService.ResolvePhysicalPath(targetPath); seenPreviously = previouslyEnumeratedDirectories.Contains(realPath); previouslyEnumeratedDirectories.Add(realPath); @@ -118,12 +118,12 @@ public IEnumerator GetEnumerator() if (seenPreviously) { - logger.LogVerbose($"Encountered real path {targetPath} before. Short-Circuiting directory traversal"); + this.logger.LogVerbose($"Encountered real path {targetPath} before. Short-Circuiting directory traversal"); return false; } // This is actually a *directory* name (not FileName) and the directory containing that directory. - if (entry.IsDirectory && directoryExclusionPredicate != null && directoryExclusionPredicate(entry.FileName, entry.Directory)) + if (entry.IsDirectory && this.directoryExclusionPredicate != null && this.directoryExclusionPredicate(entry.FileName, entry.Directory)) { return false; } @@ -134,7 +134,7 @@ public IEnumerator GetEnumerator() foreach (var file in fse) { - if (fileMatchingPredicate == null || fileMatchingPredicate(file.File)) + if (this.fileMatchingPredicate == null || this.fileMatchingPredicate(file.File)) { yield return file; } @@ -143,7 +143,7 @@ public IEnumerator GetEnumerator() IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator(); + return this.GetEnumerator(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs index 541793b08..b528d73c9 100644 --- a/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs +++ b/src/Microsoft.ComponentDetection.Common/SafeFileEnumerableFactory.cs @@ -17,7 +17,7 @@ public class SafeFileEnumerableFactory : ISafeFileEnumerableFactory public IEnumerable CreateSafeFileEnumerable(DirectoryInfo directory, IEnumerable searchPatterns, ExcludeDirectoryPredicate directoryExclusionPredicate) { - return new SafeFileEnumerable(directory, searchPatterns, Logger, PathUtilityService, directoryExclusionPredicate); + return new SafeFileEnumerable(directory, searchPatterns, this.Logger, this.PathUtilityService, directoryExclusionPredicate); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs b/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs index a6e1c5260..2dfce3163 100644 --- a/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs +++ b/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs @@ -19,7 +19,7 @@ public class TabularStringFormat public TabularStringFormat(IList columns, char horizontalLineChar = DefaultHorizontalLineChar, char verticalLineChar = DefaultVerticalLineChar, string tableTitle = null) { this.columns = columns; - totalWidth = columns.Count + 1 + columns.Sum(x => x.Width); + this.totalWidth = columns.Count + 1 + columns.Sum(x => x.Width); this.horizontalLineChar = horizontalLineChar; this.verticalLineChar = verticalLineChar; this.tableTitle = tableTitle; @@ -28,39 +28,39 @@ public TabularStringFormat(IList columns, char horizontalLineChar = Defa public string GenerateString(IEnumerable> rows) { StringBuilder sb = new StringBuilder(); - if (!string.IsNullOrWhiteSpace(tableTitle)) + if (!string.IsNullOrWhiteSpace(this.tableTitle)) { - PrintTitleSection(sb); + this.PrintTitleSection(sb); } else { - WriteFlatLine(sb, false); + this.WriteFlatLine(sb, false); } - sb.Append(verticalLineChar); - foreach (var column in columns) + sb.Append(this.verticalLineChar); + foreach (var column in this.columns) { sb.Append(column.Header.PadRight(column.Width)); - sb.Append(verticalLineChar); + sb.Append(this.verticalLineChar); } - WriteFlatLine(sb); + this.WriteFlatLine(sb); foreach (var row in rows) { - sb.Append(verticalLineChar); - if (row.Count != columns.Count) + sb.Append(this.verticalLineChar); + if (row.Count != this.columns.Count) { throw new InvalidOperationException("All rows must have length equal to the number of columns present."); } - for (var i = 0; i < columns.Count; i++) + for (var i = 0; i < this.columns.Count; i++) { - var dataString = columns[i].Format != null ? string.Format(columns[i].Format, row[i]) : row[i].ToString(); - sb.Append(dataString.PadRight(columns[i].Width)); - sb.Append(verticalLineChar); + var dataString = this.columns[i].Format != null ? string.Format(this.columns[i].Format, row[i]) : row[i].ToString(); + sb.Append(dataString.PadRight(this.columns[i].Width)); + sb.Append(this.verticalLineChar); } - WriteFlatLine(sb); + this.WriteFlatLine(sb); } return sb.ToString(); @@ -68,37 +68,37 @@ public string GenerateString(IEnumerable> rows) private void PrintTitleSection(StringBuilder sb) { - WriteFlatLine(sb, false); - var tableWidth = columns.Sum(column => column.Width); - sb.Append(verticalLineChar); - sb.Append(tableTitle.PadRight(tableWidth + columns.Count - 1)); - sb.Append(verticalLineChar); + this.WriteFlatLine(sb, false); + var tableWidth = this.columns.Sum(column => column.Width); + sb.Append(this.verticalLineChar); + sb.Append(this.tableTitle.PadRight(tableWidth + this.columns.Count - 1)); + sb.Append(this.verticalLineChar); sb.AppendLine(); - sb.Append(verticalLineChar); - for (var i = 0; i < columns.Count - 1; i++) + sb.Append(this.verticalLineChar); + for (var i = 0; i < this.columns.Count - 1; i++) { - sb.Append(string.Empty.PadRight(columns[i].Width, horizontalLineChar)); - sb.Append(horizontalLineChar); + sb.Append(string.Empty.PadRight(this.columns[i].Width, this.horizontalLineChar)); + sb.Append(this.horizontalLineChar); } - sb.Append(string.Empty.PadRight(columns[columns.Count - 1].Width, horizontalLineChar)); - sb.Append(verticalLineChar); + sb.Append(string.Empty.PadRight(this.columns[this.columns.Count - 1].Width, this.horizontalLineChar)); + sb.Append(this.verticalLineChar); sb.AppendLine(); } private void WriteFlatLine(StringBuilder sb, bool withPipes = true) { - var splitCharacter = withPipes ? verticalLineChar : horizontalLineChar; + var splitCharacter = withPipes ? this.verticalLineChar : this.horizontalLineChar; sb.AppendLine(); sb.Append(splitCharacter); - for (var i = 0; i < columns.Count; i++) + for (var i = 0; i < this.columns.Count; i++) { - sb.Append(string.Empty.PadRight(columns[i].Width, horizontalLineChar)); + sb.Append(string.Empty.PadRight(this.columns[i].Width, this.horizontalLineChar)); sb.Append(splitCharacter); } sb.AppendLine(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs index 3b786a00f..7314acd12 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/TelemetryServiceAttribute.cs @@ -8,7 +8,7 @@ public class TelemetryServiceAttribute : Attribute public TelemetryServiceAttribute(string serviceType) { - ServiceType = serviceType; + this.ServiceType = serviceType; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs index 3eec11a5e..6dfec5e82 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs @@ -27,12 +27,12 @@ internal class CommandLineTelemetryService : ITelemetryService public void Flush() { - FileWritingService.WriteFile(TelemetryRelativePath, JsonConvert.SerializeObject(records)); + this.FileWritingService.WriteFile(TelemetryRelativePath, JsonConvert.SerializeObject(records)); } public void PostRecord(IDetectionTelemetryRecord record) { - if (telemetryMode != TelemetryMode.Disabled) + if (this.telemetryMode != TelemetryMode.Disabled) { var jsonRecord = JObject.FromObject(record); jsonRecord.Add("Timestamp", DateTime.UtcNow); @@ -40,16 +40,16 @@ public void PostRecord(IDetectionTelemetryRecord record) records.Enqueue(jsonRecord); - if (telemetryMode == TelemetryMode.Debug) + if (this.telemetryMode == TelemetryMode.Debug) { - Logger.LogInfo(jsonRecord.ToString()); + this.Logger.LogInfo(jsonRecord.ToString()); } } } public void SetMode(TelemetryMode mode) { - telemetryMode = mode; + this.telemetryMode = mode; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs index b303df421..f7cb52677 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs @@ -15,15 +15,15 @@ public abstract class BaseDetectionTelemetryRecord : IDetectionTelemetryRecord protected BaseDetectionTelemetryRecord() { - stopwatch.Start(); + this.stopwatch.Start(); } public void StopExecutionTimer() { - if (stopwatch.IsRunning) + if (this.stopwatch.IsRunning) { - stopwatch.Stop(); - ExecutionTime = stopwatch.Elapsed; + this.stopwatch.Stop(); + this.ExecutionTime = this.stopwatch.Elapsed; } } @@ -31,21 +31,21 @@ public void StopExecutionTimer() protected virtual void Dispose(bool disposing) { - if (!disposedValue) + if (!this.disposedValue) { if (disposing) { - StopExecutionTimer(); + this.StopExecutionTimer(); TelemetryRelay.Instance.PostTelemetryRecord(this); } - disposedValue = true; + this.disposedValue = true; } } public void Dispose() { - Dispose(true); + this.Dispose(true); } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs index 45650e3cf..4b47a1884 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs @@ -19,23 +19,23 @@ public class CommandLineInvocationTelemetryRecord : BaseDetectionTelemetryRecord internal void Track(CommandLineExecutionResult result, string path, string parameters) { - ExitCode = result.ExitCode; - StandardError = result.StdErr; - TrackCommon(path, parameters); + this.ExitCode = result.ExitCode; + this.StandardError = result.StdErr; + this.TrackCommon(path, parameters); } internal void Track(Exception ex, string path, string parameters) { - ExitCode = -1; - UnhandledException = ex.ToString(); - TrackCommon(path, parameters); + this.ExitCode = -1; + this.UnhandledException = ex.ToString(); + this.TrackCommon(path, parameters); } private void TrackCommon(string path, string parameters) { - PathThatWasRan = path; - Parameters = parameters; - StopExecutionTimer(); + this.PathThatWasRan = path; + this.Parameters = parameters; + this.StopExecutionTimer(); } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs index c255fbffe..57d986b22 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs @@ -11,7 +11,7 @@ public class DetectedComponentScopeRecord : BaseDetectionTelemetryRecord [MethodImpl(MethodImplOptions.Synchronized)] public void IncrementProvidedScopeCount() { - MavenProvidedScopeCount++; + this.MavenProvidedScopeCount++; } } } diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs index 4f691ca43..3e1f7dc64 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs @@ -16,20 +16,20 @@ public class NuGetProjectAssetsTelemetryRecord : IDetectionTelemetryRecord, IDis protected virtual void Dispose(bool disposing) { - if (!disposedValue) + if (!this.disposedValue) { if (disposing) { TelemetryRelay.Instance.PostTelemetryRecord(this); } - disposedValue = true; + this.disposedValue = true; } } public void Dispose() { - Dispose(true); + this.Dispose(true); } } } diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs index 4c3ba76ab..3d09af1c2 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs @@ -39,7 +39,7 @@ public override object ReadJson( JToken jo = JToken.Load(reader); var value = (ComponentType)Enum.Parse(typeof(ComponentType), (string)jo["type"]); - var targetType = componentTypesToTypes[value]; + var targetType = this.componentTypesToTypes[value]; var instanceOfTypedComponent = Activator.CreateInstance(targetType, true); serializer.Populate(jo.CreateReader(), instanceOfTypedComponent); diff --git a/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs b/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs index 69470bfdb..a3e8aa0f6 100644 --- a/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/DetectedComponent.cs @@ -17,22 +17,22 @@ public class DetectedComponent /// Id of the layer the component was found, this is only necessary if the component was found inside a container. public DetectedComponent(TypedComponent.TypedComponent component, IComponentDetector detector = null, int? containerDetailsId = null, int? containerLayerId = null) { - Component = component; - FilePaths = new HashSet(); - DetectedBy = detector; - ContainerDetailIds = new HashSet(); - ContainerLayerIds = new Dictionary>(); + this.Component = component; + this.FilePaths = new HashSet(); + this.DetectedBy = detector; + this.ContainerDetailIds = new HashSet(); + this.ContainerLayerIds = new Dictionary>(); if (containerDetailsId.HasValue) { - ContainerDetailIds.Add(containerDetailsId.Value); + this.ContainerDetailIds.Add(containerDetailsId.Value); if (containerLayerId.HasValue) { - ContainerLayerIds.Add(containerDetailsId.Value, new List() { containerLayerId.Value }); + this.ContainerLayerIds.Add(containerDetailsId.Value, new List() { containerLayerId.Value }); } } } - private string DebuggerDisplay => $"{Component.DebuggerDisplay}"; + private string DebuggerDisplay => $"{this.Component.DebuggerDisplay}"; /// /// Gets or sets the detector that detected this component. @@ -65,9 +65,9 @@ public DetectedComponent(TypedComponent.TypedComponent component, IComponentDete /// The file path to add to the hashset. public void AddComponentFilePath(string filePath) { - lock (hashLock) + lock (this.hashLock) { - FilePaths.Add(filePath); + this.FilePaths.Add(filePath); } } } diff --git a/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs b/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs index 64dfda48b..8728f3556 100644 --- a/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs +++ b/src/Microsoft.ComponentDetection.Contracts/DockerReference.cs @@ -97,14 +97,14 @@ public class DigestReference : DockerReference public override string ToString() { - return $"{Digest}"; + return $"{this.Digest}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Digest = Digest, + Digest = this.Digest, }; } } @@ -122,16 +122,16 @@ public class CanonicalReference : DockerReference public override string ToString() { - return $"{Domain}/{Repository}@${Digest}"; + return $"{this.Domain}/{this.Repository}@${this.Digest}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Domain = Domain, - Digest = Digest, - Repository = Repository, + Domain = this.Domain, + Digest = this.Digest, + Repository = this.Repository, }; } } @@ -147,15 +147,15 @@ public class RepositoryReference : DockerReference public override string ToString() { - return $"{Repository}"; + return $"{this.Repository}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Domain = Domain, - Repository = Repository, + Domain = this.Domain, + Repository = this.Repository, }; } } @@ -173,16 +173,16 @@ public class TaggedReference : DockerReference public override string ToString() { - return $"{Domain}/{Repository}:${Tag}"; + return $"{this.Domain}/{this.Repository}:${this.Tag}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Domain = Domain, - Tag = Tag, - Repository = Repository, + Domain = this.Domain, + Tag = this.Tag, + Repository = this.Repository, }; } } @@ -202,18 +202,18 @@ public class DualReference : DockerReference public override string ToString() { - return $"{Domain}/{Repository}:${Tag}@${Digest}"; + return $"{this.Domain}/{this.Repository}:${this.Tag}@${this.Digest}"; } public override TypedComponent.DockerReferenceComponent ToTypedDockerReferenceComponent() { return new TypedComponent.DockerReferenceComponent(this) { - Domain = Domain, - Digest = Digest, - Tag = Tag, - Repository = Repository, + Domain = this.Domain, + Digest = this.Digest, + Tag = this.Tag, + Repository = this.Repository, }; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs index d6428b456..45a13523f 100644 --- a/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Contracts/FileComponentDetector.cs @@ -63,20 +63,20 @@ public abstract class FileComponentDetector : IComponentDetector /// public async virtual Task ExecuteDetectorAsync(ScanRequest request) { - ComponentRecorder = request.ComponentRecorder; - Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1); - return await ScanDirectoryAsync(request); + this.ComponentRecorder = request.ComponentRecorder; + this.Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1); + return await this.ScanDirectoryAsync(request); } /// private Task ScanDirectoryAsync(ScanRequest request) { - CurrentScanRequest = request; + this.CurrentScanRequest = request; - var filteredObservable = Scanner.GetFilteredComponentStreamObservable(request.SourceDirectory, SearchPatterns, request.ComponentRecorder); + var filteredObservable = this.Scanner.GetFilteredComponentStreamObservable(request.SourceDirectory, this.SearchPatterns, request.ComponentRecorder); - Logger?.LogVerbose($"Registered {GetType().FullName}"); - return ProcessAsync(filteredObservable, request.DetectorArgs); + this.Logger?.LogVerbose($"Registered {this.GetType().FullName}"); + return this.ProcessAsync(filteredObservable, request.DetectorArgs); } /// @@ -87,14 +87,14 @@ private Task ScanDirectoryAsync(ScanRequest reques /// protected Task> GetFileStreamsAsync(DirectoryInfo sourceDirectory, ExcludeDirectoryPredicate exclusionPredicate) { - return Task.FromResult(ComponentStreamEnumerableFactory.GetComponentStreams(sourceDirectory, SearchPatterns, exclusionPredicate)); + return Task.FromResult(this.ComponentStreamEnumerableFactory.GetComponentStreams(sourceDirectory, this.SearchPatterns, exclusionPredicate)); } private async Task ProcessAsync(IObservable processRequests, IDictionary detectorArgs) { - var processor = new ActionBlock(async processRequest => await OnFileFound(processRequest, detectorArgs)); + var processor = new ActionBlock(async processRequest => await this.OnFileFound(processRequest, detectorArgs)); - var preprocessedObserbable = await OnPrepareDetection(processRequests, detectorArgs); + var preprocessedObserbable = await this.OnPrepareDetection(processRequests, detectorArgs); await preprocessedObserbable.ForEachAsync(processRequest => processor.Post(processRequest)); @@ -102,12 +102,12 @@ private async Task ProcessAsync(IObservableDetector component recorder. public ScanRequest(DirectoryInfo sourceDirectory, ExcludeDirectoryPredicate directoryExclusionPredicate, ILogger logger, IDictionary detectorArgs, IEnumerable imagesToScan, IComponentRecorder componentRecorder) { - SourceDirectory = sourceDirectory; - DirectoryExclusionPredicate = directoryExclusionPredicate; - DetectorArgs = detectorArgs; - ImagesToScan = imagesToScan; - ComponentRecorder = componentRecorder; + this.SourceDirectory = sourceDirectory; + this.DirectoryExclusionPredicate = directoryExclusionPredicate; + this.DetectorArgs = detectorArgs; + this.ImagesToScan = imagesToScan; + this.ComponentRecorder = componentRecorder; } /// Gets the source directory to consider the working directory for the detection operation. diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs index 0859dd0f6..ca196e6b6 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CargoComponent.cs @@ -11,8 +11,8 @@ private CargoComponent() public CargoComponent(string name, string version) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Cargo)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Cargo)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Cargo)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Cargo)); } public string Name { get; set; } @@ -21,8 +21,8 @@ public CargoComponent(string name, string version) public override ComponentType Type => ComponentType.Cargo; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("cargo", string.Empty, Name, Version, null, string.Empty); + public override PackageURL PackageUrl => new PackageURL("cargo", string.Empty, this.Name, this.Version, null, string.Empty); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs index feddfebd1..55637e208 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs @@ -9,14 +9,14 @@ private CondaComponent() public CondaComponent(string name, string version, string build, string channel, string subdir, string @namespace, string url, string md5) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Conda)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Conda)); - Build = build; - Channel = channel; - Subdir = subdir; - Namespace = @namespace; - Url = url; - MD5 = md5; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Conda)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Conda)); + this.Build = build; + this.Channel = channel; + this.Subdir = subdir; + this.Namespace = @namespace; + this.Url = url; + this.MD5 = md5; } public string Build { get; set; } @@ -37,6 +37,6 @@ public CondaComponent(string name, string version, string build, string channel, public override ComponentType Type => ComponentType.Conda; - public override string Id => $"{Name} {Version} {Build} {Channel} {Subdir} {Namespace} {Url} {MD5} - {Type}"; + public override string Id => $"{this.Name} {this.Version} {this.Build} {this.Channel} {this.Subdir} {this.Namespace} {this.Url} {this.MD5} - {this.Type}"; } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs index d531516de..c104665ff 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerImageComponent.cs @@ -9,9 +9,9 @@ private DockerImageComponent() public DockerImageComponent(string hash, string name = null, string tag = null) { - Digest = ValidateRequiredInput(hash, nameof(Digest), nameof(ComponentType.DockerImage)); - Name = name; - Tag = tag; + this.Digest = this.ValidateRequiredInput(hash, nameof(this.Digest), nameof(ComponentType.DockerImage)); + this.Name = name; + this.Tag = tag; } public string Name { get; set; } @@ -22,6 +22,6 @@ public DockerImageComponent(string hash, string name = null, string tag = null) public override ComponentType Type => ComponentType.DockerImage; - public override string Id => $"{Name} {Tag} {Digest}"; + public override string Id => $"{this.Name} {this.Tag} {this.Digest}"; } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs index 2181a3819..5ad27a1ed 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/DockerReferenceComponent.cs @@ -9,9 +9,9 @@ private DockerReferenceComponent() public DockerReferenceComponent(string hash, string repository = null, string tag = null) { - Digest = ValidateRequiredInput(hash, nameof(Digest), nameof(ComponentType.DockerReference)); - Repository = repository; - Tag = tag; + this.Digest = this.ValidateRequiredInput(hash, nameof(this.Digest), nameof(ComponentType.DockerReference)); + this.Repository = repository; + this.Tag = tag; } public DockerReferenceComponent(DockerReference reference) @@ -32,10 +32,10 @@ public DockerReference FullReference { get { - return DockerReference.CreateDockerReference(Repository, Domain, Digest, Tag); + return DockerReference.CreateDockerReference(this.Repository, this.Domain, this.Digest, this.Tag); } } - public override string Id => $"{Repository} {Tag} {Digest}"; + public override string Id => $"{this.Repository} {this.Tag} {this.Digest}"; } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs index 0da30ec3e..fd1fb3bfd 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs @@ -11,14 +11,14 @@ private GitComponent() public GitComponent(Uri repositoryUrl, string commitHash) { - RepositoryUrl = ValidateRequiredInput(repositoryUrl, nameof(RepositoryUrl), nameof(ComponentType.Git)); - CommitHash = ValidateRequiredInput(commitHash, nameof(CommitHash), nameof(ComponentType.Git)); + this.RepositoryUrl = this.ValidateRequiredInput(repositoryUrl, nameof(this.RepositoryUrl), nameof(ComponentType.Git)); + this.CommitHash = this.ValidateRequiredInput(commitHash, nameof(this.CommitHash), nameof(ComponentType.Git)); } public GitComponent(Uri repositoryUrl, string commitHash, string tag) : this(repositoryUrl, commitHash) { - Tag = tag; + this.Tag = tag; } public Uri RepositoryUrl { get; set; } @@ -29,6 +29,6 @@ public GitComponent(Uri repositoryUrl, string commitHash, string tag) public override ComponentType Type => ComponentType.Git; - public override string Id => $"{RepositoryUrl} : {CommitHash} - {Type}"; + public override string Id => $"{this.RepositoryUrl} : {this.CommitHash} - {this.Type}"; } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs index d6bb745ba..6f844e900 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs @@ -12,16 +12,16 @@ private GoComponent() public GoComponent(string name, string version) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Go)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Go)); - Hash = string.Empty; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Go)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Go)); + this.Hash = string.Empty; } public GoComponent(string name, string version, string hash) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Go)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Go)); - Hash = ValidateRequiredInput(hash, nameof(Hash), nameof(ComponentType.Go)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Go)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Go)); + this.Hash = this.ValidateRequiredInput(hash, nameof(this.Hash), nameof(ComponentType.Go)); } public string Name { get; set; } @@ -32,12 +32,12 @@ public GoComponent(string name, string version, string hash) public override ComponentType Type => ComponentType.Go; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; public override bool Equals(object other) { GoComponent otherComponent = other as GoComponent; - return otherComponent != null && Equals(otherComponent); + return otherComponent != null && this.Equals(otherComponent); } public bool Equals(GoComponent other) @@ -47,18 +47,16 @@ public bool Equals(GoComponent other) return false; } - return Name == other.Name && - Version == other.Version && - Hash == other.Hash; + return this.Name == other.Name && this.Version == other.Version && this.Hash == other.Hash; } public override int GetHashCode() { - return Name.GetHashCode() ^ Version.GetHashCode() ^ Hash.GetHashCode(); + return this.Name.GetHashCode() ^ this.Version.GetHashCode() ^ this.Hash.GetHashCode(); } // Commit should be used in place of version when available // https://github.com/package-url/purl-spec/blame/180c46d266c45aa2bd81a2038af3f78e87bb4a25/README.rst#L610 - public override PackageURL PackageUrl => new PackageURL("golang", null, Name, string.IsNullOrWhiteSpace(Hash) ? Version : Hash, null, null); + public override PackageURL PackageUrl => new PackageURL("golang", null, this.Name, string.IsNullOrWhiteSpace(this.Hash) ? this.Version : this.Hash, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs index 0b03bb5a3..30f18aaf0 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/LinuxComponent.cs @@ -11,10 +11,10 @@ private LinuxComponent() public LinuxComponent(string distribution, string release, string name, string version) { - Distribution = ValidateRequiredInput(distribution, nameof(Distribution), nameof(ComponentType.Linux)); - Release = ValidateRequiredInput(release, nameof(Release), nameof(ComponentType.Linux)); - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Linux)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Linux)); + this.Distribution = this.ValidateRequiredInput(distribution, nameof(this.Distribution), nameof(ComponentType.Linux)); + this.Release = this.ValidateRequiredInput(release, nameof(this.Release), nameof(ComponentType.Linux)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Linux)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Linux)); } public string Distribution { get; set; } @@ -27,7 +27,7 @@ public LinuxComponent(string distribution, string release, string name, string v public override ComponentType Type => ComponentType.Linux; - public override string Id => $"{Distribution} {Release} {Name} {Version} - {Type}"; + public override string Id => $"{this.Distribution} {this.Release} {this.Name} {this.Version} - {this.Type}"; public override PackageURL PackageUrl { @@ -35,18 +35,18 @@ public override PackageURL PackageUrl { string packageType = null; - if (IsUbuntu() || IsDebian()) + if (this.IsUbuntu() || this.IsDebian()) { packageType = "deb"; } - else if (IsCentOS() || IsFedora() || IsRHEL()) + else if (this.IsCentOS() || this.IsFedora() || this.IsRHEL()) { packageType = "rpm"; } if (packageType != null) { - return new PackageURL(packageType, Distribution, Name, Version, null, null); + return new PackageURL(packageType, this.Distribution, this.Name, this.Version, null, null); } return null; @@ -55,27 +55,27 @@ public override PackageURL PackageUrl private bool IsUbuntu() { - return Distribution.ToLowerInvariant() == "ubuntu"; + return this.Distribution.ToLowerInvariant() == "ubuntu"; } private bool IsDebian() { - return Distribution.ToLowerInvariant() == "debian"; + return this.Distribution.ToLowerInvariant() == "debian"; } private bool IsCentOS() { - return Distribution.ToLowerInvariant() == "centos"; + return this.Distribution.ToLowerInvariant() == "centos"; } private bool IsFedora() { - return Distribution.ToLowerInvariant() == "fedora"; + return this.Distribution.ToLowerInvariant() == "fedora"; } private bool IsRHEL() { - return Distribution.ToLowerInvariant() == "red hat enterprise linux"; + return this.Distribution.ToLowerInvariant() == "red hat enterprise linux"; } } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs index b418ead37..a644b052f 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs @@ -11,9 +11,9 @@ private MavenComponent() public MavenComponent(string groupId, string artifactId, string version) { - GroupId = ValidateRequiredInput(groupId, nameof(GroupId), nameof(ComponentType.Maven)); - ArtifactId = ValidateRequiredInput(artifactId, nameof(ArtifactId), nameof(ComponentType.Maven)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Maven)); + this.GroupId = this.ValidateRequiredInput(groupId, nameof(this.GroupId), nameof(ComponentType.Maven)); + this.ArtifactId = this.ValidateRequiredInput(artifactId, nameof(this.ArtifactId), nameof(ComponentType.Maven)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Maven)); } public string GroupId { get; set; } @@ -24,8 +24,8 @@ public MavenComponent(string groupId, string artifactId, string version) public override ComponentType Type => ComponentType.Maven; - public override string Id => $"{GroupId} {ArtifactId} {Version} - {Type}"; + public override string Id => $"{this.GroupId} {this.ArtifactId} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("maven", GroupId, ArtifactId, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("maven", this.GroupId, this.ArtifactId, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs index afad4cdf8..c656caebc 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs @@ -12,10 +12,10 @@ private NpmComponent() public NpmComponent(string name, string version, string hash = null, NpmAuthor author = null) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Npm)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Npm)); - Hash = hash; // Not required; only found in package-lock.json, not package.json - Author = author; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Npm)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Npm)); + this.Hash = hash; // Not required; only found in package-lock.json, not package.json + this.Author = author; } public string Name { get; set; } @@ -28,8 +28,8 @@ public NpmComponent(string name, string version, string hash = null, NpmAuthor a public override ComponentType Type => ComponentType.Npm; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("npm", null, Name, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("npm", null, this.Name, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs index cfbcdf15e..683d95d92 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs @@ -11,9 +11,9 @@ private NuGetComponent() public NuGetComponent(string name, string version, string[] authors = null) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.NuGet)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.NuGet)); - Authors = authors; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.NuGet)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.NuGet)); + this.Authors = authors; } public string Name { get; set; } @@ -24,8 +24,8 @@ public NuGetComponent(string name, string version, string[] authors = null) public override ComponentType Type => ComponentType.NuGet; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("nuget", null, Name, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("nuget", null, this.Name, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs index 063552227..584cd34b7 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/OtherComponent.cs @@ -11,10 +11,10 @@ private OtherComponent() public OtherComponent(string name, string version, Uri downloadUrl, string hash) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Other)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Other)); - DownloadUrl = ValidateRequiredInput(downloadUrl, nameof(DownloadUrl), nameof(ComponentType.Other)); - Hash = hash; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Other)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Other)); + this.DownloadUrl = this.ValidateRequiredInput(downloadUrl, nameof(this.DownloadUrl), nameof(ComponentType.Other)); + this.Hash = hash; } public string Name { get; set; } @@ -27,6 +27,6 @@ public OtherComponent(string name, string version, Uri downloadUrl, string hash) public override ComponentType Type => ComponentType.Other; - public override string Id => $"{Name} {Version} {DownloadUrl} - {Type}"; + public override string Id => $"{this.Name} {this.Version} {this.DownloadUrl} - {this.Type}"; } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs index b11792f17..e83365e2e 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PipComponent.cs @@ -11,8 +11,8 @@ private PipComponent() public PipComponent(string name, string version) { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Pip)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Pip)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Pip)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Pip)); } public string Name { get; set; } @@ -21,8 +21,8 @@ public PipComponent(string name, string version) public override ComponentType Type => ComponentType.Pip; - public override string Id => $"{Name} {Version} - {Type}".ToLowerInvariant(); + public override string Id => $"{this.Name} {this.Version} - {this.Type}".ToLowerInvariant(); - public override PackageURL PackageUrl => new PackageURL("pypi", null, Name, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("pypi", null, this.Name, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs index f35a19b8e..3a2fa8ab4 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs @@ -12,9 +12,9 @@ private PodComponent() public PodComponent(string name, string version, string specRepo = "") { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Pod)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.Pod)); - SpecRepo = specRepo; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Pod)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.Pod)); + this.SpecRepo = specRepo; } public string Name { get; set; } @@ -25,19 +25,19 @@ public PodComponent(string name, string version, string specRepo = "") public override ComponentType Type => ComponentType.Pod; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; public override PackageURL PackageUrl { get { var qualifiers = new SortedDictionary(); - if (!string.IsNullOrWhiteSpace(SpecRepo)) + if (!string.IsNullOrWhiteSpace(this.SpecRepo)) { - qualifiers.Add("repository_url", SpecRepo); + qualifiers.Add("repository_url", this.SpecRepo); } - return new PackageURL("cocoapods", null, Name, Version, qualifiers, null); + return new PackageURL("cocoapods", null, this.Name, this.Version, qualifiers, null); } } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs index 8a0daf5df..130e4acdb 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/RubyGemsComponent.cs @@ -11,9 +11,9 @@ private RubyGemsComponent() public RubyGemsComponent(string name, string version, string source = "") { - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.RubyGems)); - Version = ValidateRequiredInput(version, nameof(Version), nameof(ComponentType.RubyGems)); - Source = source; + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.RubyGems)); + this.Version = this.ValidateRequiredInput(version, nameof(this.Version), nameof(ComponentType.RubyGems)); + this.Source = source; } public string Name { get; set; } @@ -24,8 +24,8 @@ public RubyGemsComponent(string name, string version, string source = "") public override ComponentType Type => ComponentType.RubyGems; - public override string Id => $"{Name} {Version} - {Type}"; + public override string Id => $"{this.Name} {this.Version} - {this.Type}"; - public override PackageURL PackageUrl => new PackageURL("gem", null, Name, Version, null, null); + public override PackageURL PackageUrl => new PackageURL("gem", null, this.Name, this.Version, null, null); } } diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs index 5ec716c5e..1dac70180 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs @@ -12,13 +12,12 @@ private SpdxComponent() public SpdxComponent(string spdxVersion, Uri documentNamespace, string name, string checksum, string rootElementId, string path) { - SpdxVersion = ValidateRequiredInput(spdxVersion, nameof(SpdxVersion), nameof(ComponentType.Spdx)); - DocumentNamespace = - ValidateRequiredInput(documentNamespace, nameof(DocumentNamespace), nameof(ComponentType.Spdx)); - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Spdx)); - Checksum = ValidateRequiredInput(checksum, nameof(Checksum), nameof(ComponentType.Spdx)); - RootElementId = ValidateRequiredInput(rootElementId, nameof(RootElementId), nameof(ComponentType.Spdx)); - Path = ValidateRequiredInput(path, nameof(Path), nameof(ComponentType.Spdx)); + this.SpdxVersion = this.ValidateRequiredInput(spdxVersion, nameof(this.SpdxVersion), nameof(ComponentType.Spdx)); + this.DocumentNamespace = this.ValidateRequiredInput(documentNamespace, nameof(this.DocumentNamespace), nameof(ComponentType.Spdx)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Spdx)); + this.Checksum = this.ValidateRequiredInput(checksum, nameof(this.Checksum), nameof(ComponentType.Spdx)); + this.RootElementId = this.ValidateRequiredInput(rootElementId, nameof(this.RootElementId), nameof(ComponentType.Spdx)); + this.Path = this.ValidateRequiredInput(path, nameof(this.Path), nameof(ComponentType.Spdx)); } public override ComponentType Type => ComponentType.Spdx; @@ -35,6 +34,6 @@ public SpdxComponent(string spdxVersion, Uri documentNamespace, string name, str public string Path { get; } - public override string Id => $"{Name}-{SpdxVersion}-{Checksum}"; + public override string Id => $"{this.Name}-{this.SpdxVersion}-{this.Checksum}"; } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs index 0bf401458..503ff4591 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/TypedComponent.cs @@ -28,19 +28,19 @@ internal TypedComponent() public virtual PackageURL PackageUrl { get; } [JsonIgnore] - internal string DebuggerDisplay => $"{Id}"; + internal string DebuggerDisplay => $"{this.Id}"; protected string ValidateRequiredInput(string input, string fieldName, string componentType) { return string.IsNullOrWhiteSpace(input) - ? throw new ArgumentNullException(fieldName, NullPropertyExceptionMessage(fieldName, componentType)) + ? throw new ArgumentNullException(fieldName, this.NullPropertyExceptionMessage(fieldName, componentType)) : input; } protected T ValidateRequiredInput(T input, string fieldName, string componentType) { // Null coalescing for generic types is not available until C# 8 - return EqualityComparer.Default.Equals(input, default(T)) ? throw new ArgumentNullException(fieldName, NullPropertyExceptionMessage(fieldName, componentType)) : input; + return EqualityComparer.Default.Equals(input, default(T)) ? throw new ArgumentNullException(fieldName, this.NullPropertyExceptionMessage(fieldName, componentType)) : input; } protected string NullPropertyExceptionMessage(string propertyName, string componentType) diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs index aee536fb4..3765b6632 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/VcpkgComponent.cs @@ -13,13 +13,13 @@ public VcpkgComponent(string spdxid, string name, string version, string triplet { int.TryParse(portVersion, out var port); - SPDXID = ValidateRequiredInput(spdxid, nameof(SPDXID), nameof(ComponentType.Vcpkg)); - Name = ValidateRequiredInput(name, nameof(Name), nameof(ComponentType.Vcpkg)); - Version = version; - PortVersion = port; - Triplet = triplet; - Description = description; - DownloadLocation = downloadLocation; + this.SPDXID = this.ValidateRequiredInput(spdxid, nameof(this.SPDXID), nameof(ComponentType.Vcpkg)); + this.Name = this.ValidateRequiredInput(name, nameof(this.Name), nameof(ComponentType.Vcpkg)); + this.Version = version; + this.PortVersion = port; + this.Triplet = triplet; + this.Description = description; + this.DownloadLocation = downloadLocation; } public string SPDXID { get; set; } @@ -42,13 +42,13 @@ public override string Id { get { - if (PortVersion > 0) + if (this.PortVersion > 0) { - return $"{Name} {Version}#{PortVersion} - {Type}"; + return $"{this.Name} {this.Version}#{this.PortVersion} - {this.Type}"; } else { - return $"{Name} {Version} - {Type}"; + return $"{this.Name} {this.Version} - {this.Type}"; } } } @@ -57,17 +57,17 @@ public override PackageURL PackageUrl { get { - if (PortVersion > 0) + if (this.PortVersion > 0) { - return new PackageURL($"pkg:vcpkg/{Name}@{Version}?port_version={PortVersion}"); + return new PackageURL($"pkg:vcpkg/{this.Name}@{this.Version}?port_version={this.PortVersion}"); } - else if (Version != null) + else if (this.Version != null) { - return new PackageURL($"pkg:vcpkg/{Name}@{Version}"); + return new PackageURL($"pkg:vcpkg/{this.Name}@{this.Version}"); } else { - return new PackageURL($"pkg:vcpkg/{Name}"); + return new PackageURL($"pkg:vcpkg/{this.Name}"); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs index a368ac227..aade4069b 100644 --- a/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs @@ -35,9 +35,9 @@ private class Pod : IYamlConvertible public IList Dependencies { get; set; } - public string Podspec => Name.Split('/', 2)[0]; + public string Podspec => this.Name.Split('/', 2)[0]; - public bool IsSubspec => Name != Podspec; + public bool IsSubspec => this.Name != this.Podspec; public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { @@ -49,18 +49,18 @@ public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObj var podInfo = parser.Consume(); var components = podInfo.Value.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries); - Name = components[0].Trim(); - Version = components[1].Trim(); + this.Name = components[0].Trim(); + this.Version = components[1].Trim(); if (hasDependencies) { - Dependencies = (IList)nestedObjectDeserializer(typeof(IList)); + this.Dependencies = (IList)nestedObjectDeserializer(typeof(IList)); parser.Consume(); } else { - Dependencies = Array.Empty(); + this.Dependencies = Array.Empty(); } } @@ -76,16 +76,16 @@ private class PodDependency : IYamlConvertible public string PodVersion { get; set; } - public string Podspec => PodName.Split('/', 2)[0]; + public string Podspec => this.PodName.Split('/', 2)[0]; - public bool IsSubspec => PodName != Podspec; + public bool IsSubspec => this.PodName != this.Podspec; public void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { var scalar = parser.Consume(); var components = scalar.Value.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries); - PodName = components[0].Trim(); - PodVersion = components.Length > 1 ? components[1].Trim() : null; + this.PodName = components[0].Trim(); + this.PodVersion = components.Length > 1 ? components[1].Trim() : null; } public void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) @@ -122,17 +122,17 @@ private class PodfileLock public PodfileLock() { - Dependencies = Array.Empty(); - PodspecRepositories = new Dictionary>(); - PodspecChecksums = new Dictionary(); - ExternalSources = new Dictionary>(); - CheckoutOptions = new Dictionary>(); - Pods = Array.Empty(); + this.Dependencies = Array.Empty(); + this.PodspecRepositories = new Dictionary>(); + this.PodspecChecksums = new Dictionary(); + this.ExternalSources = new Dictionary>(); + this.CheckoutOptions = new Dictionary>(); + this.Pods = Array.Empty(); } public string GetSpecRepositoryOfSpec(string specName) { - foreach (var repository in PodspecRepositories) + foreach (var repository in this.PodspecRepositories) { if (repository.Value.Contains(specName)) { @@ -159,17 +159,17 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - Logger.LogVerbose($"Found {file.Pattern}: {file.Location}"); + this.Logger.LogVerbose($"Found {file.Pattern}: {file.Location}"); try { var podfileLock = await ParsePodfileLock(file); - ProcessPodfileLock(singleFileComponentRecorder, podfileLock); + this.ProcessPodfileLock(singleFileComponentRecorder, podfileLock); } catch (Exception e) { - Logger.LogFailedReadingFile(file.Location, e); + this.Logger.LogFailedReadingFile(file.Location, e); } } @@ -311,7 +311,7 @@ private void ProcessPodfileLock( } else { - Logger.LogWarning($"Missing podspec declaration. podspec={dependency.Podspec}, version={dependency.PodVersion}"); + this.Logger.LogWarning($"Missing podspec declaration. podspec={dependency.Podspec}, version={dependency.PodVersion}"); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs index d9f03dbaa..10db0140d 100644 --- a/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs @@ -39,7 +39,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; var filePath = file.Location; - Logger.LogInfo($"Discovered dockerfile: {file.Location}"); + this.Logger.LogInfo($"Discovered dockerfile: {file.Location}"); string contents; using (var reader = new StreamReader(file.Stream)) @@ -48,7 +48,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio } var stageNameMap = new Dictionary(); - var dockerFileComponent = ParseDockerFile(contents, file.Location, singleFileComponentRecorder, stageNameMap); + var dockerFileComponent = this.ParseDockerFile(contents, file.Location, singleFileComponentRecorder, stageNameMap); } private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFileComponentRecorder singleFileComponentRecorder, Dictionary stageNameMap) @@ -57,7 +57,7 @@ private Task ParseDockerFile(string fileContents, string fileLocation, ISingleFi var instructions = dockerfileModel.Items; foreach (var instruction in instructions) { - var imageReference = ProcessDockerfileConstruct(instruction, dockerfileModel.EscapeChar, stageNameMap); + var imageReference = this.ProcessDockerfileConstruct(instruction, dockerfileModel.EscapeChar, stageNameMap); if (imageReference != null) { singleFileComponentRecorder.RegisterUsage(new DetectedComponent(imageReference.ToTypedDockerReferenceComponent())); @@ -79,10 +79,10 @@ private DockerReference ProcessDockerfileConstruct(DockerfileConstruct construct switch (constructType) { case "FromInstruction": - baseImage = ParseFromInstruction(construct, escapeChar, stageNameMap); + baseImage = this.ParseFromInstruction(construct, escapeChar, stageNameMap); break; case "CopyInstruction": - baseImage = ParseCopyInstruction(construct, escapeChar, stageNameMap); + baseImage = this.ParseCopyInstruction(construct, escapeChar, stageNameMap); break; default: break; @@ -92,8 +92,8 @@ private DockerReference ProcessDockerfileConstruct(DockerfileConstruct construct return baseImage; } catch (Exception e) { - Logger.LogError($"Failed to detect a DockerReference component, the component will not be registered. \n Error Message: <{e.Message}>"); - Logger.LogException(e, isError: true, printException: true); + this.Logger.LogError($"Failed to detect a DockerReference component, the component will not be registered. \n Error Message: <{e.Message}>"); + this.Logger.LogException(e, isError: true, printException: true); return null; } } @@ -102,7 +102,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char { var tokens = construct.Tokens.ToArray(); var resolvedFromStatement = construct.ResolveVariables(escapeChar).TrimEnd(); - var fromInstruction = (Valleysoft.DockerfileModel.FromInstruction)construct; + var fromInstruction = (FromInstruction)construct; string reference = fromInstruction.ImageName; if (string.IsNullOrWhiteSpace(resolvedFromStatement) || string.IsNullOrEmpty(reference)) { @@ -126,7 +126,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char if (!string.IsNullOrEmpty(stageNameReference)) { - if (HasUnresolvedVariables(stageNameReference)) + if (this.HasUnresolvedVariables(stageNameReference)) { return null; } @@ -134,7 +134,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char return DockerReferenceUtility.ParseFamiliarName(stageNameReference); } - if (HasUnresolvedVariables(reference)) + if (this.HasUnresolvedVariables(reference)) { return null; } @@ -145,7 +145,7 @@ private DockerReference ParseFromInstruction(DockerfileConstruct construct, char private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char escapeChar, Dictionary stageNameMap) { var resolvedCopyStatement = construct.ResolveVariables(escapeChar).TrimEnd(); - var copyInstruction = (Valleysoft.DockerfileModel.CopyInstruction)construct; + var copyInstruction = (CopyInstruction)construct; var reference = copyInstruction.FromStageName; if (string.IsNullOrWhiteSpace(resolvedCopyStatement) || string.IsNullOrWhiteSpace(reference)) { @@ -155,7 +155,7 @@ private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char stageNameMap.TryGetValue(reference, out var stageNameReference); if (!string.IsNullOrEmpty(stageNameReference)) { - if (HasUnresolvedVariables(stageNameReference)) + if (this.HasUnresolvedVariables(stageNameReference)) { return null; } @@ -165,7 +165,7 @@ private DockerReference ParseCopyInstruction(DockerfileConstruct construct, char } } - if (HasUnresolvedVariables(reference)) + if (this.HasUnresolvedVariables(reference)) { return null; } diff --git a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs index 973bdec64..a6bb78c98 100644 --- a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs @@ -44,7 +44,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var file = processRequest.ComponentStream; var projectRootDirectory = Directory.GetParent(file.Location); - if (projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) + if (this.projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) { return; } @@ -52,26 +52,26 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var wasGoCliScanSuccessful = false; try { - if (!IsGoCliManuallyDisabled()) + if (!this.IsGoCliManuallyDisabled()) { - wasGoCliScanSuccessful = await UseGoCliToScan(file.Location, singleFileComponentRecorder); + wasGoCliScanSuccessful = await this.UseGoCliToScan(file.Location, singleFileComponentRecorder); } else { - Logger.LogInfo("Go cli scan was manually disabled, fallback strategy performed." + - " More info: https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy"); + this.Logger.LogInfo("Go cli scan was manually disabled, fallback strategy performed." + + " More info: https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy"); } } catch (Exception ex) { - Logger.LogError($"Failed to detect components using go cli. Location: {file.Location}"); - Logger.LogException(ex, isError: true, printException: true); + this.Logger.LogError($"Failed to detect components using go cli. Location: {file.Location}"); + this.Logger.LogException(ex, isError: true, printException: true); } finally { if (wasGoCliScanSuccessful) { - projectRoots.Add(projectRootDirectory.FullName); + this.projectRoots.Add(projectRootDirectory.FullName); } else { @@ -80,15 +80,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio { case ".mod": { - Logger.LogVerbose("Found Go.mod: " + file.Location); - ParseGoModFile(singleFileComponentRecorder, file); + this.Logger.LogVerbose("Found Go.mod: " + file.Location); + this.ParseGoModFile(singleFileComponentRecorder, file); break; } case ".sum": { - Logger.LogVerbose("Found Go.sum: " + file.Location); - ParseGoSumFile(singleFileComponentRecorder, file); + this.Logger.LogVerbose("Found Go.sum: " + file.Location); + this.ParseGoSumFile(singleFileComponentRecorder, file); break; } @@ -109,32 +109,32 @@ private async Task UseGoCliToScan(string location, ISingleFileComponentRec var projectRootDirectory = Directory.GetParent(location); record.ProjectRoot = projectRootDirectory.FullName; - var isGoAvailable = await CommandLineInvocationService.CanCommandBeLocated("go", null, workingDirectory: projectRootDirectory, new[] { "version" }); + var isGoAvailable = await this.CommandLineInvocationService.CanCommandBeLocated("go", null, workingDirectory: projectRootDirectory, new[] { "version" }); record.IsGoAvailable = isGoAvailable; if (!isGoAvailable) { - Logger.LogInfo("Go CLI was not found in the system"); + this.Logger.LogInfo("Go CLI was not found in the system"); return false; } - Logger.LogInfo("Go CLI was found in system and will be used to generate dependency graph. " + - "Detection time may be improved by activating fallback strategy (https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy). " + - "But, it will introduce noise into the detected components."); - var goDependenciesProcess = await CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-m", "-json", "all" }); + this.Logger.LogInfo("Go CLI was found in system and will be used to generate dependency graph. " + + "Detection time may be improved by activating fallback strategy (https://github.com/microsoft/component-detection/blob/main/docs/detectors/go.md#fallback-detection-strategy). " + + "But, it will introduce noise into the detected components."); + var goDependenciesProcess = await this.CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-m", "-json", "all" }); if (goDependenciesProcess.ExitCode != 0) { - Logger.LogError($"Go CLI command \"go list -m -json all\" failed with error:\n {goDependenciesProcess.StdErr}"); - Logger.LogError($"Go CLI could not get dependency build list at location: {location}. Fallback go.sum/go.mod parsing will be used."); + this.Logger.LogError($"Go CLI command \"go list -m -json all\" failed with error:\n {goDependenciesProcess.StdErr}"); + this.Logger.LogError($"Go CLI could not get dependency build list at location: {location}. Fallback go.sum/go.mod parsing will be used."); return false; } - RecordBuildDependencies(goDependenciesProcess.StdOut, singleFileComponentRecorder); + this.RecordBuildDependencies(goDependenciesProcess.StdOut, singleFileComponentRecorder); - var generateGraphProcess = await CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new List { "mod", "graph" }.ToArray()); + var generateGraphProcess = await this.CommandLineInvocationService.ExecuteCommand("go", null, workingDirectory: projectRootDirectory, new List { "mod", "graph" }.ToArray()); if (generateGraphProcess.ExitCode == 0) { - PopulateDependencyGraph(generateGraphProcess.StdOut, singleFileComponentRecorder); + this.PopulateDependencyGraph(generateGraphProcess.StdOut, singleFileComponentRecorder); record.WasGraphSuccessful = true; } @@ -156,13 +156,13 @@ private void ParseGoModFile( // Stopping at the first ) restrict the detection to only the require section. while ((line = reader.ReadLine()) != null && !line.EndsWith(")")) { - if (TryToCreateGoComponentFromModLine(line, out var goComponent)) + if (this.TryToCreateGoComponentFromModLine(line, out var goComponent)) { singleFileComponentRecorder.RegisterUsage(new DetectedComponent(goComponent)); } else { - Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]"); + this.Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]"); } } } @@ -195,13 +195,13 @@ private void ParseGoSumFile( string line; while ((line = reader.ReadLine()) != null) { - if (TryToCreateGoComponentFromSumLine(line, out var goComponent)) + if (this.TryToCreateGoComponentFromSumLine(line, out var goComponent)) { singleFileComponentRecorder.RegisterUsage(new DetectedComponent(goComponent)); } else { - Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]"); + this.Logger.LogWarning($"Line could not be parsed for component [{line.Trim()}]"); } } } @@ -238,16 +238,16 @@ private void PopulateDependencyGraph(string goGraphOutput, ISingleFileComponentR continue; } - Logger.LogWarning("Unexpected relationship output from go mod graph:"); - Logger.LogWarning(relationship); + this.Logger.LogWarning("Unexpected relationship output from go mod graph:"); + this.Logger.LogWarning(relationship); continue; } GoComponent parentComponent; GoComponent childComponent; - var isParentParsed = TryCreateGoComponentFromRelationshipPart(components[0], out parentComponent); - var isChildParsed = TryCreateGoComponentFromRelationshipPart(components[1], out childComponent); + var isParentParsed = this.TryCreateGoComponentFromRelationshipPart(components[0], out parentComponent); + var isChildParsed = this.TryCreateGoComponentFromRelationshipPart(components[1], out childComponent); if (!isParentParsed) { @@ -257,14 +257,14 @@ private void PopulateDependencyGraph(string goGraphOutput, ISingleFileComponentR if (isChildParsed) { - if (IsModuleInBuildList(componentRecorder, parentComponent) && IsModuleInBuildList(componentRecorder, childComponent)) + if (this.IsModuleInBuildList(componentRecorder, parentComponent) && this.IsModuleInBuildList(componentRecorder, childComponent)) { componentRecorder.RegisterUsage(new DetectedComponent(childComponent), parentComponentId: parentComponent.Id); } } else { - Logger.LogWarning($"Failed to parse components from relationship string {relationship}"); + this.Logger.LogWarning($"Failed to parse components from relationship string {relationship}"); } } } @@ -324,7 +324,7 @@ private bool TryCreateGoComponentFromRelationshipPart(string relationship, out G private bool IsGoCliManuallyDisabled() { - return EnvVarService.IsEnvironmentVariableValueTrue("DisableGoCliScan"); + return this.EnvVarService.IsEnvironmentVariableValueTrue("DisableGoCliScan"); } private class GoBuildModule diff --git a/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs index 873f4eba1..0382b0a8a 100644 --- a/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs @@ -31,8 +31,8 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs) { - if (await IsAntLocallyAvailableAsync()) + if (await this.IsAntLocallyAvailableAsync()) { return processRequests; } - Logger.LogVerbose("Skipping Ivy detection as ant is not available in the local PATH."); + this.Logger.LogVerbose("Skipping Ivy detection as ant is not available in the local PATH."); return Enumerable.Empty().ToObservable(); } @@ -80,18 +80,18 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio { if (File.Exists(ivySettingsFilePath)) { - Logger.LogInfo($"Processing {ivyXmlFile.Location} and ivysettings.xml."); - await ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, ivySettingsFilePath); + this.Logger.LogInfo($"Processing {ivyXmlFile.Location} and ivysettings.xml."); + await this.ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, ivySettingsFilePath); } else { - Logger.LogInfo($"Processing {ivyXmlFile.Location}."); - await ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, null); + this.Logger.LogInfo($"Processing {ivyXmlFile.Location}."); + await this.ProcessIvyAndIvySettingsFilesAsync(singleFileComponentRecorder, ivyXmlFile.Location, null); } } else { - Logger.LogError($"File {ivyXmlFile.Location} passed to OnFileFound, but does not exist!"); + this.Logger.LogError($"File {ivyXmlFile.Location} passed to OnFileFound, but does not exist!"); } } @@ -103,27 +103,27 @@ private async Task ProcessIvyAndIvySettingsFilesAsync( try { string workingDirectory = Path.Combine(Path.GetTempPath(), "ComponentDetection_Ivy"); - Logger.LogVerbose($"Preparing temporary Ivy project in {workingDirectory}"); + this.Logger.LogVerbose($"Preparing temporary Ivy project in {workingDirectory}"); if (Directory.Exists(workingDirectory)) { Directory.Delete(workingDirectory, recursive: true); } - InitTemporaryAntProject(workingDirectory, ivyXmlFile, ivySettingsXmlFile); - if (await RunAntToDetectDependenciesAsync(workingDirectory)) + this.InitTemporaryAntProject(workingDirectory, ivyXmlFile, ivySettingsXmlFile); + if (await this.RunAntToDetectDependenciesAsync(workingDirectory)) { string instructionsFile = Path.Combine(workingDirectory, "target", "RegisterUsage.json"); - RegisterUsagesFromFile(singleFileComponentRecorder, instructionsFile); + this.RegisterUsagesFromFile(singleFileComponentRecorder, instructionsFile); } Directory.Delete(workingDirectory, recursive: true); } catch (Exception e) { - Logger.LogError("Exception occurred during Ivy file processing: " + e); + this.Logger.LogError("Exception occurred during Ivy file processing: " + e); // If something went wrong, just ignore the file - Logger.LogFailedReadingFile(ivyXmlFile, e); + this.Logger.LogFailedReadingFile(ivyXmlFile, e); } } @@ -156,40 +156,40 @@ private async Task IsAntLocallyAvailableAsync() { // Note: calling CanCommandBeLocated populates a cache of valid commands. If it is not called before ExecuteCommand, // ExecuteCommand calls CanCommandBeLocated with no arguments, which fails. - return await CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, AntVersionArgument); + return await this.CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, AntVersionArgument); } private async Task RunAntToDetectDependenciesAsync(string workingDirectory) { bool ret = false; - Logger.LogVerbose($"Executing command `ant resolve-dependencies` in directory {workingDirectory}"); - CommandLineExecutionResult result = await CommandLineInvocationService.ExecuteCommand(PrimaryCommand, additionalCandidateCommands: AdditionalValidCommands, "-buildfile", workingDirectory, "resolve-dependencies"); + this.Logger.LogVerbose($"Executing command `ant resolve-dependencies` in directory {workingDirectory}"); + CommandLineExecutionResult result = await this.CommandLineInvocationService.ExecuteCommand(PrimaryCommand, additionalCandidateCommands: AdditionalValidCommands, "-buildfile", workingDirectory, "resolve-dependencies"); if (result.ExitCode == 0) { - Logger.LogVerbose("Ant command succeeded"); + this.Logger.LogVerbose("Ant command succeeded"); ret = true; } else { - Logger.LogError($"Ant command failed with return code {result.ExitCode}"); + this.Logger.LogError($"Ant command failed with return code {result.ExitCode}"); } if (string.IsNullOrWhiteSpace(result.StdOut)) { - Logger.LogVerbose("Ant command wrote nothing to stdout."); + this.Logger.LogVerbose("Ant command wrote nothing to stdout."); } else { - Logger.LogVerbose("Ant command stdout:\n" + result.StdOut); + this.Logger.LogVerbose("Ant command stdout:\n" + result.StdOut); } if (string.IsNullOrWhiteSpace(result.StdErr)) { - Logger.LogVerbose("Ant command wrote nothing to stderr."); + this.Logger.LogVerbose("Ant command wrote nothing to stderr."); } else { - Logger.LogWarning("Ant command stderr:\n" + result.StdErr); + this.Logger.LogWarning("Ant command stderr:\n" + result.StdErr); } return ret; @@ -228,7 +228,7 @@ private void RegisterUsagesFromFile(ISingleFileComponentRecorder singleFileCompo } else { - Logger.LogWarning($"Dependency \"{component.Id}\" could not be resolved by Ivy, and so has not been recorded by Component Detection."); + this.Logger.LogWarning($"Dependency \"{component.Id}\" could not be resolved by Ivy, and so has not been recorded by Component Detection."); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs b/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs index 69d8fa481..ce54f799a 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/Contracts/SyftOutput.cs @@ -313,7 +313,7 @@ public partial struct ConfigurationUnion public static implicit operator ConfigurationUnion(double Double) => new ConfigurationUnion { Double = Double }; public static implicit operator ConfigurationUnion(long Integer) => new ConfigurationUnion { Integer = Integer }; public static implicit operator ConfigurationUnion(string String) => new ConfigurationUnion { String = String }; - public bool IsNull => AnythingArray == null && Bool == null && Double == null && Integer == null && AnythingMap == null && String == null; + public bool IsNull => this.AnythingArray == null && this.Bool == null && this.Double == null && this.Integer == null && this.AnythingMap == null && this.String == null; } public partial struct Author diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs index 4ae74067e..4a174b1a6 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs @@ -46,26 +46,26 @@ public async Task ExecuteDetectorAsync(ScanRequest if (imagesToProcess == null || !imagesToProcess.Any()) { - Logger.LogInfo("No instructions received to scan docker images."); + this.Logger.LogInfo("No instructions received to scan docker images."); return EmptySuccessfulScan(); } var cancellationTokenSource = new CancellationTokenSource(GetTimeout(request.DetectorArgs)); - if (!await DockerService.CanRunLinuxContainersAsync(cancellationTokenSource.Token)) + if (!await this.DockerService.CanRunLinuxContainersAsync(cancellationTokenSource.Token)) { using var record = new LinuxContainerDetectorUnsupportedOs { Os = RuntimeInformation.OSDescription, }; - Logger.LogInfo("Linux containers are not available on this host."); + this.Logger.LogInfo("Linux containers are not available on this host."); return EmptySuccessfulScan(); } var results = Enumerable.Empty(); try { - results = await ProcessImagesAsync(imagesToProcess, request.ComponentRecorder, cancellationTokenSource.Token); + results = await this.ProcessImagesAsync(imagesToProcess, request.ComponentRecorder, cancellationTokenSource.Token); } catch (OperationCanceledException) { @@ -91,15 +91,15 @@ private async Task> ProcessImagesAsync( try { // Check image exists locally. Try docker pull if not - if (!(await DockerService.ImageExistsLocallyAsync(image, cancellationToken) || - await DockerService.TryPullImageAsync(image, cancellationToken))) + if (!(await this.DockerService.ImageExistsLocallyAsync(image, cancellationToken) || + await this.DockerService.TryPullImageAsync(image, cancellationToken))) { throw new InvalidUserInputException( $"Docker image {image} could not be found locally and could not be pulled. Verify the image is either available locally or through docker pull.", null); } - var imageDetails = await DockerService.InspectImageAsync(image, cancellationToken); + var imageDetails = await this.DockerService.InspectImageAsync(image, cancellationToken); // Unable to fetch image details if (imageDetails == null) @@ -111,7 +111,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken))) } catch (Exception e) { - Logger.LogWarning($"Processing of image {image} failed with exception: {e.Message}"); + this.Logger.LogWarning($"Processing of image {image} failed with exception: {e.Message}"); using var record = new LinuxContainerDetectorImageDetectionFailed { ExceptionType = e.GetType().ToString(), @@ -130,7 +130,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken))) { var internalContainerDetails = kvp.Value; var image = kvp.Key; - int baseImageLayerCount = await GetBaseImageLayerCount(internalContainerDetails, image, cancellationToken); + int baseImageLayerCount = await this.GetBaseImageLayerCount(internalContainerDetails, image, cancellationToken); //Update the layer information to specify if a layer was fond in the specified baseImage internalContainerDetails.Layers = internalContainerDetails.Layers.Select(layer => new DockerLayer @@ -140,7 +140,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken))) IsBaseImage = layer.LayerIndex < baseImageLayerCount, }); - var layers = await LinuxScanner.ScanLinuxAsync(kvp.Value.ImageId, internalContainerDetails.Layers, baseImageLayerCount, cancellationToken); + var layers = await this.LinuxScanner.ScanLinuxAsync(kvp.Value.ImageId, internalContainerDetails.Layers, baseImageLayerCount, cancellationToken); var components = layers.SelectMany(layer => layer.LinuxComponents.Select(linuxComponent => new DetectedComponent(linuxComponent, null, internalContainerDetails.Id, layer.DockerLayer.LayerIndex))); internalContainerDetails.Layers = layers.Select(layer => layer.DockerLayer); @@ -154,7 +154,7 @@ await DockerService.TryPullImageAsync(image, cancellationToken))) } catch (Exception e) { - Logger.LogWarning($"Scanning of image {kvp.Key} failed with exception: {e.Message}"); + this.Logger.LogWarning($"Scanning of image {kvp.Key} failed with exception: {e.Message}"); using var record = new LinuxContainerDetectorImageDetectionFailed { ExceptionType = e.GetType().ToString(), @@ -212,11 +212,11 @@ private async Task GetBaseImageLayerCount(ContainerDetails scannedImageDeta if (string.IsNullOrEmpty(scannedImageDetails.BaseImageRef)) { record.BaseImageLayerMessage = $"Base image annotations not found on image {image}, Results will not be mapped to base image layers"; - Logger.LogInfo(record.BaseImageLayerMessage); + this.Logger.LogInfo(record.BaseImageLayerMessage); return 0; } else if (scannedImageDetails.BaseImageRef == "scratch") { record.BaseImageLayerMessage = $"{image} has no base image"; - Logger.LogInfo(record.BaseImageLayerMessage); + this.Logger.LogInfo(record.BaseImageLayerMessage); return 0; } @@ -225,19 +225,19 @@ private async Task GetBaseImageLayerCount(ContainerDetails scannedImageDeta record.BaseImageDigest = baseImageDigest; record.BaseImageRef = scannedImageDetails.BaseImageRef; - if (!(await DockerService.ImageExistsLocallyAsync(refWithDigest, cancellationToken) || - await DockerService.TryPullImageAsync(refWithDigest, cancellationToken))) + if (!(await this.DockerService.ImageExistsLocallyAsync(refWithDigest, cancellationToken) || + await this.DockerService.TryPullImageAsync(refWithDigest, cancellationToken))) { record.BaseImageLayerMessage = $"Base image {refWithDigest} could not be found locally and could not be pulled. Results will not be mapped to base image layers"; - Logger.LogInfo(record.BaseImageLayerMessage); + this.Logger.LogInfo(record.BaseImageLayerMessage); return 0; } - var baseImageDetails = await DockerService.InspectImageAsync(refWithDigest, cancellationToken); - if (!ValidateBaseImageLayers(scannedImageDetails, baseImageDetails)) + var baseImageDetails = await this.DockerService.InspectImageAsync(refWithDigest, cancellationToken); + if (!this.ValidateBaseImageLayers(scannedImageDetails, baseImageDetails)) { record.BaseImageLayerMessage = $"Docker image {image} was set to have base image {refWithDigest} but is not built off of it. Results will not be mapped to base image layers"; - Logger.LogInfo(record.BaseImageLayerMessage); + this.Logger.LogInfo(record.BaseImageLayerMessage); return 0; } diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs index 5b3ba1493..2a01a3678 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs @@ -58,19 +58,19 @@ public async Task> ScanLinuxAsync(string try { var command = new List { imageHash }.Concat(CmdParameters).ToList(); - (stdout, stderr) = await DockerService.CreateAndRunContainerAsync(ScannerImage, command, cancellationToken); + (stdout, stderr) = await this.DockerService.CreateAndRunContainerAsync(ScannerImage, command, cancellationToken); } catch (Exception e) { syftTelemetryRecord.Exception = JsonConvert.SerializeObject(e); - Logger.LogException(e, false); + this.Logger.LogException(e, false); throw; } } else { record.SemaphoreFailure = true; - Logger.LogWarning($"Failed to enter the docker semaphore for image {imageHash}"); + this.Logger.LogWarning($"Failed to enter the docker semaphore for image {imageHash}"); } } finally diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs b/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs index 679ae7e48..c4ad7fc0d 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs @@ -10,7 +10,7 @@ public class GraphNode { public GraphNode(T value) { - Value = value; + this.Value = value; } public T Value { get; set; } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs index 01ed2656f..574238bea 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs @@ -29,18 +29,18 @@ public class MavenCommandService : IMavenCommandService public async Task MavenCLIExists() { - return await CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, MvnVersionArgument); + return await this.CommandLineInvocationService.CanCommandBeLocated(PrimaryCommand, AdditionalValidCommands, MvnVersionArgument); } public async Task GenerateDependenciesFile(ProcessRequest processRequest) { var pomFile = processRequest.ComponentStream; - var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={BcdeMvnDependencyFileName}", "-DoutputType=text", $"-f{pomFile.Location}" }; - var result = await CommandLineInvocationService.ExecuteCommand(PrimaryCommand, AdditionalValidCommands, cliParameters); + var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={this.BcdeMvnDependencyFileName}", "-DoutputType=text", $"-f{pomFile.Location}" }; + var result = await this.CommandLineInvocationService.ExecuteCommand(PrimaryCommand, AdditionalValidCommands, cliParameters); if (result.ExitCode != 0) { - Logger.LogVerbose($"Mvn execution failed for pom file: {pomFile.Location}"); - Logger.LogError(string.IsNullOrEmpty(result.StdErr) ? result.StdOut : result.StdErr); + this.Logger.LogVerbose($"Mvn execution failed for pom file: {pomFile.Location}"); + this.Logger.LogError(string.IsNullOrEmpty(result.StdErr) ? result.StdOut : result.StdErr); } } @@ -49,7 +49,7 @@ public void ParseDependenciesFile(ProcessRequest processRequest) using StreamReader sr = new StreamReader(processRequest.ComponentStream.Stream); var lines = sr.ReadToEnd().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); - ParserService.Parse(lines, processRequest.SingleFileComponentRecorder); + this.ParserService.Parse(lines, processRequest.SingleFileComponentRecorder); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs index 8efc18f47..95dfe38a7 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs @@ -21,12 +21,12 @@ public class MavenStyleDependencyGraphParser private void StartDependencyCategory(string categoryName) { - if (DependencyCategory != null) + if (this.DependencyCategory != null) { throw new InvalidOperationException("Current category must be finished before starting new category."); } - DependencyCategory = new GraphNode(categoryName); + this.DependencyCategory = new GraphNode(categoryName); } public GraphNode Parse(string[] lines) @@ -34,21 +34,21 @@ public GraphNode Parse(string[] lines) foreach (var line in lines) { var localLine = line.Trim(TrimCharacters); - if (!string.IsNullOrWhiteSpace(localLine) && DependencyCategory == null) + if (!string.IsNullOrWhiteSpace(localLine) && this.DependencyCategory == null) { - StartDependencyCategory(localLine); + this.StartDependencyCategory(localLine); } else { var splitterOrDefault = ComponentSplitters.FirstOrDefault(x => localLine.Contains(x)); if (splitterOrDefault != null) { - TrackDependency(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim()); + this.TrackDependency(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim()); } } } - return DependencyCategory; + return this.DependencyCategory; } public void Parse(string[] lines, ISingleFileComponentRecorder singleFileComponentRecorder) @@ -56,10 +56,10 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone foreach (var line in lines) { var localLine = line.Trim(TrimCharacters); - if (!string.IsNullOrWhiteSpace(localLine) && topLevelComponent == null) + if (!string.IsNullOrWhiteSpace(localLine) && this.topLevelComponent == null) { var topLevelMavenStringInfo = MavenParsingUtilities.GenerateDetectedComponentAndMetadataFromMavenString(localLine); - topLevelComponent = topLevelMavenStringInfo.Component; + this.topLevelComponent = topLevelMavenStringInfo.Component; singleFileComponentRecorder.RegisterUsage( topLevelMavenStringInfo.Component, isDevelopmentDependency: topLevelMavenStringInfo.IsDevelopmentDependency, @@ -71,7 +71,7 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone if (splitterOrDefault != null) { - RecordDependencies(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim(), singleFileComponentRecorder); + this.RecordDependencies(line.IndexOf(splitterOrDefault), localLine.Split(new[] { splitterOrDefault }, StringSplitOptions.None)[1].Trim(), singleFileComponentRecorder); } } } @@ -79,40 +79,40 @@ public void Parse(string[] lines, ISingleFileComponentRecorder singleFileCompone private void TrackDependency(int position, string versionedComponent) { - while (stack.Count > 0 && stack.Peek().ParseLevel >= position) + while (this.stack.Count > 0 && this.stack.Peek().ParseLevel >= position) { - stack.Pop(); + this.stack.Pop(); } var myNode = new GraphNodeAtLevel(position, versionedComponent); - if (stack.Count > 0) + if (this.stack.Count > 0) { - var parent = stack.Peek(); + var parent = this.stack.Peek(); parent.Children.Add(myNode); myNode.Parents.Add(parent); } else { - DependencyCategory.Children.Add(myNode); + this.DependencyCategory.Children.Add(myNode); } - stack.Push(myNode); + this.stack.Push(myNode); } private void RecordDependencies(int position, string versionedComponent, ISingleFileComponentRecorder componentRecorder) { - while (tupleStack.Count > 0 && tupleStack.Peek().ParseLevel >= position) + while (this.tupleStack.Count > 0 && this.tupleStack.Peek().ParseLevel >= position) { - tupleStack.Pop(); + this.tupleStack.Pop(); } var componentAndDevDependencyTuple = MavenParsingUtilities.GenerateDetectedComponentAndMetadataFromMavenString(versionedComponent); var newTuple = (ParseLevel: position, componentAndDevDependencyTuple.Component); - if (tupleStack.Count > 0) + if (this.tupleStack.Count > 0) { - var parent = tupleStack.Peek().Component; + var parent = this.tupleStack.Peek().Component; componentRecorder.RegisterUsage(parent); componentRecorder.RegisterUsage( newTuple.Component, @@ -125,12 +125,12 @@ private void RecordDependencies(int position, string versionedComponent, ISingle componentRecorder.RegisterUsage( newTuple.Component, isExplicitReferencedDependency: true, - parentComponentId: topLevelComponent.Component.Id, + parentComponentId: this.topLevelComponent.Component.Id, isDevelopmentDependency: componentAndDevDependencyTuple.IsDevelopmentDependency, dependencyScope: componentAndDevDependencyTuple.dependencyScope); } - tupleStack.Push(newTuple); + this.tupleStack.Push(newTuple); } private class GraphNodeAtLevel : GraphNode @@ -140,7 +140,7 @@ private class GraphNodeAtLevel : GraphNode public GraphNodeAtLevel(int level, T value) : base(value) { - ParseLevel = level; + this.ParseLevel = level; } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs index c7c72de52..19c2e74da 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs @@ -32,15 +32,15 @@ public class MvnCliComponentDetector : FileComponentDetector protected override async Task> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs) { - if (!await MavenCommandService.MavenCLIExists()) + if (!await this.MavenCommandService.MavenCLIExists()) { - Logger.LogVerbose("Skipping maven detection as maven is not available in the local PATH."); + this.Logger.LogVerbose("Skipping maven detection as maven is not available in the local PATH."); return Enumerable.Empty().ToObservable(); } - var processPomFile = new ActionBlock(MavenCommandService.GenerateDependenciesFile); + var processPomFile = new ActionBlock(this.MavenCommandService.GenerateDependenciesFile); - await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => + await this.RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => { processPomFile.Post(processRequest); }); @@ -49,7 +49,8 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => await processPomFile.Completion; - return ComponentStreamEnumerableFactory.GetComponentStreams(CurrentScanRequest.SourceDirectory, new[] { MavenCommandService.BcdeMvnDependencyFileName }, CurrentScanRequest.DirectoryExclusionPredicate) + return this.ComponentStreamEnumerableFactory.GetComponentStreams(this.CurrentScanRequest.SourceDirectory, new[] { + this.MavenCommandService.BcdeMvnDependencyFileName }, this.CurrentScanRequest.DirectoryExclusionPredicate) .Select(componentStream => { // The file stream is going to be disposed after the iteration is finished @@ -64,7 +65,7 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => Location = componentStream.Location, Pattern = componentStream.Pattern, }, - SingleFileComponentRecorder = ComponentRecorder.CreateSingleFileComponentRecorder( + SingleFileComponentRecorder = this.ComponentRecorder.CreateSingleFileComponentRecorder( Path.Combine(Path.GetDirectoryName(componentStream.Location), "pom.xml")), }; }) @@ -73,7 +74,7 @@ await RemoveNestedPomXmls(processRequests).ForEachAsync(processRequest => protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) { - MavenCommandService.ParseDependenciesFile(processRequest); + this.MavenCommandService.ParseDependenciesFile(processRequest); File.Delete(processRequest.ComponentStream.Location); @@ -135,7 +136,7 @@ private IObservable RemoveNestedPomXmls(IObservable string.Equals(Path.GetFileName(x.Location), "pom.xml", StringComparison.OrdinalIgnoreCase)) != null) { - Logger.LogVerbose($"Ignoring pom.xml at {item.Location}, as it has a parent pom.xml that will be processed at {current.Name}\\pom.xml ."); + this.Logger.LogVerbose($"Ignoring pom.xml at {item.Location}, as it has a parent pom.xml that will be processed at {current.Name}\\pom.xml ."); break; } diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs index 7dcae4c45..e964ba0fd 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs @@ -43,16 +43,16 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio contents = await reader.ReadToEndAsync(); } - await SafeProcessAllPackageJTokens(filePath, contents, (token) => + await this.SafeProcessAllPackageJTokens(filePath, contents, (token) => { if (token["name"] == null || token["version"] == null) { - Logger.LogInfo($"{filePath} does not contain a name and/or version. These are required fields for a valid package.json file." + - $"It and its dependencies will not be registered."); + this.Logger.LogInfo($"{filePath} does not contain a name and/or version. These are required fields for a valid package.json file." + + $"It and its dependencies will not be registered."); return false; } - return ProcessIndividualPackageJTokens(filePath, singleFileComponentRecorder, token); + return this.ProcessIndividualPackageJTokens(filePath, singleFileComponentRecorder, token); }); } @@ -60,13 +60,13 @@ private async Task SafeProcessAllPackageJTokens(string sourceFilePath, string co { try { - await ProcessAllPackageJTokensAsync(contents, jtokenProcessor); + await this.ProcessAllPackageJTokensAsync(contents, jtokenProcessor); } catch (Exception e) { // If something went wrong, just ignore the component - Logger.LogBuildWarning($"Could not parse Jtokens from file {sourceFilePath}."); - Logger.LogFailedReadingFile(sourceFilePath, e); + this.Logger.LogBuildWarning($"Could not parse Jtokens from file {sourceFilePath}."); + this.Logger.LogFailedReadingFile(sourceFilePath, e); return; } } @@ -86,11 +86,11 @@ protected virtual bool ProcessIndividualPackageJTokens(string filePath, ISingleF if (!SemanticVersion.TryParse(version, out _)) { - Logger.LogWarning($"Unable to parse version \"{version}\" for package \"{name}\" found at path \"{filePath}\". This may indicate an invalid npm package component and it will not be registered."); + this.Logger.LogWarning($"Unable to parse version \"{version}\" for package \"{name}\" found at path \"{filePath}\". This may indicate an invalid npm package component and it will not be registered."); return false; } - NpmComponent npmComponent = new NpmComponent(name, version, author: GetAuthor(authorToken, name, filePath)); + NpmComponent npmComponent = new NpmComponent(name, version, author: this.GetAuthor(authorToken, name, filePath)); singleFileComponentRecorder.RegisterUsage(new DetectedComponent(npmComponent)); return true; @@ -135,13 +135,13 @@ private NpmAuthor GetAuthor(JToken authorToken, string packageName, string fileP } else { - Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered."); + this.Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered."); return null; } if (string.IsNullOrEmpty(authorName)) { - Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered."); + this.Logger.LogWarning($"Unable to parse author:[{authorString}] for package:[{packageName}] found at path:[{filePath}]. This may indicate an invalid npm package author, and author will not be registered."); return null; } diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs index 58a9677fb..8e0d9f4d2 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetectorWithRoots.cs @@ -49,15 +49,15 @@ public class NpmComponentDetectorWithRoots : FileComponentDetector protected override Task> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs) { - return Task.FromResult(RemoveNodeModuleNestedFiles(processRequests) + return Task.FromResult(this.RemoveNodeModuleNestedFiles(processRequests) .Where(pr => { if (pr.ComponentStream.Pattern.Equals(LernaSearchPattern)) { // Lock LernaFiles so we don't add while we are enumerating in processFiles - lock (lernaFilesLock) + lock (this.lernaFilesLock) { - LernaFiles.Add(pr); + this.LernaFiles.Add(pr); return false; } } @@ -72,15 +72,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - IEnumerable packageJsonComponentStream = ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(file.Location).Directory, packageJsonPattern, (name, directoryName) => false, false); + IEnumerable packageJsonComponentStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(file.Location).Directory, packageJsonPattern, (name, directoryName) => false, false); bool foundUnderLerna = false; IList lernaFilesClone; // ToList LernaFiles to generate a copy we can act on without holding the lock for a long time - lock (lernaFilesLock) + lock (this.lernaFilesLock) { - lernaFilesClone = LernaFiles.ToList(); + lernaFilesClone = this.LernaFiles.ToList(); } foreach (var lernaProcessRequest in lernaFilesClone) @@ -88,23 +88,23 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var lernaFile = lernaProcessRequest.ComponentStream; // We have extra validation on lock files not found below a lerna.json - if (PathUtilityService.IsFileBelowAnother(lernaFile.Location, file.Location)) + if (this.PathUtilityService.IsFileBelowAnother(lernaFile.Location, file.Location)) { foundUnderLerna = true; break; } } - await SafeProcessAllPackageJTokens(file, (token) => + await this.SafeProcessAllPackageJTokens(file, (token) => { if (!foundUnderLerna && (token["name"] == null || token["version"] == null || string.IsNullOrWhiteSpace(token["name"].Value()) || string.IsNullOrWhiteSpace(token["version"].Value()))) { - Logger.LogInfo($"{file.Location} does not contain a valid name and/or version. These are required fields for a valid package-lock.json file." + - $"It and its dependencies will not be registered."); + this.Logger.LogInfo($"{file.Location} does not contain a valid name and/or version. These are required fields for a valid package-lock.json file." + + $"It and its dependencies will not be registered."); return false; } - ProcessIndividualPackageJTokens(singleFileComponentRecorder, token, packageJsonComponentStream, skipValidation: foundUnderLerna); + this.ProcessIndividualPackageJTokens(singleFileComponentRecorder, token, packageJsonComponentStream, skipValidation: foundUnderLerna); return true; }); } @@ -124,7 +124,7 @@ private IObservable RemoveNodeModuleNestedFiles(IObservable RemoveNodeModuleNestedFiles(IObservable item.Location.Contains(folder)); + string skippedFolder = this.SkippedFolders.FirstOrDefault(folder => item.Location.Contains(folder)); // When node_modules is part of the path down to a given item, we skip the item. Otherwise, we yield the item. if (string.IsNullOrEmpty(skippedFolder)) @@ -144,7 +144,7 @@ private IObservable RemoveNodeModuleNestedFiles(IObservable topLevelDependencies, IDictionary dependencyLookup, ISingleFileComponentRecorder singleFileComponentRecorder) @@ -256,7 +256,7 @@ private void TraverseRequirementAndDependencyTree(IEnumerable<(JProperty, TypedC // iterate through everything for a top level dependency with a single explicitReferencedDependency value foreach (var (currentDependency, _) in topLevelDependencies) { - var typedComponent = NpmComponentUtilities.GetTypedComponent(currentDependency, NpmRegistryHost, Logger); + var typedComponent = NpmComponentUtilities.GetTypedComponent(currentDependency, NpmRegistryHost, this.Logger); if (typedComponent == null) { continue; @@ -266,14 +266,14 @@ private void TraverseRequirementAndDependencyTree(IEnumerable<(JProperty, TypedC Queue<(JProperty, TypedComponent)> subQueue = new Queue<(JProperty, TypedComponent)>(); NpmComponentUtilities.TraverseAndRecordComponents(currentDependency, singleFileComponentRecorder, typedComponent, explicitReferencedDependency: typedComponent); - EnqueueDependencies(subQueue, currentDependency.Value["dependencies"], parentComponent: typedComponent); - TryEnqueueFirstLevelDependencies(subQueue, currentDependency.Value["requires"], dependencyLookup, parentComponent: typedComponent); + this.EnqueueDependencies(subQueue, currentDependency.Value["dependencies"], parentComponent: typedComponent); + this.TryEnqueueFirstLevelDependencies(subQueue, currentDependency.Value["requires"], dependencyLookup, parentComponent: typedComponent); while (subQueue.Count != 0) { var (currentSubDependency, parentComponent) = subQueue.Dequeue(); - var typedSubComponent = NpmComponentUtilities.GetTypedComponent(currentSubDependency, NpmRegistryHost, Logger); + var typedSubComponent = NpmComponentUtilities.GetTypedComponent(currentSubDependency, NpmRegistryHost, this.Logger); // only process components that we haven't seen before that have been brought in by the same explicitReferencedDependency, resolves circular npm 'requires' loop if (typedSubComponent == null || previouslyAddedComponents.Contains(typedSubComponent.Id)) @@ -285,8 +285,8 @@ private void TraverseRequirementAndDependencyTree(IEnumerable<(JProperty, TypedC NpmComponentUtilities.TraverseAndRecordComponents(currentSubDependency, singleFileComponentRecorder, typedSubComponent, explicitReferencedDependency: typedComponent, parentComponent.Id); - EnqueueDependencies(subQueue, currentSubDependency.Value["dependencies"], parentComponent: typedSubComponent); - TryEnqueueFirstLevelDependencies(subQueue, currentSubDependency.Value["requires"], dependencyLookup, parentComponent: typedSubComponent); + this.EnqueueDependencies(subQueue, currentSubDependency.Value["dependencies"], parentComponent: typedSubComponent); + this.TryEnqueueFirstLevelDependencies(subQueue, currentSubDependency.Value["requires"], dependencyLookup, parentComponent: typedSubComponent); } } } @@ -336,4 +336,4 @@ private bool TryEnqueueFirstLevelDependencies(Queue<(JProperty, TypedComponent)> return isValid; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs index 7c654b4f9..a04c606bd 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs @@ -40,11 +40,11 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio if (NugetConfigFileName.Equals(stream.Pattern, StringComparison.OrdinalIgnoreCase)) { - await ProcessAdditionalDirectory(processRequest, ignoreNugetConfig); + await this.ProcessAdditionalDirectory(processRequest, ignoreNugetConfig); } else { - await ProcessFile(processRequest); + await this.ProcessFile(processRequest); } } @@ -55,21 +55,21 @@ private async Task ProcessAdditionalDirectory(ProcessRequest processRequest, boo if (!ignoreNugetConfig) { - var additionalPaths = GetRepositoryPathsFromNugetConfig(stream); - Uri rootPath = new Uri(CurrentScanRequest.SourceDirectory.FullName + Path.DirectorySeparatorChar); + var additionalPaths = this.GetRepositoryPathsFromNugetConfig(stream); + Uri rootPath = new Uri(this.CurrentScanRequest.SourceDirectory.FullName + Path.DirectorySeparatorChar); foreach (var additionalPath in additionalPaths) { // Only paths outside of our sourceDirectory need to be added if (!rootPath.IsBaseOf(new Uri(additionalPath.FullName + Path.DirectorySeparatorChar))) { - Logger.LogInfo($"Found path override in nuget configuration file. Adding {additionalPath} to the package search path."); - Logger.LogWarning($"Path {additionalPath} is not rooted in the source tree. More components may be detected than expected if this path is shared across code projects."); + this.Logger.LogInfo($"Found path override in nuget configuration file. Adding {additionalPath} to the package search path."); + this.Logger.LogWarning($"Path {additionalPath} is not rooted in the source tree. More components may be detected than expected if this path is shared across code projects."); - Scanner.Initialize(additionalPath, (name, directoryName) => false, 1); + this.Scanner.Initialize(additionalPath, (name, directoryName) => false, 1); - await Scanner.GetFilteredComponentStreamObservable(additionalPath, SearchPatterns.Where(sp => !NugetConfigFileName.Equals(sp)), singleFileComponentRecorder.GetParentComponentRecorder()) - .ForEachAsync(async fi => await ProcessFile(fi)); + await this.Scanner.GetFilteredComponentStreamObservable(additionalPath, this.SearchPatterns.Where(sp => !NugetConfigFileName.Equals(sp)), singleFileComponentRecorder.GetParentComponentRecorder()) + .ForEachAsync(async fi => await this.ProcessFile(fi)); } } } @@ -112,7 +112,7 @@ private async Task ProcessFile(ProcessRequest processRequest) if (!NuGetVersion.TryParse(version, out NuGetVersion parsedVer)) { - Logger.LogInfo($"Version '{version}' from {stream.Location} could not be parsed as a NuGet version"); + this.Logger.LogInfo($"Version '{version}' from {stream.Location} could not be parsed as a NuGet version"); return; } @@ -126,7 +126,7 @@ private async Task ProcessFile(ProcessRequest processRequest) catch (Exception e) { // If something went wrong, just ignore the component - Logger.LogFailedReadingFile(stream.Location, e); + this.Logger.LogFailedReadingFile(stream.Location, e); } } @@ -149,7 +149,7 @@ private IList GetRepositoryPathsFromNugetConfig(IComponentStream foreach (var entry in config.Elements()) { - if (entry.Attributes().Any(x => repositoryPathKeyNames.Contains(x.Value.ToLower()))) + if (entry.Attributes().Any(x => this.repositoryPathKeyNames.Contains(x.Value.ToLower()))) { string value = entry.Attributes().SingleOrDefault(x => string.Equals(x.Name.LocalName, "value", StringComparison.OrdinalIgnoreCase))?.Value; @@ -174,13 +174,13 @@ private IList GetRepositoryPathsFromNugetConfig(IComponentStream { path = new DirectoryInfo(Path.GetFullPath(potentialPath)); } - else if (IsValidPath(componentStream.Location)) + else if (this.IsValidPath(componentStream.Location)) { path = new DirectoryInfo(Path.GetFullPath(Path.Combine(Path.GetDirectoryName(componentStream.Location), potentialPath))); } else { - Logger.LogWarning($"Excluding discovered path {potentialPath} from location {componentStream.Location} as it could not be determined to be valid."); + this.Logger.LogWarning($"Excluding discovered path {potentialPath} from location {componentStream.Location} as it could not be determined to be valid."); continue; } diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs index 03a70d1bc..013ca7932 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs @@ -52,10 +52,9 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary frameworkComponents = GetFrameworkComponents(lockFile); - var explicitReferencedDependencies = - GetTopLevelLibraries(lockFile) - .Select(x => GetLibraryComponentWithDependencyLookup(lockFile.Libraries, x.name, x.version, x.versionRange)) + HashSet frameworkComponents = this.GetFrameworkComponents(lockFile); + var explicitReferencedDependencies = this.GetTopLevelLibraries(lockFile) + .Select(x => this.GetLibraryComponentWithDependencyLookup(lockFile.Libraries, x.name, x.version, x.versionRange)) .ToList(); var explicitlyReferencedComponentIds = explicitReferencedDependencies @@ -63,20 +62,20 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary target.GetTargetLibrary(x.Name)).Where(x => x != null)) { - NavigateAndRegister(target, explicitlyReferencedComponentIds, singleFileComponentRecorder, library, null, frameworkComponents); + this.NavigateAndRegister(target, explicitlyReferencedComponentIds, singleFileComponentRecorder, library, null, frameworkComponents); } } } catch (Exception e) { // If something went wrong, just ignore the package - Logger.LogFailedReadingFile(processRequest.ComponentStream.Location, e); + this.Logger.LogFailedReadingFile(processRequest.ComponentStream.Location, e); } return Task.CompletedTask; @@ -84,7 +83,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary dotnetRuntimePackageNames, HashSet visited = null) { - if (IsAFrameworkComponent(dotnetRuntimePackageNames, library.Name, library.Dependencies) - || library.Type == ProjectDependencyType) + if (this.IsAFrameworkComponent(dotnetRuntimePackageNames, library.Name, library.Dependencies) + || library.Type == ProjectDependencyType) { return; } @@ -127,7 +126,7 @@ private void NavigateAndRegister( else { visited.Add(dependency.Id); - NavigateAndRegister(target, explicitlyReferencedComponentIds, singleFileComponentRecorder, targetLibrary, libraryComponent.Component.Id, dotnetRuntimePackageNames, visited); + this.NavigateAndRegister(target, explicitlyReferencedComponentIds, singleFileComponentRecorder, targetLibrary, libraryComponent.Component.Id, dotnetRuntimePackageNames, visited); } } } @@ -138,14 +137,14 @@ private bool IsAFrameworkComponent(HashSet frameworkComponents, string l if (isAFrameworkComponent) { - frameworkComponentsThatWereOmmittedWithCount.AddOrUpdate(libraryName, 1, (name, existing) => existing + 1); + this.frameworkComponentsThatWereOmmittedWithCount.AddOrUpdate(libraryName, 1, (name, existing) => existing + 1); if (dependencies != null) { // Also track shallow children if this is a top level library so we have a rough count of how many things have been ommitted + root relationships foreach (var item in dependencies) { - frameworkComponentsThatWereOmmittedWithCount.AddOrUpdate(item.Id, 1, (name, existing) => existing + 1); + this.frameworkComponentsThatWereOmmittedWithCount.AddOrUpdate(item.Id, 1, (name, existing) => existing + 1); } } } @@ -219,10 +218,10 @@ private LockFileLibrary GetLibraryComponentWithDependencyLookup(IList GetFrameworkComponents(LockFile lockFile) var frameworkDependencies = new HashSet(); foreach (var projectFileDependencyGroup in lockFile.ProjectFileDependencyGroups) { - var topLevelLibraries = GetTopLevelLibraries(lockFile); + var topLevelLibraries = this.GetTopLevelLibraries(lockFile); foreach (var (name, version, versionRange) in topLevelLibraries) { - if (netCoreFrameworkNames.Contains(name)) + if (this.netCoreFrameworkNames.Contains(name)) { frameworkDependencies.Add(name); foreach (var target in lockFile.Targets) { var matchingLibrary = target.Libraries.FirstOrDefault(x => x.Name == name); - HashSet dependencyComponents = GetDependencyComponentIds(lockFile, target, matchingLibrary.Dependencies); + HashSet dependencyComponents = this.GetDependencyComponentIds(lockFile, target, matchingLibrary.Dependencies); frameworkDependencies.UnionWith(dependencyComponents); } } } } - foreach (var netstandardDep in netStandardDependencies) + foreach (var netstandardDep in this.netStandardDependencies) { frameworkDependencies.Add(netstandardDep); } @@ -279,7 +278,7 @@ private HashSet GetDependencyComponentIds(LockFile lockFile, LockFileTar else { visited.Add(dependency.Id); - currentComponents.UnionWith(GetDependencyComponentIds(lockFile, target, libraryToExpand.Dependencies, visited)); + currentComponents.UnionWith(this.GetDependencyComponentIds(lockFile, target, libraryToExpand.Dependencies, visited)); } } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs b/src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs index 79761a2af..3d37501df 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/IPyPiClient.cs @@ -63,7 +63,7 @@ public class PyPiClient : IPyPiClient public PyPiClient() { - cacheTelemetry = new PypiCacheTelemetryRecord() + this.cacheTelemetry = new PypiCacheTelemetryRecord() { NumCacheHits = 0, FinalCacheSize = 0, @@ -72,8 +72,8 @@ public PyPiClient() ~PyPiClient() { - cacheTelemetry.FinalCacheSize = cachedResponses.Count; - cacheTelemetry.Dispose(); + this.cacheTelemetry.FinalCacheSize = this.cachedResponses.Count; + this.cacheTelemetry.Dispose(); } /// @@ -84,23 +84,23 @@ public PyPiClient() /// The cached response or a new result from PyPi. private async Task GetAndCachePyPiResponse(string uri) { - if (!checkedMaxEntriesVariable) + if (!this.checkedMaxEntriesVariable) { - InitializeNonDefaultMemoryCache(); + this.InitializeNonDefaultMemoryCache(); } - if (cachedResponses.TryGetValue(uri, out HttpResponseMessage result)) + if (this.cachedResponses.TryGetValue(uri, out HttpResponseMessage result)) { - cacheTelemetry.NumCacheHits++; - Logger.LogVerbose("Retrieved cached Python data from " + uri); + this.cacheTelemetry.NumCacheHits++; + this.Logger.LogVerbose("Retrieved cached Python data from " + uri); return result; } - Logger.LogInfo("Getting Python data from " + uri); + this.Logger.LogInfo("Getting Python data from " + uri); var response = await HttpClient.GetAsync(uri); // The `first - wins` response accepted into the cache. This might be different from the input if another caller wins the race. - return await cachedResponses.GetOrCreateAsync(uri, cacheEntry => + return await this.cachedResponses.GetOrCreateAsync(uri, cacheEntry => { cacheEntry.SlidingExpiration = TimeSpan.FromSeconds(CACHEINTERVALSECONDS); // This entry will expire after CACHEINTERVALSECONDS seconds from last use cacheEntry.Size = 1; // Specify a size of 1 so a set number of entries can always be in the cache @@ -114,14 +114,14 @@ private async Task GetAndCachePyPiResponse(string uri) /// private void InitializeNonDefaultMemoryCache() { - var maxEntriesVariable = EnvironmentVariableService.GetEnvironmentVariable("PyPiMaxCacheEntries"); + var maxEntriesVariable = this.EnvironmentVariableService.GetEnvironmentVariable("PyPiMaxCacheEntries"); if (!string.IsNullOrEmpty(maxEntriesVariable) && long.TryParse(maxEntriesVariable, out var maxEntries)) { - Logger.LogInfo($"Setting IPyPiClient max cache entries to {maxEntries}"); - cachedResponses = new MemoryCache(new MemoryCacheOptions { SizeLimit = maxEntries }); + this.Logger.LogInfo($"Setting IPyPiClient max cache entries to {maxEntries}"); + this.cachedResponses = new MemoryCache(new MemoryCacheOptions { SizeLimit = maxEntries }); } - checkedMaxEntriesVariable = true; + this.checkedMaxEntriesVariable = true; } public async Task> FetchPackageDependencies(string name, string version, PythonProjectRelease release) @@ -129,11 +129,11 @@ public async Task> FetchPackageDependencies(st var dependencies = new List(); var uri = release.Url.ToString(); - var response = await GetAndCachePyPiResponse(uri); + var response = await this.GetAndCachePyPiResponse(uri); if (!response.IsSuccessStatusCode) { - Logger.LogWarning($"Http GET at {release.Url} failed with status code {response.StatusCode}"); + this.Logger.LogWarning($"Http GET at {release.Url} failed with status code {response.StatusCode}"); return dependencies; } @@ -197,25 +197,25 @@ public async Task>> GetRele { using var r = new PypiRetryTelemetryRecord { Name = spec.Name, DependencySpecifiers = spec.DependencySpecifiers?.ToArray(), StatusCode = result.Result.StatusCode }; - Logger.LogWarning($"Received {(int)result.Result.StatusCode} {result.Result.ReasonPhrase} from {requestUri}. Waiting {timeSpan} before retry attempt {retryCount}"); + this.Logger.LogWarning($"Received {(int)result.Result.StatusCode} {result.Result.ReasonPhrase} from {requestUri}. Waiting {timeSpan} before retry attempt {retryCount}"); - Interlocked.Increment(ref retries); + Interlocked.Increment(ref this.retries); }) .ExecuteAsync(() => { - if (Interlocked.Read(ref retries) >= MAXRETRIES) + if (Interlocked.Read(ref this.retries) >= MAXRETRIES) { return Task.FromResult(null); } - return GetAndCachePyPiResponse(requestUri); + return this.GetAndCachePyPiResponse(requestUri); }); if (request == null) { using var r = new PypiMaxRetriesReachedTelemetryRecord { Name = spec.Name, DependencySpecifiers = spec.DependencySpecifiers?.ToArray() }; - Logger.LogWarning($"Call to pypi.org failed, but no more retries allowed!"); + this.Logger.LogWarning($"Call to pypi.org failed, but no more retries allowed!"); return new SortedDictionary>(); } @@ -224,7 +224,7 @@ public async Task>> GetRele { using var r = new PypiFailureTelemetryRecord { Name = spec.Name, DependencySpecifiers = spec.DependencySpecifiers?.ToArray(), StatusCode = request.StatusCode }; - Logger.LogWarning($"Received {(int)request.StatusCode} {request.ReasonPhrase} from {requestUri}"); + this.Logger.LogWarning($"Received {(int)request.StatusCode} {request.ReasonPhrase} from {requestUri}"); return new SortedDictionary>(); } @@ -247,8 +247,8 @@ public async Task>> GetRele } catch (ArgumentException ae) { - Logger.LogError($"Component {release.Key} : {JsonConvert.SerializeObject(release.Value)} could not be added to the sorted list of pip components for spec={spec.Name}. Usually this happens with unexpected PyPi version formats (e.g. prerelease/dev versions). Error details follow:"); - Logger.LogException(ae, true); + this.Logger.LogError($"Component {release.Key} : {JsonConvert.SerializeObject(release.Value)} could not be added to the sorted list of pip components for spec={spec.Name}. Usually this happens with unexpected PyPi version formats (e.g. prerelease/dev versions). Error details follow:"); + this.Logger.LogException(ae, true); continue; } } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs index eb1a63811..7534a04a9 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs @@ -31,10 +31,10 @@ public class PipComponentDetector : FileComponentDetector protected override async Task> OnPrepareDetection(IObservable processRequests, IDictionary detectorArgs) { - CurrentScanRequest.DetectorArgs.TryGetValue("Pip.PythonExePath", out string pythonExePath); - if (!await PythonCommandService.PythonExists(pythonExePath)) + this.CurrentScanRequest.DetectorArgs.TryGetValue("Pip.PythonExePath", out string pythonExePath); + if (!await this.PythonCommandService.PythonExists(pythonExePath)) { - Logger.LogInfo($"No python found on system. Python detection will not run."); + this.Logger.LogInfo($"No python found on system. Python detection will not run."); return Enumerable.Empty().ToObservable(); } @@ -44,13 +44,13 @@ protected override async Task> OnPrepareDetection(IO protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) { - CurrentScanRequest.DetectorArgs.TryGetValue("Pip.PythonExePath", out string pythonExePath); + this.CurrentScanRequest.DetectorArgs.TryGetValue("Pip.PythonExePath", out string pythonExePath); var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; try { - var initialPackages = await PythonCommandService.ParseFile(file.Location, pythonExePath); + var initialPackages = await this.PythonCommandService.ParseFile(file.Location, pythonExePath); var listedPackage = initialPackages.Where(tuple => tuple.Item1 != null) .Select(tuple => tuple.Item1) .Where(x => !string.IsNullOrWhiteSpace(x)) @@ -58,7 +58,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio .Where(x => !x.PackageIsUnsafe()) .ToList(); - var roots = await PythonResolver.ResolveRoots(listedPackage); + var roots = await this.PythonResolver.ResolveRoots(listedPackage); RecordComponents( singleFileComponentRecorder, @@ -71,7 +71,7 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio } catch (Exception e) { - Logger.LogFailedReadingFile(file.Location, e); + this.Logger.LogFailedReadingFile(file.Location, e); } } @@ -121,4 +121,4 @@ private static void RecordComponents( } } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs index 495b843cf..4dd05a539 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PipDependencySpecification.cs @@ -11,7 +11,7 @@ namespace Microsoft.ComponentDetection.Detectors.Pip [DebuggerDisplay("{DebuggerDisplay,nq}")] public class PipDependencySpecification { - private string DebuggerDisplay => $"{Name} ({string.Join(';', DependencySpecifiers)})"; + private string DebuggerDisplay => $"{this.Name} ({string.Join(';', this.DependencySpecifiers)})"; /// /// Gets or sets the package (ex: pyyaml). @@ -58,7 +58,7 @@ public class PipDependencySpecification /// public bool PackageIsUnsafe() { - return PackagesToIgnore.Contains(Name); + return PackagesToIgnore.Contains(this.Name); } /// @@ -86,13 +86,13 @@ public PipDependencySpecification(string packageString, bool requiresDist = fals continue; } - if (string.IsNullOrWhiteSpace(Name)) + if (string.IsNullOrWhiteSpace(this.Name)) { - Name = distMatch.Groups[i].Value; + this.Name = distMatch.Groups[i].Value; } else { - DependencySpecifiers = distMatch.Groups[i].Value.Split(','); + this.DependencySpecifiers = distMatch.Groups[i].Value.Split(','); } } } @@ -103,20 +103,20 @@ public PipDependencySpecification(string packageString, bool requiresDist = fals if (nameMatches.Captures.Count > 0) { - Name = nameMatches.Captures[0].Value; + this.Name = nameMatches.Captures[0].Value; } else { - Name = packageString; + this.Name = packageString; } if (versionMatches.Captures.Count > 0) { - DependencySpecifiers = versionMatches.Captures[0].Value.Split(','); + this.DependencySpecifiers = versionMatches.Captures[0].Value.Split(','); } } - DependencySpecifiers = DependencySpecifiers.Where(x => !x.Contains("python_version")).ToList(); + this.DependencySpecifiers = this.DependencySpecifiers.Where(x => !x.Contains("python_version")).ToList(); } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PipGraphNode.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PipGraphNode.cs index 22606f725..a6aad1e77 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PipGraphNode.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PipGraphNode.cs @@ -11,7 +11,7 @@ public class PipGraphNode { public PipGraphNode(PipComponent value) { - Value = value; + this.Value = value; } public PipComponent Value { get; set; } @@ -20,4 +20,4 @@ public PipGraphNode(PipComponent value) public List Parents { get; } = new List(); } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs index 5ff88f1f2..af53600bb 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs @@ -18,7 +18,7 @@ public class PythonCommandService : IPythonCommandService public async Task PythonExists(string pythonPath = null) { - return !string.IsNullOrEmpty(await ResolvePython(pythonPath)); + return !string.IsNullOrEmpty(await this.ResolvePython(pythonPath)); } public async Task> ParseFile(string filePath, string pythonPath = null) @@ -30,13 +30,13 @@ public async Task PythonExists(string pythonPath = null) if (filePath.EndsWith(".py")) { - return (await ParseSetupPyFile(filePath, pythonPath)) + return (await this.ParseSetupPyFile(filePath, pythonPath)) .Select(component => (component, null)) .ToList(); } else if (filePath.EndsWith(".txt")) { - return ParseRequirementsTextFile(filePath); + return this.ParseRequirementsTextFile(filePath); } else { @@ -46,7 +46,7 @@ public async Task PythonExists(string pythonPath = null) private async Task> ParseSetupPyFile(string filePath, string pythonExePath = null) { - var pythonExecutable = await ResolvePython(pythonExePath); + var pythonExecutable = await this.ResolvePython(pythonExePath); if (string.IsNullOrEmpty(pythonExecutable)) { @@ -55,7 +55,7 @@ private async Task> ParseSetupPyFile(string filePath, string pytho // This calls out to python and prints out an array like: [ packageA, packageB, packageC ] // We need to have python interpret this file because install_requires can be composed at runtime - var command = await CommandLineInvocationService.ExecuteCommand(pythonExecutable, null, $"-c \"import distutils.core; setup=distutils.core.run_setup('{filePath.Replace('\\', '/')}'); print(setup.install_requires)\""); + var command = await this.CommandLineInvocationService.ExecuteCommand(pythonExecutable, null, $"-c \"import distutils.core; setup=distutils.core.run_setup('{filePath.Replace('\\', '/')}'); print(setup.install_requires)\""); if (command.ExitCode != 0) { @@ -130,7 +130,7 @@ private async Task ResolvePython(string pythonPath = null) { string pythonCommand = string.IsNullOrEmpty(pythonPath) ? "python" : pythonPath; - if (await CanCommandBeLocated(pythonCommand)) + if (await this.CanCommandBeLocated(pythonCommand)) { return pythonCommand; } @@ -140,7 +140,7 @@ private async Task ResolvePython(string pythonPath = null) private async Task CanCommandBeLocated(string pythonPath) { - return await CommandLineInvocationService.CanCommandBeLocated(pythonPath, new List { "python3", "python2" }, "--version"); + return await this.CommandLineInvocationService.CanCommandBeLocated(pythonPath, new List { "python3", "python2" }, "--version"); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs index 2444149f9..a563c6642 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs @@ -32,7 +32,7 @@ public async Task> ResolveRoots(IList> ResolveRoots(IList(); + return await this.ProcessQueue(state) ?? new List(); } private async Task> ProcessQueue(PythonResolverState state) @@ -68,7 +68,7 @@ private async Task> ProcessQueue(PythonResolverState state) var (root, currentNode) = state.ProcessingQueue.Dequeue(); // gather all dependencies for the current node - var dependencies = (await FetchPackageDependencies(state, currentNode)).Where(x => !x.PackageIsUnsafe()); + var dependencies = (await this.FetchPackageDependencies(state, currentNode)).Where(x => !x.PackageIsUnsafe()); foreach (var dependencyNode in dependencies) { @@ -81,13 +81,13 @@ private async Task> ProcessQueue(PythonResolverState state) } else if (node != null) { - Logger.LogWarning($"Candidate version ({node.Value.Id}) for {dependencyNode.Name} already exists in map and the version is NOT valid."); - Logger.LogWarning($"Specifiers: {string.Join(',', dependencyNode.DependencySpecifiers)} for package {currentNode.Name} caused this."); + this.Logger.LogWarning($"Candidate version ({node.Value.Id}) for {dependencyNode.Name} already exists in map and the version is NOT valid."); + this.Logger.LogWarning($"Specifiers: {string.Join(',', dependencyNode.DependencySpecifiers)} for package {currentNode.Name} caused this."); // The currently selected version is invalid, try to see if there is another valid version available - if (!await InvalidateAndReprocessAsync(state, node, dependencyNode)) + if (!await this.InvalidateAndReprocessAsync(state, node, dependencyNode)) { - Logger.LogWarning($"Version Resolution for {dependencyNode.Name} failed, assuming last valid version is used."); + this.Logger.LogWarning($"Version Resolution for {dependencyNode.Name} failed, assuming last valid version is used."); // there is no valid version available for the node, dependencies are incompatible, } @@ -95,7 +95,7 @@ private async Task> ProcessQueue(PythonResolverState state) else { // We haven't encountered this package before, so let's fetch it and find a candidate - var result = await PypiClient.GetReleases(dependencyNode); + var result = await this.PypiClient.GetReleases(dependencyNode); if (result.Keys.Any()) { @@ -103,13 +103,13 @@ private async Task> ProcessQueue(PythonResolverState state) var candidateVersion = state.ValidVersionMap[dependencyNode.Name].Keys.Any() ? state.ValidVersionMap[dependencyNode.Name].Keys.Last() : null; - AddGraphNode(state, state.NodeReferences[currentNode.Name], dependencyNode.Name, candidateVersion); + this.AddGraphNode(state, state.NodeReferences[currentNode.Name], dependencyNode.Name, candidateVersion); state.ProcessingQueue.Enqueue((root, dependencyNode)); } else { - Logger.LogWarning($"Dependency Package {dependencyNode.Name} not found in Pypi. Skipping package"); + this.Logger.LogWarning($"Dependency Package {dependencyNode.Name} not found in Pypi. Skipping package"); } } } @@ -146,7 +146,7 @@ private async Task InvalidateAndReprocessAsync( node.Value = new PipComponent(pipComponent.Name, candidateVersion); - var dependencies = (await FetchPackageDependencies(state, newSpec)).ToDictionary(x => x.Name, x => x); + var dependencies = (await this.FetchPackageDependencies(state, newSpec)).ToDictionary(x => x.Name, x => x); var toRemove = new List(); foreach (var child in node.Children) @@ -159,7 +159,7 @@ private async Task InvalidateAndReprocessAsync( } else if (!PythonVersionUtilities.VersionValidForSpec(pipChild.Version, newDependency.DependencySpecifiers)) { - if (!await InvalidateAndReprocessAsync(state, child, newDependency)) + if (!await this.InvalidateAndReprocessAsync(state, child, newDependency)) { return false; } @@ -187,7 +187,7 @@ private async Task> FetchPackageDependencies( return new List(); } - return await PypiClient.FetchPackageDependencies(spec.Name, candidateVersion, packageToFetch); + return await this.PypiClient.FetchPackageDependencies(spec.Name, candidateVersion, packageToFetch); } private void AddGraphNode(PythonResolverState state, PipGraphNode parent, string name, string version) diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersion.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersion.cs index 9fb9a63a0..ecaf57c01 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersion.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonVersion.cs @@ -16,7 +16,7 @@ public class PythonVersion : IComparable public bool Valid { get; set; } - public bool IsReleasedPackage => string.IsNullOrEmpty(PreReleaseLabel) && !PreReleaseNumber.HasValue && !DevNumber.HasValue; + public bool IsReleasedPackage => string.IsNullOrEmpty(this.PreReleaseLabel) && !this.PreReleaseNumber.HasValue && !this.DevNumber.HasValue; public int Epoch { get; set; } @@ -41,60 +41,60 @@ public PythonVersion(string version) var toOperate = version; if (version.EndsWith(".*")) { - Floating = true; + this.Floating = true; toOperate = toOperate.Replace(".*", string.Empty); } - match = PythonVersionRegex.Match(version); + this.match = PythonVersionRegex.Match(version); - if (!match.Success || !string.Equals(match.Value, toOperate, StringComparison.OrdinalIgnoreCase)) + if (!this.match.Success || !string.Equals(this.match.Value, toOperate, StringComparison.OrdinalIgnoreCase)) { - Valid = false; + this.Valid = false; return; } - var groups = match.Groups; + var groups = this.match.Groups; // Epoch is optional, implicitly 0 if not present if (groups["epoch"].Success && int.TryParse(groups["epoch"].Value, out int epoch)) { - Epoch = epoch; + this.Epoch = epoch; } else { - Epoch = 0; + this.Epoch = 0; } - Release = groups["release"].Success ? groups["release"].Value : string.Empty; - PreReleaseLabel = groups["pre_l"].Success ? groups["pre_l"].Value : string.Empty; + this.Release = groups["release"].Success ? groups["release"].Value : string.Empty; + this.PreReleaseLabel = groups["pre_l"].Success ? groups["pre_l"].Value : string.Empty; if (groups["pre_n"].Success && int.TryParse(groups["pre_n"].Value, out int preReleaseNumber)) { - PreReleaseNumber = preReleaseNumber; + this.PreReleaseNumber = preReleaseNumber; } if (groups["post_n1"].Success && int.TryParse(groups["post_n1"].Value, out int postRelease1)) { - PostNumber = postRelease1; + this.PostNumber = postRelease1; } if (groups["post_n2"].Success && int.TryParse(groups["post_n2"].Value, out int postRelease2)) { - PostNumber = postRelease2; + this.PostNumber = postRelease2; } if (groups["dev_l"].Success) { - DevLabel = groups["dev_l"].Value; - DevNumber = 0; + this.DevLabel = groups["dev_l"].Value; + this.DevNumber = 0; } if (groups["dev_n"].Success && int.TryParse(groups["dev_n"].Value, out int devNumber)) { - DevNumber = devNumber; + this.DevNumber = devNumber; } - Valid = true; + this.Valid = true; } public static bool operator >(PythonVersion operand1, PythonVersion operand2) @@ -124,16 +124,16 @@ public int CompareTo(PythonVersion other) return 1; } - if (Epoch > other.Epoch) + if (this.Epoch > other.Epoch) { return 1; } - else if (Epoch < other.Epoch) + else if (this.Epoch < other.Epoch) { return -1; } - if (!string.Equals(Release, other.Release, StringComparison.OrdinalIgnoreCase)) + if (!string.Equals(this.Release, other.Release, StringComparison.OrdinalIgnoreCase)) { int result = CompareReleaseVersions(this, other); if (result != 0) @@ -327,4 +327,4 @@ private static int CompareReleaseVersions(PythonVersion a, PythonVersion b) return lengthCompare; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/Package.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/Package.cs index 26983714c..1bbeafaa0 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/Package.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/Package.cs @@ -17,7 +17,7 @@ public class Package public override string ToString() { - return name; + return this.name; } } #pragma warning restore SA1300 diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetector.cs index affc9c8d1..6c759b7ee 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetector.cs @@ -27,7 +27,7 @@ public class PnpmComponentDetector : FileComponentDetector public PnpmComponentDetector() { - NeedsAutomaticRootDependencyCalculation = true; + this.NeedsAutomaticRootDependencyCalculation = true; } protected override async Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) @@ -35,21 +35,21 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - Logger.LogVerbose("Found yaml file: " + file.Location); - string skippedFolder = SkippedFolders.FirstOrDefault(folder => file.Location.Contains(folder)); + this.Logger.LogVerbose("Found yaml file: " + file.Location); + string skippedFolder = this.SkippedFolders.FirstOrDefault(folder => file.Location.Contains(folder)); if (!string.IsNullOrEmpty(skippedFolder)) { - Logger.LogVerbose($"Skipping found file, it was detected as being within a {skippedFolder} folder."); + this.Logger.LogVerbose($"Skipping found file, it was detected as being within a {skippedFolder} folder."); } try { var pnpmYaml = await PnpmParsingUtilities.DeserializePnpmYamlFile(file); - RecordDependencyGraphFromFile(pnpmYaml, singleFileComponentRecorder); + this.RecordDependencyGraphFromFile(pnpmYaml, singleFileComponentRecorder); } catch (Exception e) { - Logger.LogFailedReadingFile(file.Location, e); + this.Logger.LogFailedReadingFile(file.Location, e); } } @@ -73,12 +73,12 @@ private void RecordDependencyGraphFromFile(PnpmYaml yaml, ISingleFileComponentRe foreach (var dependency in packageKeyValue.Value.dependencies) { // Ignore local packages. - if (IsLocalDependency(dependency)) + if (this.IsLocalDependency(dependency)) { continue; } - var childDetectedComponent = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPath(pnpmPackagePath: CreatePnpmPackagePathFromDependency(dependency.Key, dependency.Value)); + var childDetectedComponent = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPath(pnpmPackagePath: this.CreatePnpmPackagePathFromDependency(dependency.Key, dependency.Value)); // Older code used the root's dev dependency value. We're leaving this null until we do a second pass to look at each components' top level referrers. singleFileComponentRecorder.RegisterUsage(childDetectedComponent, parentComponentId: parentDetectedComponent.Component.Id, isDevelopmentDependency: null); @@ -110,4 +110,4 @@ private string CreatePnpmPackagePathFromDependency(string dependencyName, string return dependencyVersion.Contains('/') ? dependencyVersion : $"/{dependencyName}/{dependencyVersion}"; } } -} \ No newline at end of file +} diff --git a/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs index 7d8e12c50..ef743bce0 100644 --- a/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs @@ -28,7 +28,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary(); poetryLock.package.ToList().ForEach(package => diff --git a/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs index b9f3ee6cc..fe6394380 100644 --- a/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs @@ -67,18 +67,18 @@ private class Dependency public string Location { get; } - public string Id => $"{Name}:{Location}"; + public string Id => $"{this.Name}:{this.Location}"; public Dependency(string name, string location) { - Name = name; - Location = location; + this.Name = name; + this.Location = location; } } public RubyComponentDetector() { - NeedsAutomaticRootDependencyCalculation = true; + this.NeedsAutomaticRootDependencyCalculation = true; } protected override Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) @@ -86,8 +86,8 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary lines, Dictionar var version = splits[1].Substring(1, splits[1].Length - 2); TypedComponent newComponent; - if (IsVersionRelative(version)) + if (this.IsVersionRelative(version)) { - Logger.LogWarning($"Found component with invalid version, name = {name} and version = {version}"); + this.Logger.LogWarning($"Found component with invalid version, name = {name} and version = {version}"); wasParentDependencyExcluded = true; continue; } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs b/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs index aaed25503..d19b2160f 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs @@ -14,10 +14,10 @@ public class CargoDependencyData public CargoDependencyData() { - CargoWorkspaces = new HashSet(); - CargoWorkspaceExclusions = new HashSet(); - NonDevDependencies = new List(); - DevDependencies = new List(); + this.CargoWorkspaces = new HashSet(); + this.CargoWorkspaceExclusions = new HashSet(); + this.NonDevDependencies = new List(); + this.DevDependencies = new List(); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs index 8b2e711ae..bf8b19cc2 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs @@ -29,16 +29,14 @@ public class CargoPackage public override bool Equals(object obj) { var package = obj as CargoPackage; - return package != null && - name.Equals(package.name) && - version.Equals(package.version, StringComparison.OrdinalIgnoreCase); + return package != null && this.name.Equals(package.name) && this.version.Equals(package.version, StringComparison.OrdinalIgnoreCase); } public override int GetHashCode() { var hashCode = -2143789899; - hashCode = (hashCode * -1521134295) + EqualityComparer.Default.GetHashCode(name); - hashCode = (hashCode * -1521134295) + EqualityComparer.Default.GetHashCode(version.ToLowerInvariant()); + hashCode = (hashCode * -1521134295) + EqualityComparer.Default.GetHashCode(this.name); + hashCode = (hashCode * -1521134295) + EqualityComparer.Default.GetHashCode(this.version.ToLowerInvariant()); return hashCode; } } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs b/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs index 2115c6e3b..9094ebe94 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs @@ -13,7 +13,7 @@ public class DependencySpecification public DependencySpecification() { - dependencies = new Dictionary>>(); + this.dependencies = new Dictionary>>(); } public void Add(string name, string cargoVersionSpecifier) @@ -25,22 +25,22 @@ public void Add(string name, string cargoVersionSpecifier) ranges.Add(new Range(specifier.Trim())); } - if (!dependencies.ContainsKey(name)) + if (!this.dependencies.ContainsKey(name)) { - dependencies.Add(name, new HashSet>()); + this.dependencies.Add(name, new HashSet>()); } - dependencies[name].Add(ranges); + this.dependencies[name].Add(ranges); } public bool MatchesPackage(CargoPackage package) { - if (!dependencies.ContainsKey(package.name)) + if (!this.dependencies.ContainsKey(package.name)) { return false; } - foreach (var ranges in dependencies[package.name]) + foreach (var ranges in this.dependencies[package.name]) { var allSatisfied = true; foreach (var range in ranges) diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs index df47d2875..df5878761 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs @@ -37,12 +37,12 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary cargoTomlComponentStream = ComponentStreamEnumerableFactory.GetComponentStreams(lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, (name, directoryName) => false, recursivelyScanDirectories: false); + IEnumerable cargoTomlComponentStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, (name, directoryName) => false, recursivelyScanDirectories: false); CargoDependencyData cargoDependencyData = RustCrateUtilities.ExtractRootDependencyAndWorkspaceSpecifications(cargoTomlComponentStream, singleFileComponentRecorder); @@ -53,7 +53,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary cargoTomlWorkspaceComponentStreams = ComponentStreamEnumerableFactory.GetComponentStreams( + IEnumerable cargoTomlWorkspaceComponentStreams = this.ComponentStreamEnumerableFactory.GetComponentStreams( lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, RustCrateUtilities.BuildExcludeDirectoryPredicateFromWorkspaces(lockFileInfo, cargoDependencyData.CargoWorkspaces, cargoDependencyData.CargoWorkspaceExclusions), @@ -68,14 +68,14 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary 1) { - Logger.LogWarning($"We are expecting exactly 1 accompanying Cargo.toml file next to the cargo.lock file found at {cargoLockFile.Location}"); + this.Logger.LogWarning($"We are expecting exactly 1 accompanying Cargo.toml file next to the cargo.lock file found at {cargoLockFile.Location}"); return Task.CompletedTask; } // If there is a mismatch between the number of expected and found workspaces, exit if (expectedWorkspaceTomlCount > numWorkspaceComponentStreams) { - Logger.LogWarning($"We are expecting at least {expectedWorkspaceTomlCount} accompanying Cargo.toml file(s) from workspaces outside of the root directory {lockFileInfo.DirectoryName}, but found {numWorkspaceComponentStreams}"); + this.Logger.LogWarning($"We are expecting at least {expectedWorkspaceTomlCount} accompanying Cargo.toml file(s) from workspaces outside of the root directory {lockFileInfo.DirectoryName}, but found {numWorkspaceComponentStreams}"); return Task.CompletedTask; } @@ -85,7 +85,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary(RustCrateUtilities.WorkspaceKey); + TomlTable workspaces = cargoToml.Get(WorkspaceKey); - TomlObject workspaceMembers = workspaces.ContainsKey(RustCrateUtilities.WorkspaceMemberKey) ? workspaces[RustCrateUtilities.WorkspaceMemberKey] : null; - TomlObject workspaceExclusions = workspaces.ContainsKey(RustCrateUtilities.WorkspaceExcludeKey) ? workspaces[RustCrateUtilities.WorkspaceExcludeKey] : null; + TomlObject workspaceMembers = workspaces.ContainsKey(WorkspaceMemberKey) ? workspaces[WorkspaceMemberKey] : null; + TomlObject workspaceExclusions = workspaces.ContainsKey(WorkspaceExcludeKey) ? workspaces[WorkspaceExcludeKey] : null; if (workspaceMembers != null) { if (workspaceMembers.TomlType != TomlObjectType.Array) { - throw new InvalidRustTomlFileException($"In accompanying Cargo.toml file expected {RustCrateUtilities.WorkspaceMemberKey} within {RustCrateUtilities.WorkspaceKey} to be of type Array, but found {workspaceMembers.TomlType}"); + throw new InvalidRustTomlFileException($"In accompanying Cargo.toml file expected {WorkspaceMemberKey} within {WorkspaceKey} to be of type Array, but found {workspaceMembers.TomlType}"); } // TomlObject arrays do not natively implement a HashSet get, so add from a list @@ -78,14 +78,14 @@ public static CargoDependencyData ExtractRootDependencyAndWorkspaceSpecification { if (workspaceExclusions.TomlType != TomlObjectType.Array) { - throw new InvalidRustTomlFileException($"In accompanying Cargo.toml file expected {RustCrateUtilities.WorkspaceExcludeKey} within {RustCrateUtilities.WorkspaceKey} to be of type Array, but found {workspaceExclusions.TomlType}"); + throw new InvalidRustTomlFileException($"In accompanying Cargo.toml file expected {WorkspaceExcludeKey} within {WorkspaceKey} to be of type Array, but found {workspaceExclusions.TomlType}"); } cargoDependencyData.CargoWorkspaceExclusions.UnionWith(workspaceExclusions.Get>()); } } - RustCrateUtilities.GenerateDependencies(cargoToml, cargoDependencyData.NonDevDependencies, cargoDependencyData.DevDependencies); + GenerateDependencies(cargoToml, cargoDependencyData.NonDevDependencies, cargoDependencyData.DevDependencies); break; } @@ -110,7 +110,7 @@ public static void ExtractDependencySpecifications(IEnumerable singleFileComponentRecorder.AddAdditionalRelatedFile(cargoTomlFile.Location); - RustCrateUtilities.GenerateDependencies(cargoToml, nonDevDependencySpecifications, devDependencySpecifications); + GenerateDependencies(cargoToml, nonDevDependencySpecifications, devDependencySpecifications); } } @@ -122,8 +122,8 @@ public static void ExtractDependencySpecifications(IEnumerable /// Current list of development dependencies. private static void GenerateDependencies(TomlTable cargoToml, IList nonDevDependencySpecifications, IList devDependencySpecifications) { - var dependencySpecification = RustCrateUtilities.GenerateDependencySpecifications(cargoToml, RustCrateUtilities.NonDevDependencyKeys); - var devDependencySpecification = RustCrateUtilities.GenerateDependencySpecifications(cargoToml, RustCrateUtilities.DevDependencyKeys); + var dependencySpecification = GenerateDependencySpecifications(cargoToml, NonDevDependencyKeys); + var devDependencySpecification = GenerateDependencySpecifications(cargoToml, DevDependencyKeys); // If null, this indicates the toml is an internal file that should not be tracked as a component. if (dependencySpecification != null) diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateV2Detector.cs b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateV2Detector.cs index 3598ef97f..2430038f9 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateV2Detector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateV2Detector.cs @@ -37,12 +37,12 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary cargoTomlComponentStream = ComponentStreamEnumerableFactory.GetComponentStreams(lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, (name, directoryName) => false, recursivelyScanDirectories: false); + IEnumerable cargoTomlComponentStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, (name, directoryName) => false, recursivelyScanDirectories: false); CargoDependencyData cargoDependencyData = RustCrateUtilities.ExtractRootDependencyAndWorkspaceSpecifications(cargoTomlComponentStream, singleFileComponentRecorder); @@ -53,7 +53,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary cargoTomlWorkspaceComponentStreams = ComponentStreamEnumerableFactory.GetComponentStreams( + IEnumerable cargoTomlWorkspaceComponentStreams = this.ComponentStreamEnumerableFactory.GetComponentStreams( lockFileInfo.Directory, new List { RustCrateUtilities.CargoTomlSearchPattern }, RustCrateUtilities.BuildExcludeDirectoryPredicateFromWorkspaces(lockFileInfo, cargoDependencyData.CargoWorkspaces, cargoDependencyData.CargoWorkspaceExclusions), @@ -68,14 +68,14 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary 1) { - Logger.LogWarning($"We are expecting exactly 1 accompanying Cargo.toml file next to the cargo.lock file found at {cargoLockFile.Location}"); + this.Logger.LogWarning($"We are expecting exactly 1 accompanying Cargo.toml file next to the cargo.lock file found at {cargoLockFile.Location}"); return Task.CompletedTask; } // If there is a mismatch between the number of expected and found workspaces, exit if (expectedWorkspaceTomlCount > numWorkspaceComponentStreams) { - Logger.LogWarning($"We are expecting at least {expectedWorkspaceTomlCount} accompanying Cargo.toml file(s) from workspaces outside of the root directory {lockFileInfo.DirectoryName}, but found {numWorkspaceComponentStreams}"); + this.Logger.LogWarning($"We are expecting at least {expectedWorkspaceTomlCount} accompanying Cargo.toml file(s) from workspaces outside of the root directory {lockFileInfo.DirectoryName}, but found {numWorkspaceComponentStreams}"); return Task.CompletedTask; } @@ -85,7 +85,7 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary=0.0.0 - ComparatorType = Operator.GreaterThanOrEqual; - Version = new SemVersion(0, 0, 0); + this.ComparatorType = Operator.GreaterThanOrEqual; + this.Version = new SemVersion(0, 0, 0); } else if (!partialVersion.Minor.HasValue) { - Version = new SemVersion(partialVersion.Major.Value + 1, 0, 0); + this.Version = new SemVersion(partialVersion.Major.Value + 1, 0, 0); } else { - Version = new SemVersion(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); + this.Version = new SemVersion(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); } break; case Operator.GreaterThan: - ComparatorType = Operator.GreaterThanOrEqual; + this.ComparatorType = Operator.GreaterThanOrEqual; if (!partialVersion.Major.HasValue) { // >* is unsatisfiable, so use <0.0.0 - ComparatorType = Operator.LessThan; - Version = new SemVersion(0, 0, 0); + this.ComparatorType = Operator.LessThan; + this.Version = new SemVersion(0, 0, 0); } else if (!partialVersion.Minor.HasValue) { // eg. >1.x -> >=2.0 - Version = new SemVersion(partialVersion.Major.Value + 1, 0, 0); + this.Version = new SemVersion(partialVersion.Major.Value + 1, 0, 0); } else { // eg. >1.2.x -> >=1.3 - Version = new SemVersion(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); + this.Version = new SemVersion(partialVersion.Major.Value, partialVersion.Minor.Value + 1, 0); } break; default: // <1.2.x means <1.2.0 // >=1.2.x means >=1.2.0 - Version = partialVersion.ToZeroVersion(); + this.Version = partialVersion.ToZeroVersion(); break; } } else { - Version = partialVersion.ToZeroVersion(); + this.Version = partialVersion.ToZeroVersion(); } } @@ -108,8 +108,8 @@ public Comparator(Operator comparatorType, SemVersion comparatorVersion) throw new NullReferenceException("Null comparator version"); } - ComparatorType = comparatorType; - Version = comparatorVersion; + this.ComparatorType = comparatorType; + this.Version = comparatorVersion; } public static Tuple TryParse(string input) @@ -145,18 +145,18 @@ private static Operator ParseComparatorType(string input) public bool IsSatisfied(SemVersion version) { - switch (ComparatorType) + switch (this.ComparatorType) { case Operator.Equal: - return version == Version; + return version == this.Version; case Operator.LessThan: - return version < Version; + return version < this.Version; case Operator.LessThanOrEqual: - return version <= Version; + return version <= this.Version; case Operator.GreaterThan: - return version > Version; + return version > this.Version; case Operator.GreaterThanOrEqual: - return version >= Version; + return version >= this.Version; default: throw new InvalidOperationException("Comparator type not recognised."); } @@ -175,17 +175,17 @@ public bool Intersects(Comparator other) c.ComparatorType == Operator.Equal || c.ComparatorType == Operator.LessThanOrEqual; - if (Version > other.Version && (operatorIsLessThan(this) || operatorIsGreaterThan(other))) + if (this.Version > other.Version && (operatorIsLessThan(this) || operatorIsGreaterThan(other))) { return true; } - if (Version < other.Version && (operatorIsGreaterThan(this) || operatorIsLessThan(other))) + if (this.Version < other.Version && (operatorIsGreaterThan(this) || operatorIsLessThan(other))) { return true; } - if (Version == other.Version && ( + if (this.Version == other.Version && ( (operatorIncludesEqual(this) && operatorIncludesEqual(other)) || (operatorIsLessThan(this) && operatorIsLessThan(other)) || (operatorIsGreaterThan(this) && operatorIsGreaterThan(other)))) @@ -208,7 +208,7 @@ public enum Operator public override string ToString() { string operatorString = null; - switch (ComparatorType) + switch (this.ComparatorType) { case Operator.Equal: operatorString = "="; @@ -229,7 +229,7 @@ public override string ToString() throw new InvalidOperationException("Comparator type not recognised."); } - return string.Format("{0}{1}", operatorString, Version); + return string.Format("{0}{1}", operatorString, this.Version); } public bool Equals(Comparator other) @@ -239,17 +239,17 @@ public bool Equals(Comparator other) return false; } - return ComparatorType == other.ComparatorType && Version == other.Version; + return this.ComparatorType == other.ComparatorType && this.Version == other.Version; } public override bool Equals(object other) { - return Equals(other as Comparator); + return this.Equals(other as Comparator); } public override int GetHashCode() { - return ToString().GetHashCode(); + return this.ToString().GetHashCode(); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/ComparatorSet.cs b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/ComparatorSet.cs index a2ecca69b..9a5b79a36 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/ComparatorSet.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/ComparatorSet.cs @@ -20,7 +20,7 @@ internal class ComparatorSet : IEquatable public ComparatorSet(string spec) { - comparators = new List { }; + this.comparators = new List { }; spec = spec.Trim(); if (spec == string.Empty) @@ -50,7 +50,7 @@ public ComparatorSet(string spec) if (result != null) { position += result.Item1; - comparators.AddRange(result.Item2); + this.comparators.AddRange(result.Item2); } } @@ -59,7 +59,7 @@ public ComparatorSet(string spec) if (comparatorResult != null) { position += comparatorResult.Item1; - comparators.Add(comparatorResult.Item2); + this.comparators.Add(comparatorResult.Item2); } if (position == iterStartPosition) @@ -77,13 +77,13 @@ private ComparatorSet(IEnumerable comparators) public bool IsSatisfied(SemVersion version) { - bool satisfied = comparators.All(c => c.IsSatisfied(version)); + bool satisfied = this.comparators.All(c => c.IsSatisfied(version)); if (version.Prerelease != string.Empty) { // If the version is a pre-release, then one of the // comparators must have the same version and also include // a pre-release tag. - return satisfied && comparators.Any(c => + return satisfied && this.comparators.Any(c => c.Version.Prerelease != string.Empty && c.Version.Major == version.Major && c.Version.Minor == version.Minor && @@ -170,25 +170,25 @@ public bool Equals(ComparatorSet other) return false; } - var thisSet = new HashSet(comparators); + var thisSet = new HashSet(this.comparators); return thisSet.SetEquals(other.comparators); } public override bool Equals(object other) { - return Equals(other as ComparatorSet); + return this.Equals(other as ComparatorSet); } public override string ToString() { - return string.Join(" ", comparators.Select(c => c.ToString()).ToArray()); + return string.Join(" ", this.comparators.Select(c => c.ToString()).ToArray()); } public override int GetHashCode() { // XOR is commutative, so this hash code is independent // of the order of comparators. - return comparators.Aggregate(0, (accum, next) => accum ^ next.GetHashCode()); + return this.comparators.Aggregate(0, (accum, next) => accum ^ next.GetHashCode()); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/PartialVersion.cs b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/PartialVersion.cs index f376383ef..5d66fe3e5 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/PartialVersion.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/PartialVersion.cs @@ -61,22 +61,22 @@ public PartialVersion(string input) if (xValues.Contains(match.Groups[1].Value)) { - Major = null; + this.Major = null; } else { - Major = int.Parse(match.Groups[1].Value); + this.Major = int.Parse(match.Groups[1].Value); } if (match.Groups[2].Success) { if (xValues.Contains(match.Groups[3].Value)) { - Minor = null; + this.Minor = null; } else { - Minor = int.Parse(match.Groups[3].Value); + this.Minor = int.Parse(match.Groups[3].Value); } } @@ -84,32 +84,28 @@ public PartialVersion(string input) { if (xValues.Contains(match.Groups[5].Value)) { - Patch = null; + this.Patch = null; } else { - Patch = int.Parse(match.Groups[5].Value); + this.Patch = int.Parse(match.Groups[5].Value); } } if (match.Groups[6].Success) { - PreRelease = match.Groups[7].Value; + this.PreRelease = match.Groups[7].Value; } } public SemVersion ToZeroVersion() { - return new SemVersion( - Major ?? 0, - Minor ?? 0, - Patch ?? 0, - PreRelease); + return new SemVersion(this.Major ?? 0, this.Minor ?? 0, this.Patch ?? 0, this.PreRelease); } public bool IsFull() { - return Major.HasValue && Minor.HasValue && Patch.HasValue; + return this.Major.HasValue && this.Minor.HasValue && this.Patch.HasValue; } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Range.cs b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Range.cs index 30a7e74f8..20846e8ed 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Range.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/SemVer/Range.cs @@ -33,13 +33,13 @@ public Range(string rangeSpec, bool loose = false) { this.rangeSpec = rangeSpec; var comparatorSetSpecs = rangeSpec.Split(new[] { "||" }, StringSplitOptions.None); - comparatorSets = comparatorSetSpecs.Select(s => new ComparatorSet(s)).ToArray(); + this.comparatorSets = comparatorSetSpecs.Select(s => new ComparatorSet(s)).ToArray(); } private Range(IEnumerable comparatorSets) { this.comparatorSets = comparatorSets.ToArray(); - rangeSpec = string.Join(" || ", comparatorSets.Select(cs => cs.ToString()).ToArray()); + this.rangeSpec = string.Join(" || ", comparatorSets.Select(cs => cs.ToString()).ToArray()); } /// @@ -49,7 +49,7 @@ private Range(IEnumerable comparatorSets) /// true if the range is satisfied by the version. public bool IsSatisfied(SemVersion version) { - return comparatorSets.Any(s => s.IsSatisfied(version)); + return this.comparatorSets.Any(s => s.IsSatisfied(version)); } /// @@ -64,7 +64,7 @@ public bool IsSatisfied(string versionString, bool loose = false) try { SemVersion.TryParse(versionString, out SemVersion version, loose); - return IsSatisfied(version); + return this.IsSatisfied(version); } catch (ArgumentException) { @@ -79,7 +79,7 @@ public bool IsSatisfied(string versionString, bool loose = false) /// An IEnumerable of satisfying versions. public IEnumerable Satisfying(IEnumerable versions) { - return versions.Where(IsSatisfied); + return versions.Where(this.IsSatisfied); } /// @@ -91,7 +91,7 @@ public IEnumerable Satisfying(IEnumerable versions) /// An IEnumerable of satisfying version strings. public IEnumerable Satisfying(IEnumerable versions, bool loose = false) { - return versions.Where(v => IsSatisfied(v, loose)); + return versions.Where(v => this.IsSatisfied(v, loose)); } /// @@ -101,7 +101,7 @@ public IEnumerable Satisfying(IEnumerable versions, bool loose = /// The maximum satisfying version, or null if no versions satisfied this range. public SemVersion MaxSatisfying(IEnumerable versions) { - return Satisfying(versions).Max(); + return this.Satisfying(versions).Max(); } /// @@ -112,8 +112,8 @@ public SemVersion MaxSatisfying(IEnumerable versions) /// The maximum satisfying version string, or null if no versions satisfied this range. public string MaxSatisfying(IEnumerable versionStrings, bool loose = false) { - var versions = ValidVersions(versionStrings, loose); - var maxVersion = MaxSatisfying(versions); + var versions = this.ValidVersions(versionStrings, loose); + var maxVersion = this.MaxSatisfying(versions); return maxVersion == null ? null : maxVersion.ToString(); } @@ -124,7 +124,7 @@ public string MaxSatisfying(IEnumerable versionStrings, bool loose = fal /// The Range intersection. public Range Intersect(Range other) { - var allIntersections = comparatorSets.SelectMany( + var allIntersections = this.comparatorSets.SelectMany( thisCs => other.comparatorSets.Select(thisCs.Intersect)) .Where(cs => cs != null).ToList(); @@ -142,7 +142,7 @@ public Range Intersect(Range other) /// The range string. public override string ToString() { - return rangeSpec; + return this.rangeSpec; } public bool Equals(Range other) @@ -152,13 +152,13 @@ public bool Equals(Range other) return false; } - var thisSet = new HashSet(comparatorSets); + var thisSet = new HashSet(this.comparatorSets); return thisSet.SetEquals(other.comparatorSets); } public override bool Equals(object other) { - return Equals(other as Range); + return this.Equals(other as Range); } public static bool operator ==(Range a, Range b) @@ -180,7 +180,7 @@ public override int GetHashCode() { // XOR is commutative, so this hash code is independent // of the order of comparators. - return comparatorSets.Aggregate(0, (accum, next) => accum ^ next.GetHashCode()); + return this.comparatorSets.Aggregate(0, (accum, next) => accum ^ next.GetHashCode()); } // Static convenience methods diff --git a/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs index 58eb2408a..316d333e9 100644 --- a/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs @@ -35,12 +35,12 @@ public class Spdx22ComponentDetector : FileComponentDetector, IDefaultOffCompone protected override Task OnFileFound(ProcessRequest processRequest, IDictionary detectorArgs) { - Logger.LogVerbose($"Discovered SPDX2.2 manifest file at: {processRequest.ComponentStream.Location}"); + this.Logger.LogVerbose($"Discovered SPDX2.2 manifest file at: {processRequest.ComponentStream.Location}"); var file = processRequest.ComponentStream; try { - var hash = GetSHA1HashFromStream(file.Stream); + var hash = this.GetSHA1HashFromStream(file.Stream); // Reset buffer to starting position after hash generation. file.Stream.Seek(0, SeekOrigin.Begin); @@ -54,35 +54,35 @@ protected override Task OnFileFound(ProcessRequest processRequest, IDictionary(reader); if (document != null) { - if (IsSPDXVersionSupported(document)) + if (this.IsSPDXVersionSupported(document)) { - var sbomComponent = ConvertJObjectToSbomComponent(processRequest, document, hash); + var sbomComponent = this.ConvertJObjectToSbomComponent(processRequest, document, hash); processRequest.SingleFileComponentRecorder.RegisterUsage(new DetectedComponent(sbomComponent)); } else { - Logger.LogWarning($"Discovered SPDX at {processRequest.ComponentStream.Location} is not SPDX-2.2 document, skipping"); + this.Logger.LogWarning($"Discovered SPDX at {processRequest.ComponentStream.Location} is not SPDX-2.2 document, skipping"); } } else { - Logger.LogWarning($"Discovered SPDX file at {processRequest.ComponentStream.Location} is not a valid document, skipping"); + this.Logger.LogWarning($"Discovered SPDX file at {processRequest.ComponentStream.Location} is not a valid document, skipping"); } } catch (JsonReaderException) { - Logger.LogWarning($"Unable to parse file at {processRequest.ComponentStream.Location}, skipping"); + this.Logger.LogWarning($"Unable to parse file at {processRequest.ComponentStream.Location}, skipping"); } } catch (Exception e) { - Logger.LogFailedReadingFile(file.Location, e); + this.Logger.LogFailedReadingFile(file.Location, e); } return Task.CompletedTask; } - private bool IsSPDXVersionSupported(JObject document) => supportedSPDXVersions.Contains(document["spdxVersion"]?.ToString(), StringComparer.OrdinalIgnoreCase); + private bool IsSPDXVersionSupported(JObject document) => this.supportedSPDXVersions.Contains(document["spdxVersion"]?.ToString(), StringComparer.OrdinalIgnoreCase); private SpdxComponent ConvertJObjectToSbomComponent(ProcessRequest processRequest, JObject document, string fileHash) { @@ -93,12 +93,12 @@ private SpdxComponent ConvertJObjectToSbomComponent(ProcessRequest processReques if (rootElements != null && rootElements.Count() > 1) { - Logger.LogWarning($"SPDX file at {processRequest.ComponentStream.Location} has more than one element in documentDescribes, first will be selected as root element."); + this.Logger.LogWarning($"SPDX file at {processRequest.ComponentStream.Location} has more than one element in documentDescribes, first will be selected as root element."); } if (rootElements != null && rootElements.Any()) { - Logger.LogWarning($"SPDX file at {processRequest.ComponentStream.Location} does not have root elements in documentDescribes section, considering SPDXRef-Document as a root element."); + this.Logger.LogWarning($"SPDX file at {processRequest.ComponentStream.Location} does not have root elements in documentDescribes section, considering SPDXRef-Document as a root element."); } var rootElementId = rootElements?.FirstOrDefault() ?? "SPDXRef-Document"; diff --git a/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs index 2e31046ea..f2195bb0f 100644 --- a/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs @@ -38,15 +38,15 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - Logger.LogWarning($"vcpkg detector found {file}"); + this.Logger.LogWarning($"vcpkg detector found {file}"); var projectRootDirectory = Directory.GetParent(file.Location); - if (projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) + if (this.projectRoots.Any(path => projectRootDirectory.FullName.StartsWith(path))) { return; } - await ParseSpdxFile(singleFileComponentRecorder, file); + await this.ParseSpdxFile(singleFileComponentRecorder, file); } private async Task ParseSpdxFile( @@ -78,7 +78,7 @@ private async Task ParseSpdxFile( continue; } - Logger.LogWarning($"parsed package {item.Name}"); + this.Logger.LogWarning($"parsed package {item.Name}"); if (item.SPDXID == "SPDXRef-port") { var split = item.VersionInfo.Split('#'); @@ -107,7 +107,7 @@ private async Task ParseSpdxFile( } catch (Exception) { - Logger.LogWarning($"failed while handling {item.Name}"); + this.Logger.LogWarning($"failed while handling {item.Name}"); } } } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs index ae0153dc8..4189f4348 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs @@ -55,16 +55,16 @@ public class YarnBlockFile : IYarnBlockFile private YarnBlockFile(IList parsedFileLines) { - fileLines = parsedFileLines; + this.fileLines = parsedFileLines; - if (fileLines.Count > 0) + if (this.fileLines.Count > 0) { - ReadVersionHeader(); + this.ReadVersionHeader(); } else { - VersionHeader = string.Empty; - YarnLockVersion = YarnLockVersion.Invalid; + this.VersionHeader = string.Empty; + this.YarnLockVersion = YarnLockVersion.Invalid; } } @@ -89,9 +89,9 @@ public static async Task CreateBlockFileAsync(Stream stream) public IEnumerator GetEnumerator() { - while (ReadToNextMajorBlock()) + while (this.ReadToNextMajorBlock()) { - yield return ParseBlock(); + yield return this.ParseBlock(); } yield break; @@ -99,38 +99,38 @@ public IEnumerator GetEnumerator() private void ReadVersionHeader() { - YarnLockVersion = YarnLockVersion.Invalid; + this.YarnLockVersion = YarnLockVersion.Invalid; do { - if (fileLines[fileLineIndex].StartsWith("#")) + if (this.fileLines[this.fileLineIndex].StartsWith("#")) { - if (fileLines[fileLineIndex].Contains("yarn lockfile")) + if (this.fileLines[this.fileLineIndex].Contains("yarn lockfile")) { - YarnLockVersion = YarnLockVersion.V1; - VersionHeader = fileLines[fileLineIndex]; + this.YarnLockVersion = YarnLockVersion.V1; + this.VersionHeader = this.fileLines[this.fileLineIndex]; break; } } - else if (string.IsNullOrEmpty(fileLines[fileLineIndex])) + else if (string.IsNullOrEmpty(this.fileLines[this.fileLineIndex])) { // If the comment header does not specify V1, a V2 metadata block will follow a line break - if (IncrementIndex()) + if (this.IncrementIndex()) { - if (fileLines[fileLineIndex].StartsWith("__metadata:")) + if (this.fileLines[this.fileLineIndex].StartsWith("__metadata:")) { - VersionHeader = fileLines[fileLineIndex]; - YarnLockVersion = YarnLockVersion.V2; + this.VersionHeader = this.fileLines[this.fileLineIndex]; + this.YarnLockVersion = YarnLockVersion.V2; - YarnBlock metadataBlock = ParseBlock(); + YarnBlock metadataBlock = this.ParseBlock(); if (metadataBlock.Values.ContainsKey("version") && metadataBlock.Values.ContainsKey("cacheKey")) { break; } - VersionHeader = null; - YarnLockVersion = YarnLockVersion.Invalid; + this.VersionHeader = null; + this.YarnLockVersion = YarnLockVersion.Invalid; } } } @@ -139,7 +139,7 @@ private void ReadVersionHeader() break; } } - while (IncrementIndex()); + while (this.IncrementIndex()); } /// @@ -156,27 +156,27 @@ private YarnBlock ParseBlock(int level = 0) } // Assuming the pointer has been set up to a block - YarnBlock block = new YarnBlock { Title = fileLines[fileLineIndex].TrimEnd(':').Trim('\"').Trim() }; + YarnBlock block = new YarnBlock { Title = this.fileLines[this.fileLineIndex].TrimEnd(':').Trim('\"').Trim() }; - while (IncrementIndex()) + while (this.IncrementIndex()) { - if (!fileLines[fileLineIndex].StartsWith(currentLevelDelimiter) || string.IsNullOrWhiteSpace(fileLines[fileLineIndex])) + if (!this.fileLines[this.fileLineIndex].StartsWith(currentLevelDelimiter) || string.IsNullOrWhiteSpace(this.fileLines[this.fileLineIndex])) { break; } - if (fileLines[fileLineIndex].EndsWith(":")) + if (this.fileLines[this.fileLineIndex].EndsWith(":")) { - block.Children.Add(ParseBlock(level + 1)); - fileLineIndex--; + block.Children.Add(this.ParseBlock(level + 1)); + this.fileLineIndex--; } else { - string toParse = fileLines[fileLineIndex].Trim(); + string toParse = this.fileLines[this.fileLineIndex].Trim(); // Yarn V1 and V2 have slightly different formats, where V2 adds a : between property name and value // Match on the specified version - var matches = YarnLockVersion == YarnLockVersion.V1 ? YarnV1Regex.Match(toParse) : YarnV2Regex.Match(toParse); + var matches = this.YarnLockVersion == YarnLockVersion.V1 ? YarnV1Regex.Match(toParse) : YarnV2Regex.Match(toParse); if (matches.Groups.Count != 3) // Whole group + two captures { @@ -186,7 +186,7 @@ private YarnBlock ParseBlock(int level = 0) block.Values.Add(matches.Groups[1].Value.Trim('\"'), matches.Groups[2].Value.Trim('\"')); } - if (!Peek() || !fileLines[fileLineIndex].StartsWith(currentLevelDelimiter) || string.IsNullOrWhiteSpace(fileLines[fileLineIndex])) + if (!this.Peek() || !this.fileLines[this.fileLineIndex].StartsWith(currentLevelDelimiter) || string.IsNullOrWhiteSpace(this.fileLines[this.fileLineIndex])) { break; } @@ -197,7 +197,7 @@ private YarnBlock ParseBlock(int level = 0) IEnumerator IEnumerable.GetEnumerator() { - return GetEnumerator(); + return this.GetEnumerator(); } /// @@ -209,13 +209,13 @@ private bool ReadToNextMajorBlock() string line; do { - if (!IncrementIndex()) + if (!this.IncrementIndex()) { return false; } else { - line = fileLines[fileLineIndex]; + line = this.fileLines[this.fileLineIndex]; } } while (string.IsNullOrWhiteSpace(line) || line.StartsWith(" ") || line.StartsWith("\t") || line.StartsWith("#")); @@ -225,9 +225,9 @@ private bool ReadToNextMajorBlock() private bool IncrementIndex() { - fileLineIndex++; + this.fileLineIndex++; - return Peek(); + return this.Peek(); } /// @@ -236,7 +236,7 @@ private bool IncrementIndex() /// private bool Peek() { - if (fileLineIndex >= fileLines.Count) + if (this.fileLineIndex >= this.fileLines.Count) { return false; } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs index 71e30558b..fd4e8c9a4 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs @@ -40,11 +40,11 @@ public YarnLockFile Parse(IYarnBlockFile blockFile, ILogger logger) { YarnEntry yarnEntry = new YarnEntry(); var satisfiedPackages = block.Title.Split(',').Select(x => x.Trim()) - .Select(GenerateBlockTitleNormalizer(block)); + .Select(this.GenerateBlockTitleNormalizer(block)); foreach (var package in satisfiedPackages) { - if (!TryReadNameAndSatisfiedVersion(package, out Tuple parsed)) + if (!this.TryReadNameAndSatisfiedVersion(package, out Tuple parsed)) { continue; } @@ -117,10 +117,10 @@ private Func GenerateBlockTitleNormalizer(YarnBlock block) return blockTitleMember; } - var versionValue = block.Values.FirstOrDefault(x => string.Equals(x.Key, YarnLockParser.VersionString, StringComparison.OrdinalIgnoreCase)); + var versionValue = block.Values.FirstOrDefault(x => string.Equals(x.Key, VersionString, StringComparison.OrdinalIgnoreCase)); if (default(KeyValuePair).Equals(versionValue)) { - Logger.LogWarning("Block without version detected"); + this.Logger.LogWarning("Block without version detected"); return blockTitleMember; } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs index 80831f96d..4668d2674 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs @@ -2,7 +2,7 @@ { public class YarnDependency { - public string LookupKey => $"{Name}@{Version}"; + public string LookupKey => $"{this.Name}@{this.Version}"; public string Name { get; set; } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs index 8984525ea..2fb8a187e 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs @@ -4,7 +4,7 @@ namespace Microsoft.ComponentDetection.Detectors.Yarn { public class YarnEntry { - public string LookupKey => $"{Name}@{Version}"; + public string LookupKey => $"{this.Name}@{this.Version}"; /// /// Gets or sets the non-version qualified name of the entry. diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs index 5ce75013d..14705702c 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs @@ -35,24 +35,24 @@ protected override async Task OnFileFound(ProcessRequest processRequest, IDictio var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - string skippedFolder = SkippedFolders.FirstOrDefault(folder => file.Location.Contains(folder)); + string skippedFolder = this.SkippedFolders.FirstOrDefault(folder => file.Location.Contains(folder)); if (!string.IsNullOrEmpty(skippedFolder)) { - Logger.LogInfo($"Yarn.Lock file {file.Location} was found in a {skippedFolder} folder and will be skipped."); + this.Logger.LogInfo($"Yarn.Lock file {file.Location} was found in a {skippedFolder} folder and will be skipped."); return; } - Logger.LogInfo($"Processing file {file.Location}"); + this.Logger.LogInfo($"Processing file {file.Location}"); try { - var parsed = await YarnLockFileFactory.ParseYarnLockFileAsync(file.Stream, Logger); - DetectComponents(parsed, file.Location, singleFileComponentRecorder); + var parsed = await YarnLockFileFactory.ParseYarnLockFileAsync(file.Stream, this.Logger); + this.DetectComponents(parsed, file.Location, singleFileComponentRecorder); } catch (Exception ex) { - Logger.LogBuildWarning($"Could not read components from file {file.Location}."); - Logger.LogFailedReadingFile(file.Location, ex); + this.Logger.LogBuildWarning($"Could not read components from file {file.Location}."); + this.Logger.LogFailedReadingFile(file.Location, ex); } } @@ -73,12 +73,12 @@ private void DetectComponents(YarnLockFile file, string location, ISingleFileCom var addSuccessful = yarnPackages.TryAdd(key, entry); if (!addSuccessful) { - Logger.LogWarning($"Found duplicate entry {key} in {location}"); + this.Logger.LogWarning($"Found duplicate entry {key} in {location}"); } } } - if (yarnPackages.Count == 0 || !TryReadPeerPackageJsonRequestsAsYarnEntries(location, yarnPackages, out List yarnRoots)) + if (yarnPackages.Count == 0 || !this.TryReadPeerPackageJsonRequestsAsYarnEntries(location, yarnPackages, out List yarnRoots)) { return; } @@ -86,7 +86,7 @@ private void DetectComponents(YarnLockFile file, string location, ISingleFileCom foreach (var dependency in yarnRoots) { var root = new DetectedComponent(new NpmComponent(dependency.Name, dependency.Version)); - AddDetectedComponentToGraph(root, null, singleFileComponentRecorder, isRootComponent: true); + this.AddDetectedComponentToGraph(root, null, singleFileComponentRecorder, isRootComponent: true); } // It's important that all of the root dependencies get registered *before* we start processing any non-root @@ -94,7 +94,7 @@ private void DetectComponents(YarnLockFile file, string location, ISingleFileCom // transitive dependencies. foreach (var dependency in yarnRoots) { - ParseTreeWithAssignedRoot(dependency, yarnPackages, singleFileComponentRecorder); + this.ParseTreeWithAssignedRoot(dependency, yarnPackages, singleFileComponentRecorder); } // Catch straggler top level packages in the yarn.lock file that aren't in the package.lock file for whatever reason @@ -103,7 +103,7 @@ private void DetectComponents(YarnLockFile file, string location, ISingleFileCom var component = new DetectedComponent(new NpmComponent(entry.Name, entry.Version)); if (singleFileComponentRecorder.GetComponent(component.Component.Id) == null) { - AddDetectedComponentToGraph(component, parentComponent: null, singleFileComponentRecorder); + this.AddDetectedComponentToGraph(component, parentComponent: null, singleFileComponentRecorder); } } } @@ -124,18 +124,18 @@ private void ParseTreeWithAssignedRoot(YarnEntry root, Dictionary 0) { var (currentEntry, parentEntry) = queue.Dequeue(); - DetectedComponent currentComponent = singleFileComponentRecorder.GetComponent(YarnEntryToComponentId(currentEntry)); - DetectedComponent parentComponent = parentEntry != null ? singleFileComponentRecorder.GetComponent(YarnEntryToComponentId(parentEntry)) : null; + DetectedComponent currentComponent = singleFileComponentRecorder.GetComponent(this.YarnEntryToComponentId(currentEntry)); + DetectedComponent parentComponent = parentEntry != null ? singleFileComponentRecorder.GetComponent(this.YarnEntryToComponentId(parentEntry)) : null; if (currentComponent != null) { - AddDetectedComponentToGraph(currentComponent, parentComponent, singleFileComponentRecorder, isDevDependency: root.DevDependency); + this.AddDetectedComponentToGraph(currentComponent, parentComponent, singleFileComponentRecorder, isDevDependency: root.DevDependency); } else { // If this is the first time we've seen a component... var detectedComponent = new DetectedComponent(new NpmComponent(currentEntry.Name, currentEntry.Version)); - AddDetectedComponentToGraph(detectedComponent, parentComponent, singleFileComponentRecorder, isDevDependency: root.DevDependency); + this.AddDetectedComponentToGraph(detectedComponent, parentComponent, singleFileComponentRecorder, isDevDependency: root.DevDependency); } // Ensure that we continue to parse the tree for dependencies @@ -156,7 +156,7 @@ private void ParseTreeWithAssignedRoot(YarnEntry root, Dictionary(); - var pkgJsons = ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(location).Directory, new List { "package.json" }, (name, directoryName) => false, recursivelyScanDirectories: false); + var pkgJsons = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(location).Directory, new List { "package.json" }, (name, directoryName) => false, recursivelyScanDirectories: false); IDictionary> combinedDependencies = new Dictionary>(); @@ -190,13 +190,13 @@ private bool TryReadPeerPackageJsonRequestsAsYarnEntries(string location, Dictio if (pkgJsonCount != 1) { - Logger.LogWarning($"No package.json was found for file at {location}. It will not be registered."); + this.Logger.LogWarning($"No package.json was found for file at {location}. It will not be registered."); return false; } if (yarnWorkspaces.Count > 0) { - GetWorkspaceDependencies(yarnWorkspaces, new FileInfo(location).Directory, combinedDependencies); + this.GetWorkspaceDependencies(yarnWorkspaces, new FileInfo(location).Directory, combinedDependencies); } // Convert all of the dependencies we retrieved from package.json @@ -209,7 +209,7 @@ private bool TryReadPeerPackageJsonRequestsAsYarnEntries(string location, Dictio var entryKey = $"{name}@npm:{version.Key}"; if (!yarnEntries.ContainsKey(entryKey)) { - Logger.LogWarning($"A package was requested in the package.json file that was a peer of {location} but was not contained in the lockfile. {name} - {version.Key}"); + this.Logger.LogWarning($"A package was requested in the package.json file that was a peer of {location} but was not contained in the lockfile. {name} - {version.Key}"); continue; } @@ -240,16 +240,16 @@ private void GetWorkspaceDependencies(IList yarnWorkspaces, DirectoryInf { var glob = Glob.Parse($"{root.FullName.Replace('\\', '/')}/{workspacePattern}/package.json", globOptions); - var componentStreams = ComponentStreamEnumerableFactory.GetComponentStreams(root, (file) => glob.IsMatch(file.FullName.Replace('\\', '/')), null, true); + var componentStreams = this.ComponentStreamEnumerableFactory.GetComponentStreams(root, (file) => glob.IsMatch(file.FullName.Replace('\\', '/')), null, true); foreach (var stream in componentStreams) { - Logger.LogInfo($"{stream.Location} found for workspace {workspacePattern}"); + this.Logger.LogInfo($"{stream.Location} found for workspace {workspacePattern}"); var combinedDependencies = NpmComponentUtilities.TryGetAllPackageJsonDependencies(stream.Stream, out _); foreach (var dependency in combinedDependencies) { - ProcessWorkspaceDependency(dependencies, dependency); + this.ProcessWorkspaceDependency(dependencies, dependency); } } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentHelper.cs b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentHelper.cs index 05323b4d1..7b6db51b4 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentHelper.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentHelper.cs @@ -14,12 +14,12 @@ public class ArgumentHelper : IArgumentHelper public ArgumentHelper() { - ArgumentSets = Enumerable.Empty(); + this.ArgumentSets = Enumerable.Empty(); } public ParserResult ParseArguments(string[] args) { - return Parser.Default.ParseArguments(args, ArgumentSets.Select(x => x.GetType()).ToArray()); + return Parser.Default.ParseArguments(args, this.ArgumentSets.Select(x => x.GetType()).ToArray()); } public ParserResult ParseArguments(string[] args, bool ignoreInvalidArgs = false) diff --git a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BaseArguments.cs b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BaseArguments.cs index 9633eed60..ffb057e7e 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BaseArguments.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BaseArguments.cs @@ -20,7 +20,7 @@ public class BaseArguments : IScanArguments [Option("AdditionalPluginDirectories", Separator = ';', Required = false, Hidden = true, HelpText = "Semi-colon delimited list of directories to search for plugins")] public IEnumerable AdditionalPluginDirectories { get; set; } - public IEnumerable AdditionalPluginDirectoriesSerialized => AdditionalPluginDirectories?.Select(x => x.ToString()) ?? new List(); + public IEnumerable AdditionalPluginDirectoriesSerialized => this.AdditionalPluginDirectories?.Select(x => x.ToString()) ?? new List(); [Option("CorrelationId", Required = false, HelpText = "Identifier used to correlate all telemetry for a given execution. If not provided, a new GUID will be generated.")] public Guid CorrelationId { get; set; } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BcdeArguments.cs b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BcdeArguments.cs index 0e985c6a8..0d6609d86 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BcdeArguments.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/ArgumentSets/BcdeArguments.cs @@ -20,13 +20,13 @@ public class BcdeArguments : BaseArguments, IDetectionArguments [Option("SourceDirectory", Required = true, HelpText = "Directory to operate on.")] public DirectoryInfo SourceDirectory { get; set; } - public string SourceDirectorySerialized => SourceDirectory?.ToString(); + public string SourceDirectorySerialized => this.SourceDirectory?.ToString(); [JsonIgnore] [Option("SourceFileRoot", Required = false, HelpText = "Directory where source files can be found.")] public DirectoryInfo SourceFileRoot { get; set; } - public string SourceFileRootSerialized => SourceFileRoot?.ToString(); + public string SourceFileRootSerialized => this.SourceFileRoot?.ToString(); [Option("DetectorArgs", Separator = ',', Required = false, HelpText = "Comma separated list of properties that can affect the detectors execution, like EnableIfDefaultOff that allows a specific detector that is in beta to run, the format for this property is " + "DetectorId=EnableIfDefaultOff, for example Pip=EnableIfDefaultOff.")] @@ -43,7 +43,7 @@ public class BcdeArguments : BaseArguments, IDetectionArguments [Option("ManifestFile", Required = false, HelpText = "The file to write scan results to.")] public FileInfo ManifestFile { get; set; } - public string ManifestFileSerialized => ManifestFile?.ToString(); + public string ManifestFileSerialized => this.ManifestFile?.ToString(); [Option("DockerImagesToScan", Required = false, Separator = ',', HelpText = "Comma separated list of docker image names or hashes to execute container scanning on, ex: ubuntu:16.04, 56bab49eef2ef07505f6a1b0d5bd3a601dfc3c76ad4460f24c91d6fa298369ab")] public IEnumerable DockerImagesToScan { get; set; } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/CommandLineArgumentsExporter.cs b/src/Microsoft.ComponentDetection.Orchestrator/CommandLineArgumentsExporter.cs index 795bf9def..f7ec65808 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/CommandLineArgumentsExporter.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/CommandLineArgumentsExporter.cs @@ -9,7 +9,7 @@ public class CommandLineArgumentsExporter { public CommandLineArgumentsExporter() { - DelayedInjectionLazy = new Lazy(() => ArgumentsForDelayedInjection); + this.DelayedInjectionLazy = new Lazy(() => ArgumentsForDelayedInjection); } [Export("InjectableDetectionArguments")] diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Orchestrator.cs b/src/Microsoft.ComponentDetection.Orchestrator/Orchestrator.cs index 81173871a..aef3c5527 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Orchestrator.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Orchestrator.cs @@ -68,7 +68,7 @@ public ScanResult Load(string[] args) var returnResult = BcdeExecutionTelemetryRecord.Track( (record) => { - var executionResult = HandleCommand(args, record); + var executionResult = this.HandleCommand(args, record); if (executionResult.ResultCode == ProcessingResultCode.PartialSuccess) { shouldFailureBeSuppressed = true; @@ -139,18 +139,18 @@ public ScanResult HandleCommand(string[] args, BcdeExecutionTelemetryRecord tele // Don't set production telemetry if we are running the build task in DevFabric. 0.36.0 is set in the task.json for the build task in development, but is calculated during deployment for production. TelemetryConstants.CorrelationId = argumentSet.CorrelationId; - telemetryRecord.Command = GetVerb(argumentSet); + telemetryRecord.Command = this.GetVerb(argumentSet); - scanResult = SafelyExecute(telemetryRecord, () => + scanResult = this.SafelyExecute(telemetryRecord, () => { - GenerateEnvironmentSpecificTelemetry(telemetryRecord); + this.GenerateEnvironmentSpecificTelemetry(telemetryRecord); telemetryRecord.Arguments = JsonConvert.SerializeObject(argumentSet); FileWritingService.Init(argumentSet.Output); Logger.Init(argumentSet.Verbosity); Logger.LogInfo($"Run correlation id: {TelemetryConstants.CorrelationId.ToString()}"); - return Dispatch(argumentSet, CancellationToken.None).GetAwaiter().GetResult(); + return this.Dispatch(argumentSet, CancellationToken.None).GetAwaiter().GetResult(); }); }) .WithNotParsed(errors => diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeDevCommandService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeDevCommandService.cs index fb73045d2..fc0171c60 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeDevCommandService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeDevCommandService.cs @@ -23,7 +23,7 @@ public async Task Handle(IScanArguments arguments) // Run BCDE with the given arguments var detectionArguments = arguments as BcdeArguments; - var result = await BcdeScanExecutionService.ExecuteScanAsync(detectionArguments); + var result = await this.BcdeScanExecutionService.ExecuteScanAsync(detectionArguments); var detectedComponents = result.ComponentsFound.ToList(); foreach (var detectedComponent in detectedComponents) { diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanCommandService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanCommandService.cs index 8e19b0a78..ac7ddcb95 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanCommandService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanCommandService.cs @@ -27,8 +27,8 @@ public bool CanHandle(IScanArguments arguments) public async Task Handle(IScanArguments arguments) { BcdeArguments bcdeArguments = (BcdeArguments)arguments; - var result = await BcdeScanExecutionService.ExecuteScanAsync(bcdeArguments); - WriteComponentManifest(bcdeArguments, result); + var result = await this.BcdeScanExecutionService.ExecuteScanAsync(bcdeArguments); + this.WriteComponentManifest(bcdeArguments, result); return result; } @@ -38,21 +38,21 @@ private void WriteComponentManifest(IDetectionArguments detectionArguments, Scan if (detectionArguments.ManifestFile != null) { - Logger.LogInfo($"Scan Manifest file: {detectionArguments.ManifestFile.FullName}"); + this.Logger.LogInfo($"Scan Manifest file: {detectionArguments.ManifestFile.FullName}"); userRequestedManifestPath = detectionArguments.ManifestFile; } else { - Logger.LogInfo($"Scan Manifest file: {FileWritingService.ResolveFilePath(ManifestRelativePath)}"); + this.Logger.LogInfo($"Scan Manifest file: {this.FileWritingService.ResolveFilePath(ManifestRelativePath)}"); } if (userRequestedManifestPath == null) { - FileWritingService.AppendToFile(ManifestRelativePath, JsonConvert.SerializeObject(scanResult, Formatting.Indented)); + this.FileWritingService.AppendToFile(ManifestRelativePath, JsonConvert.SerializeObject(scanResult, Formatting.Indented)); } else { - FileWritingService.WriteFile(userRequestedManifestPath, JsonConvert.SerializeObject(scanResult, Formatting.Indented)); + this.FileWritingService.WriteFile(userRequestedManifestPath, JsonConvert.SerializeObject(scanResult, Formatting.Indented)); } } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanExecutionService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanExecutionService.cs index 0fbb0fc14..a7ba18209 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanExecutionService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/BcdeScanExecutionService.cs @@ -47,23 +47,23 @@ private DetectorRestrictions GetDetectorRestrictions(IDetectionArguments detecti public async Task ExecuteScanAsync(IDetectionArguments detectionArguments) { - Logger.LogCreateLoggingGroup(); - var initialDetectors = DetectorRegistryService.GetDetectors(detectionArguments.AdditionalPluginDirectories, detectionArguments.AdditionalDITargets).ToImmutableList(); + this.Logger.LogCreateLoggingGroup(); + var initialDetectors = this.DetectorRegistryService.GetDetectors(detectionArguments.AdditionalPluginDirectories, detectionArguments.AdditionalDITargets).ToImmutableList(); if (!initialDetectors.Any()) { throw new NoDetectorsFoundException(); } - DetectorRestrictions detectorRestrictions = GetDetectorRestrictions(detectionArguments); - var detectors = DetectorRestrictionService.ApplyRestrictions(detectorRestrictions, initialDetectors).ToImmutableList(); + DetectorRestrictions detectorRestrictions = this.GetDetectorRestrictions(detectionArguments); + var detectors = this.DetectorRestrictionService.ApplyRestrictions(detectorRestrictions, initialDetectors).ToImmutableList(); - Logger.LogVerbose($"Finished applying restrictions to detectors."); - Logger.LogCreateLoggingGroup(); + this.Logger.LogVerbose($"Finished applying restrictions to detectors."); + this.Logger.LogCreateLoggingGroup(); - var processingResult = await DetectorProcessingService.ProcessDetectorsAsync(detectionArguments, detectors, detectorRestrictions); + var processingResult = await this.DetectorProcessingService.ProcessDetectorsAsync(detectionArguments, detectors, detectorRestrictions); - var graphTranslationService = GraphTranslationServices.OrderBy(gts => gts.Metadata.Priority).Last().Value; + var graphTranslationService = this.GraphTranslationServices.OrderBy(gts => gts.Metadata.Priority).Last().Value; var scanResult = graphTranslationService.GenerateScanResultFromProcessingResult(processingResult, detectionArguments); diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorListingCommandService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorListingCommandService.cs index c474938ec..d6a1db6b3 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorListingCommandService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorListingCommandService.cs @@ -20,7 +20,7 @@ public bool CanHandle(IScanArguments arguments) public async Task Handle(IScanArguments arguments) { - await ListDetectorsAsync(arguments as IListDetectionArgs); + await this.ListDetectorsAsync(arguments as IListDetectionArgs); return new ScanResult() { ResultCode = ProcessingResultCode.Success, @@ -29,12 +29,12 @@ public async Task Handle(IScanArguments arguments) private async Task ListDetectorsAsync(IScanArguments listArguments) { - var detectors = DetectorRegistryService.GetDetectors(listArguments.AdditionalPluginDirectories, listArguments.AdditionalDITargets); + var detectors = this.DetectorRegistryService.GetDetectors(listArguments.AdditionalPluginDirectories, listArguments.AdditionalDITargets); if (detectors.Any()) { foreach (var detector in detectors) { - Logger.LogInfo($"{detector.Id}"); + this.Logger.LogInfo($"{detector.Id}"); } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs index 0ff0806f8..e7028d961 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs @@ -35,8 +35,8 @@ public class DetectorProcessingService : ServiceBase, IDetectorProcessingService public async Task ProcessDetectorsAsync(IDetectionArguments detectionArguments, IEnumerable detectors, DetectorRestrictions detectorRestrictions) { - Logger.LogCreateLoggingGroup(); - Logger.LogInfo($"Finding components..."); + this.Logger.LogCreateLoggingGroup(); + this.Logger.LogInfo($"Finding components..."); Stopwatch stopwatch = Stopwatch.StartNew(); var exitCode = ProcessingResultCode.Success; @@ -45,9 +45,9 @@ public async Task ProcessDetectorsAsync(IDetectionArgu ConcurrentDictionary providerElapsedTime = new ConcurrentDictionary(); var detectorArguments = GetDetectorArgs(detectionArguments.DetectorArgs); - ExcludeDirectoryPredicate exclusionPredicate = IsOSLinuxOrMac() - ? GenerateDirectoryExclusionPredicate(detectionArguments.SourceDirectory.ToString(), detectionArguments.DirectoryExclusionList, detectionArguments.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: false) - : GenerateDirectoryExclusionPredicate(detectionArguments.SourceDirectory.ToString(), detectionArguments.DirectoryExclusionList, detectionArguments.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); + ExcludeDirectoryPredicate exclusionPredicate = this.IsOSLinuxOrMac() + ? this.GenerateDirectoryExclusionPredicate(detectionArguments.SourceDirectory.ToString(), detectionArguments.DirectoryExclusionList, detectionArguments.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: false) + : this.GenerateDirectoryExclusionPredicate(detectionArguments.SourceDirectory.ToString(), detectionArguments.DirectoryExclusionList, detectionArguments.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); IEnumerable> scanTasks = detectors .Select(async detector => @@ -55,7 +55,7 @@ public async Task ProcessDetectorsAsync(IDetectionArgu Stopwatch providerStopwatch = new Stopwatch(); providerStopwatch.Start(); - var componentRecorder = new ComponentRecorder(Logger, !detector.NeedsAutomaticRootDependencyCalculation); + var componentRecorder = new ComponentRecorder(this.Logger, !detector.NeedsAutomaticRootDependencyCalculation); var isExperimentalDetector = detector is IExperimentalDetector && !(detectorRestrictions.ExplicitlyEnabledDetectorIds?.Contains(detector.Id)).GetValueOrDefault(); @@ -65,13 +65,13 @@ public async Task ProcessDetectorsAsync(IDetectionArgu IndividualDetectorScanResult result; using (var record = new DetectorExecutionTelemetryRecord()) { - result = await WithExperimentalScanGuards( - () => detector.ExecuteDetectorAsync(new ScanRequest(detectionArguments.SourceDirectory, exclusionPredicate, Logger, detectorArguments, detectionArguments.DockerImagesToScan, componentRecorder)), + result = await this.WithExperimentalScanGuards( + () => detector.ExecuteDetectorAsync(new ScanRequest(detectionArguments.SourceDirectory, exclusionPredicate, this.Logger, detectorArguments, detectionArguments.DockerImagesToScan, componentRecorder)), isExperimentalDetector, record); // Make sure top level enumerables are at least empty and not null. - result = CoalesceResult(result); + result = this.CoalesceResult(result); detectedComponents = componentRecorder.GetDetectedComponents(); resultCode = result.ResultCode; @@ -118,13 +118,13 @@ public async Task ProcessDetectorsAsync(IDetectionArgu var results = await Task.WhenAll(scanTasks); - DetectorProcessingResult detectorProcessingResult = ConvertDetectorResultsIntoResult(results, exitCode); + DetectorProcessingResult detectorProcessingResult = this.ConvertDetectorResultsIntoResult(results, exitCode); var totalElapsedTime = stopwatch.Elapsed.TotalSeconds; - LogTabularOutput(Logger, providerElapsedTime, totalElapsedTime); + this.LogTabularOutput(this.Logger, providerElapsedTime, totalElapsedTime); - Logger.LogCreateLoggingGroup(); - Logger.LogInfo($"Detection time: {totalElapsedTime} seconds."); + this.Logger.LogCreateLoggingGroup(); + this.Logger.LogInfo($"Detection time: {totalElapsedTime} seconds."); return detectorProcessingResult; } @@ -219,9 +219,9 @@ private void LogTabularOutput(ILogger logger, ConcurrentDictionary GetDetectors(IEnumerable a directoriesToSearch.AddRange(additionalSearchDirectories); } - ComponentDetectors = GetComponentDetectors(directoriesToSearch, extraDetectorAssemblies); + this.ComponentDetectors = this.GetComponentDetectors(directoriesToSearch, extraDetectorAssemblies); - if (!ComponentDetectors.Any()) + if (!this.ComponentDetectors.Any()) { - Logger.LogError($"No component detectors were found in {searchPath} or other provided search paths."); + this.Logger.LogError($"No component detectors were found in {searchPath} or other provided search paths."); } - return ComponentDetectors; + return this.ComponentDetectors; } public IEnumerable GetDetectors(Assembly assemblyToSearch, IEnumerable extraDetectorAssemblies) { - Logger.LogInfo($"Attempting to load component detectors from {assemblyToSearch.FullName}"); + this.Logger.LogInfo($"Attempting to load component detectors from {assemblyToSearch.FullName}"); - var loadedDetectors = LoadComponentDetectorsFromAssemblies(new List { assemblyToSearch }, extraDetectorAssemblies); + var loadedDetectors = this.LoadComponentDetectorsFromAssemblies(new List { assemblyToSearch }, extraDetectorAssemblies); var pluralPhrase = loadedDetectors.Count == 1 ? "detector was" : "detectors were"; - Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {assemblyToSearch.FullName}\n"); + this.Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {assemblyToSearch.FullName}\n"); return loadedDetectors; } @@ -62,14 +62,14 @@ private IList GetComponentDetectors(IEnumerable GetComponentDetectors(IEnumerable x.FullName)); + var assemblies = this.SafeLoadAssemblies(searchPath.GetFiles("*.dll", SearchOption.AllDirectories).Select(x => x.FullName)); - var loadedDetectors = LoadComponentDetectorsFromAssemblies(assemblies, extraDetectorAssemblies); + var loadedDetectors = this.LoadComponentDetectorsFromAssemblies(assemblies, extraDetectorAssemblies); var pluralPhrase = loadedDetectors.Count == 1 ? "detector was" : "detectors were"; - Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {searchPath}\n"); + this.Logger.LogInfo($"{loadedDetectors.Count} {pluralPhrase} found in {searchPath}\n"); detectors.AddRange(loadedDetectors); @@ -105,7 +105,7 @@ private IList GetComponentDetectors(IEnumerable LoadComponentDetectorsFromAssemblies(IEnumerable assemblies, IEnumerable extraDetectorAssemblies) { - new InjectionParameters(DetectorDependencies); + new InjectionParameters(this.DetectorDependencies); var configuration = new ContainerConfiguration() .WithAssemblies(assemblies); diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs index bd74f56ba..5d2607831 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs @@ -28,9 +28,10 @@ public IEnumerable ApplyRestrictions(DetectorRestrictions ar IEnumerable allowedIds = argSpecifiedRestrictions.AllowedDetectorIds; // If we have retired detectors in the arg specified list and don't have the new detector, add the new detector - if (allowedIds.Where(a => oldDetectorIds.Contains(a, StringComparer.OrdinalIgnoreCase)).Any() && !allowedIds.Contains(newDetectorId, StringComparer.OrdinalIgnoreCase)) + if (allowedIds.Where(a => this.oldDetectorIds.Contains(a, StringComparer.OrdinalIgnoreCase)).Any() && !allowedIds.Contains(this.newDetectorId, StringComparer.OrdinalIgnoreCase)) { - allowedIds = allowedIds.Concat(new string[] { newDetectorId }); + allowedIds = allowedIds.Concat(new string[] { + this.newDetectorId }); } detectors = detectors.Where(d => allowedIds.Contains(d.Id, StringComparer.OrdinalIgnoreCase)).ToList(); @@ -39,13 +40,13 @@ public IEnumerable ApplyRestrictions(DetectorRestrictions ar { if (!detectors.Select(d => d.Id).Contains(id, StringComparer.OrdinalIgnoreCase)) { - if (!oldDetectorIds.Contains(id, StringComparer.OrdinalIgnoreCase)) + if (!this.oldDetectorIds.Contains(id, StringComparer.OrdinalIgnoreCase)) { throw new InvalidDetectorFilterException($"Detector '{id}' was not found"); } else { - Logger.LogWarning($"The detector '{id}' has been phased out, we will run the '{newDetectorId}' detector which replaced its functionality."); + this.Logger.LogWarning($"The detector '{id}' has been phased out, we will run the '{this.newDetectorId}' detector which replaced its functionality."); } } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs index ebd160b04..d5366b606 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs @@ -22,15 +22,15 @@ public ScanResult GenerateScanResultFromProcessingResult(DetectorProcessingResul { var recorderDetectorPairs = detectorProcessingResult.ComponentRecorders; - var unmergedComponents = GatherSetOfDetectedComponentsUnmerged(recorderDetectorPairs, detectionArguments.SourceDirectory); + var unmergedComponents = this.GatherSetOfDetectedComponentsUnmerged(recorderDetectorPairs, detectionArguments.SourceDirectory); - var mergedComponents = FlattenAndMergeComponents(unmergedComponents); + var mergedComponents = this.FlattenAndMergeComponents(unmergedComponents); - LogComponentScopeTelemetry(mergedComponents); + this.LogComponentScopeTelemetry(mergedComponents); return new DefaultGraphScanResult { - ComponentsFound = mergedComponents.Select(x => ConvertToContract(x)).ToList(), + ComponentsFound = mergedComponents.Select(x => this.ConvertToContract(x)).ToList(), ContainerDetailsMap = detectorProcessingResult.ContainersDetailsMap, DependencyGraphs = GraphTranslationUtility.AccumulateAndConvertToContract(recorderDetectorPairs .Select(tuple => tuple.recorder) @@ -79,8 +79,8 @@ private IEnumerable GatherSetOfDetectedComponentsUnmerged(IEn var dependencyGraph = graphKvp.Value; // Calculate roots of the component - AddRootsToDetectedComponent(component, dependencyGraph, componentRecorder); - component.DevelopmentDependency = MergeDevDependency(component.DevelopmentDependency, dependencyGraph.IsDevelopmentDependency(component.Component.Id)); + this.AddRootsToDetectedComponent(component, dependencyGraph, componentRecorder); + component.DevelopmentDependency = this.MergeDevDependency(component.DevelopmentDependency, dependencyGraph.IsDevelopmentDependency(component.Component.Id)); component.DependencyScope = DependencyScopeComparer.GetMergedDependencyScope(component.DependencyScope, dependencyGraph.GetDependencyScope(component.Component.Id)); component.DetectedBy = detector; @@ -88,7 +88,7 @@ private IEnumerable GatherSetOfDetectedComponentsUnmerged(IEn var locations = dependencyGraph.GetAdditionalRelatedFiles(); locations.Add(location); - var relativePaths = MakeFilePathsRelative(Logger, rootDirectory, locations); + var relativePaths = this.MakeFilePathsRelative(this.Logger, rootDirectory, locations); foreach (var additionalRelatedFile in relativePaths ?? Enumerable.Empty()) { @@ -106,7 +106,7 @@ private List FlattenAndMergeComponents(IEnumerable flattenedAndMergedComponents = new List(); foreach (var grouping in components.GroupBy(x => x.Component.Id + x.DetectedBy.Id)) { - flattenedAndMergedComponents.Add(MergeComponents(grouping)); + flattenedAndMergedComponents.Add(this.MergeComponents(grouping)); } return flattenedAndMergedComponents; @@ -149,7 +149,7 @@ private DetectedComponent MergeComponents(IEnumerable enumera firstComponent.DependencyRoots.Add(root); } - firstComponent.DevelopmentDependency = MergeDevDependency(firstComponent.DevelopmentDependency, nextComponent.DevelopmentDependency); + firstComponent.DevelopmentDependency = this.MergeDevDependency(firstComponent.DevelopmentDependency, nextComponent.DevelopmentDependency); firstComponent.DependencyScope = DependencyScopeComparer.GetMergedDependencyScope(firstComponent.DependencyScope, nextComponent.DependencyScope); if (nextComponent.ContainerDetailIds.Count > 0) diff --git a/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs index f3d0d3a22..36a5ce76d 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs @@ -20,7 +20,7 @@ public class BaseDetectionTelemetryRecordTests public void Initialize() { // this only discovers types in a single assembly, since that's the current situation! - recordTypes = typeof(BaseDetectionTelemetryRecord).Assembly.GetTypes() + this.recordTypes = typeof(BaseDetectionTelemetryRecord).Assembly.GetTypes() .Where(type => typeof(BaseDetectionTelemetryRecord).IsAssignableFrom(type)) .Where(type => !type.IsAbstract) .ToArray(); @@ -31,7 +31,7 @@ public void UniqueRecordNames() { var dic = new Dictionary(); - foreach (var type in recordTypes) + foreach (var type in this.recordTypes) { var inst = Activator.CreateInstance(type) as IDetectionTelemetryRecord; Assert.IsNotNull(inst); @@ -65,7 +65,7 @@ public void SerializableProperties() typeof(HttpStatusCode), }); - foreach (var type in recordTypes) + foreach (var type in this.recordTypes) { foreach (var property in type.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { diff --git a/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs index ed1eaff7a..21109aea2 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs @@ -18,42 +18,42 @@ public class CommandLineInvocationServiceTests [TestInitialize] public void TestInitialize() { - commandLineService = new CommandLineInvocationService(); + this.commandLineService = new CommandLineInvocationService(); } [SkipTestIfNotWindows] public async Task ShowsCmdExeAsExecutable() { - Assert.IsTrue(await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C")); + Assert.IsTrue(await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C")); } [SkipTestIfNotWindows] public async Task FallbackWorksIfBadCommandsAreFirst() { - Assert.IsTrue(await commandLineService.CanCommandBeLocated("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe", "cmd.exe" }, "/C")); + Assert.IsTrue(await this.commandLineService.CanCommandBeLocated("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe", "cmd.exe" }, "/C")); } [SkipTestIfNotWindows] public async Task ReturnsFalseIfNoValidCommandIsFound() { - Assert.IsFalse(await commandLineService.CanCommandBeLocated("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe" }, "/C")); + Assert.IsFalse(await this.commandLineService.CanCommandBeLocated("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe" }, "/C")); } [SkipTestIfNotWindows] public async Task ReturnsStandardOutput() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); - var taskResult = await commandLineService.ExecuteCommand("cmd.exe", default, "/C echo Expected Output"); + var taskResult = await this.commandLineService.ExecuteCommand("cmd.exe", default, "/C echo Expected Output"); Assert.AreEqual(0, taskResult.ExitCode); Assert.AreEqual(string.Empty, taskResult.StdErr); - Assert.AreEqual("Expected Output", taskResult.StdOut.Replace(System.Environment.NewLine, string.Empty)); + Assert.AreEqual("Expected Output", taskResult.StdOut.Replace(Environment.NewLine, string.Empty)); } [SkipTestIfNotWindows] public async Task ExecutesCommandEvenWithLargeStdOut() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); StringBuilder largeStringBuilder = new StringBuilder(); while (largeStringBuilder.Length < 8100) // Cmd.exe command limit is in the 8100s @@ -61,7 +61,7 @@ public async Task ExecutesCommandEvenWithLargeStdOut() largeStringBuilder.Append("Some sample text"); } - var taskResult = await commandLineService.ExecuteCommand("cmd.exe", default, $"/C echo {largeStringBuilder.ToString()}"); + var taskResult = await this.commandLineService.ExecuteCommand("cmd.exe", default, $"/C echo {largeStringBuilder.ToString()}"); Assert.AreEqual(0, taskResult.ExitCode); Assert.AreEqual(string.Empty, taskResult.StdErr); Assert.IsTrue(taskResult.StdOut.Length > 8099, taskResult.StdOut.Length < 100 ? $"Stdout was '{taskResult.StdOut}', which is shorter than 8100 chars" : $"Length was {taskResult.StdOut.Length}, which is less than 8100"); @@ -70,7 +70,7 @@ public async Task ExecutesCommandEvenWithLargeStdOut() [SkipTestIfNotWindows] public async Task ExecutesCommandCapturingErrorOutput() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); StringBuilder largeStringBuilder = new StringBuilder(); while (largeStringBuilder.Length < 9000) // Pick a command that is "too big" for cmd. @@ -78,7 +78,7 @@ public async Task ExecutesCommandCapturingErrorOutput() largeStringBuilder.Append("Some sample text"); } - var taskResult = await commandLineService.ExecuteCommand("cmd.exe", default, $"/C echo {largeStringBuilder.ToString()}"); + var taskResult = await this.commandLineService.ExecuteCommand("cmd.exe", default, $"/C echo {largeStringBuilder.ToString()}"); Assert.AreEqual(1, taskResult.ExitCode); Assert.IsTrue(taskResult.StdErr.Contains("too long"), $"Expected '{taskResult.StdErr}' to contain 'too long'"); Assert.AreEqual(string.Empty, taskResult.StdOut); @@ -87,12 +87,12 @@ public async Task ExecutesCommandCapturingErrorOutput() [SkipTestIfNotWindows] public async Task ExecutesInAWorkingDirectory() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); string tempDirectoryPath = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var tempDirectory = Directory.CreateDirectory(tempDirectoryPath); - var taskResult = await commandLineService.ExecuteCommand("cmd.exe", default, workingDirectory: tempDirectory, "/C cd"); + var taskResult = await this.commandLineService.ExecuteCommand("cmd.exe", default, workingDirectory: tempDirectory, "/C cd"); taskResult.ExitCode.Should().Be(0); taskResult.StdOut.Should().Contain(tempDirectoryPath); } @@ -100,12 +100,12 @@ public async Task ExecutesInAWorkingDirectory() [SkipTestIfNotWindows] public async Task ThrowsIfWorkingDirectoryDoesNotExist() { - var isLocated = await commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); + var isLocated = await this.commandLineService.CanCommandBeLocated("cmd.exe", default, "/C"); Assert.IsTrue(isLocated); var tempDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); - Func action = async () => await commandLineService.ExecuteCommand("cmd.exe", default, workingDirectory: tempDirectory, "/C cd"); + Func action = async () => await this.commandLineService.ExecuteCommand("cmd.exe", default, workingDirectory: tempDirectory, "/C cd"); await action.Should() .ThrowAsync() diff --git a/test/Microsoft.ComponentDetection.Common.Tests/ComponentRecorderTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/ComponentRecorderTests.cs index 91e72947e..c66aa1a22 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/ComponentRecorderTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/ComponentRecorderTests.cs @@ -17,7 +17,7 @@ public class ComponentRecorderTests [TestInitialize] public void TestInitialize() { - componentRecorder = new ComponentRecorder(); + this.componentRecorder = new ComponentRecorder(); } [TestMethod] @@ -25,13 +25,13 @@ public void RegisterUsage_RegisterNewDetectedComponent_NodeInTheGraphIsCreated() { var location = "location"; - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(location); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(location); var detectedComponent = new DetectedComponent(new NpmComponent("test", "1.0.0")); singleFileComponentRecorder.RegisterUsage(detectedComponent); singleFileComponentRecorder.GetComponent(detectedComponent.Component.Id).Should().NotBeNull(); - var dependencyGraph = componentRecorder.GetDependencyGraphForLocation(location); + var dependencyGraph = this.componentRecorder.GetDependencyGraphForLocation(location); dependencyGraph.GetDependenciesForComponent(detectedComponent.Component.Id).Should().NotBeNull(); } @@ -41,7 +41,7 @@ public void RegisterUsage_NewDetectedComponentHasParent_NewRelationshipIsInserte { var location = "location"; - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(location); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(location); var detectedComponent = new DetectedComponent(new NpmComponent("test", "1.0.0")); var parentComponent = new DetectedComponent(new NpmComponent("test2", "2.0.0")); @@ -49,7 +49,7 @@ public void RegisterUsage_NewDetectedComponentHasParent_NewRelationshipIsInserte singleFileComponentRecorder.RegisterUsage(parentComponent); singleFileComponentRecorder.RegisterUsage(detectedComponent, parentComponentId: parentComponent.Component.Id); - var dependencyGraph = componentRecorder.GetDependencyGraphForLocation(location); + var dependencyGraph = this.componentRecorder.GetDependencyGraphForLocation(location); dependencyGraph.GetDependenciesForComponent(parentComponent.Component.Id).Should().Contain(detectedComponent.Component.Id); } @@ -57,7 +57,7 @@ public void RegisterUsage_NewDetectedComponentHasParent_NewRelationshipIsInserte [TestMethod] public void RegisterUsage_DetectedComponentIsNull_ArgumentNullExceptionIsThrown() { - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("location"); Action action = () => singleFileComponentRecorder.RegisterUsage(null); @@ -68,11 +68,11 @@ public void RegisterUsage_DetectedComponentIsNull_ArgumentNullExceptionIsThrown( public void RegisterUsage_DevelopmentDependencyHasValue_componentNodeHasDependencyScope() { var location = "location"; - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(location); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(location); var detectedComponent = new DetectedComponent(new MavenComponent("org.apache.maven", "maven-artifact", "3.6.1")); singleFileComponentRecorder.RegisterUsage(detectedComponent, dependencyScope: DependencyScope.MavenProvided); - var dependencyGraph = componentRecorder.GetDependencyGraphForLocation(location); + var dependencyGraph = this.componentRecorder.GetDependencyGraphForLocation(location); dependencyGraph.GetDependencyScope(detectedComponent.Component.Id).Should().NotBeNull(); dependencyGraph.GetDependencyScope(detectedComponent.Component.Id).Should().Be(DependencyScope.MavenProvided); @@ -81,7 +81,7 @@ public void RegisterUsage_DevelopmentDependencyHasValue_componentNodeHasDependen [TestMethod] public void RegisterUsage_DetectedComponentWithNullComponent_ArgumentExceptionIsThrown() { - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("location"); var detectedComponent = new DetectedComponent(null); Action action = () => singleFileComponentRecorder.RegisterUsage(detectedComponent); @@ -92,7 +92,7 @@ public void RegisterUsage_DetectedComponentWithNullComponent_ArgumentExceptionIs [TestMethod] public void RegisterUsage_DetectedComponentExistAndUpdateFunctionIsNull_NotExceptionIsThrown() { - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("location"); var detectedComponent = new DetectedComponent(new NpmComponent("test", "1.0.0")); singleFileComponentRecorder.RegisterUsage(detectedComponent); @@ -104,33 +104,33 @@ public void RegisterUsage_DetectedComponentExistAndUpdateFunctionIsNull_NotExcep [TestMethod] public void CreateComponentsingleFileComponentRecorderForLocation_LocationIsNull_ArgumentNullExceptionIsThrown() { - Action action = () => componentRecorder.CreateSingleFileComponentRecorder(null); + Action action = () => this.componentRecorder.CreateSingleFileComponentRecorder(null); action.Should().Throw(); - action = () => componentRecorder.CreateSingleFileComponentRecorder(string.Empty); + action = () => this.componentRecorder.CreateSingleFileComponentRecorder(string.Empty); action.Should().Throw(); - action = () => componentRecorder.CreateSingleFileComponentRecorder(" "); + action = () => this.componentRecorder.CreateSingleFileComponentRecorder(" "); action.Should().Throw(); } [TestMethod] public void GetComponent_ComponentNotExist_NullIsReturned() { - componentRecorder.CreateSingleFileComponentRecorder("someMockLocation").GetComponent("nonexistedcomponentId").Should().BeNull(); + this.componentRecorder.CreateSingleFileComponentRecorder("someMockLocation").GetComponent("nonexistedcomponentId").Should().BeNull(); } [TestMethod] public void GetDetectedComponents_AreComponentsRegistered_ComponentsAreReturned() { - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("location"); var detectedComponent1 = new DetectedComponent(new NpmComponent("test", "1.0.0")); var detectedComponent2 = new DetectedComponent(new NpmComponent("test", "2.0.0")); singleFileComponentRecorder.RegisterUsage(detectedComponent1); singleFileComponentRecorder.RegisterUsage(detectedComponent2); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); detectedComponents.Should().HaveCount(2); detectedComponents.Should().Contain(detectedComponent1); @@ -140,7 +140,7 @@ public void GetDetectedComponents_AreComponentsRegistered_ComponentsAreReturned( [TestMethod] public void GetDetectedComponents_NoComponentsAreRegistered_EmptyCollectionIsReturned() { - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); detectedComponents.Should().NotBeNull(); detectedComponents.Should().BeEmpty(); @@ -150,7 +150,7 @@ public void GetDetectedComponents_NoComponentsAreRegistered_EmptyCollectionIsRet public void GetAllDependencyGraphs_ReturnsImmutableDictionaryWithContents() { // Setup an initial, simple graph. - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/some/location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("/some/location"); // We want to take a look at how the class is used by it's friends var internalsView = (ComponentRecorder.SingleFileComponentRecorder)singleFileComponentRecorder; @@ -164,7 +164,7 @@ public void GetAllDependencyGraphs_ReturnsImmutableDictionaryWithContents() component1.DependencyIds.Add(component2.Id); // Get readonly content from graph - var allGraphs = componentRecorder.GetDependencyGraphsByLocation(); + var allGraphs = this.componentRecorder.GetDependencyGraphsByLocation(); var expectedGraph = allGraphs["/some/location"]; // Verify content looks correct @@ -193,7 +193,7 @@ public void GetAllDependencyGraphs_ReturnsImmutableDictionaryWithContents() public void GetAllDependencyGraphs_ReturnedGraphsAreImmutable() { // Setup an initial, simple graph. - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/some/location"); + var singleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder("/some/location"); // We want to take a look at how the class is used by it's friends var internalsView = (ComponentRecorder.SingleFileComponentRecorder)singleFileComponentRecorder; @@ -208,7 +208,7 @@ public void GetAllDependencyGraphs_ReturnedGraphsAreImmutable() component1.DependencyIds.Add(component2.Id); // Get readonly content from graph - var allGraphs = componentRecorder.GetDependencyGraphsByLocation(); + var allGraphs = this.componentRecorder.GetDependencyGraphsByLocation(); var expectedGraph = allGraphs["/some/location"]; // Verify content looks correct diff --git a/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs index 80df72875..fdb15abac 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs @@ -17,7 +17,7 @@ public class ComponentStreamEnumerableTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); + this.loggerMock = new Mock(); } [TestMethod] @@ -38,7 +38,7 @@ public void GetEnumerator_WorksOverExpectedFiles() File = new FileInfo(tempFileTwo), Pattern = "Some Pattern", }, - }, loggerMock.Object); + }, this.loggerMock.Object); enumerable.Count() .Should().Be(2); @@ -60,7 +60,7 @@ public void GetEnumerator_LogsAndBreaksEnumerationWhenFileIsMissing() var tempFileTwo = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName()); var tempFileThree = Path.GetTempFileName(); File.Delete(tempFileTwo); - loggerMock.Setup(x => x.LogWarning(Match.Create(message => message.Contains("not exist")))); + this.loggerMock.Setup(x => x.LogWarning(Match.Create(message => message.Contains("not exist")))); var enumerable = new ComponentStreamEnumerable( new[] { @@ -74,12 +74,12 @@ public void GetEnumerator_LogsAndBreaksEnumerationWhenFileIsMissing() File = new FileInfo(tempFileTwo), Pattern = "Some Pattern", }, - }, loggerMock.Object).ToList(); + }, this.loggerMock.Object).ToList(); enumerable.Count .Should().Be(1); - loggerMock.VerifyAll(); + this.loggerMock.VerifyAll(); } } } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs index ec7018d53..6110a1804 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs @@ -14,7 +14,7 @@ public class DependencyGraphTests public void TestInitializer() { // Default value of true -- some tests will create their own, though. - dependencyGraph = new DependencyGraph.DependencyGraph(true); + this.dependencyGraph = new DependencyGraph.DependencyGraph(true); } [TestMethod] @@ -25,25 +25,25 @@ public void AddComponent_ParentComponentIdIsPresent_DependencyRelationIsAdded() var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; var componentD = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentD" }; - dependencyGraph.AddComponent(componentD); - dependencyGraph.AddComponent(componentB, parentComponentId: componentD.Id); - dependencyGraph.AddComponent(componentC, parentComponentId: componentB.Id); - dependencyGraph.AddComponent(componentA, parentComponentId: componentB.Id); - dependencyGraph.AddComponent(componentA, parentComponentId: componentC.Id); + this.dependencyGraph.AddComponent(componentD); + this.dependencyGraph.AddComponent(componentB, parentComponentId: componentD.Id); + this.dependencyGraph.AddComponent(componentC, parentComponentId: componentB.Id); + this.dependencyGraph.AddComponent(componentA, parentComponentId: componentB.Id); + this.dependencyGraph.AddComponent(componentA, parentComponentId: componentC.Id); - var componentAChildren = dependencyGraph.GetDependenciesForComponent(componentA.Id); + var componentAChildren = this.dependencyGraph.GetDependenciesForComponent(componentA.Id); componentAChildren.Should().HaveCount(0); - var componentBChildren = dependencyGraph.GetDependenciesForComponent(componentB.Id); + var componentBChildren = this.dependencyGraph.GetDependenciesForComponent(componentB.Id); componentBChildren.Should().HaveCount(2); componentBChildren.Should().Contain(componentA.Id); componentBChildren.Should().Contain(componentC.Id); - var componentCChildren = dependencyGraph.GetDependenciesForComponent(componentC.Id); + var componentCChildren = this.dependencyGraph.GetDependenciesForComponent(componentC.Id); componentCChildren.Should().HaveCount(1); componentCChildren.Should().Contain(componentA.Id); - var componentDChildren = dependencyGraph.GetDependenciesForComponent(componentD.Id); + var componentDChildren = this.dependencyGraph.GetDependenciesForComponent(componentD.Id); componentDChildren.Should().HaveCount(1); componentDChildren.Should().Contain(componentB.Id); } @@ -53,16 +53,16 @@ public void AddComponent_parentComponentIdIsNotPresent_AdditionTakePlaceWithoutT { var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA", IsExplicitReferencedDependency = true }; - Action action = () => dependencyGraph.AddComponent(componentA); + Action action = () => this.dependencyGraph.AddComponent(componentA); action.Should().NotThrow(); - dependencyGraph.Contains(componentA.Id).Should().BeTrue(); + this.dependencyGraph.Contains(componentA.Id).Should().BeTrue(); } [TestMethod] public void AddComponent_ComponentIsNull_ArgumentNullExceptionIsThrow() { - Action action = () => dependencyGraph.AddComponent(null); + Action action = () => this.dependencyGraph.AddComponent(null); action.Should().Throw(); } @@ -71,15 +71,15 @@ public void AddComponent_ComponentIsNull_ArgumentNullExceptionIsThrow() public void AddComponent_ComponentHasNoId_ArgumentNullExceptionIsThrow() { var component = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = null }; - Action action = () => dependencyGraph.AddComponent(component); + Action action = () => this.dependencyGraph.AddComponent(component); action.Should().Throw(); component = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = string.Empty }; - action = () => dependencyGraph.AddComponent(component); + action = () => this.dependencyGraph.AddComponent(component); action.Should().Throw(); component = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = " " }; - action = () => dependencyGraph.AddComponent(component); + action = () => this.dependencyGraph.AddComponent(component); action.Should().Throw(); } @@ -88,7 +88,7 @@ public void AddComponent_ParentComponentWasNotAddedPreviously_ArgumentExceptionI { var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA" }; - Action action = () => dependencyGraph.AddComponent(componentA, parentComponentId: "nonexistingComponent"); + Action action = () => this.dependencyGraph.AddComponent(componentA, parentComponentId: "nonexistingComponent"); action.Should().Throw(); } @@ -103,34 +103,34 @@ public void GetExplicitReferencedDependencyIds_ComponentsWereAddedSpecifyingRoot var componentE = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentE", IsExplicitReferencedDependency = true }; var componentF = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentF" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC, componentB.Id); - dependencyGraph.AddComponent(componentE); - dependencyGraph.AddComponent(componentD, componentE.Id); - dependencyGraph.AddComponent(componentC, componentD.Id); - dependencyGraph.AddComponent(componentF, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC, componentB.Id); + this.dependencyGraph.AddComponent(componentE); + this.dependencyGraph.AddComponent(componentD, componentE.Id); + this.dependencyGraph.AddComponent(componentC, componentD.Id); + this.dependencyGraph.AddComponent(componentF, componentC.Id); - var rootsForComponentA = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var rootsForComponentA = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); rootsForComponentA.Should().HaveCount(1); - var rootsForComponentE = dependencyGraph.GetExplicitReferencedDependencyIds(componentE.Id); + var rootsForComponentE = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentE.Id); rootsForComponentE.Should().HaveCount(1); - var rootsForComponentB = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var rootsForComponentB = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); rootsForComponentB.Should().HaveCount(1); rootsForComponentB.Should().Contain(componentA.Id); - var rootsForComponentD = dependencyGraph.GetExplicitReferencedDependencyIds(componentD.Id); + var rootsForComponentD = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentD.Id); rootsForComponentD.Should().HaveCount(1); rootsForComponentD.Should().Contain(componentE.Id); - var rootsForComponentC = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var rootsForComponentC = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); rootsForComponentC.Should().HaveCount(2); rootsForComponentC.Should().Contain(componentA.Id); rootsForComponentC.Should().Contain(componentE.Id); - var rootsForComponentF = dependencyGraph.GetExplicitReferencedDependencyIds(componentF.Id); + var rootsForComponentF = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentF.Id); rootsForComponentF.Should().HaveCount(2); rootsForComponentF.Should().Contain(componentA.Id); rootsForComponentF.Should().Contain(componentE.Id); @@ -142,13 +142,13 @@ public void GetExplicitReferencedDependencyIds_ComponentsWereAddedWithoutSpecify var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA" }; var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); - var rootsForComponentA = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var rootsForComponentA = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); rootsForComponentA.Should().HaveCount(0); - var rootsForComponentB = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var rootsForComponentB = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); rootsForComponentB.Should().HaveCount(0); } @@ -156,9 +156,9 @@ public void GetExplicitReferencedDependencyIds_ComponentsWereAddedWithoutSpecify public void GetExplicitReferencedDependencyIds_ComponentIsRoot_ARootIsRootOfItSelf() { var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentA); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(1); aRoots.Should().Contain(componentA.Id); } @@ -170,20 +170,20 @@ public void GetExplicitReferencedDependencyIds_RootHasParent_ReturnItselfAndItsP var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsExplicitReferencedDependency = true }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC, componentB.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC, componentB.Id); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(1); aRoots.Should().Contain(componentA.Id); - var bRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); bRoots.Should().HaveCount(2); bRoots.Should().Contain(componentA.Id); bRoots.Should().Contain(componentB.Id); - var cRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); cRoots.Should().HaveCount(3); cRoots.Should().Contain(componentA.Id); cRoots.Should().Contain(componentB.Id); @@ -197,26 +197,26 @@ public void GetExplicitReferencedDependencyIds_InsertionOrderNotAffectedRoots() var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB" }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentB); + this.dependencyGraph.AddComponent(componentB); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(2); aRoots.Should().Contain(componentA.Id); aRoots.Should().Contain(componentC.Id); - var bRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); bRoots.Should().HaveCount(3); bRoots.Should().Contain(componentA.Id); bRoots.Should().Contain(componentB.Id); bRoots.Should().Contain(componentC.Id); - var cRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); cRoots.Should().HaveCount(1); cRoots.Should().Contain(componentC.Id); } @@ -224,78 +224,78 @@ public void GetExplicitReferencedDependencyIds_InsertionOrderNotAffectedRoots() [TestMethod] public void GetExplicitReferencedDependencyIds_UseManualSelectionTurnedOff_ComponentsWithNoParentsAreSelectedAsExplicitReferencedDependencies() { - dependencyGraph = new DependencyGraph.DependencyGraph(false); + this.dependencyGraph = new DependencyGraph.DependencyGraph(false); var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA" }; var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB" }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(1); aRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse(); - var bRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); bRoots.Should().HaveCount(1); bRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse(); - var cRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); cRoots.Should().HaveCount(1); cRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue(); } [TestMethod] public void GetExplicitReferencedDependencyIds_UseManualSelectionTurnedOff_PropertyIsExplicitReferencedDependencyIsIgnored() { - dependencyGraph = new DependencyGraph.DependencyGraph(false); + this.dependencyGraph = new DependencyGraph.DependencyGraph(false); var componentA = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA", IsExplicitReferencedDependency = true }; var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsExplicitReferencedDependency = true }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC", IsExplicitReferencedDependency = true }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); - var aRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); + var aRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentA.Id); aRoots.Should().HaveCount(1); aRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentA.Id).Should().BeFalse(); - var bRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); + var bRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentB.Id); bRoots.Should().HaveCount(1); bRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentB.Id).Should().BeFalse(); - var cRoots = dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); + var cRoots = this.dependencyGraph.GetExplicitReferencedDependencyIds(componentC.Id); cRoots.Should().HaveCount(1); cRoots.Should().Contain(componentC.Id); - ((IDependencyGraph)dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue(); + ((IDependencyGraph)this.dependencyGraph).IsComponentExplicitlyReferenced(componentC.Id).Should().BeTrue(); } [TestMethod] public void GetExplicitReferencedDependencyIds_NullComponentId_ArgumentNullExceptionIsThrown() { - Action action = () => dependencyGraph.GetExplicitReferencedDependencyIds(null); + Action action = () => this.dependencyGraph.GetExplicitReferencedDependencyIds(null); action.Should().Throw(); - action = () => dependencyGraph.GetExplicitReferencedDependencyIds(string.Empty); + action = () => this.dependencyGraph.GetExplicitReferencedDependencyIds(string.Empty); action.Should().Throw(); - action = () => dependencyGraph.GetExplicitReferencedDependencyIds(" "); + action = () => this.dependencyGraph.GetExplicitReferencedDependencyIds(" "); action.Should().Throw(); } [TestMethod] public void GetExplicitReferencedDependencyIds_ComponentIdIsNotRegisteredInGraph_ArgumentExceptionIsThrown() { - Action action = () => dependencyGraph.GetExplicitReferencedDependencyIds("nonExistingId"); + Action action = () => this.dependencyGraph.GetExplicitReferencedDependencyIds("nonExistingId"); action.Should().Throw(); } @@ -306,14 +306,14 @@ public void IsDevelopmentDependency_ReturnsAsExpected() var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsDevelopmentDependency = false }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); - dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(true); - dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(null); + this.dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(true); + this.dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(null); } [TestMethod] @@ -323,32 +323,32 @@ public void IsDevelopmentDependency_ReturnsAsExpected_AfterMerge() var componentB = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsDevelopmentDependency = false }; var componentC = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; - dependencyGraph.AddComponent(componentA); - dependencyGraph.AddComponent(componentB, componentA.Id); - dependencyGraph.AddComponent(componentC); - dependencyGraph.AddComponent(componentA, componentC.Id); + this.dependencyGraph.AddComponent(componentA); + this.dependencyGraph.AddComponent(componentB, componentA.Id); + this.dependencyGraph.AddComponent(componentC); + this.dependencyGraph.AddComponent(componentA, componentC.Id); var componentANewValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA", IsDevelopmentDependency = false }; var componentBNewValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB", IsDevelopmentDependency = true }; var componentCNewValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC", IsDevelopmentDependency = true }; - dependencyGraph.AddComponent(componentANewValue); - dependencyGraph.AddComponent(componentBNewValue); - dependencyGraph.AddComponent(componentCNewValue); + this.dependencyGraph.AddComponent(componentANewValue); + this.dependencyGraph.AddComponent(componentBNewValue); + this.dependencyGraph.AddComponent(componentCNewValue); - dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(true); + this.dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(true); var componentANullValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentA" }; var componentBNullValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentB" }; var componentCNullValue = new DependencyGraph.DependencyGraph.ComponentRefNode { Id = "componentC" }; - dependencyGraph.AddComponent(componentANullValue); - dependencyGraph.AddComponent(componentBNullValue); - dependencyGraph.AddComponent(componentCNullValue); + this.dependencyGraph.AddComponent(componentANullValue); + this.dependencyGraph.AddComponent(componentBNullValue); + this.dependencyGraph.AddComponent(componentCNullValue); - dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); - dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(true); + this.dependencyGraph.IsDevelopmentDependency(componentA.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentB.Id).Should().Be(false); + this.dependencyGraph.IsDevelopmentDependency(componentC.Id).Should().Be(true); } } } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs index a36adb549..4c2ed79a6 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs @@ -21,35 +21,35 @@ public class DockerServiceTests [TestInitialize] public void TestInitialize() { - dockerService = new DockerService(); + this.dockerService = new DockerService(); } [TestMethod] public async Task DockerService_CanPingDocker() { - var canPingDocker = await dockerService.CanPingDockerAsync(); + var canPingDocker = await this.dockerService.CanPingDockerAsync(); Assert.IsTrue(canPingDocker); } [SkipTestOnWindows] public async Task DockerService_CanRunLinuxContainersAsync() { - var isLinuxContainerModeEnabled = await dockerService.CanRunLinuxContainersAsync(); + var isLinuxContainerModeEnabled = await this.dockerService.CanRunLinuxContainersAsync(); Assert.IsTrue(isLinuxContainerModeEnabled); } [SkipTestOnWindows] public async Task DockerService_CanPullImage() { - Func action = async () => await dockerService.TryPullImageAsync(TestImage); + Func action = async () => await this.dockerService.TryPullImageAsync(TestImage); await action.Should().NotThrowAsync(); } [SkipTestOnWindows] public async Task DockerService_CanInspectImage() { - await dockerService.TryPullImageAsync(TestImage); - var details = await dockerService.InspectImageAsync(TestImage); + await this.dockerService.TryPullImageAsync(TestImage); + var details = await this.dockerService.InspectImageAsync(TestImage); details.Should().NotBeNull(); details.Tags.Should().Contain("governancecontainerregistry.azurecr.io/testcontainers/hello-world:latest"); } @@ -57,8 +57,8 @@ public async Task DockerService_CanInspectImage() [SkipTestOnWindows] public async Task DockerService_PopulatesBaseImageAndLayerDetails() { - await dockerService.TryPullImageAsync(TestImageWithBaseDetails); - var details = await dockerService.InspectImageAsync(TestImageWithBaseDetails); + await this.dockerService.TryPullImageAsync(TestImageWithBaseDetails); + var details = await this.dockerService.InspectImageAsync(TestImageWithBaseDetails); details.Should().NotBeNull(); details.Tags.Should().Contain("governancecontainerregistry.azurecr.io/testcontainers/dockertags_test:testtag"); @@ -77,7 +77,7 @@ public async Task DockerService_PopulatesBaseImageAndLayerDetails() [SkipTestOnWindows] public async Task DockerService_CanCreateAndRunImage() { - var (stdout, stderr) = await dockerService.CreateAndRunContainerAsync(TestImage, new List()); + var (stdout, stderr) = await this.dockerService.CreateAndRunContainerAsync(TestImage, new List()); stdout.Should().StartWith("\nHello from Docker!"); stderr.Should().BeEmpty(); } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/EnvironmentVariableServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/EnvironmentVariableServiceTests.cs index 6ff7dd50a..854e5d072 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/EnvironmentVariableServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/EnvironmentVariableServiceTests.cs @@ -13,30 +13,30 @@ public class EnvironmentVariableServiceTests [TestInitialize] public void TestInitialize() { - testSubject = new EnvironmentVariableService(); - Environment.SetEnvironmentVariable(EnvironmentVariableServiceTests.MyEnvVar, "true"); + this.testSubject = new EnvironmentVariableService(); + Environment.SetEnvironmentVariable(MyEnvVar, "true"); } [TestCleanup] public void TestCleanup() { - Environment.SetEnvironmentVariable(EnvironmentVariableServiceTests.MyEnvVar, null); + Environment.SetEnvironmentVariable(MyEnvVar, null); } [TestMethod] public void DoesEnvironmentVariableExist_ChecksAreCaseInsensitive() { - Assert.IsFalse(testSubject.DoesEnvironmentVariableExist("THIS_ENVIRONMENT_VARIABLE_DOES_NOT_EXIST")); + Assert.IsFalse(this.testSubject.DoesEnvironmentVariableExist("THIS_ENVIRONMENT_VARIABLE_DOES_NOT_EXIST")); - Assert.IsTrue(testSubject.DoesEnvironmentVariableExist(MyEnvVar)); - Assert.IsTrue(testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToLower())); - Assert.IsTrue(testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToUpper())); + Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar)); + Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToLower())); + Assert.IsTrue(this.testSubject.DoesEnvironmentVariableExist(MyEnvVar.ToUpper())); } [TestMethod] public void GetEnvironmentVariable_returnNullIfVariableDoesNotExist() { - Assert.IsNull(testSubject.GetEnvironmentVariable("NonExistentVar")); + Assert.IsNull(this.testSubject.GetEnvironmentVariable("NonExistentVar")); } [TestMethod] @@ -45,7 +45,7 @@ public void GetEnvironmentVariable_returnCorrectValue() string envVariableKey = nameof(envVariableKey); string envVariableValue = nameof(envVariableValue); Environment.SetEnvironmentVariable(envVariableKey, envVariableValue); - var result = testSubject.GetEnvironmentVariable(envVariableKey); + var result = this.testSubject.GetEnvironmentVariable(envVariableKey); Assert.IsNotNull(result); Assert.AreEqual(envVariableValue, result); Environment.SetEnvironmentVariable(envVariableKey, null); @@ -58,8 +58,8 @@ public void IsEnvironmentVariableValueTrue_returnsTrueForValidKey_caseInsensitiv string envVariableKey2 = nameof(envVariableKey2); Environment.SetEnvironmentVariable(envVariableKey1, "True"); Environment.SetEnvironmentVariable(envVariableKey2, "tRuE"); - var result1 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); - var result2 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result2 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); Assert.IsTrue(result1); Assert.IsTrue(result2); Environment.SetEnvironmentVariable(envVariableKey1, null); @@ -73,8 +73,8 @@ public void IsEnvironmentVariableValueTrue_returnsFalseForValidKey_caseInsensiti string envVariableKey2 = nameof(envVariableKey2); Environment.SetEnvironmentVariable(envVariableKey1, "False"); Environment.SetEnvironmentVariable(envVariableKey2, "fAlSe"); - var result1 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); - var result2 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result2 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); Assert.IsFalse(result1); Assert.IsFalse(result2); Environment.SetEnvironmentVariable(envVariableKey1, null); @@ -87,8 +87,8 @@ public void IsEnvironmentVariableValueTrue_returnsFalseForInvalidAndNull() string envVariableKey1 = nameof(envVariableKey1); string nonExistentKey = nameof(nonExistentKey); Environment.SetEnvironmentVariable(envVariableKey1, "notABoolean"); - var result1 = testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); - var result2 = testSubject.IsEnvironmentVariableValueTrue(nonExistentKey); + var result1 = this.testSubject.IsEnvironmentVariableValueTrue(envVariableKey1); + var result2 = this.testSubject.IsEnvironmentVariableValueTrue(nonExistentKey); Assert.IsFalse(result1); Assert.IsFalse(result2); Environment.SetEnvironmentVariable(envVariableKey1, null); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs index 2ee9dfc25..5a612a3e7 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs @@ -18,31 +18,31 @@ public class FileWritingServiceTests [TestInitialize] public void TestInitialize() { - serviceUnderTest = new FileWritingService(); + this.serviceUnderTest = new FileWritingService(); // Get a temp file and repurpose it as a temp folder var tempFile = Path.GetTempFileName(); File.Delete(tempFile); Directory.CreateDirectory(tempFile); - tempFolder = tempFile; + this.tempFolder = tempFile; - serviceUnderTest.Init(tempFolder); + this.serviceUnderTest.Init(this.tempFolder); } [TestCleanup] public void TestCleanup() { - Directory.Delete(tempFolder, true); + Directory.Delete(this.tempFolder, true); } [TestMethod] public void AppendToFile_AppendsToFiles() { var relativeDir = "someOtherFileName.txt"; - var fileLocation = Path.Combine(tempFolder, relativeDir); + var fileLocation = Path.Combine(this.tempFolder, relativeDir); File.Create(fileLocation).Dispose(); - serviceUnderTest.AppendToFile(relativeDir, "someSampleText"); - var text = File.ReadAllText(Path.Combine(tempFolder, relativeDir)); + this.serviceUnderTest.AppendToFile(relativeDir, "someSampleText"); + var text = File.ReadAllText(Path.Combine(this.tempFolder, relativeDir)); text .Should().Be("someSampleText"); } @@ -51,8 +51,8 @@ public void AppendToFile_AppendsToFiles() public void WriteFile_CreatesAFile() { var relativeDir = "someFileName.txt"; - serviceUnderTest.WriteFile(relativeDir, "sampleText"); - var text = File.ReadAllText(Path.Combine(tempFolder, relativeDir)); + this.serviceUnderTest.WriteFile(relativeDir, "sampleText"); + var text = File.ReadAllText(Path.Combine(this.tempFolder, relativeDir)); text .Should().Be("sampleText"); } @@ -61,23 +61,23 @@ public void WriteFile_CreatesAFile() public void WriteFile_AppendToFile_WorkWithTemplatizedPaths() { var relativeDir = "somefile_{timestamp}.txt"; - serviceUnderTest.WriteFile(relativeDir, "sampleText"); - serviceUnderTest.AppendToFile(relativeDir, "sampleText2"); - var files = Directory.GetFiles(tempFolder); + this.serviceUnderTest.WriteFile(relativeDir, "sampleText"); + this.serviceUnderTest.AppendToFile(relativeDir, "sampleText2"); + var files = Directory.GetFiles(this.tempFolder); files .Should().NotBeEmpty(); File.ReadAllText(files[0]) .Should().Contain($"sampleTextsampleText2"); - VerifyTimestamp(files[0], "somefile_", ".txt"); + this.VerifyTimestamp(files[0], "somefile_", ".txt"); } [TestMethod] public void ResolveFilePath_ResolvedTemplatizedPaths() { var relativeDir = "someOtherFile_{timestamp}.txt"; - serviceUnderTest.WriteFile(relativeDir, string.Empty); - var fullPath = serviceUnderTest.ResolveFilePath(relativeDir); - VerifyTimestamp(fullPath, "someOtherFile_", ".txt"); + this.serviceUnderTest.WriteFile(relativeDir, string.Empty); + var fullPath = this.serviceUnderTest.ResolveFilePath(relativeDir); + this.VerifyTimestamp(fullPath, "someOtherFile_", ".txt"); } [TestMethod] @@ -85,7 +85,7 @@ public void InitLogger_FailsOnDirectoryThatDoesNotExist() { var relativeDir = Guid.NewGuid(); var actualServiceUnderTest = new FileWritingService(); - Action action = () => actualServiceUnderTest.Init(Path.Combine(serviceUnderTest.BasePath, relativeDir.ToString())); + Action action = () => actualServiceUnderTest.Init(Path.Combine(this.serviceUnderTest.BasePath, relativeDir.ToString())); action.Should().Throw(); } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/LoggerTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/LoggerTests.cs index e167a4bc2..2e2dd71c2 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/LoggerTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/LoggerTests.cs @@ -15,30 +15,30 @@ public class LoggerTests [TestInitialize] public void TestInitialize() { - consoleWritingServiceMock = new Mock(); - fileWritingServiceMock = new Mock(); + this.consoleWritingServiceMock = new Mock(); + this.fileWritingServiceMock = new Mock(); } [TestCleanup] public void TestCleanup() { - consoleWritingServiceMock.VerifyAll(); - fileWritingServiceMock.VerifyAll(); + this.consoleWritingServiceMock.VerifyAll(); + this.fileWritingServiceMock.VerifyAll(); } private Logger CreateLogger(VerbosityMode verbosityMode) { var serviceUnderTest = new Logger { - ConsoleWriter = consoleWritingServiceMock.Object, - FileWritingService = fileWritingServiceMock.Object, + ConsoleWriter = this.consoleWritingServiceMock.Object, + FileWritingService = this.fileWritingServiceMock.Object, }; serviceUnderTest.Init(verbosityMode); // We're not explicitly testing init behavior here, so we reset mock expecations. Another test should verify these. - consoleWritingServiceMock.Invocations.Clear(); - fileWritingServiceMock.Invocations.Clear(); + this.consoleWritingServiceMock.Invocations.Clear(); + this.fileWritingServiceMock.Invocations.Clear(); return serviceUnderTest; } @@ -47,15 +47,15 @@ public void LogCreateLoggingGroup_HandlesFailedInit() { var logger = new Logger { - ConsoleWriter = consoleWritingServiceMock.Object, + ConsoleWriter = this.consoleWritingServiceMock.Object, FileWritingService = null, }; // This should throw an exception while setting up the file writing service, but handle it logger.Init(VerbosityMode.Normal); - consoleWritingServiceMock.Invocations.Clear(); - consoleWritingServiceMock.Setup(x => x.Write(Environment.NewLine)); + this.consoleWritingServiceMock.Invocations.Clear(); + this.consoleWritingServiceMock.Setup(x => x.Write(Environment.NewLine)); // This should not fail, despite not initializing the file writing service logger.LogCreateLoggingGroup(); @@ -63,7 +63,7 @@ public void LogCreateLoggingGroup_HandlesFailedInit() // As a result of handling the file writing service failure, the verbosity should now be Verbose var verboseMessage = "verboseMessage"; var expectedMessage = $"[VERBOSE] {verboseMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); logger.LogVerbose(verboseMessage); } @@ -71,113 +71,113 @@ public void LogCreateLoggingGroup_HandlesFailedInit() [TestMethod] public void LogCreateLoggingGroup_WritesOnNormal() { - var logger = CreateLogger(VerbosityMode.Normal); - consoleWritingServiceMock.Setup(x => x.Write(Environment.NewLine)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, Environment.NewLine)); + var logger = this.CreateLogger(VerbosityMode.Normal); + this.consoleWritingServiceMock.Setup(x => x.Write(Environment.NewLine)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, Environment.NewLine)); logger.LogCreateLoggingGroup(); } [TestMethod] public void LogCreateLoggingGroup_SkipsConsoleOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, Environment.NewLine)); + var logger = this.CreateLogger(VerbosityMode.Quiet); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, Environment.NewLine)); logger.LogCreateLoggingGroup(); } [TestMethod] public void LogWarning_WritesOnNormal() { - var logger = CreateLogger(VerbosityMode.Normal); + var logger = this.CreateLogger(VerbosityMode.Normal); var warningMessage = "warningMessage"; var expectedMessage = $"[WARN] {warningMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogWarning(warningMessage); } [TestMethod] public void LogWarning_SkipsConsoleOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var warningMessage = "warningMessage"; var expectedMessage = $"[WARN] {warningMessage} {Environment.NewLine}"; - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogWarning(warningMessage); } [TestMethod] public void LogInfo_WritesOnNormal() { - var logger = CreateLogger(VerbosityMode.Normal); + var logger = this.CreateLogger(VerbosityMode.Normal); var infoMessage = "informationalMessage"; var expectedMessage = $"[INFO] {infoMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogInfo(infoMessage); } [TestMethod] public void LogInfo_SkipsConsoleOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var infoMessage = "informationalMessage"; var expectedMessage = $"[INFO] {infoMessage} {Environment.NewLine}"; - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogInfo(infoMessage); } [TestMethod] public void LogVerbose_WritesOnVerbose() { - var logger = CreateLogger(VerbosityMode.Verbose); + var logger = this.CreateLogger(VerbosityMode.Verbose); var verboseMessage = "verboseMessage"; var expectedMessage = $"[VERBOSE] {verboseMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogVerbose(verboseMessage); } [TestMethod] public void LogVerbose_SkipsConsoleOnNormal() { - var logger = CreateLogger(VerbosityMode.Normal); + var logger = this.CreateLogger(VerbosityMode.Normal); var verboseMessage = "verboseMessage"; var expectedMessage = $"[VERBOSE] {verboseMessage} {Environment.NewLine}"; - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogVerbose(verboseMessage); } [TestMethod] public void LogError_WritesOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var errorMessage = "errorMessage"; var expectedMessage = $"[ERROR] {errorMessage} {Environment.NewLine}"; - consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); - fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); + this.consoleWritingServiceMock.Setup(x => x.Write(expectedMessage)); + this.fileWritingServiceMock.Setup(x => x.AppendToFile(Logger.LogRelativePath, expectedMessage)); logger.LogError(errorMessage); } [TestMethod] public void LogFailedReadingFile_WritesOnVerbose() { - var logger = CreateLogger(VerbosityMode.Verbose); + var logger = this.CreateLogger(VerbosityMode.Verbose); var filePath = "some/bad/file/path"; var error = new UnauthorizedAccessException("Some unauthorized access error"); var consoleSequence = new MockSequence(); - consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write(Environment.NewLine)); - consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write( + this.consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write(Environment.NewLine)); + this.consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write( Match.Create(message => message.StartsWith("[VERBOSE]") && message.Contains(filePath)))); - consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write( + this.consoleWritingServiceMock.InSequence(consoleSequence).Setup(x => x.Write( Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); var fileSequence = new MockSequence(); - fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( + this.fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[VERBOSE]") && message.Contains(filePath)))); - fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( + this.fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); @@ -187,15 +187,15 @@ public void LogFailedReadingFile_WritesOnVerbose() [TestMethod] public void LogFailedReadingFile_SkipsConsoleOnQuiet() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var filePath = "some/bad/file/path"; var error = new UnauthorizedAccessException("Some unauthorized access error"); var fileSequence = new MockSequence(); - fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( + this.fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[VERBOSE]") && message.Contains(filePath)))); - fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( + this.fileWritingServiceMock.InSequence(fileSequence).Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); @@ -205,13 +205,13 @@ public void LogFailedReadingFile_SkipsConsoleOnQuiet() [TestMethod] public void LogException_WritesOnQuietIfError() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var error = new UnauthorizedAccessException("Some unauthorized access error"); - consoleWritingServiceMock.Setup(x => x.Write( + this.consoleWritingServiceMock.Setup(x => x.Write( Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.Message)))); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.ToString())))); @@ -221,13 +221,13 @@ public void LogException_WritesOnQuietIfError() [TestMethod] public void LogException_DoesNotLogFullExceptionByDefault() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var error = new UnauthorizedAccessException("Some unauthorized access error"); - consoleWritingServiceMock.Setup(x => x.Write( + this.consoleWritingServiceMock.Setup(x => x.Write( Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.Message) && !message.Contains(error.ToString())))); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.ToString())))); @@ -237,13 +237,13 @@ public void LogException_DoesNotLogFullExceptionByDefault() [TestMethod] public void LogException_LogsFullExceptionOnRequest() { - var logger = CreateLogger(VerbosityMode.Quiet); + var logger = this.CreateLogger(VerbosityMode.Quiet); var error = new UnauthorizedAccessException("Some unauthorized access error"); - consoleWritingServiceMock.Setup(x => x.Write( + this.consoleWritingServiceMock.Setup(x => x.Write( Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.ToString())))); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[ERROR]") && message.Contains(error.ToString())))); @@ -253,10 +253,10 @@ public void LogException_LogsFullExceptionOnRequest() [TestMethod] public void LogException_SkipsConsoleIfNotErrorAndNormalLogging() { - var logger = CreateLogger(VerbosityMode.Normal); + var logger = this.CreateLogger(VerbosityMode.Normal); var error = new UnauthorizedAccessException("Some unauthorized access error"); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.ToString())))); @@ -266,13 +266,13 @@ public void LogException_SkipsConsoleIfNotErrorAndNormalLogging() [TestMethod] public void LogException_WritesEverythingIfNotErrorAndVerboseLogging() { - var logger = CreateLogger(VerbosityMode.Verbose); + var logger = this.CreateLogger(VerbosityMode.Verbose); var error = new UnauthorizedAccessException("Some unauthorized access error"); - consoleWritingServiceMock.Setup(x => x.Write( + this.consoleWritingServiceMock.Setup(x => x.Write( Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); - fileWritingServiceMock.Setup(x => x.AppendToFile( + this.fileWritingServiceMock.Setup(x => x.AppendToFile( Logger.LogRelativePath, Match.Create(message => message.StartsWith("[INFO]") && message.Contains(error.Message)))); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs index 35b4fff30..5f5601fc9 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs @@ -22,35 +22,35 @@ public class SafeFileEnumerableTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - pathUtilityServiceMock = new Mock(); - temporaryDirectory = GetTemporaryDirectory(); + this.loggerMock = new Mock(); + this.pathUtilityServiceMock = new Mock(); + this.temporaryDirectory = this.GetTemporaryDirectory(); } [TestCleanup] public void TestCleanup() { - CleanupTemporaryDirectory(temporaryDirectory); + this.CleanupTemporaryDirectory(this.temporaryDirectory); } [TestMethod] public void GetEnumerator_WorksOverExpectedFiles() { - var subDir = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "SubDir")); + var subDir = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "SubDir")); string name = string.Format("{0}.txt", Guid.NewGuid()); - var file0 = Path.Combine(temporaryDirectory, name); - var subFile0 = Path.Combine(temporaryDirectory, "SubDir", name); + var file0 = Path.Combine(this.temporaryDirectory, name); + var subFile0 = Path.Combine(this.temporaryDirectory, "SubDir", name); File.Create(file0).Close(); File.Create(subFile0).Close(); IEnumerable searchPatterns = new List { name }; - pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(It.IsAny())).Returns((s) => s); - pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); + this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(It.IsAny())).Returns((s) => s); + this.pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); - var enumerable = new SafeFileEnumerable(new DirectoryInfo(temporaryDirectory), searchPatterns, loggerMock.Object, pathUtilityServiceMock.Object, (directoryName, span) => false, true); + var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, true); int filesFound = 0; foreach (var file in enumerable) @@ -65,19 +65,19 @@ public void GetEnumerator_WorksOverExpectedFiles() [TestMethod] public void GetEnumerator_IgnoresSubDirectories() { - var subDir = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "SubDir")); + var subDir = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "SubDir")); string name = string.Format("{0}.txt", Guid.NewGuid()); - var file0 = Path.Combine(temporaryDirectory, name); + var file0 = Path.Combine(this.temporaryDirectory, name); File.Create(file0).Close(); - File.Create(Path.Combine(temporaryDirectory, "SubDir", name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, "SubDir", name)).Close(); IEnumerable searchPatterns = new List { name }; - pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); + this.pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); - var enumerable = new SafeFileEnumerable(new DirectoryInfo(temporaryDirectory), searchPatterns, loggerMock.Object, pathUtilityServiceMock.Object, (directoryName, span) => false, false); + var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, false); int filesFound = 0; foreach (var file in enumerable) @@ -93,20 +93,20 @@ public void GetEnumerator_IgnoresSubDirectories() public void GetEnumerator_CallsSymlinkCode() { Assert.Inconclusive("Need actual symlinks to accurately test this"); - var subDir = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "SubDir")); + var subDir = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "SubDir")); string name = string.Format("{0}.txt", Guid.NewGuid()); - File.Create(Path.Combine(temporaryDirectory, name)).Close(); - File.Create(Path.Combine(temporaryDirectory, "SubDir", name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, "SubDir", name)).Close(); IEnumerable searchPatterns = new List { name }; - var enumerable = new SafeFileEnumerable(new DirectoryInfo(temporaryDirectory), searchPatterns, loggerMock.Object, pathUtilityServiceMock.Object, (directoryName, span) => false, true); + var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, true); foreach (var file in enumerable) { } - pathUtilityServiceMock.Verify(x => x.ResolvePhysicalPath(temporaryDirectory), Times.AtLeastOnce); + this.pathUtilityServiceMock.Verify(x => x.ResolvePhysicalPath(this.temporaryDirectory), Times.AtLeastOnce); } [TestMethod] @@ -115,28 +115,28 @@ public void GetEnumerator_DuplicatePathIgnored() Assert.Inconclusive("Need actual symlinks to accurately test this"); Environment.SetEnvironmentVariable("GovernanceSymlinkAwareMode", bool.TrueString, EnvironmentVariableTarget.Process); - var subDir = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "SubDir")); - var fakeSymlink = Directory.CreateDirectory(Path.Combine(temporaryDirectory, "FakeSymlink")); + var subDir = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "SubDir")); + var fakeSymlink = Directory.CreateDirectory(Path.Combine(this.temporaryDirectory, "FakeSymlink")); string name = string.Format("{0}.txt", Guid.NewGuid()); string canary = string.Format("{0}.txt", Guid.NewGuid()); - File.Create(Path.Combine(temporaryDirectory, name)).Close(); - File.Create(Path.Combine(temporaryDirectory, "SubDir", name)).Close(); - File.Create(Path.Combine(temporaryDirectory, "FakeSymlink", canary)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, "SubDir", name)).Close(); + File.Create(Path.Combine(this.temporaryDirectory, "FakeSymlink", canary)).Close(); - pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(temporaryDirectory)).Returns(temporaryDirectory); - pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(subDir.FullName)).Returns(subDir.FullName); - pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(fakeSymlink.FullName)).Returns(subDir.FullName); + this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(this.temporaryDirectory)).Returns(this.temporaryDirectory); + this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(subDir.FullName)).Returns(subDir.FullName); + this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(fakeSymlink.FullName)).Returns(subDir.FullName); IEnumerable searchPatterns = new List { name }; - var enumerable = new SafeFileEnumerable(new DirectoryInfo(temporaryDirectory), searchPatterns, loggerMock.Object, pathUtilityServiceMock.Object, (directoryName, span) => false, true); + var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, true); foreach (var file in enumerable) { - file.File.FullName.Should().NotBe(Path.Combine(temporaryDirectory, "FakeSymlink", canary)); + file.File.FullName.Should().NotBe(Path.Combine(this.temporaryDirectory, "FakeSymlink", canary)); } - pathUtilityServiceMock.Verify(x => x.ResolvePhysicalPath(temporaryDirectory), Times.AtLeastOnce); + this.pathUtilityServiceMock.Verify(x => x.ResolvePhysicalPath(this.temporaryDirectory), Times.AtLeastOnce); } private string GetTemporaryDirectory() diff --git a/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs index 2b3b18b6e..8f93d11c4 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs @@ -17,29 +17,29 @@ public class TabularStringFormatTests [TestInitialize] public void TestInitialize() { - columns = new Column[] + this.columns = new Column[] { new Column { Header = "ColumnA", Width = 50, Format = null }, new Column { Header = "ColumnB", Width = 60, Format = "prefix{0}suffix" }, new Column { Header = "ColumnC", Width = 30, Format = null }, }; - rows = new[] + this.rows = new[] { // One row new[] { "a", "b", "c" }, }; - tsf = new TabularStringFormat(columns); + this.tsf = new TabularStringFormat(this.columns); } [TestMethod] public void GenerateString_AllRowsObeyHeaderLength() { - var generatedString = tsf.GenerateString(rows); + var generatedString = this.tsf.GenerateString(this.rows); // Column width + border characters, one per column + one to 'close' the table. - var lineLength = columns.Sum(x => x.Width) + columns.Length + 1; + var lineLength = this.columns.Sum(x => x.Width) + this.columns.Length + 1; var splitStrings = generatedString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); foreach (var line in splitStrings) { @@ -50,31 +50,31 @@ public void GenerateString_AllRowsObeyHeaderLength() [TestMethod] public void GenerateString_ColumnHeadersAreWritten() { - var generatedString = tsf.GenerateString(rows); + var generatedString = this.tsf.GenerateString(this.rows); var splitStrings = generatedString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Second row has the headers var headerCells = splitStrings[1].Split(new[] { TabularStringFormat.DefaultVerticalLineChar }, StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < columns.Length; i++) + for (int i = 0; i < this.columns.Length; i++) { headerCells[i] - .Should().Contain(columns[i].Header); + .Should().Contain(this.columns[i].Header); } } [TestMethod] public void GenerateString_RowContentsAreWritten() { - var generatedString = tsf.GenerateString(rows); + var generatedString = this.tsf.GenerateString(this.rows); var splitStrings = generatedString.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); // Fourth row should have some info var rowCells = splitStrings[3].Split(new[] { TabularStringFormat.DefaultVerticalLineChar }, StringSplitOptions.RemoveEmptyEntries); - for (int i = 0; i < columns.Length; i++) + for (int i = 0; i < this.columns.Length; i++) { rowCells[i] - .Should().Contain(rows[0][i].ToString()); + .Should().Contain(this.rows[0][i].ToString()); } } } diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/ScanResultSerializationTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/ScanResultSerializationTests.cs index ddb338c3a..410bdd95a 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/ScanResultSerializationTests.cs +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/ScanResultSerializationTests.cs @@ -18,7 +18,7 @@ public class ScanResultSerializationTests [TestInitialize] public void TestInitialize() { - scanResultUnderTest = new ScanResult + this.scanResultUnderTest = new ScanResult { ResultCode = ProcessingResultCode.PartialSuccess, ComponentsFound = new[] @@ -59,7 +59,7 @@ public void TestInitialize() [TestMethod] public void ScanResultSerialization_HappyPath() { - var serializedResult = JsonConvert.SerializeObject(scanResultUnderTest); + var serializedResult = JsonConvert.SerializeObject(this.scanResultUnderTest); var actual = JsonConvert.DeserializeObject(serializedResult); actual.ResultCode.Should().Be(ProcessingResultCode.PartialSuccess); @@ -91,7 +91,7 @@ public void ScanResultSerialization_HappyPath() [TestMethod] public void ScanResultSerialization_ExpectedJsonFormat() { - var serializedResult = JsonConvert.SerializeObject(scanResultUnderTest); + var serializedResult = JsonConvert.SerializeObject(this.scanResultUnderTest); JObject json = JObject.Parse(serializedResult); json.Value("resultCode").Should().Be("PartialSuccess"); diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/TypedComponentSerializationTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/TypedComponentSerializationTests.cs index a1039a638..4d2adb862 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/TypedComponentSerializationTests.cs +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/TypedComponentSerializationTests.cs @@ -45,7 +45,7 @@ public void TypedComponent_Serialization_NuGet() [TestMethod] public void TypedComponent_Serialization_Npm() { - NpmAuthor npmAuthor = new Internal.NpmAuthor("someAuthorName", "someAuthorEmail"); + NpmAuthor npmAuthor = new NpmAuthor("someAuthorName", "someAuthorEmail"); var npmCompObj = new NpmComponent("SomeNpmComponent", "1.2.3") { Author = npmAuthor, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs index 5ac54b820..18cf3de23 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs @@ -28,31 +28,31 @@ public class GoComponentDetectorTests [TestInitialize] public void TestInitialize() { - commandLineMock = new Mock(); - envVarService = new Mock(); + this.commandLineMock = new Mock(); + this.envVarService = new Mock(); var loggerMock = new Mock(); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(true); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(true); var detector = new GoComponentDetector { - CommandLineInvocationService = commandLineMock.Object, + CommandLineInvocationService = this.commandLineMock.Object, Logger = loggerMock.Object, - EnvVarService = envVarService.Object, + EnvVarService = this.envVarService.Object, }; var tempPath = Path.GetTempPath(); var detectionPath = Path.Combine(tempPath, Guid.NewGuid().ToString()); Directory.CreateDirectory(detectionPath); - scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); + this.scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); - detectorTestUtility = DetectorTestUtilityCreator.Create() - .WithScanRequest(scanRequest) + this.detectorTestUtility = DetectorTestUtilityCreator.Create() + .WithScanRequest(this.scanRequest) .WithDetector(detector); - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(false); } @@ -68,7 +68,7 @@ public async Task TestGoModDetectorWithValidFile_ReturnsSuccessfully() gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 github.com/dgrijalva/jwt-go v3.2.0+incompatible )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", goMod) .ExecuteDetector(); @@ -99,7 +99,7 @@ public async Task TestGoSumDetectorWithValidFile_ReturnsSuccessfully() github.com/golang/protobuf v1.3.2/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.sum", goSum) .ExecuteDetector(); @@ -135,7 +135,7 @@ public async Task TestGoModDetector_MultipleSpaces_ReturnsSuccessfully() github.com/dgrijalva/jwt-go v3.2.0+incompatible )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", goMod) .ExecuteDetector(); @@ -173,7 +173,7 @@ public async Task TestGoModDetector_ComponentsWithMultipleLocations_ReturnsSucce github.com/Azure/go-autorest v10.15.2+incompatible )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", goMod1) .WithFile("go.mod", goMod2, fileLocation: Path.Join(Path.GetTempPath(), "another-location", "go.mod")) .ExecuteDetector(); @@ -199,7 +199,7 @@ lorem ipsum four score and seven bugs ago $#26^#25%4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", invalidGoMod) .ExecuteDetector(); @@ -216,7 +216,7 @@ public async Task TestGoSumDetection_TwoEntriesForTheSameComponent_ReturnsSucces github.com/exponent-io/jsonpath v0.0.0-20151013193312-d6023ce2651d/go.mod h1:ZZMPRZwes7CROmyNKgQzC3XPs6L/G2EJLHddWejkmf4= )"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.sum", goSum) .ExecuteDetector(); @@ -241,7 +241,7 @@ public async Task TestGoModDetector_DetectorOnlyDetectInsideRequireSection() github.com/docker/distribution => github.com/docker/distribution v0.0.0-20191216044856-a8371794149d ) "; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", goMod) .ExecuteDetector(); @@ -258,54 +258,54 @@ public async Task TestGoModDetector_DetectorOnlyDetectInsideRequireSection() [TestMethod] public async Task TestGoDetector_GoCommandNotFound() { - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(false); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); } [TestMethod] public async Task TestGoDetector_GoCommandThrows() { - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(() => throw new Exception("Some horrible error occured")); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); } [TestMethod] public async Task TestGoDetector_GoGraphCommandFails() { - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - commandLineMock.Setup(x => x.ExecuteCommand("go mod graph", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.ExecuteCommand("go mod graph", null, It.IsAny(), It.IsAny())) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 1, }); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); } [TestMethod] public async Task TestGoDetector_GoGraphCommandThrows() { - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - commandLineMock.Setup(x => x.ExecuteCommand("go mod graph", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.ExecuteCommand("go mod graph", null, It.IsAny(), It.IsAny())) .ReturnsAsync(() => throw new Exception("Some horrible error occured")); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); } [TestMethod] @@ -342,26 +342,26 @@ public async Task TestGoDetector_GoGraphHappyPath() }"; var goGraph = "example.com/mainModule some-package@v1.2.3\nsome-package@v1.2.3 other@v1.0.0\nsome-package@v1.2.3 other@v1.2.0\ntest@v2.0.0 a@v1.5.0"; - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "list", "-m", "-json", "all" })) + this.commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "list", "-m", "-json", "all" })) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "mod", "graph" })) + this.commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "mod", "graph" })) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = goGraph, }); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", string.Empty) .ExecuteDetector(); @@ -404,26 +404,26 @@ public async Task TestGoDetector_GoGraphCyclicDependencies() var goGraph = @" github.com/prometheus/common@v0.32.1 github.com/prometheus/client_golang@v1.11.0 github.com/prometheus/client_golang@v1.12.1 github.com/prometheus/common@v0.32.1"; - commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) + this.commandLineMock.Setup(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "list", "-m", "-json", "all" })) + this.commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "list", "-m", "-json", "all" })) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "mod", "graph" })) + this.commandLineMock.Setup(x => x.ExecuteCommand("go", null, It.IsAny(), new[] { "mod", "graph" })) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = goGraph, }); - envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); + this.envVarService.Setup(x => x.IsEnvironmentVariableValueTrue("DisableGoCliScan")).Returns(false); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("go.mod", string.Empty) .ExecuteDetector(); @@ -436,9 +436,9 @@ public async Task TestGoDetector_GoGraphCyclicDependencies() [TestMethod] public async Task TestGoDetector_GoCliRequiresEnvVarToRun() { - await TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); + await this.TestGoSumDetectorWithValidFile_ReturnsSuccessfully(); - commandLineMock.Verify(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny()), Times.Never); + this.commandLineMock.Verify(x => x.CanCommandBeLocated("go", null, It.IsAny(), It.IsAny()), Times.Never); } } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs index 33428084f..a37943290 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs @@ -21,13 +21,13 @@ public class GradleComponentDetectorTests [TestInitialize] public void TestInitialize() { - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] public async Task TestGradleDetectorWithNoFiles_ReturnsSuccessfully() { - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -42,7 +42,7 @@ public async Task TestGradleDetectorWithValidFile_DetectsComponentsSuccessfully( org.springframework:spring-core:5.0.5.RELEASE org.springframework:spring-jcl:5.0.5.RELEASE"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", validFileOne) .ExecuteDetector(); @@ -73,7 +73,7 @@ public async Task TestGradleDetectorWithValidSingleLockfilePerProject_DetectsCom org.springframework:spring-core:5.0.5.RELEASE=debugCompile,releaseCompile org.springframework:spring-jcl:5.0.5.RELEASE=lintClassPath,debugCompile,releaseCompile"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", validFileOne) .ExecuteDetector(); @@ -112,7 +112,7 @@ public async Task TestGradleDetectorWithValidFiles_ReturnsSuccessfully() org.msgpack:msgpack-core:0.8.16 org.springframework:spring-jcl:5.0.5.RELEASE"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", validFileOne) .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetector(); @@ -157,7 +157,7 @@ public async Task TestGradleDetector_SameComponentDifferentLocations_DifferentLo string validFileTwo = "org.springframework:spring-beans:5.0.5.RELEASE"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", validFileOne) .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetector(); @@ -195,7 +195,7 @@ lorem ipsum four score and seven bugs ago $#26^#25%4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("gradle.lockfile", invalidFileOne) .WithFile("gradle2.lockfile", validFileTwo) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs index 3d3eac1be..339c965ce 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs @@ -26,12 +26,12 @@ public class IvyDetectorTests [TestInitialize] public void InitializeTests() { - commandLineMock = new Mock(); + this.commandLineMock = new Mock(); var loggerMock = new Mock(); var detector = new IvyDetector { - CommandLineInvocationService = commandLineMock.Object, + CommandLineInvocationService = this.commandLineMock.Object, Logger = loggerMock.Object, }; @@ -39,26 +39,26 @@ public void InitializeTests() var detectionPath = Path.Combine(tempPath, Guid.NewGuid().ToString()); Directory.CreateDirectory(detectionPath); - scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); + this.scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); - detectorTestUtility = DetectorTestUtilityCreator.Create() - .WithScanRequest(scanRequest) + this.detectorTestUtility = DetectorTestUtilityCreator.Create() + .WithScanRequest(this.scanRequest) .WithDetector(detector); } [TestCleanup] public void TestCleanup() { - scanRequest.SourceDirectory.Delete(recursive: true); + this.scanRequest.SourceDirectory.Delete(recursive: true); } [TestMethod] public async Task IfAntIsNotAvailableThenExitDetectorGracefully() { - commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) + this.commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) .ReturnsAsync(false); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 0); Assert.AreEqual(detectorResult.ResultCode, ProcessingResultCode.Success); @@ -75,9 +75,9 @@ public async Task AntAvailableHappyPath() "{ \"gav\": { \"g\": \"d3g\", \"a\": \"d3a\", \"v\": \"3.3.3\"}, \"DevelopmentDependency\": false, \"resolved\": true, \"parent_gav\": { \"g\": \"d2g\", \"a\": \"d2a\", \"v\": \"2.2.2\"}},\n" + "]}"; - IvyHappyPath(content: registerUsageContent); + this.IvyHappyPath(content: registerUsageContent); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); // IsDevelopmentDependency = true in componentRecorder but null in detectedComponents... why? Assert.AreEqual(3, detectedComponents.Count()); @@ -102,10 +102,10 @@ public async Task AntAvailableHappyPath() [TestMethod] public async Task IvyDetector_FileObservableIsNotPresent_DetectionShouldNotFail() { - commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) + this.commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) .ReturnsAsync(true); - Func action = async () => await detectorTestUtility.ExecuteDetector(); + Func action = async () => await this.detectorTestUtility.ExecuteDetector(); await action.Should().NotThrowAsync(); } @@ -125,9 +125,9 @@ public async Task IvyDependencyGraph() var d2Id = "d2g d2a 2.2.2 - Maven"; var d3Id = "d3g d3a 3.3.3 - Maven"; - IvyHappyPath(content: registerUsageContent); + this.IvyHappyPath(content: registerUsageContent); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); // IsDevelopmentDependency = true in componentRecorder but null in detectedComponents... why? Assert.AreEqual(3, detectedComponents.Count()); @@ -152,17 +152,17 @@ public async Task IvyDependencyGraph() private void IvyHappyPath(string content) { - commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) + this.commandLineMock.Setup(x => x.CanCommandBeLocated(IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, IvyDetector.AntVersionArgument)) .ReturnsAsync(true); - var expectedIvyXmlLocation = scanRequest.SourceDirectory.FullName; + var expectedIvyXmlLocation = this.scanRequest.SourceDirectory.FullName; File.WriteAllText(Path.Combine(expectedIvyXmlLocation, "ivy.xml"), "(dummy content)"); File.WriteAllText(Path.Combine(expectedIvyXmlLocation, "ivysettings.xml"), "(dummy content)"); - detectorTestUtility + this.detectorTestUtility .WithFile("ivy.xml", "(dummy content)", fileLocation: Path.Combine(expectedIvyXmlLocation, "ivy.xml")); - commandLineMock.Setup( + this.commandLineMock.Setup( x => x.ExecuteCommand( IvyDetector.PrimaryCommand, IvyDetector.AdditionalValidCommands, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs index 112d1514b..be092d7a6 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs @@ -39,18 +39,18 @@ public class LinuxContainerDetectorTests [TestInitialize] public void TestInitialize() { - mockDockerService = new Mock(); - mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) + this.mockDockerService = new Mock(); + this.mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) .ReturnsAsync(true); - mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())) + this.mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(true); - mockDockerService.Setup(service => service.InspectImageAsync(It.IsAny(), It.IsAny())) + this.mockDockerService.Setup(service => service.InspectImageAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(new ContainerDetails { Id = 1, ImageId = NodeLatestDigest, Layers = Enumerable.Empty() }); - mockLogger = new Mock(); + this.mockLogger = new Mock(); - mockSyftLinuxScanner = new Mock(); - mockSyftLinuxScanner.Setup(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) + this.mockSyftLinuxScanner = new Mock(); + this.mockSyftLinuxScanner.Setup(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny())) .ReturnsAsync(LinuxComponents); } @@ -59,14 +59,14 @@ public async Task TestLinuxContainerDetector() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage }, componentRecorder); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -87,17 +87,17 @@ public async Task TestLinuxContainerDetector_CantRunLinuxContainers() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, null, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage }, componentRecorder); - mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) + this.mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) .ReturnsAsync(false); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -107,7 +107,7 @@ public async Task TestLinuxContainerDetector_CantRunLinuxContainers() scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); detectedComponents.Should().HaveCount(0); scanResult.ContainerDetails.Should().HaveCount(0); - mockLogger.Verify(logger => logger.LogInfo(It.IsAny())); + this.mockLogger.Verify(logger => logger.LogInfo(It.IsAny())); } [TestMethod] @@ -115,14 +115,14 @@ public async Task TestLinuxContainerDetector_TestNull() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, null, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, null, componentRecorder); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -132,7 +132,7 @@ public async Task TestLinuxContainerDetector_TestNull() scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); detectedComponents.Should().HaveCount(0); scanResult.ContainerDetails.Should().HaveCount(0); - mockLogger.Verify(logger => logger.LogInfo(It.IsAny())); + this.mockLogger.Verify(logger => logger.LogInfo(It.IsAny())); } [TestMethod] @@ -140,14 +140,14 @@ public async Task TestLinuxContainerDetector_VerifyLowerCase() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, null, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { "UPPERCASE" }, componentRecorder); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -166,14 +166,14 @@ public async Task TestLinuxContainerDetector_SameImagePassedMultipleTimes() { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, null, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage, NodeLatestDigest }, componentRecorder); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; var scanResult = await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -185,21 +185,21 @@ public async Task TestLinuxContainerDetector_SameImagePassedMultipleTimes() detectedComponents.Should().HaveCount(1); detectedComponents.First().Component.Id.Should().Be(BashPackageId); detectedComponents.All(dc => dc.ContainerDetailIds.Contains(scanResult.ContainerDetails.First().Id)).Should().BeTrue(); - mockSyftLinuxScanner.Verify(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Once); + this.mockSyftLinuxScanner.Verify(scanner => scanner.ScanLinuxAsync(It.IsAny(), It.IsAny>(), It.IsAny(), It.IsAny()), Times.Once); } [TestMethod] public async Task TestLinuxContainerDetector_TimeoutParameterSpecified() { var detectorArgs = new Dictionary { { "Linux.ScanningTimeoutSec", "2" } }; - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, mockLogger.Object, + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, detectorArgs, new List { NodeLatestImage }, new ComponentRecorder()); var linuxContainerDetector = new LinuxContainerDetector { - LinuxScanner = mockSyftLinuxScanner.Object, - Logger = mockLogger.Object, - DockerService = mockDockerService.Object, + LinuxScanner = this.mockSyftLinuxScanner.Object, + Logger = this.mockLogger.Object, + DockerService = this.mockDockerService.Object, }; Func action = async () => await linuxContainerDetector.ExecuteDetectorAsync(scanRequest); @@ -211,12 +211,12 @@ public async Task TestLinuxContainerDetector_HandlesScratchBase() { // Setup docker service to throw an exception on scratch // then specify that the base image is scratch, to test this // is coped with. - mockDockerService.Setup(service => service.TryPullImageAsync("scratch", It.IsAny())) + this.mockDockerService.Setup(service => service.TryPullImageAsync("scratch", It.IsAny())) .Throws(new IOException()); - mockDockerService.Setup(service => service.InspectImageAsync(It.IsAny(), It.IsAny())) - // Specify BaseImageRef = scratch to verify that cope + this.mockDockerService.Setup(service => service.InspectImageAsync(It.IsAny(), It.IsAny())) + // Specify BaseImageRef = scratch to verify that cope .ReturnsAsync(new ContainerDetails { Id = 1, ImageId = NodeLatestDigest, Layers = Enumerable.Empty() , BaseImageRef = "scratch"}); - await TestLinuxContainerDetector(); + await this.TestLinuxContainerDetector(); } } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs index efdf650fb..a0452f579 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs @@ -42,20 +42,20 @@ public class LinuxScannerTests [TestInitialize] public void TestInitialize() { - mockDockerService = new Mock(); - mockDockerService.Setup(service => service.CanPingDockerAsync(It.IsAny())) + this.mockDockerService = new Mock(); + this.mockDockerService.Setup(service => service.CanPingDockerAsync(It.IsAny())) .ReturnsAsync(true); - mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())); - mockDockerService.Setup(service => service.CreateAndRunContainerAsync(It.IsAny(), It.IsAny>(), It.IsAny())) + this.mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())); + this.mockDockerService.Setup(service => service.CreateAndRunContainerAsync(It.IsAny(), It.IsAny>(), It.IsAny())) .ReturnsAsync((SyftOutput, string.Empty)); - linuxScanner = new LinuxScanner { DockerService = mockDockerService.Object }; + this.linuxScanner = new LinuxScanner { DockerService = this.mockDockerService.Object }; } [TestMethod] public async Task TestLinuxScanner() { - var result = (await linuxScanner.ScanLinuxAsync("fake_hash", new[] { new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" } }, 0)).First().LinuxComponents; + var result = (await this.linuxScanner.ScanLinuxAsync("fake_hash", new[] { new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" } }, 0)).First().LinuxComponents; result.Should().HaveCount(1); var package = result.First(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs index b0debcd7c..118190be6 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs @@ -25,15 +25,15 @@ public class MavenCommandServiceTests [TestInitialize] public void InitializeTests() { - commandLineMock = new Mock(); + this.commandLineMock = new Mock(); var loggerMock = new Mock(); - parserServiceMock = new Mock(); + this.parserServiceMock = new Mock(); - mavenCommandService = new MavenCommandService + this.mavenCommandService = new MavenCommandService { - CommandLineInvocationService = commandLineMock.Object, - ParserService = parserServiceMock.Object, + CommandLineInvocationService = this.commandLineMock.Object, + ParserService = this.parserServiceMock.Object, Logger = loggerMock.Object, }; } @@ -41,12 +41,12 @@ public void InitializeTests() [TestMethod] public async Task MavenCLIExists_ExpectedArguments_ReturnTrue() { - commandLineMock.Setup(x => x.CanCommandBeLocated( + this.commandLineMock.Setup(x => x.CanCommandBeLocated( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(true); - var result = await mavenCommandService.MavenCLIExists(); + var result = await this.mavenCommandService.MavenCLIExists(); result.Should().BeTrue(); } @@ -54,12 +54,12 @@ public async Task MavenCLIExists_ExpectedArguments_ReturnTrue() [TestMethod] public async Task MavenCLIExists_ExpectedArguments_ReturnFalse() { - commandLineMock.Setup(x => x.CanCommandBeLocated( + this.commandLineMock.Setup(x => x.CanCommandBeLocated( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(false); - var result = await mavenCommandService.MavenCLIExists(); + var result = await this.mavenCommandService.MavenCLIExists(); result.Should().BeFalse(); } @@ -79,19 +79,19 @@ public async Task GenerateDependenciesFile_Success() var bcdeMvnFileName = "bcde.mvndeps"; var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={bcdeMvnFileName}", "-DoutputType=text", $"-f{pomLocation}" }; - commandLineMock.Setup(x => x.ExecuteCommand( + this.commandLineMock.Setup(x => x.ExecuteCommand( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, - It.Is(y => ShouldBeEquivalentTo(y, cliParameters)))) + It.Is(y => this.ShouldBeEquivalentTo(y, cliParameters)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, }) .Verifiable(); - await mavenCommandService.GenerateDependenciesFile(processRequest); + await this.mavenCommandService.GenerateDependenciesFile(processRequest); - Mock.Verify(commandLineMock); + Mock.Verify(this.commandLineMock); } [TestMethod] @@ -111,11 +111,11 @@ public void ParseDependenciesFile_Success() }; var lines = new[] { "com.bcde.test:top-level:jar:1.0.0", $"\\- {componentString}" }; - parserServiceMock.Setup(x => x.Parse(lines, It.IsAny())).Verifiable(); + this.parserServiceMock.Setup(x => x.Parse(lines, It.IsAny())).Verifiable(); - mavenCommandService.ParseDependenciesFile(processRequest); + this.mavenCommandService.ParseDependenciesFile(processRequest); - Mock.Verify(parserServiceMock); + Mock.Verify(this.parserServiceMock); } protected bool ShouldBeEquivalentTo(IEnumerable result, IEnumerable expected) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs index eb2a7786c..7144d3dc9 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs @@ -17,7 +17,7 @@ public class MavenStyleDependencyGraphParserTests [TestMethod] public void MavenFormat_ExpectedParse() { - var sampleMavenDependencyTree = File.ReadAllLines(sampleMavenDependencyTreePath); + var sampleMavenDependencyTree = File.ReadAllLines(this.sampleMavenDependencyTreePath); MavenStyleDependencyGraphParser parser = new MavenStyleDependencyGraphParser(); var parsedGraph = parser.Parse(sampleMavenDependencyTree); @@ -45,7 +45,7 @@ public void MavenFormat_ExpectedParse() [TestMethod] public void MavenFormat_WithSingleFileComponentRecorder_ExpectedParse() { - var sampleMavenDependencyTree = File.ReadAllLines(sampleMavenDependencyTreePath); + var sampleMavenDependencyTree = File.ReadAllLines(this.sampleMavenDependencyTreePath); MavenStyleDependencyGraphParser parser = new MavenStyleDependencyGraphParser(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs index ead741ce9..daa83cabc 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs @@ -28,10 +28,10 @@ public class MvnCliDetectorTests [TestInitialize] public void InitializeTests() { - commandLineMock = new Mock(); - mavenCommandService = new MavenCommandService + this.commandLineMock = new Mock(); + this.mavenCommandService = new MavenCommandService { - CommandLineInvocationService = commandLineMock.Object, + CommandLineInvocationService = this.commandLineMock.Object, ParserService = new MavenStyleDependencyGraphParserService(), }; @@ -39,7 +39,7 @@ public void InitializeTests() var detector = new MvnCliComponentDetector { - MavenCommandService = mavenCommandService, + MavenCommandService = this.mavenCommandService, Logger = loggerMock.Object, }; @@ -47,28 +47,28 @@ public void InitializeTests() var detectionPath = Path.Combine(tempPath, Guid.NewGuid().ToString()); Directory.CreateDirectory(detectionPath); - scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); + this.scanRequest = new ScanRequest(new DirectoryInfo(detectionPath), (name, directoryName) => false, loggerMock.Object, null, null, new ComponentRecorder()); - detectorTestUtility = DetectorTestUtilityCreator.Create() - .WithScanRequest(scanRequest) + this.detectorTestUtility = DetectorTestUtilityCreator.Create() + .WithScanRequest(this.scanRequest) .WithDetector(detector); } [TestCleanup] public void TestCleanup() { - scanRequest.SourceDirectory.Delete(); + this.scanRequest.SourceDirectory.Delete(); } [TestMethod] public async Task IfMavenIsNotAvailableThenExitDetectorGracefully() { - commandLineMock.Setup(x => x.CanCommandBeLocated( + this.commandLineMock.Setup(x => x.CanCommandBeLocated( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(false); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(componentRecorder.GetDetectedComponents().Count(), 0); Assert.AreEqual(detectorResult.ResultCode, ProcessingResultCode.Success); @@ -79,9 +79,9 @@ public async Task MavenAvailableHappyPath() { const string componentString = "org.apache.maven:maven-compat:jar:3.6.1-SNAPSHOT"; - MvnCliHappyPath(content: componentString); + this.MvnCliHappyPath(content: componentString); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(detectedComponents.Count(), 1); @@ -98,12 +98,12 @@ public async Task MavenAvailableHappyPath() [TestMethod] public async Task MavenCli_FileObservableIsNotPresent_DetectionShouldNotFail() { - commandLineMock.Setup(x => x.CanCommandBeLocated( + this.commandLineMock.Setup(x => x.CanCommandBeLocated( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(true); - Func action = async () => await detectorTestUtility.ExecuteDetector(); + Func action = async () => await this.detectorTestUtility.ExecuteDetector(); await action.Should().NotThrowAsync(); } @@ -116,9 +116,9 @@ public async Task MavenRoots() string content = $@"com.bcde.test:top-level:jar:1.0.0{Environment.NewLine}\- {componentString}{Environment.NewLine} \- {childComponentString}"; - MvnCliHappyPath(content); + this.MvnCliHappyPath(content); - var (detectorResult, componentRecorder) = await detectorTestUtility + var (detectorResult, componentRecorder) = await this.detectorTestUtility .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -154,9 +154,9 @@ public async Task MavenDependencyGraph() const string intermediateParentComponentId = "org.apache.maven maven-compat-parent 3.6.1-SNAPSHOT - Maven"; const string leafComponentId = "org.apache.maven maven-compat-child 3.6.1-SNAPSHOT - Maven"; - MvnCliHappyPath(content); + this.MvnCliHappyPath(content); - var (detectorResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (detectorResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); componentRecorder.GetDetectedComponents().Should().HaveCount(4); detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -178,20 +178,20 @@ public async Task MavenDependencyGraph() private void MvnCliHappyPath(string content) { - commandLineMock.Setup(x => x.CanCommandBeLocated(MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(true); + this.commandLineMock.Setup(x => x.CanCommandBeLocated(MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, MavenCommandService.MvnVersionArgument)).ReturnsAsync(true); - var expectedPomLocation = scanRequest.SourceDirectory.FullName; + var expectedPomLocation = this.scanRequest.SourceDirectory.FullName; var bcdeMvnFileName = "bcde.mvndeps"; - detectorTestUtility.WithFile("pom.xml", content, fileLocation: expectedPomLocation) + this.detectorTestUtility.WithFile("pom.xml", content, fileLocation: expectedPomLocation) .WithFile("pom.xml", content, searchPatterns: new[] { bcdeMvnFileName }, fileLocation: Path.Combine(expectedPomLocation, "pom.xml")); var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={bcdeMvnFileName}", "-DoutputType=text", $"-f{expectedPomLocation}" }; - commandLineMock.Setup(x => x.ExecuteCommand( + this.commandLineMock.Setup(x => x.ExecuteCommand( MavenCommandService.PrimaryCommand, MavenCommandService.AdditionalValidCommands, - It.Is(y => ShouldBeEquivalentTo(y, cliParameters)))) + It.Is(y => this.ShouldBeEquivalentTo(y, cliParameters)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs index 6e3c0021c..2dd66fda0 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs @@ -28,10 +28,10 @@ public class NpmDetectorTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - pathUtilityService = new Mock(); - pathUtilityService.Setup(x => x.GetParentDirectory(It.IsAny())).Returns((string path) => Path.GetDirectoryName(path)); - componentRecorder = new ComponentRecorder(); + this.loggerMock = new Mock(); + this.pathUtilityService = new Mock(); + this.pathUtilityService.Setup(x => x.GetParentDirectory(It.IsAny())).Returns((string path) => Path.GetDirectoryName(path)); + this.componentRecorder = new ComponentRecorder(); } [TestMethod] @@ -43,9 +43,9 @@ public async Task TestNpmDetector_NameAndVersionDetected() NpmTestUtilities.GetPackageJsonNoDependenciesForNameAndVersion(componentName, version); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -63,9 +63,9 @@ public async Task TestNpmDetector_AuthorNameAndEmailDetected_AuthorInJsonFormat( var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailInJsonFormat(authorName, authorEmail); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -83,9 +83,9 @@ public async Task TestNpmDetector_AuthorNameDetectedWhenEmailIsNotPresent_Author NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailInJsonFormat(authorName, null); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -105,9 +105,9 @@ public async Task TestNpmDetector_AuthorNameAndAuthorEmailDetected_WhenAuthorNam NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName, authorEmail, authroUrl); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -126,9 +126,9 @@ public async Task TestNpmDetector_AuthorNameDetected_WhenEmailNotPresentAndUrlIs NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName, null, authroUrl); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -148,9 +148,9 @@ public async Task TestNpmDetector_AuthorNull_WhenAuthorMalformed_AuthorAsSingleS NpmTestUtilities.GetPackageJsonNoDependenciesMalformedAuthorAsSingleString(authorName, authorEmail, authroUrl); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -168,9 +168,9 @@ public async Task TestNpmDetector_AuthorNameDetected_WhenEmailNotPresentAndUrlNo NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -189,9 +189,9 @@ public async Task TestNpmDetector_AuthorNameAndAuthorEmailDetected_WhenUrlNotPre NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName, authorEmail); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -211,9 +211,9 @@ public async Task TestNpmDetector_NullAuthor_WhenAuthorNameIsNullOrEmpty_AuthorA NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailInJsonFormat(authorName, authorEmail); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -232,9 +232,9 @@ public async Task TestNpmDetector_NullAuthor_WhenAuthorNameIsNullOrEmpty_AuthorA NpmTestUtilities.GetPackageJsonNoDependenciesForAuthorAndEmailAsSingleString(authorName, authorEmail); var detector = new NpmComponentDetector(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs index c6e7fbd06..7c1d50c74 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs @@ -33,10 +33,10 @@ public class NpmDetectorWithRootsTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - pathUtilityService = new Mock(); - pathUtilityService.Setup(x => x.GetParentDirectory(It.IsAny())).Returns((string path) => Path.GetDirectoryName(path)); - componentRecorder = new ComponentRecorder(); + this.loggerMock = new Mock(); + this.pathUtilityService = new Mock(); + this.pathUtilityService.Setup(x => x.GetParentDirectory(It.IsAny())).Returns((string path) => Path.GetDirectoryName(path)); + this.componentRecorder = new ComponentRecorder(); } [TestMethod] @@ -45,18 +45,18 @@ public async Task TestNpmDetector_PackageLockReturnsValid() string componentName0 = Guid.NewGuid().ToString("N"); string version0 = NewRandomVersion(); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName0, version0); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName0, version0); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, version0); var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -77,18 +77,18 @@ public async Task TestNpmDetector_MismatchedFilesReturnsEmpty() string componentName0 = Guid.NewGuid().ToString("N"); string version0 = NewRandomVersion(); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName); var (packageJsonName, packageJsonContents, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, version0); var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonName, packageJsonContents, packageJsonSearchPattern, fileLocation: packageJsonPath) + .WithFile(packageJsonName, packageJsonContents, this.packageJsonSearchPattern, fileLocation: packageJsonPath) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -98,14 +98,14 @@ public async Task TestNpmDetector_MismatchedFilesReturnsEmpty() [TestMethod] public async Task TestNpmDetector_MissingPackageJsonReturnsEmpty() { - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName); var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) .ExecuteDetector(); @@ -124,7 +124,7 @@ public async Task TestNpmDetector_PackageLockMultiRoot() string version2 = NewRandomVersion(); string componentName3 = Guid.NewGuid().ToString("N"); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName0, version0, componentName2, version2, packageName1: componentName1, packageName3: componentName3); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName0, version0, componentName2, version2, packageName1: componentName1, packageName3: componentName3); string packagejson = @"{{ ""name"": ""test"", @@ -139,13 +139,13 @@ public async Task TestNpmDetector_PackageLockMultiRoot() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -186,7 +186,7 @@ public async Task TestNpmDetector_VerifyMultiRoot_DependencyGraph() string componentName2 = Guid.NewGuid().ToString("N"); string version2 = NewRandomVersion(); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName0, version0, componentName2, version2); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName0, version0, componentName2, version2); string packagejson = @"{{ ""name"": ""test"", @@ -201,13 +201,13 @@ public async Task TestNpmDetector_VerifyMultiRoot_DependencyGraph() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); var graphsByLocation = componentRecorder.GetDependencyGraphsByLocation(); @@ -271,13 +271,13 @@ public async Task TestNpmDetector_EmptyVersionSkipped() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -330,13 +330,13 @@ public async Task TestNpmDetector_InvalidNameSkipped() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -346,8 +346,8 @@ public async Task TestNpmDetector_InvalidNameSkipped() [TestMethod] public async Task TestNpmDetector_LernaDirectory() { - string lockFileLocation = Path.Combine(Path.GetTempPath(), Path.Combine("belowLerna", packageLockJsonFileName)); - string packageJsonFileLocation = Path.Combine(Path.GetTempPath(), Path.Combine("belowLerna", packageJsonFileName)); + string lockFileLocation = Path.Combine(Path.GetTempPath(), Path.Combine("belowLerna", this.packageLockJsonFileName)); + string packageJsonFileLocation = Path.Combine(Path.GetTempPath(), Path.Combine("belowLerna", this.packageJsonFileName)); string lernaFileLocation = Path.Combine(Path.GetTempPath(), "lerna.json"); string componentName0 = Guid.NewGuid().ToString("N"); @@ -395,14 +395,14 @@ public async Task TestNpmDetector_LernaDirectory() var packageJsonTemplate = string.Format(packagejson, componentName0, version0, componentName1, version1, componentName2, version2); var detector = new NpmComponentDetectorWithRoots(); - pathUtilityService.Setup(x => x.IsFileBelowAnother(It.IsAny(), It.IsAny())).Returns(true); - detector.PathUtilityService = pathUtilityService.Object; + this.pathUtilityService.Setup(x => x.IsFileBelowAnother(It.IsAny(), It.IsAny())).Returns(true); + detector.PathUtilityService = this.pathUtilityService.Object; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile("lerna.json", "unused string", detector.SearchPatterns, fileLocation: lernaFileLocation) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns, fileLocation: lockFileLocation) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern, fileLocation: packageJsonFileLocation) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns, fileLocation: lockFileLocation) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern, fileLocation: packageJsonFileLocation) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -412,7 +412,7 @@ public async Task TestNpmDetector_LernaDirectory() [TestMethod] public async Task TestNpmDetector_CircularRequirementsResolve() { - string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), packageLockJsonFileName); + string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), this.packageLockJsonFileName); string componentName0 = Guid.NewGuid().ToString("N"); string version0 = NewRandomVersion(); @@ -457,13 +457,13 @@ public async Task TestNpmDetector_CircularRequirementsResolve() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -484,7 +484,7 @@ public async Task TestNpmDetector_CircularRequirementsResolve() public async Task TestNpmDetector_ShrinkwrapLockReturnsValid() { string lockFileName = "npm-shrinkwrap.json"; - string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), packageJsonFileName); + string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), this.packageJsonFileName); string componentName0 = Guid.NewGuid().ToString("N"); string version0 = NewRandomVersion(); @@ -494,13 +494,13 @@ public async Task TestNpmDetector_ShrinkwrapLockReturnsValid() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonFileName, packageJsonContents, packageJsonSearchPattern) + .WithFile(this.packageJsonFileName, packageJsonContents, this.packageJsonSearchPattern) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -520,16 +520,16 @@ public async Task TestNpmDetector_IgnoresPackageLocksInSubFolders() { string pathRoot = Path.GetTempPath(); - string packageLockUnderNodeModules = Path.Combine(pathRoot, Path.Combine("node_modules", packageLockJsonFileName)); - string packageJsonUnderNodeModules = Path.Combine(pathRoot, Path.Combine("node_modules", packageJsonFileName)); + string packageLockUnderNodeModules = Path.Combine(pathRoot, Path.Combine("node_modules", this.packageLockJsonFileName)); + string packageJsonUnderNodeModules = Path.Combine(pathRoot, Path.Combine("node_modules", this.packageJsonFileName)); string componentName0 = Guid.NewGuid().ToString("N"); string version0 = NewRandomVersion(); string componentName2 = Guid.NewGuid().ToString("N"); string version2 = NewRandomVersion(); - var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName0, version0); - var (packageLockName2, packageLockContents2, packageLockPath2) = NpmTestUtilities.GetWellFormedPackageLock2(packageLockJsonFileName, componentName2, version2, packageName0: "test2"); + var (packageLockName, packageLockContents, packageLockPath) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName0, version0); + var (packageLockName2, packageLockContents2, packageLockPath2) = NpmTestUtilities.GetWellFormedPackageLock2(this.packageLockJsonFileName, componentName2, version2, packageName0: "test2"); string packagejson = @"{{ ""name"": ""{2}"", @@ -545,17 +545,17 @@ public async Task TestNpmDetector_IgnoresPackageLocksInSubFolders() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) /* Top level */ .WithFile(packageLockName, packageLockContents, detector.SearchPatterns, fileLocation: packageLockPath) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) /* Under node_modules */ .WithFile(packageLockName2, packageLockContents2, detector.SearchPatterns, fileLocation: packageLockUnderNodeModules) - .WithFile(packageJsonFileName, packageJsonTemplate2, packageJsonSearchPattern, fileLocation: packageJsonUnderNodeModules) + .WithFile(this.packageJsonFileName, packageJsonTemplate2, this.packageJsonSearchPattern, fileLocation: packageJsonUnderNodeModules) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); @@ -573,7 +573,7 @@ public async Task TestNpmDetector_IgnoresPackageLocksInSubFolders() [TestMethod] public async Task TestNpmDetector_DependencyGraphIsCreated() { - string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), packageLockJsonFileName); + string packageJsonComponentPath = Path.Combine(Path.GetTempPath(), this.packageLockJsonFileName); var componentA = (Name: "componentA", Version: "1.0.0"); var componentB = (Name: "componentB", Version: "1.0.0"); @@ -626,13 +626,13 @@ public async Task TestNpmDetector_DependencyGraphIsCreated() var detector = new NpmComponentDetectorWithRoots { - PathUtilityService = pathUtilityService.Object, + PathUtilityService = this.pathUtilityService.Object, }; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithDetector(detector) - .WithFile(packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) - .WithFile(packageJsonFileName, packageJsonTemplate, packageJsonSearchPattern) + .WithFile(this.packageLockJsonFileName, packageLockTemplate, detector.SearchPatterns) + .WithFile(this.packageJsonFileName, packageJsonTemplate, this.packageJsonSearchPattern) .ExecuteDetector(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs index e2640c9d6..c1991f3f0 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs @@ -22,7 +22,7 @@ public class NpmUtilitiesTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); + this.loggerMock = new Mock(); } [TestMethod] @@ -38,7 +38,7 @@ public void TestGetTypedComponent() JObject j = JObject.Parse(json); - var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNotNull(componentFromJProperty); Assert.AreEqual(componentFromJProperty.Type, ComponentType.Npm); @@ -61,7 +61,7 @@ public void TestGetTypedComponent_FailsOnMalformed() JObject j = JObject.Parse(json); - var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); } @@ -78,7 +78,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }"; JObject j = JObject.Parse(jsonInvalidCharacter); - var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + var componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); string jsonUrlName = @"{ @@ -90,7 +90,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }"; j = JObject.Parse(jsonUrlName); - componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); string jsonInvalidInitialCharacter1 = @"{ @@ -102,7 +102,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }"; j = JObject.Parse(jsonInvalidInitialCharacter1); - componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); string jsonInvalidInitialCharacter2 = @"{ @@ -114,7 +114,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }"; j = JObject.Parse(jsonInvalidInitialCharacter2); - componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); var longPackageName = new string('a', 214); @@ -127,7 +127,7 @@ public void TestGetTypedComponent_FailsOnInvalidPackageName() }}"; j = JObject.Parse(jsonLongName); - componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", loggerMock.Object); + componentFromJProperty = NpmComponentUtilities.GetTypedComponent(j.Children().Single(), "registry.npmjs.org", this.loggerMock.Object); Assert.IsNull(componentFromJProperty); } @@ -164,7 +164,7 @@ public void TestTraverseAndGetRequirementsAndDependencies() var currentDependency = jsonChildren.Single(); var dependencyLookup = jsonChildren.ToDictionary(dependency => dependency.Name); - var typedComponent = NpmComponentUtilities.GetTypedComponent(currentDependency, "registry.npmjs.org", loggerMock.Object); + var typedComponent = NpmComponentUtilities.GetTypedComponent(currentDependency, "registry.npmjs.org", this.loggerMock.Object); ComponentRecorder componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder1 = componentRecorder.CreateSingleFileComponentRecorder("/this/is/a/test/path/"); @@ -196,7 +196,7 @@ public void TestTraverseAndGetRequirementsAndDependencies() var currentDependency1 = jsonChildren1.Single(); var dependencyLookup1 = jsonChildren1.ToDictionary(dependency => dependency.Name); - var typedComponent1 = NpmComponentUtilities.GetTypedComponent(currentDependency1, "registry.npmjs.org", loggerMock.Object); + var typedComponent1 = NpmComponentUtilities.GetTypedComponent(currentDependency1, "registry.npmjs.org", this.loggerMock.Object); NpmComponentUtilities.TraverseAndRecordComponents(currentDependency1, singleFileComponentRecorder2, typedComponent1, typedComponent1); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs index 79a962b03..213058f9f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs @@ -28,14 +28,14 @@ public class NuGetComponentDetectorTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.loggerMock = new Mock(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] public async Task TestNuGetDetectorWithNoFiles_ReturnsSuccessfully() { - var (scanResult, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (scanResult, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); Assert.AreEqual(0, componentRecorder.GetDetectedComponents().Count()); @@ -49,14 +49,14 @@ public async Task TestNugetDetector_ReturnsValidNuspecComponent() var testAuthors = new string[] { "author 1", "author 2" }; var nuspec = NugetTestUtilities.GetValidNuspec(testComponentName, testVersion, testAuthors); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("*.nuspec", nuspec) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode, "Result code does Not match."); Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count(), "Componet count does not match"); var detectedComponent = componentRecorder.GetDetectedComponents().First().Component; - Assert.AreEqual(Contracts.TypedComponent.ComponentType.NuGet, detectedComponent.Type); + Assert.AreEqual(ComponentType.NuGet, detectedComponent.Type); var nuGetComponent = (NuGetComponent)detectedComponent; Assert.AreEqual(testComponentName, nuGetComponent.Name, "Component name does not match."); Assert.AreEqual(testVersion, nuGetComponent.Version, "Component version does not match."); @@ -71,14 +71,14 @@ public async Task TestNugetDetector_ReturnsValidNuspecComponent_SingleAuthor() var testAuthors = new string[] { "author 1" }; var nuspec = NugetTestUtilities.GetValidNuspec(testComponentName, testVersion, testAuthors); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("*.nuspec", nuspec) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode, "Result code does Not match."); Assert.AreEqual(1, componentRecorder.GetDetectedComponents().Count(), "Componet count does not match"); var detectedComponent = componentRecorder.GetDetectedComponents().First().Component; - Assert.AreEqual(Contracts.TypedComponent.ComponentType.NuGet, detectedComponent.Type); + Assert.AreEqual(ComponentType.NuGet, detectedComponent.Type); var nuGetComponent = (NuGetComponent)detectedComponent; Assert.AreEqual(testComponentName, nuGetComponent.Name, "Component name does not match."); Assert.AreEqual(testVersion, nuGetComponent.Version, "Component version does not match."); @@ -90,7 +90,7 @@ public async Task TestNugetDetector_ReturnsValidNupkgComponent() { var nupkg = await NugetTestUtilities.ZipNupkgComponent("test.nupkg", NugetTestUtilities.GetRandomValidNuspec()); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("test.nupkg", nupkg) .ExecuteDetector(); @@ -104,7 +104,7 @@ public async Task TestNugetDetector_ReturnsValidMixedComponent() var nuspec = NugetTestUtilities.GetRandomValidNuSpecComponent(); var nupkg = await NugetTestUtilities.ZipNupkgComponent("test.nupkg", NugetTestUtilities.GetRandomValidNuspec()); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("test.nuspec", nuspec) .WithFile("test.nupkg", nupkg) .ExecuteDetector(); @@ -120,14 +120,14 @@ public async Task TestNugetDetector_HandlesMalformedComponentsInComponentList() var malformedNupkg = await NugetTestUtilities.ZipNupkgComponent("malformed.nupkg", NugetTestUtilities.GetRandomMalformedNuPkgComponent()); var nuspec = NugetTestUtilities.GetRandomValidNuSpecComponent(); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithLogger(loggerMock) + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithLogger(this.loggerMock) .WithFile("test.nuspec", nuspec) .WithFile("test.nupkg", validNupkg) .WithFile("malformed.nupkg", malformedNupkg) .ExecuteDetector(); - loggerMock.Verify(x => x.LogFailedReadingFile(Path.Join(Path.GetTempPath(), "malformed.nupkg"), It.IsAny())); + this.loggerMock.Verify(x => x.LogFailedReadingFile(Path.Join(Path.GetTempPath(), "malformed.nupkg"), It.IsAny())); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); Assert.AreEqual(2, componentRecorder.GetDetectedComponents().Count()); @@ -139,15 +139,15 @@ public async Task TestNugetDetector_AdditionalDirectories() var component1 = NugetTestUtilities.GetRandomValidNuSpecComponentStream(); var streamsDetectedInNormalPass = new List { component1 }; - var additionalDirectory = CreateTemporaryDirectory(); + var additionalDirectory = this.CreateTemporaryDirectory(); var nugetConfigComponent = NugetTestUtilities.GetValidNuGetConfig(additionalDirectory); var streamsDetectedInAdditionalDirectoryPass = new List { nugetConfigComponent }; var componentRecorder = new ComponentRecorder(); var detector = new NuGetComponentDetector(); - var sourceDirectoryPath = CreateTemporaryDirectory(); + var sourceDirectoryPath = this.CreateTemporaryDirectory(); - detector.Logger = loggerMock.Object; + detector.Logger = this.loggerMock.Object; // Use strict mock evaluation because we're doing some "fun" stuff with this mock. var componentStreamEnumerableFactoryMock = new Mock(MockBehavior.Strict); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs index deee5b235..b273e4933 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs @@ -43,16 +43,16 @@ public void TestInitialize() .Returns(true); detector.FileUtilityService = fileUtilityServiceMock.Object; - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithDetector(detector); } [TestMethod] public async Task ScanDirectoryAsync_Base_2_2_Verification() { - string osAgnostic = Convert22SampleToOSAgnostic(TestResources.project_assets_2_2); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + string osAgnostic = this.Convert22SampleToOSAgnostic(TestResources.project_assets_2_2); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -73,9 +73,9 @@ public async Task ScanDirectoryAsync_Base_2_2_Verification() [TestMethod] public async Task ScanDirectoryAsync_Base_2_2_additional_Verification() { - string osAgnostic = Convert22SampleToOSAgnostic(TestResources.project_assets_2_2_additional); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + string osAgnostic = this.Convert22SampleToOSAgnostic(TestResources.project_assets_2_2_additional); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -99,9 +99,9 @@ public async Task ScanDirectoryAsync_Base_2_2_additional_Verification() [TestMethod] public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_2_2_Verification() { - string osAgnostic = Convert22SampleToOSAgnostic(TestResources.project_assets_2_2); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + string osAgnostic = this.Convert22SampleToOSAgnostic(TestResources.project_assets_2_2); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var ommittedComponentInformationJson = scanResult.AdditionalTelemetryDetails[NuGetProjectModelProjectCentricComponentDetector.OmittedFrameworkComponentsTelemetryKey]; @@ -114,9 +114,9 @@ public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_2_2_Verification [TestMethod] public async Task ScanDirectoryAsync_DependencyGraph_2_2_additional_Verification() { - string osAgnostic = Convert22SampleToOSAgnostic(TestResources.project_assets_2_2_additional); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + string osAgnostic = this.Convert22SampleToOSAgnostic(TestResources.project_assets_2_2_additional); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var graphsByLocation = componentRecorder.GetDependencyGraphsByLocation(); var graph = graphsByLocation.Values.First(); @@ -194,9 +194,9 @@ public async Task ScanDirectoryAsync_DependencyGraph_2_2_additional_Verification [TestMethod] public async Task ScanDirectoryAsync_Base_3_1_Verification() { - string osAgnostic = Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + string osAgnostic = this.Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); // Number of unique nodes in ProjectAssetsJson @@ -216,9 +216,9 @@ public async Task ScanDirectoryAsync_Base_3_1_Verification() [TestMethod] public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_3_1_Verification() { - string osAgnostic = Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + string osAgnostic = this.Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var ommittedComponentInformationJson = scanResult.AdditionalTelemetryDetails[NuGetProjectModelProjectCentricComponentDetector.OmittedFrameworkComponentsTelemetryKey]; @@ -232,9 +232,9 @@ public async Task ScanDirectoryAsync_ExcludedFrameworkComponent_3_1_Verification [TestMethod] public async Task ScanDirectoryAsync_DependencyGraph_3_1_Verification() { - string osAgnostic = Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + string osAgnostic = this.Convert31SampleToOSAgnostic(TestResources.project_assets_3_1); + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); var graphsByLocation = componentRecorder.GetDependencyGraphsByLocation(); @@ -286,8 +286,8 @@ public async Task ScanDirectory_NoPackageSpec() }, ""packageFolders"": {} }"; - var (scanResult, componentRecorder) = await detectorTestUtility - .WithFile(projectAssetsJsonFileName, osAgnostic) + var (scanResult, componentRecorder) = await this.detectorTestUtility + .WithFile(this.projectAssetsJsonFileName, osAgnostic) .ExecuteDetector(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs index aa76ae8cd..acd34abeb 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs @@ -27,41 +27,41 @@ public class PipComponentDetectorTests [TestInitialize] public void TestInitialize() { - pythonCommandService = new Mock(); - pythonResolver = new Mock(); - loggerMock = new Mock(); + this.pythonCommandService = new Mock(); + this.pythonResolver = new Mock(); + this.loggerMock = new Mock(); var detector = new PipComponentDetector { - PythonCommandService = pythonCommandService.Object, - PythonResolver = pythonResolver.Object, - Logger = loggerMock.Object, + PythonCommandService = this.pythonCommandService.Object, + PythonResolver = this.pythonResolver.Object, + Logger = this.loggerMock.Object, }; - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithDetector(detector); } [TestMethod] public async Task TestPipDetector_PythonNotInstalled() { - pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(false); + this.pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(false); - loggerMock.Setup(x => x.LogInfo(It.Is(l => l.Contains("No python found")))); + this.loggerMock.Setup(x => x.LogInfo(It.Is(l => l.Contains("No python found")))); - var (result, componentRecorder) = await detectorTestUtility + var (result, componentRecorder) = await this.detectorTestUtility .WithFile("setup.py", string.Empty) - .WithLogger(loggerMock) + .WithLogger(this.loggerMock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); - loggerMock.VerifyAll(); + this.loggerMock.VerifyAll(); } [TestMethod] public async Task TestPipDetector_PythonInstalledNoFiles() { - var (result, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (result, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); } @@ -69,14 +69,14 @@ public async Task TestPipDetector_PythonInstalledNoFiles() [TestMethod] public async Task TestPipDetector_SetupPyAndRequirementsTxt() { - pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); + this.pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); - var baseSetupPyDependencies = ToGitTuple(new List { "a==1.0", "b>=2.0,!=2.1", "c!=1.1" }); - var baseRequirementsTextDependencies = ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1" }); + var baseSetupPyDependencies = this.ToGitTuple(new List { "a==1.0", "b>=2.0,!=2.1", "c!=1.1" }); + var baseRequirementsTextDependencies = this.ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1" }); baseRequirementsTextDependencies.Add((null, new GitComponent(new Uri("https://github.com/example/example"), "deadbee"))); - pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); - pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); + this.pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); + this.pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); var setupPyRoots = new List { @@ -94,10 +94,10 @@ public async Task TestPipDetector_SetupPyAndRequirementsTxt() new PipGraphNode(new PipComponent("f", "1.1")), }; - pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "b")))).ReturnsAsync(setupPyRoots); - pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "d")))).ReturnsAsync(requirementsTxtRoots); + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "b")))).ReturnsAsync(setupPyRoots); + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "d")))).ReturnsAsync(requirementsTxtRoots); - var (result, componentRecorder) = await detectorTestUtility + var (result, componentRecorder) = await this.detectorTestUtility .WithFile("setup.py", string.Empty) .WithFile("requirements.txt", string.Empty) .ExecuteDetector(); @@ -128,12 +128,12 @@ public async Task TestPipDetector_SetupPyAndRequirementsTxt() [TestMethod] public async Task TestPipDetector_ComponentsDedupedAcrossFiles() { - pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); + this.pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); - var baseRequirementsTextDependencies = ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1", "h==1.3" }); - var baseRequirementsTextDependencies2 = ToGitTuple(new List { "D~=1.0", "E<=2.0", "F===1.1", "g==2" }); - pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); - pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "TEST", "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies2); + var baseRequirementsTextDependencies = this.ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1", "h==1.3" }); + var baseRequirementsTextDependencies2 = this.ToGitTuple(new List { "D~=1.0", "E<=2.0", "F===1.1", "g==2" }); + this.pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); + this.pythonCommandService.Setup(x => x.ParseFile(Path.Join(Path.GetTempPath(), "TEST", "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies2); var requirementsTxtRoots = new List { @@ -150,10 +150,10 @@ public async Task TestPipDetector_ComponentsDedupedAcrossFiles() new PipGraphNode(new PipComponent("g", "1.2")), }; - pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "h")))).ReturnsAsync(requirementsTxtRoots); - pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "g")))).ReturnsAsync(requirementsTxtRoots2); + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "h")))).ReturnsAsync(requirementsTxtRoots); + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "g")))).ReturnsAsync(requirementsTxtRoots2); - var (result, componentRecorder) = await detectorTestUtility + var (result, componentRecorder) = await this.detectorTestUtility .WithFile("requirements.txt", string.Empty) .WithFile("requirements.txt", string.Empty, fileLocation: Path.Join(Path.GetTempPath(), "TEST", "requirements.txt")) .ExecuteDetector(); @@ -165,15 +165,15 @@ public async Task TestPipDetector_ComponentsDedupedAcrossFiles() [TestMethod] public async Task TestPipDetector_ComponentRecorder() { - pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); + this.pythonCommandService.Setup(x => x.PythonExists(It.IsAny())).ReturnsAsync(true); const string file1 = "c:\\repo\\setup.py"; const string file2 = "c:\\repo\\lib\\requirements.txt"; - var baseReqs = ToGitTuple(new List { "a~=1.0", "b<=2.0", }); - var altReqs = ToGitTuple(new List { "c~=1.0", "d<=2.0", "e===1.1" }); - pythonCommandService.Setup(x => x.ParseFile(file1, null)).ReturnsAsync(baseReqs); - pythonCommandService.Setup(x => x.ParseFile(file2, null)).ReturnsAsync(altReqs); + var baseReqs = this.ToGitTuple(new List { "a~=1.0", "b<=2.0", }); + var altReqs = this.ToGitTuple(new List { "c~=1.0", "d<=2.0", "e===1.1" }); + this.pythonCommandService.Setup(x => x.ParseFile(file1, null)).ReturnsAsync(baseReqs); + this.pythonCommandService.Setup(x => x.ParseFile(file2, null)).ReturnsAsync(altReqs); var rootA = new PipGraphNode(new PipComponent("a", "1.0")); var rootB = new PipGraphNode(new PipComponent("b", "2.1")); @@ -198,15 +198,15 @@ public async Task TestPipDetector_ComponentRecorder() blue.Children.Add(cat); blue.Children.Add(dog); - pythonResolver.Setup(x => + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "a")))) .ReturnsAsync(new List { rootA, rootB, }); - pythonResolver.Setup(x => + this.pythonResolver.Setup(x => x.ResolveRoots(It.Is>(p => p.Any(d => d.Name == "c")))) .ReturnsAsync(new List { rootC, rootD, rootE, }); - var (result, componentRecorder) = await detectorTestUtility + var (result, componentRecorder) = await this.detectorTestUtility .WithFile("setup.py", string.Empty, fileLocation: file1) .WithFile("setup.py", string.Empty, fileLocation: file2) .ExecuteDetector(); @@ -232,12 +232,12 @@ public async Task TestPipDetector_ComponentRecorder() x => x.Id == rootId); } - CheckChild(componentRecorder, "red 0.2 - pip", new[] { "a 1.0 - pip", "c 1.0 - pip", }); - CheckChild(componentRecorder, "green 1.3 - pip", new[] { "b 2.1 - pip", }); - CheckChild(componentRecorder, "blue 0.4 - pip", new[] { "c 1.0 - pip", }); - CheckChild(componentRecorder, "cat 1.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); - CheckChild(componentRecorder, "lion 3.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); - CheckChild(componentRecorder, "dog 2.1 - pip", new[] { "c 1.0 - pip", }); + this.CheckChild(componentRecorder, "red 0.2 - pip", new[] { "a 1.0 - pip", "c 1.0 - pip", }); + this.CheckChild(componentRecorder, "green 1.3 - pip", new[] { "b 2.1 - pip", }); + this.CheckChild(componentRecorder, "blue 0.4 - pip", new[] { "c 1.0 - pip", }); + this.CheckChild(componentRecorder, "cat 1.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); + this.CheckChild(componentRecorder, "lion 3.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); + this.CheckChild(componentRecorder, "dog 2.1 - pip", new[] { "c 1.0 - pip", }); var graphsByLocations = componentRecorder.GetDependencyGraphsByLocation(); Assert.AreEqual(2, graphsByLocations.Count); @@ -255,7 +255,7 @@ public async Task TestPipDetector_ComponentRecorder() var graph1 = graphsByLocations[file1]; Assert.IsTrue(graph1ComponentsWithDeps.Keys.Take(2).All(graph1.IsComponentExplicitlyReferenced)); Assert.IsTrue(graph1ComponentsWithDeps.Keys.Skip(2).All(a => !graph1.IsComponentExplicitlyReferenced(a))); - CheckGraphStructure(graph1, graph1ComponentsWithDeps); + this.CheckGraphStructure(graph1, graph1ComponentsWithDeps); var graph2ComponentsWithDeps = new Dictionary { @@ -272,7 +272,7 @@ public async Task TestPipDetector_ComponentRecorder() var graph2 = graphsByLocations[file2]; Assert.IsTrue(graph2ComponentsWithDeps.Keys.Take(3).All(graph2.IsComponentExplicitlyReferenced)); Assert.IsTrue(graph2ComponentsWithDeps.Keys.Skip(3).All(a => !graph2.IsComponentExplicitlyReferenced(a))); - CheckGraphStructure(graph2, graph2ComponentsWithDeps); + this.CheckGraphStructure(graph2, graph2ComponentsWithDeps); } private void CheckGraphStructure(IDependencyGraph graph, Dictionary graphComponentsWithDeps) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs index 3f4a4a77b..a3909a9f0 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs @@ -21,8 +21,8 @@ public class PipResolverTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - pyPiClient = new Mock(); + this.loggerMock = new Mock(); + this.pyPiClient = new Mock(); } [TestMethod] @@ -34,21 +34,21 @@ public async Task TestPipResolverSimpleGraph() var versions = new List { "1.0" }; - var aReleases = CreateReleasesDictionary(versions); - var bReleases = CreateReleasesDictionary(versions); - var cReleases = CreateReleasesDictionary(versions); + var aReleases = this.CreateReleasesDictionary(versions); + var bReleases = this.CreateReleasesDictionary(versions); + var cReleases = this.CreateReleasesDictionary(versions); - pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); - pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); - pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); + this.pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); + this.pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); + this.pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); - pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); - pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); var dependencies = new List { a }; - var resolver = new PythonResolver() { PypiClient = pyPiClient.Object, Logger = loggerMock.Object, }; + var resolver = new PythonResolver() { PypiClient = this.pyPiClient.Object, Logger = this.loggerMock.Object, }; var resolveResult = await resolver.ResolveRoots(dependencies); @@ -63,7 +63,7 @@ public async Task TestPipResolverSimpleGraph() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(CompareGraphs(resolveResult.First(), expectedA)); + Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); } [TestMethod] @@ -76,22 +76,22 @@ public async Task TestPipResolverNonExistantRoot() var versions = new List { "1.0" }; - var aReleases = CreateReleasesDictionary(versions); - var bReleases = CreateReleasesDictionary(versions); - var cReleases = CreateReleasesDictionary(versions); + var aReleases = this.CreateReleasesDictionary(versions); + var bReleases = this.CreateReleasesDictionary(versions); + var cReleases = this.CreateReleasesDictionary(versions); - pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); - pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); - pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); - pyPiClient.Setup(x => x.GetReleases(doesNotExist)).ReturnsAsync(CreateReleasesDictionary(new List())); + this.pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); + this.pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); + this.pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); + this.pyPiClient.Setup(x => x.GetReleases(doesNotExist)).ReturnsAsync(this.CreateReleasesDictionary(new List())); - pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); - pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); var dependencies = new List { a, doesNotExist }; - var resolver = new PythonResolver() { PypiClient = pyPiClient.Object, Logger = loggerMock.Object, }; + var resolver = new PythonResolver() { PypiClient = this.pyPiClient.Object, Logger = this.loggerMock.Object, }; var resolveResult = await resolver.ResolveRoots(dependencies); @@ -106,7 +106,7 @@ public async Task TestPipResolverNonExistantRoot() expectedB.Children.Add(expectedC); expectedC.Parents.Add(expectedB); - Assert.IsTrue(CompareGraphs(resolveResult.First(), expectedA)); + Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); } [TestMethod] @@ -118,20 +118,20 @@ public async Task TestPipResolverNonExistantLeaf() var versions = new List { "1.0" }; - var aReleases = CreateReleasesDictionary(versions); - var bReleases = CreateReleasesDictionary(versions); - var cReleases = CreateReleasesDictionary(versions); + var aReleases = this.CreateReleasesDictionary(versions); + var bReleases = this.CreateReleasesDictionary(versions); + var cReleases = this.CreateReleasesDictionary(versions); - pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); - pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); - pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(CreateReleasesDictionary(new List())); + this.pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); + this.pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); + this.pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(this.CreateReleasesDictionary(new List())); - pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); var dependencies = new List { a }; - var resolver = new PythonResolver() { PypiClient = pyPiClient.Object, Logger = loggerMock.Object, }; + var resolver = new PythonResolver() { PypiClient = this.pyPiClient.Object, Logger = this.loggerMock.Object, }; var resolveResult = await resolver.ResolveRoots(dependencies); @@ -143,8 +143,8 @@ public async Task TestPipResolverNonExistantLeaf() expectedA.Children.Add(expectedB); expectedB.Parents.Add(expectedA); - Assert.IsTrue(CompareGraphs(resolveResult.First(), expectedA)); - pyPiClient.Verify(x => x.FetchPackageDependencies(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); + Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.pyPiClient.Verify(x => x.FetchPackageDependencies(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(2)); } [TestMethod] @@ -159,22 +159,22 @@ public async Task TestPipResolverBacktrack() var otherVersions = new List { "1.0", "1.1" }; - var aReleases = CreateReleasesDictionary(versions); - var bReleases = CreateReleasesDictionary(versions); - var cReleases = CreateReleasesDictionary(otherVersions); + var aReleases = this.CreateReleasesDictionary(versions); + var bReleases = this.CreateReleasesDictionary(versions); + var cReleases = this.CreateReleasesDictionary(otherVersions); - pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); - pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); - pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); + this.pyPiClient.Setup(x => x.GetReleases(a)).ReturnsAsync(aReleases); + this.pyPiClient.Setup(x => x.GetReleases(b)).ReturnsAsync(bReleases); + this.pyPiClient.Setup(x => x.GetReleases(c)).ReturnsAsync(cReleases); - pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b, c }); - pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { cAlt }); - pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.1", cReleases["1.1"].First())).ReturnsAsync(new List { }); - pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b, c }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { cAlt }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.1", cReleases["1.1"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependencies("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); var dependencies = new List { a }; - var resolver = new PythonResolver() { PypiClient = pyPiClient.Object, Logger = loggerMock.Object, }; + var resolver = new PythonResolver() { PypiClient = this.pyPiClient.Object, Logger = this.loggerMock.Object, }; var resolveResult = await resolver.ResolveRoots(dependencies); @@ -191,8 +191,8 @@ public async Task TestPipResolverBacktrack() expectedC.Parents.Add(expectedA); expectedC.Parents.Add(expectedB); - Assert.IsTrue(CompareGraphs(resolveResult.First(), expectedA)); - pyPiClient.Verify(x => x.FetchPackageDependencies(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(4)); + Assert.IsTrue(this.CompareGraphs(resolveResult.First(), expectedA)); + this.pyPiClient.Verify(x => x.FetchPackageDependencies(It.IsAny(), It.IsAny(), It.IsAny()), Times.Exactly(4)); } private bool CompareGraphs(PipGraphNode a, PipGraphNode b) @@ -215,7 +215,7 @@ private bool CompareGraphs(PipGraphNode a, PipGraphNode b) for (int i = 0; i < a.Children.Count; i++) { - valid = CompareGraphs(a.Children[i], b.Children[i]); + valid = this.CompareGraphs(a.Children[i], b.Children[i]); } return valid; @@ -227,7 +227,8 @@ private SortedDictionary> CreateReleasesDict foreach (var version in versions) { - toReturn.Add(version, new List { CreatePythonProjectRelease() }); + toReturn.Add(version, new List { + this.CreatePythonProjectRelease() }); } return toReturn; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs index 8d3b884fb..561dcb5b0 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs @@ -24,7 +24,7 @@ public class PnpmDetectorTests public void TestInitialize() { var componentRecorder = new ComponentRecorder(enableManualTrackingOfExplicitReferences: false); - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithScanRequest(new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder)); } @@ -70,7 +70,7 @@ public async Task TestPnpmDetector_SingleFileLocatesExpectedInput() shrinkwrapMinorVersion: 7 shrinkwrapVersion: 3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile) .ExecuteDetector(); @@ -171,7 +171,7 @@ public async Task TestPnpmDetector_SameComponentMergesRootsAndLocationsAcrossMul shrinkwrapMinorVersion: 7 shrinkwrapVersion: 3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .WithFile("shrinkwrap2.yaml", yamlFile2) .ExecuteDetector(); @@ -216,7 +216,7 @@ public async Task TestPnpmDetector_SpecialDependencyVersionStringDoesntBlowUsUp( shrinkwrapMinorVersion: 7 shrinkwrapVersion: 3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetector(); @@ -245,7 +245,7 @@ public async Task TestPnpmDetector_DetectorRecognizeDevDependenciesValues() /strict-uri-encode/1.1.0: dev: true"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetector(); @@ -276,7 +276,7 @@ public async Task TestPnpmDetector_DetectorRecognizeDevDependenciesValues_InWeir shared-non-dev-dep: 0.1.2 dev: true"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetector(); @@ -291,7 +291,7 @@ public async Task TestPnpmDetector_HandlesMalformedYaml() // This is a clearly malformed Yaml. We expect parsing it to "succeed" but find no components var yamlFile1 = @"dependencies"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile1) .ExecuteDetector(); @@ -321,7 +321,7 @@ public async Task TestPnpmDetector_DependencyGraphIsCreated() /test/1.0.0: dev: true"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile) .ExecuteDetector(); @@ -369,7 +369,7 @@ public async Task TestPnpmDetector_DependenciesRefeToLocalPaths_DependenciesAreI /nth-check/2.0.0: resolution: {integrity: sha1-G7T22scAcvwxPoyc0UF7UHTAoSU=} "; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("shrinkwrap1.yaml", yamlFile) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs index b188ee5fa..25443497f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmParsingUtilitiesTest.cs @@ -38,7 +38,7 @@ public async Task DeserializePnpmYamlFile() shrinkwrapMinorVersion: 7 shrinkwrapVersion: 3"; - var parsedYaml = await PnpmParsingUtilities.DeserializePnpmYamlFile(CreateComponentStreamForShrinkwrap(yamlFile)); + var parsedYaml = await PnpmParsingUtilities.DeserializePnpmYamlFile(this.CreateComponentStreamForShrinkwrap(yamlFile)); parsedYaml.packages.Should().HaveCount(2); parsedYaml.packages.Should().ContainKey("/query-string/4.3.4"); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs index 4c00ddcc7..c6cec4a44 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs @@ -22,7 +22,7 @@ public class PodDetectorTest [TestInitialize] public void TestInitialize() { - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] @@ -32,7 +32,7 @@ public async Task TestPodDetector_EmptyPodfileLock() COCOAPODS: 1.4.0.beta.1"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -68,7 +68,7 @@ public async Task TestPodDetector_DetectorRecognizePodComponents() COCOAPODS: 0.39.0"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -77,12 +77,12 @@ public async Task TestPodDetector_DetectorRecognizePodComponents() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(6, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); - AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); - AssertPodComponentNameAndVersion(detectedComponents, "Auth", "1.44.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Auth", "1.44.1"); } [TestMethod] @@ -110,7 +110,7 @@ public async Task TestPodDetector_DetectorRecognizeSubspecsAsSinglePodComponent( COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -119,8 +119,8 @@ public async Task TestPodDetector_DetectorRecognizeSubspecsAsSinglePodComponent( var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(2, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "MSAL", "1.0.7"); - AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "MSAL", "1.0.7"); + this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); } [TestMethod] @@ -154,7 +154,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponents() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -163,7 +163,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponents() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertGitComponentHashAndUrl(detectedComponents, "da7223e3c455fe558de361c611df36c6dcc4229d", "https://github.com/microsoftgraph/msgraph-sdk-objc.git"); + this.AssertGitComponentHashAndUrl(detectedComponents, "da7223e3c455fe558de361c611df36c6dcc4229d", "https://github.com/microsoftgraph/msgraph-sdk-objc.git"); } [TestMethod] @@ -197,7 +197,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -206,7 +206,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); } [TestMethod] @@ -240,7 +240,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -249,7 +249,7 @@ public async Task TestPodDetector_DetectorRecognizeGitComponentsWithTagsAsPodCom var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "MSGraphClientSDK", "1.0.0"); } [TestMethod] @@ -277,7 +277,7 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromExternalPods COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -286,8 +286,8 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromExternalPods var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(2, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); - AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); } [TestMethod] @@ -310,7 +310,7 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromLocalPath() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .ExecuteDetector(); @@ -319,7 +319,7 @@ public async Task TestPodDetector_DetectorRecognizePodComponentsFromLocalPath() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "Keys", "1.0.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Keys", "1.0.1"); } [TestMethod] @@ -375,7 +375,7 @@ public async Task TestPodDetector_MultiplePodfileLocks() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetector(); @@ -385,14 +385,14 @@ public async Task TestPodDetector_MultiplePodfileLocks() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(8, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); - AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); - AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); - AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "SVGKit", "2.1.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); } [TestMethod] @@ -459,7 +459,7 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetector(); @@ -469,27 +469,27 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(8, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); - AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); - AssertGitComponentHashAndUrl(detectedComponents, "0d4db53890c664fb8605666e6fbccd14912ff821", "https://github.com/SVGKit/SVGKit.git"); - AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); - - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureMobile", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); - AssertGitComponentHasGitComponentDependencyRoot(componentRecorder, component: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); - - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); - AssertPodComponentHasGitComponentDependencyRoot(componentRecorder, component: (name: "CocoaLumberjack", version: "3.6.0"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); + this.AssertGitComponentHashAndUrl(detectedComponents, "0d4db53890c664fb8605666e6fbccd14912ff821", "https://github.com/SVGKit/SVGKit.git"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); + + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureMobile", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); + this.AssertGitComponentHasGitComponentDependencyRoot(componentRecorder, component: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); + + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); + this.AssertPodComponentHasGitComponentDependencyRoot(componentRecorder, component: (name: "CocoaLumberjack", version: "3.6.0"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureData", version: "0.5.0")); } [TestMethod] @@ -556,7 +556,7 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots_GitUri() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2) .ExecuteDetector(); @@ -566,27 +566,27 @@ public async Task TestPodDetector_DetectorSupportsDependencyRoots_GitUri() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(8, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); - AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); - AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); - AssertGitComponentHashAndUrl(detectedComponents, "0d4db53890c664fb8605666e6fbccd14912ff821", "https://github.com/SVGKit/SVGKit.git"); - AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); - - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureMobile", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); - AssertGitComponentHasGitComponentDependencyRoot(componentRecorder, component: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); - - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); - AssertPodComponentHasGitComponentDependencyRoot(componentRecorder, component: (name: "CocoaLumberjack", version: "3.6.0"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureData", version: "0.5.0")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureCore", version: "0.5.1")); - AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.1"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureData", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureMobile", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "CocoaLumberjack", "3.6.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "KeychainAccess", "3.2.1"); + this.AssertGitComponentHashAndUrl(detectedComponents, "0d4db53890c664fb8605666e6fbccd14912ff821", "https://github.com/SVGKit/SVGKit.git"); + this.AssertPodComponentNameAndVersion(detectedComponents, "Willow", "5.2.1"); + + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureMobile", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); + this.AssertGitComponentHasGitComponentDependencyRoot(componentRecorder, component: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); + + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureCore", version: "0.5.0"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "AzureData", version: "0.5.0"), root: (name: "AzureMobile", version: "0.5.0")); + this.AssertPodComponentHasGitComponentDependencyRoot(componentRecorder, component: (name: "CocoaLumberjack", version: "3.6.0"), root: (commit: "0d4db53890c664fb8605666e6fbccd14912ff821", repo: "https://github.com/SVGKit/SVGKit.git")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "KeychainAccess", version: "3.2.1"), root: (name: "AzureData", version: "0.5.0")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureCore", version: "0.5.1")); + this.AssertPodComponentHasPodComponentDependencyRoot(componentRecorder, component: (name: "Willow", version: "5.2.1"), root: (name: "AzureData", version: "0.5.0")); } [TestMethod] @@ -637,7 +637,7 @@ public async Task TestPodDetector_DetectorHandlesMainSpecRepoDifferences() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2) .WithFile("Podfile.lock", podfileLockContent3) @@ -648,7 +648,7 @@ public async Task TestPodDetector_DetectorHandlesMainSpecRepoDifferences() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); + this.AssertPodComponentNameAndVersion(detectedComponents, "AzureCore", "0.5.0"); } [TestMethod] @@ -684,7 +684,7 @@ public async Task TestPodDetector_DetectorRecognizeComponentsSpecRepo() COCOAPODS: 1.8.4"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("Podfile.lock", podfileLockContent) .WithFile("Podfile.lock", podfileLockContent2, fileLocation: Path.Join(Path.GetTempPath(), "sub-folder", "Podfile.lock")) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs index 7f8dc7ad2..8561d77ed 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PoetryComponentDetectorTests.cs @@ -20,7 +20,7 @@ public class PoetryComponentDetectorTests [TestInitialize] public void TestInitialize() { - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] @@ -40,7 +40,7 @@ public async Task TestPoetryDetector_TestCustomSource() reference = ""custom"" "; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("poetry.lock", poetryLockContent) .ExecuteDetector(); @@ -49,7 +49,7 @@ public async Task TestPoetryDetector_TestCustomSource() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); + this.AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); var queryString = detectedComponents.Single(component => ((PipComponent)component.Component).Name.Contains("certifi")); Assert.IsFalse(componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false)); } @@ -66,7 +66,7 @@ public async Task TestPoetryDetector_TestDevDependency() python-versions = ""*"" "; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("poetry.lock", poetryLockContent) .ExecuteDetector(); @@ -75,7 +75,7 @@ public async Task TestPoetryDetector_TestDevDependency() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); - AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); + this.AssertPipComponentNameAndVersion(detectedComponents, "certifi", "2021.10.8"); var queryString = detectedComponents.Single(component => ((PipComponent)component.Component).Name.Contains("certifi")); Assert.IsTrue(componentRecorder.GetEffectiveDevDependencyValue(queryString.Component.Id).GetValueOrDefault(false)); @@ -117,7 +117,7 @@ public async Task TestPoetryDetector_TestGitDependency() reference = ""master"" resolved_reference = ""232a5596424c98d11c3cf2e29b2f6a6c591c2ff3"""; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("poetry.lock", poetryLockContent) .ExecuteDetector(); @@ -126,7 +126,7 @@ public async Task TestPoetryDetector_TestGitDependency() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(2, detectedComponents.Count()); - AssertGitComponentHashAndUrl(detectedComponents, "232a5596424c98d11c3cf2e29b2f6a6c591c2ff3", "https://github.com/requests/requests.git"); + this.AssertGitComponentHashAndUrl(detectedComponents, "232a5596424c98d11c3cf2e29b2f6a6c591c2ff3", "https://github.com/requests/requests.git"); } private void AssertPipComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs index f64df081c..ce264c97b 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs @@ -24,7 +24,7 @@ public class PyPiClientTests [TestInitialize] public void Initialize() { - pypiClient = new PyPiClient() + this.pypiClient = new PyPiClient() { EnvironmentVariableService = new EnvironmentVariableService(), Logger = new Mock().Object, @@ -44,10 +44,10 @@ public async Task GetReleases_InvalidSpecVersion_NotThrow() }, }; - var mockHandler = MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); + var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); - Func action = async () => await pypiClient.GetReleases(pythonSpecs); + Func action = async () => await this.pypiClient.GetReleases(pythonSpecs); await action.Should().NotThrowAsync(); } @@ -64,10 +64,10 @@ public async Task GetReleases_DuplicateEntries_CallsGetAsync_Once() }, }; - var mockHandler = MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); + var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); - Func action = async () => await pypiClient.GetReleases(pythonSpecs); + Func action = async () => await this.pypiClient.GetReleases(pythonSpecs); await action.Should().NotThrowAsync(); await action.Should().NotThrowAsync(); @@ -92,13 +92,13 @@ public async Task GetReleases_DifferentEntries_CallsGetAsync_Once() }, }; - var mockHandler = MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); + var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); Func action = async () => { pythonSpecs.Name = Guid.NewGuid().ToString(); - await pypiClient.GetReleases(pythonSpecs); + await this.pypiClient.GetReleases(pythonSpecs); }; await action.Should().NotThrowAsync(); @@ -115,10 +115,10 @@ public async Task GetReleases_DifferentEntries_CallsGetAsync_Once() [TestMethod] public async Task FetchPackageDependencies_DuplicateEntries_CallsGetAsync_Once() { - var mockHandler = MockHttpMessageHandler("invalid ZIP"); + var mockHandler = this.MockHttpMessageHandler("invalid ZIP"); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); - Func action = async () => await pypiClient.FetchPackageDependencies("a", "1.0.0", new PythonProjectRelease { PackageType = "bdist_wheel", PythonVersion = "3.5.2", Size = 1000, Url = new Uri($"https://testurl") }); + Func action = async () => await this.pypiClient.FetchPackageDependencies("a", "1.0.0", new PythonProjectRelease { PackageType = "bdist_wheel", PythonVersion = "3.5.2", Size = 1000, Url = new Uri($"https://testurl") }); await action.Should().ThrowAsync(); await action.Should().ThrowAsync(); @@ -134,10 +134,10 @@ public async Task FetchPackageDependencies_DuplicateEntries_CallsGetAsync_Once() [TestMethod] public async Task FetchPackageDependencies_DifferentEntries_CallsGetAsync_Once() { - var mockHandler = MockHttpMessageHandler("invalid ZIP"); + var mockHandler = this.MockHttpMessageHandler("invalid ZIP"); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); - Func action = async () => await pypiClient.FetchPackageDependencies("a", "1.0.0", new PythonProjectRelease { PackageType = "bdist_wheel", PythonVersion = "3.5.2", Size = 1000, Url = new Uri($"https://{Guid.NewGuid()}") }); + Func action = async () => await this.pypiClient.FetchPackageDependencies("a", "1.0.0", new PythonProjectRelease { PackageType = "bdist_wheel", PythonVersion = "3.5.2", Size = 1000, Url = new Uri($"https://{Guid.NewGuid()}") }); await action.Should().ThrowAsync(); await action.Should().ThrowAsync(); @@ -162,7 +162,7 @@ public async Task GetReleases_MaxEntriesVariable_CreatesNewCache() }, }; - var mockHandler = MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); + var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject)); PyPiClient.HttpClient = new HttpClient(mockHandler.Object); var mockLogger = new Mock(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs index 3324fc1b9..d73a35ee2 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonCommandServiceTests.cs @@ -22,15 +22,15 @@ public class PythonCommandServiceTests [TestInitialize] public void TestInitialize() { - commandLineInvokationService = new Mock(); + this.commandLineInvokationService = new Mock(); } [TestMethod] public async Task PythonCommandService_ReturnsTrueWhenPythonExists() { - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; Assert.IsTrue(await service.PythonExists()); } @@ -38,9 +38,9 @@ public async Task PythonCommandService_ReturnsTrueWhenPythonExists() [TestMethod] public async Task PythonCommandService_ReturnsFalseWhenPythonExists() { - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(false); + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(false); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; Assert.IsFalse(await service.PythonExists()); } @@ -48,9 +48,9 @@ public async Task PythonCommandService_ReturnsFalseWhenPythonExists() [TestMethod] public async Task PythonCommandService_ReturnsTrueWhenPythonExistsForAPath() { - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("test", It.IsAny>(), "--version")).ReturnsAsync(true); + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("test", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; Assert.IsTrue(await service.PythonExists("test")); } @@ -58,9 +58,9 @@ public async Task PythonCommandService_ReturnsTrueWhenPythonExistsForAPath() [TestMethod] public async Task PythonCommandService_ReturnsFalseWhenPythonExistsForAPath() { - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("test", It.IsAny>(), "--version")).ReturnsAsync(false); + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("test", It.IsAny>(), "--version")).ReturnsAsync(false); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; Assert.IsFalse(await service.PythonExists("test")); } @@ -71,11 +71,11 @@ public async Task PythonCommandService_ParsesEmptySetupPyOutputCorrectly() var fakePath = @"c:\the\fake\path.py"; var fakePathAsPassedToPython = fakePath.Replace("\\", "/"); - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - commandLineInvokationService.Setup(x => x.ExecuteCommand("python", It.IsAny>(), It.Is(c => c.Contains(fakePathAsPassedToPython)))) + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + this.commandLineInvokationService.Setup(x => x.ExecuteCommand("python", It.IsAny>(), It.Is(c => c.Contains(fakePathAsPassedToPython)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = "[]", StdErr = string.Empty }); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; var result = await service.ParseFile(fakePath); @@ -88,11 +88,11 @@ public async Task PythonCommandService_ParsesRegularSetupPyOutputCorrectly() var fakePath = @"c:\the\fake\path.py"; var fakePathAsPassedToPython = fakePath.Replace("\\", "/"); - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - commandLineInvokationService.Setup(x => x.ExecuteCommand("python", It.IsAny>(), It.Is(c => c.Contains(fakePathAsPassedToPython)))) + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + this.commandLineInvokationService.Setup(x => x.ExecuteCommand("python", It.IsAny>(), It.Is(c => c.Contains(fakePathAsPassedToPython)))) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = "['knack==0.4.1', 'setuptools>=1.0,!=1.1', 'vsts-cli-common==0.1.3', 'vsts-cli-admin==0.1.3', 'vsts-cli-build==0.1.3', 'vsts-cli-code==0.1.3', 'vsts-cli-team==0.1.3', 'vsts-cli-package==0.1.3', 'vsts-cli-work==0.1.3']", StdErr = string.Empty }); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; var result = await service.ParseFile(fakePath); var expected = new string[] { "knack==0.4.1", "setuptools>=1.0,!=1.1", "vsts-cli-common==0.1.3", "vsts-cli-admin==0.1.3", "vsts-cli-build==0.1.3", "vsts-cli-code==0.1.3", "vsts-cli-team==0.1.3", "vsts-cli-package==0.1.3", "vsts-cli-work==0.1.3" }.Select(dep => (dep, null)).ToArray(); @@ -110,8 +110,8 @@ public async Task PythonCommandService_ParsesRequirementsTxtCorrectly() { var testPath = Path.Join(Directory.GetCurrentDirectory(), string.Join(Guid.NewGuid().ToString(), ".txt")); - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; try { @@ -147,8 +147,8 @@ public async Task ParseFile_RequirementTxtHasComment_CommentAreIgnored() { var testPath = Path.Join(Directory.GetCurrentDirectory(), string.Join(Guid.NewGuid().ToString(), ".txt")); - commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; try { @@ -177,7 +177,7 @@ public async Task ParseFile_RequirementTxtHasComment_CommentAreIgnored() [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentsSupported() { - await SetupAndParseReqsTxt(requirementstxtBasicGitComponent, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtBasicGitComponent, parseResult => { parseResult.Count.Should().Be(1); @@ -194,7 +194,7 @@ await SetupAndParseReqsTxt(requirementstxtBasicGitComponent, parseResult => [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentAndEnvironmentMarker() { - await SetupAndParseReqsTxt(requirementstxtGitComponentAndEnvironmentMarker, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentAndEnvironmentMarker, parseResult => { parseResult.Count.Should().Be(1); @@ -211,7 +211,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentAndEnvironmentMarker, pars [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentAndComment() { - await SetupAndParseReqsTxt(requirementstxtGitComponentAndComment, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentAndComment, parseResult => { parseResult.Count.Should().Be(1); @@ -228,7 +228,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentAndComment, parseResult => [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentAndCommentAndEnvironmentMarker() { - await SetupAndParseReqsTxt(requirementstxtGitComponentAndCommentAndEnvironmentMarker, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentAndCommentAndEnvironmentMarker, parseResult => { parseResult.Count.Should().Be(1); @@ -245,7 +245,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentAndCommentAndEnvironmentMa [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenGivenBranch() { - await SetupAndParseReqsTxt(requirementstxtGitComponentBranchInsteadOfCommitId, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentBranchInsteadOfCommitId, parseResult => { parseResult.Count.Should().Be(0); }); @@ -254,7 +254,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentBranchInsteadOfCommitId, p [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenGivenRelease() { - await SetupAndParseReqsTxt(requirementstxtGitComponentReleaseInsteadOfCommitId, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentReleaseInsteadOfCommitId, parseResult => { parseResult.Count.Should().Be(0); }); @@ -263,7 +263,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentReleaseInsteadOfCommitId, [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentNotCreatedWhenGivenMalformedCommitHash() { - await SetupAndParseReqsTxt(requirementstxtGitComponentCommitIdWrongLength, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentCommitIdWrongLength, parseResult => { parseResult.Count.Should().Be(0); }); @@ -272,7 +272,7 @@ await SetupAndParseReqsTxt(requirementstxtGitComponentCommitIdWrongLength, parse [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentsMultiple() { - await SetupAndParseReqsTxt(requirementstxtDoubleGitComponents, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtDoubleGitComponents, parseResult => { parseResult.Count.Should().Be(2); @@ -297,7 +297,7 @@ await SetupAndParseReqsTxt(requirementstxtDoubleGitComponents, parseResult => [TestMethod] public async Task ParseFile_RequirementTxtHasComment_GitComponentWrappedInRegularComponent() { - await SetupAndParseReqsTxt(requirementstxtGitComponentWrappedinRegularComponents, parseResult => + await this.SetupAndParseReqsTxt(this.requirementstxtGitComponentWrappedinRegularComponents, parseResult => { parseResult.Count.Should().Be(3); @@ -329,8 +329,8 @@ private async Task SetupAndParseReqsTxt(string fileToParse, Action x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); - PythonCommandService service = new PythonCommandService { CommandLineInvocationService = commandLineInvokationService.Object }; + this.commandLineInvokationService.Setup(x => x.CanCommandBeLocated("python", It.IsAny>(), "--version")).ReturnsAsync(true); + PythonCommandService service = new PythonCommandService { CommandLineInvocationService = this.commandLineInvokationService.Object }; using (StreamWriter writer = File.CreateText(testPath)) { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs index 1998ff346..f73694662 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs @@ -26,15 +26,15 @@ public class RubyDetectorTest [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - rubyDetector = new RubyComponentDetector + this.loggerMock = new Mock(); + this.rubyDetector = new RubyComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithScanRequest(new ScanRequest( new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, - new ComponentRecorder(enableManualTrackingOfExplicitReferences: !rubyDetector.NeedsAutomaticRootDependencyCalculation))); + new ComponentRecorder(enableManualTrackingOfExplicitReferences: !this.rubyDetector.NeedsAutomaticRootDependencyCalculation))); } [TestMethod] @@ -71,7 +71,7 @@ BUNDLED WITH BUNDLED WITH 1.17.3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .WithFile("2Gemfile.lock", gemFileLockContent2) .ExecuteDetector(); @@ -81,13 +81,13 @@ BUNDLED WITH var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(7, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.2"); - AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.3"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.2"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.3"); } [TestMethod] @@ -101,7 +101,7 @@ public async Task TestRubyDetector_TestGemsWithUppercase_LockFile() BUNDLED WITH 2.2.28"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -111,8 +111,8 @@ BUNDLED WITH Assert.AreEqual(2, detectedComponents.Count()); // we do not record invalid/unknown versions - AssertRubyComponentNameAndVersion(detectedComponents, "CFPropertyList", "3.0.4"); - AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "2.2.28"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "CFPropertyList", "3.0.4"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "2.2.28"); } [TestMethod] @@ -134,7 +134,7 @@ public async Task TestRubyDetector_DetectorParseWithBundlerVersion() BUNDLED WITH 1.17.3"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -143,12 +143,12 @@ BUNDLED WITH var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(6, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.3"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "bundler", "1.17.3"); } [TestMethod] @@ -168,7 +168,7 @@ public async Task TestRubyDetector_DetectorRecognizeGemComponents() nokogiri (~> 1.8.2) websocket-driver (0.6.1)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -177,11 +177,11 @@ public async Task TestRubyDetector_DetectorRecognizeGemComponents() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(5, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); - AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "actioncable", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "nio4r", "5.2.1"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "websocket-driver", "0.6.1"); } [TestMethod] @@ -198,7 +198,7 @@ public async Task TestRubyDetector_ParentWithTildeInVersion_IsExcluded() mini_portile2 (~> 2.3.0) mini_portile2 (2.3.0)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -207,9 +207,9 @@ public async Task TestRubyDetector_ParentWithTildeInVersion_IsExcluded() var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(3, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, "mini_portile2", "2.3.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "acme-client", "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "faraday", "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, "mini_portile2", "2.3.0"); } [TestMethod] @@ -235,7 +235,7 @@ public async Task TestRubyDetector_DetectorCreatesADependencyGraph() nio4r (5.2.1) websocket-driver (0.6.1)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -287,7 +287,7 @@ public async Task TestRubyDetector_ComponentsRootsAreFilledCorrectly() nio4r (5.2.1) websocket-driver (0.6.1)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); @@ -342,15 +342,15 @@ public async Task TestRubyDetector_DetectorRecognizeGitComponents() specs: mini_mime (2.0.0)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(3, detectedComponents.Count()); - AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-1", repositoryUrl: "https://github.com/test/abc.git"); - AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-2", repositoryUrl: "https://github.com/mikel/mail.git"); - AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); + this.AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-1", repositoryUrl: "https://github.com/test/abc.git"); + this.AssertGitComponentHashAndUrl(detectedComponents, commitHash: "commit-hash-2", repositoryUrl: "https://github.com/mikel/mail.git"); + this.AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); } [TestMethod] @@ -371,11 +371,11 @@ public async Task TestRubyDetector_DetectorRecognizeParentChildRelationshipInGit specs: mail (2.7.2.edge)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); - AssertGitComponentAsRootAndGitComponentAsSubDependency(componentRecorder, rootHash: "commit-hash-1", subDependencyHash: "commit-hash-2"); + this.AssertGitComponentAsRootAndGitComponentAsSubDependency(componentRecorder, rootHash: "commit-hash-1", subDependencyHash: "commit-hash-2"); } [TestMethod] @@ -396,16 +396,16 @@ public async Task TestRubyDetector_DetectorRecognizeLocalDependencies() specs: test2 (1.0.0)"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("1Gemfile.lock", gemFileLockContent) .ExecuteDetector(); var detectedComponents = componentRecorder.GetDetectedComponents(); Assert.AreEqual(3, detectedComponents.Count()); - AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, name: "test", version: "1.0.0"); - AssertRubyComponentNameAndVersion(detectedComponents, name: "test2", version: "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, name: "mini_mime", version: "2.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, name: "test", version: "1.0.0"); + this.AssertRubyComponentNameAndVersion(detectedComponents, name: "test2", version: "1.0.0"); } private void AssertRubyComponentNameAndVersion(IEnumerable detectedComponents, string name, string version) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs index 7e79e95d4..69cf41cfe 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs @@ -25,16 +25,16 @@ public class RustCrateDetectorTests [TestInitialize] public void TestInitialize() { - detectorTestUtility = DetectorTestUtilityCreator.Create(); - detectorV2TestUtility = DetectorTestUtilityCreator.Create(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.detectorV2TestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] public async Task TestGraphIsCorrect() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -77,8 +77,8 @@ public async Task TestRequirePairForComponents() { var cargoDefinitionPairsMatrix = new List<(string, string)> { - (null, testCargoTomlString), - (testCargoLockString, null), + (null, this.testCargoTomlString), + (this.testCargoLockString, null), (null, null), }; @@ -86,15 +86,15 @@ public async Task TestRequirePairForComponents() { if (cargoDefinitionPairs.Item1 != null) { - detectorTestUtility.WithFile("Cargo.lock", cargoDefinitionPairs.Item1); + this.detectorTestUtility.WithFile("Cargo.lock", cargoDefinitionPairs.Item1); } if (cargoDefinitionPairs.Item2 != null) { - detectorTestUtility.WithFile("Cargo.toml", cargoDefinitionPairs.Item2, new List { "Cargo.toml" }); + this.detectorTestUtility.WithFile("Cargo.toml", cargoDefinitionPairs.Item2, new List { "Cargo.toml" }); } - var (result, componentRecorder) = await detectorTestUtility.ExecuteDetector(); + var (result, componentRecorder) = await this.detectorTestUtility.ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -108,24 +108,24 @@ public async Task TestSupportsCargoV1AndV2DefinitionPairs() var componentRecorder = new ComponentRecorder(); ScanRequest request = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder); - var (result1, _) = await detectorTestUtility + var (result1, _) = await this.detectorTestUtility /* v1 files */ - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) /* v2 files */ - .WithFile("Cargo.lock", testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.lock")) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.toml")) + .WithFile("Cargo.lock", this.testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.lock")) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.toml")) /* so we can reuse the component recorder */ .WithScanRequest(request) .ExecuteDetector(); - var (result2, _) = await detectorV2TestUtility + var (result2, _) = await this.detectorV2TestUtility /* v1 files */ - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) /* v2 files */ - .WithFile("Cargo.lock", testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.lock")) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.toml")) + .WithFile("Cargo.lock", this.testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.lock")) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "v2", "Cargo.toml")) /* so we can reuse the component recorder */ .WithScanRequest(request) .ExecuteDetector(); @@ -141,11 +141,11 @@ public async Task TestSupportsCargoV1AndV2DefinitionPairs() [TestMethod] public async Task TestSupportsMultipleCargoV1DefinitionPairs() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.lock", testCargoLockString, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.lock", this.testCargoLockString, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -166,11 +166,11 @@ public async Task TestSupportsMultipleCargoV1DefinitionPairs() [TestMethod] public async Task TestSupportsMultipleCargoV2DefinitionPairs() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testCargoLockV2String) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.lock", testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testCargoLockV2String) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.lock", this.testCargoLockV2String, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.lock")) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }, fileLocation: Path.Join(Path.GetTempPath(), "sub-path", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -191,9 +191,9 @@ public async Task TestSupportsMultipleCargoV2DefinitionPairs() [TestMethod] public async Task TestRustDetector() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -261,9 +261,9 @@ public async Task TestRustDetector() [TestMethod] public async Task TestRustV2Detector() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testCargoLockV2String) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testCargoLockV2String) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -332,9 +332,9 @@ public async Task TestRustV2Detector() [TestMethod] public async Task TestRustV2Detector_DoesNotRunV1Format() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testCargoLockString) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testCargoLockString) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -344,9 +344,9 @@ public async Task TestRustV2Detector_DoesNotRunV1Format() [TestMethod] public async Task TestRustV1Detector_DoesNotRunV2Format() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testCargoLockV2String) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testCargoLockV2String) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -425,9 +425,9 @@ public async Task TestRustV2Detector_DuplicatePackage() source = ""registry+https://github.com/rust-lang/crates.io-index"" "; - var (result, componentRecorder) = await detectorV2TestUtility + var (result, componentRecorder) = await this.detectorV2TestUtility .WithFile("Cargo.lock", testCargoLock) - .WithFile("Cargo.toml", testCargoTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testCargoTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -493,7 +493,7 @@ public async Task TestRustDetector_SupportEmptySource() version = ""0.1.12-alpha.6"" source = ""registry+https://github.com/rust-lang/crates.io-index"" "; - var (result, componentRecorder) = await detectorV2TestUtility + var (result, componentRecorder) = await this.detectorV2TestUtility .WithFile("Cargo.lock", testLockString) .WithFile("Cargo.toml", testTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); @@ -516,11 +516,11 @@ public async Task TestRustDetector_SupportEmptySource() [TestMethod] public async Task TestRustV1Detector_WorkspacesWithTopLevelDependencies() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", string.Concat(testWorkspaceLockBaseDependency, testWorkspaceLockV1NoBaseString)) - .WithFile("Cargo.toml", string.Concat(testWorkspaceTomlBaseDependency, testWorkspacesBaseTomlString), new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", string.Concat(this.testWorkspaceLockBaseDependency, this.testWorkspaceLockV1NoBaseString)) + .WithFile("Cargo.toml", string.Concat(this.testWorkspaceTomlBaseDependency, this.testWorkspacesBaseTomlString), new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -589,11 +589,11 @@ public async Task TestRustV1Detector_WorkspacesWithTopLevelDependencies() [TestMethod] public async Task TestRustV2Detector_WorkspacesWithTopLevelDependencies() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", string.Concat(testWorkspaceLockBaseDependency, testWorkspaceLockV2NoBaseString)) - .WithFile("Cargo.toml", string.Concat(testWorkspaceTomlBaseDependency, testWorkspacesBaseTomlString), new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", string.Concat(this.testWorkspaceLockBaseDependency, this.testWorkspaceLockV2NoBaseString)) + .WithFile("Cargo.toml", string.Concat(this.testWorkspaceTomlBaseDependency, this.testWorkspacesBaseTomlString), new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -662,11 +662,11 @@ public async Task TestRustV2Detector_WorkspacesWithTopLevelDependencies() [TestMethod] public async Task TestRustV1Detector_WorkspacesNoTopLevelDependencies() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testWorkspaceLockV1NoBaseString) - .WithFile("Cargo.toml", testWorkspacesBaseTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testWorkspaceLockV1NoBaseString) + .WithFile("Cargo.toml", this.testWorkspacesBaseTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -676,11 +676,11 @@ public async Task TestRustV1Detector_WorkspacesNoTopLevelDependencies() [TestMethod] public async Task TestRustV2Detector_WorkspacesNoTopLevelDependencies() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testWorkspaceLockV2NoBaseString) - .WithFile("Cargo.toml", testWorkspacesBaseTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testWorkspaceLockV2NoBaseString) + .WithFile("Cargo.toml", this.testWorkspacesBaseTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "test-work2", "Cargo.toml")) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); @@ -690,11 +690,11 @@ public async Task TestRustV2Detector_WorkspacesNoTopLevelDependencies() [TestMethod] public async Task TestRustV1Detector_WorkspacesWithSubDirectories() { - var (result, componentRecorder) = await detectorTestUtility - .WithFile("Cargo.lock", testWorkspaceLockV1NoBaseString) - .WithFile("Cargo.toml", testWorkspacesSubdirectoryTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub//test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub2//test//test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorTestUtility + .WithFile("Cargo.lock", this.testWorkspaceLockV1NoBaseString) + .WithFile("Cargo.toml", this.testWorkspacesSubdirectoryTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub//test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub2//test//test-work2", "Cargo.toml")) .ExecuteDetector(); var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); @@ -711,11 +711,11 @@ public async Task TestRustV1Detector_WorkspacesWithSubDirectories() [TestMethod] public async Task TestRustV2Detector_WorkspacesWithSubDirectories() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testWorkspaceLockV2NoBaseString) - .WithFile("Cargo.toml", testWorkspacesSubdirectoryTomlString, new List { "Cargo.toml" }) - .WithFile("Cargo.toml", testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub//test-work", "Cargo.toml")) - .WithFile("Cargo.toml", testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub2//test//test-work2", "Cargo.toml")) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testWorkspaceLockV2NoBaseString) + .WithFile("Cargo.toml", this.testWorkspacesSubdirectoryTomlString, new List { "Cargo.toml" }) + .WithFile("Cargo.toml", this.testWorkspace1TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub//test-work", "Cargo.toml")) + .WithFile("Cargo.toml", this.testWorkspace2TomlString, new List { "Cargo.toml" }, fileLocation: Path.Combine(Path.GetTempPath(), "sub2//test//test-work2", "Cargo.toml")) .ExecuteDetector(); var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); @@ -764,7 +764,7 @@ public async Task TestRustDetector_UnequalButSemverCompatibleRoot() ""c-ares"", ] "; - var (result, componentRecorder) = await detectorV2TestUtility + var (result, componentRecorder) = await this.detectorV2TestUtility .WithFile("Cargo.lock", testLockString) .WithFile("Cargo.toml", testTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); @@ -805,7 +805,7 @@ public async Task TestRustDetector_RenamedDependency() version = ""1.0.0"" source = ""registry+https://github.com/rust-lang/crates.io-index"" "; - var (result, componentRecorder) = await detectorV2TestUtility + var (result, componentRecorder) = await this.detectorV2TestUtility .WithFile("Cargo.lock", testLockString) .WithFile("Cargo.toml", testTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); @@ -829,9 +829,9 @@ public async Task TestRustDetector_RenamedDependency() [TestMethod] public async Task TestRustDetector_TargetSpecificDependencies() { - var (result, componentRecorder) = await detectorV2TestUtility - .WithFile("Cargo.lock", testTargetSpecificDependenciesLockString) - .WithFile("Cargo.toml", testTargetSpecificDependenciesTomlString, new List { "Cargo.toml" }) + var (result, componentRecorder) = await this.detectorV2TestUtility + .WithFile("Cargo.lock", this.testTargetSpecificDependenciesLockString) + .WithFile("Cargo.toml", this.testTargetSpecificDependenciesTomlString, new List { "Cargo.toml" }) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, result.ResultCode); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs index c1abdb44b..f746d7c63 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs @@ -36,7 +36,7 @@ public void DoesntMatch_WhenNoDependencyAdded() (true, "Matches_-", "some-cargo-package", "1.2.0 - 1.2.5"), (false, "DoesntMatch_-", "some-cargo-package", "1.1.0 - 1.1.5"), }; - DoAllTheTests(testCases); + this.DoAllTheTests(testCases); } public void DoAllTheTests(IEnumerable<(bool shouldMatch, string caseName, string specifierName, string specifierRange)> testCases) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs index c0811bc06..9b37d10ef 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs @@ -26,8 +26,8 @@ public class Spdx22ComponentDetectorTests public void TestInitialize() { var componentRecorder = new ComponentRecorder(enableManualTrackingOfExplicitReferences: false); - detectorTestUtility = DetectorTestUtilityCreator.Create() - .WithScanRequest(new ScanRequest(new DirectoryInfo(tempPath), null, null, new Dictionary(), null, componentRecorder)); + this.detectorTestUtility = DetectorTestUtilityCreator.Create() + .WithScanRequest(new ScanRequest(new DirectoryInfo(this.tempPath), null, null, new Dictionary(), null, componentRecorder)); } [TestMethod] @@ -98,7 +98,7 @@ public async Task TestSbomDetector_SimpleSbom() }"; var spdxFileName = "manifest.spdx.json"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile(spdxFileName, spdxFile) .ExecuteDetector(); @@ -124,7 +124,7 @@ public async Task TestSbomDetector_SimpleSbom() Assert.AreEqual(sbomComponent.DocumentNamespace, new Uri("https://sbom.microsoft/Test/1.0.0/61de1a5-57cc-4732-9af5-edb321b4a7ee")); Assert.AreEqual(sbomComponent.SpdxVersion, "SPDX-2.2"); Assert.AreEqual(sbomComponent.Checksum, checksum); - Assert.AreEqual(sbomComponent.Path, Path.Combine(tempPath, spdxFileName)); + Assert.AreEqual(sbomComponent.Path, Path.Combine(this.tempPath, spdxFileName)); } [TestMethod] @@ -132,7 +132,7 @@ public async Task TestSbomDetector_BlankJson() { var spdxFile = "{}"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("manifest.spdx.json", spdxFile) .ExecuteDetector(); @@ -148,7 +148,7 @@ public async Task TestSbomDetector_InvalidFile() { var spdxFile = "invalidspdxfile"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("manifest.spdx.json", spdxFile) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs index 84efaeb0c..5f674c5f3 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs @@ -22,7 +22,7 @@ public class VcpkgComponentDetectorTests public void TestInitialize() { var componentRecorder = new ComponentRecorder(enableManualTrackingOfExplicitReferences: false); - detectorTestUtility = DetectorTestUtilityCreator.Create() + this.detectorTestUtility = DetectorTestUtilityCreator.Create() .WithScanRequest(new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder)); } @@ -49,7 +49,7 @@ public async Task TestNlohmann() } ] }"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetector(); @@ -108,7 +108,7 @@ public async Task TestTinyxmlAndResource() } ] }"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetector(); @@ -137,7 +137,7 @@ public async Task TestBlankJson() { var spdxFile = "{}"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetector(); @@ -153,7 +153,7 @@ public async Task TestInvalidFile() { var spdxFile = "invalidspdxfile"; - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("vcpkg.spdx.json", spdxFile) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs index e67368924..7dd39496c 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs @@ -34,9 +34,9 @@ public class YarnLockDetectorTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); - componentRecorder = new ComponentRecorder(); - detectorTestUtility = DetectorTestUtilityCreator.Create(); + this.loggerMock = new Mock(); + this.componentRecorder = new ComponentRecorder(); + this.detectorTestUtility = DetectorTestUtilityCreator.Create(); } [TestMethod] @@ -45,7 +45,7 @@ public async Task WellFormedYarnLockV1WithZeroComponents_FindsNothing() var yarnLock = YarnTestUtilities.GetWellFormedEmptyYarnV1LockFile(); var packageJson = NpmTestUtilities.GetPackageJsonNoDependencies(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJson, new List { "package.json" }) .ExecuteDetector(); @@ -60,7 +60,7 @@ public async Task WellFormedYarnLockV2WithZeroComponents_FindsNothing() var yarnLock = YarnTestUtilities.GetWellFormedEmptyYarnV2LockFile(); var packageJson = NpmTestUtilities.GetPackageJsonNoDependencies(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJson, new List { "package.json" }) .ExecuteDetector(); @@ -89,7 +89,7 @@ public async Task MalformedYarnLockV1WithOneComponent_FindsNoComponent() var yarnLock = builder.ToString(); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, providedVersion0); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -108,7 +108,7 @@ public async Task MalformedYarnLockV2WithOneComponent_FindsNoComponent() var builder = new StringBuilder(); - builder.AppendLine(CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); builder.AppendLine($"{componentName0}@{providedVersion0}"); builder.AppendLine($" version {version0}"); builder.AppendLine($" resolved {resolved0}"); @@ -116,7 +116,7 @@ public async Task MalformedYarnLockV2WithOneComponent_FindsNoComponent() var yarnLock = builder.ToString(); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentName0, providedVersion0); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -137,10 +137,10 @@ public async Task WellFormedYarnLockV1WithOneComponent_FindsComponent() ResolvedVersion = "https://resolved0/a/resolved", }; - var yarnLock = CreateYarnLockV1FileContent(new List { componentA }); + var yarnLock = this.CreateYarnLockV1FileContent(new List { componentA }); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -169,10 +169,10 @@ public async Task WellFormedYarnLockV2WithOneComponent_FindsComponent() ResolvedVersion = "https://resolved0/a/resolved", }; - var yarnLock = CreateYarnLockV2FileContent(new List { componentA }); + var yarnLock = this.CreateYarnLockV2FileContent(new List { componentA }); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -203,7 +203,7 @@ public async Task WellFormedYarnLockV1WithWorkspace_FindsComponent() Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", CreateYarnLockV1FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent(new List { componentA })); var workspaceJson = new { @@ -219,7 +219,7 @@ public async Task WellFormedYarnLockV1WithWorkspace_FindsComponent() var detector = new YarnLockComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; var mock = new Mock(); @@ -233,21 +233,21 @@ public async Task WellFormedYarnLockV1WithWorkspace_FindsComponent() // The call to get the package.json that contains actual information mock.Setup(x => x.GetComponentStreams(It.IsAny(), It.IsAny>(), It.IsAny(), true)).Returns(new List { packageStream }); - var directoryWalkerMock = NpmTestUtilities.GetMockDirectoryWalker(new List { componentStream }, new List { packageStream }, directory.FullName, patterns: detector.SearchPatterns, componentRecorder: componentRecorder); + var directoryWalkerMock = NpmTestUtilities.GetMockDirectoryWalker(new List { componentStream }, new List { packageStream }, directory.FullName, patterns: detector.SearchPatterns, componentRecorder: this.componentRecorder); - var (scanResult, _) = await detectorTestUtility + var (scanResult, _) = await this.detectorTestUtility .WithObservableDirectoryWalkerFactory(directoryWalkerMock) .WithComponentStreamEnumerableFactory(mock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); - componentRecorder.AssertAllExplicitlyReferencedComponents( + this.componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, parentComponent => parentComponent.Name == componentA.Name && parentComponent.Version == version0); } @@ -266,7 +266,7 @@ public async Task WellFormedYarnLockV2WithWorkspace_FindsComponent() Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", CreateYarnLockV2FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV2FileContent(new List { componentA })); var workspaceJson = new { @@ -282,7 +282,7 @@ public async Task WellFormedYarnLockV2WithWorkspace_FindsComponent() var detector = new YarnLockComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; var mock = new Mock(); @@ -296,21 +296,21 @@ public async Task WellFormedYarnLockV2WithWorkspace_FindsComponent() // The call to get the package.json that contains actual information mock.Setup(x => x.GetComponentStreams(It.IsAny(), It.IsAny>(), It.IsAny(), true)).Returns(new List { packageStream }); - var directoryWalkerMock = NpmTestUtilities.GetMockDirectoryWalker(new List { componentStream }, new List { packageStream }, directory.FullName, patterns: detector.SearchPatterns, componentRecorder: componentRecorder); + var directoryWalkerMock = NpmTestUtilities.GetMockDirectoryWalker(new List { componentStream }, new List { packageStream }, directory.FullName, patterns: detector.SearchPatterns, componentRecorder: this.componentRecorder); - var (scanResult, _) = await detectorTestUtility + var (scanResult, _) = await this.detectorTestUtility .WithObservableDirectoryWalkerFactory(directoryWalkerMock) .WithComponentStreamEnumerableFactory(mock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); - componentRecorder.AssertAllExplicitlyReferencedComponents( + this.componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, parentComponent => parentComponent.Name == componentA.Name && parentComponent.Version == version0); } @@ -329,7 +329,7 @@ public async Task WellFormedYarnLockV1WithWorkspaceAltForm_FindsComponent() Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", CreateYarnLockV1FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent(new List { componentA })); var workspaceJson = new { @@ -345,7 +345,7 @@ public async Task WellFormedYarnLockV1WithWorkspaceAltForm_FindsComponent() var detector = new YarnLockComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; var mock = new Mock(); @@ -370,22 +370,22 @@ public async Task WellFormedYarnLockV1WithWorkspaceAltForm_FindsComponent() }.Select(cs => new ProcessRequest { ComponentStream = cs, - SingleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(cs.Location), + SingleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(cs.Location), }).ToObservable()); - var (scanResult, _) = await detectorTestUtility + var (scanResult, _) = await this.detectorTestUtility .WithObservableDirectoryWalkerFactory(directoryWalkerMock) .WithComponentStreamEnumerableFactory(mock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); - componentRecorder.AssertAllExplicitlyReferencedComponents( + this.componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, parentComponent => parentComponent.Name == componentA.Name && parentComponent.Version == version0); } @@ -404,7 +404,7 @@ public async Task WellFormedYarnLockV2WithWorkspaceAltForm_FindsComponent() Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", CreateYarnLockV2FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV2FileContent(new List { componentA })); var workspaceJson = new { @@ -420,7 +420,7 @@ public async Task WellFormedYarnLockV2WithWorkspaceAltForm_FindsComponent() var detector = new YarnLockComponentDetector { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; var mock = new Mock(); @@ -445,22 +445,22 @@ public async Task WellFormedYarnLockV2WithWorkspaceAltForm_FindsComponent() }.Select(cs => new ProcessRequest { ComponentStream = cs, - SingleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(cs.Location), + SingleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(cs.Location), }).ToObservable()); - var (scanResult, _) = await detectorTestUtility + var (scanResult, _) = await this.detectorTestUtility .WithObservableDirectoryWalkerFactory(directoryWalkerMock) .WithComponentStreamEnumerableFactory(mock) .ExecuteDetector(); Assert.AreEqual(ProcessingResultCode.Success, scanResult.ResultCode); - var detectedComponents = componentRecorder.GetDetectedComponents(); + var detectedComponents = this.componentRecorder.GetDetectedComponents(); Assert.AreEqual(1, detectedComponents.Count()); Assert.AreEqual(componentA.Name, ((NpmComponent)detectedComponents.Single().Component).Name); Assert.AreEqual(version0, ((NpmComponent)detectedComponents.Single().Component).Version); - componentRecorder.AssertAllExplicitlyReferencedComponents( + this.componentRecorder.AssertAllExplicitlyReferencedComponents( detectedComponents.Single().Component.Id, parentComponent => parentComponent.Name == componentA.Name && parentComponent.Version == version0); } @@ -488,10 +488,10 @@ public async Task WellFormedYarnLockV1WithMoreThanOneComponent_FindsComponents() componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; - var yarnLock = CreateYarnLockV1FileContent(new List { componentA, componentB }); + var yarnLock = this.CreateYarnLockV1FileContent(new List { componentA, componentB }); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -535,10 +535,10 @@ public async Task WellFormedYarnLockV2WithMoreThanOneComponent_FindsComponents() componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; - var yarnLock = CreateYarnLockV2FileContent(new List { componentA, componentB }); + var yarnLock = this.CreateYarnLockV2FileContent(new List { componentA, componentB }); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -611,7 +611,7 @@ public async Task WellFormedYarnLockV1WithMultiRootedComponent_FindsAllRoots() var yarnLock = builder.ToString(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -673,7 +673,7 @@ public async Task WellFormedYarnLockV2WithMultiRootedComponent_FindsAllRoots() var builder = new StringBuilder(); - builder.AppendLine(CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); builder.AppendLine($"{componentNameA}@{requestedVersionA}:"); builder.AppendLine($" version: {actualVersionA}"); builder.AppendLine($" resolved: {resolvedA}"); @@ -687,7 +687,7 @@ public async Task WellFormedYarnLockV2WithMultiRootedComponent_FindsAllRoots() var yarnLock = builder.ToString(); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLock) .WithFile("package.json", packageJsonContent, new List { "package.json" }) .ExecuteDetector(); @@ -743,10 +743,10 @@ public async Task DependencyGraphV1IsGeneratedCorrectly() componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; componentB.Dependencies = new List<(string, string)> { (componentC.Name, componentC.RequestedVersion) }; - var yarnLockFileContent = CreateYarnLockV1FileContent(new List { componentA, componentB, componentC }); - var packageJsonFileContent = CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); + var yarnLockFileContent = this.CreateYarnLockV1FileContent(new List { componentA, componentB, componentC }); + var packageJsonFileContent = this.CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) .ExecuteDetector(); @@ -799,10 +799,10 @@ public async Task DependencyGraphV2IsGeneratedCorrectly() componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; componentB.Dependencies = new List<(string, string)> { (componentC.Name, componentC.RequestedVersion) }; - var yarnLockFileContent = CreateYarnLockV2FileContent(new List { componentA, componentB, componentC }); - var packageJsonFileContent = CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); + var yarnLockFileContent = this.CreateYarnLockV2FileContent(new List { componentA, componentB, componentC }); + var packageJsonFileContent = this.CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) .ExecuteDetector(); @@ -836,15 +836,15 @@ public async Task MalformedYarnLockV1_Duplicate() var builder = new StringBuilder(); - builder.AppendLine(CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); builder.AppendLine($"\"{componentNameA}@{requestedVersionA}\", \"{componentNameB}@{requestedVersionB}\":"); builder.AppendLine($" version: {actualVersion}"); builder.AppendLine(); var yarnLockFileContent = builder.ToString(); - var packageJsonFileContent = CreatePackageJsonFileContent(new List()); + var packageJsonFileContent = this.CreatePackageJsonFileContent(new List()); - var (scanResult, componentRecorder) = await detectorTestUtility + var (scanResult, componentRecorder) = await this.detectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) .ExecuteDetector(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs index 6dc431925..9ae96651b 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs @@ -19,7 +19,7 @@ public class YarnParserTests [TestInitialize] public void TestInitialize() { - loggerMock = new Mock(); + this.loggerMock = new Mock(); } [TestMethod] @@ -27,7 +27,7 @@ public void YarnLockParserWithNullBlockFile_Fails() { var parser = new YarnLockParser(); - Action action = () => parser.Parse(null, loggerMock.Object); + Action action = () => parser.Parse(null, this.loggerMock.Object); Assert.ThrowsException(action); } @@ -70,7 +70,7 @@ public void YarnLockParser_ParsesEmptyFile() blockFile.Setup(x => x.YarnLockVersion).Returns(yarnLockFileVersion); blockFile.Setup(x => x.GetEnumerator()).Returns(blocks.GetEnumerator()); - var file = parser.Parse(blockFile.Object, loggerMock.Object); + var file = parser.Parse(blockFile.Object, this.loggerMock.Object); Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); Assert.AreEqual(0, file.Entries.Count()); @@ -85,16 +85,18 @@ public void YarnLockParser_ParsesBlocks() var blocks = new List { - CreateBlock("a@^1.0.0", "1.0.0", "https://a", new List { CreateDependencyBlock(new Dictionary { { "xyz", "2" } }) }), - CreateBlock("b@2.4.6", "2.4.6", "https://b", new List { CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }) }), - CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", Enumerable.Empty()), + this.CreateBlock("a@^1.0.0", "1.0.0", "https://a", new List { + this.CreateDependencyBlock(new Dictionary { { "xyz", "2" } }) }), + this.CreateBlock("b@2.4.6", "2.4.6", "https://b", new List { + this.CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }) }), + this.CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", Enumerable.Empty()), }; var blockFile = new Mock(); blockFile.Setup(x => x.YarnLockVersion).Returns(yarnLockFileVersion); blockFile.Setup(x => x.GetEnumerator()).Returns(blocks.GetEnumerator()); - var file = parser.Parse(blockFile.Object, loggerMock.Object); + var file = parser.Parse(blockFile.Object, this.loggerMock.Object); Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); Assert.AreEqual(3, file.Entries.Count()); @@ -103,7 +105,7 @@ public void YarnLockParser_ParsesBlocks() { YarnBlock block = blocks.Single(x => x.Values["resolved"] == entry.Resolved); - AssertBlockMatchesEntry(block, entry); + this.AssertBlockMatchesEntry(block, entry); } } @@ -116,15 +118,17 @@ public void YarnLockParser_ParsesNoVersionInTitleBlock() var blocks = new List { - CreateBlock("a", "1.0.0", "https://a", new List { CreateDependencyBlock(new Dictionary { { "xyz", "2" } }) }), - CreateBlock("b", "2.4.6", "https://b", new List { CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }) }), + this.CreateBlock("a", "1.0.0", "https://a", new List { + this.CreateDependencyBlock(new Dictionary { { "xyz", "2" } }) }), + this.CreateBlock("b", "2.4.6", "https://b", new List { + this.CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }) }), }; var blockFile = new Mock(); blockFile.Setup(x => x.YarnLockVersion).Returns(yarnLockFileVersion); blockFile.Setup(x => x.GetEnumerator()).Returns(blocks.GetEnumerator()); - var file = parser.Parse(blockFile.Object, loggerMock.Object); + var file = parser.Parse(blockFile.Object, this.loggerMock.Object); Assert.AreEqual(YarnLockVersion.V1, file.LockVersion); Assert.AreEqual(2, file.Entries.Count()); diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeDevCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeDevCommandServiceTests.cs index 4cead4c31..a9d29edb5 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeDevCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeDevCommandServiceTests.cs @@ -24,10 +24,10 @@ public class BcdeDevCommandServiceTests [TestInitialize] public void InitializeTest() { - scanExecutionServiceMock = new Mock(); - serviceUnderTest = new BcdeDevCommandService(); + this.scanExecutionServiceMock = new Mock(); + this.serviceUnderTest = new BcdeDevCommandService(); - scannedComponents = new ScannedComponent[] + this.scannedComponents = new ScannedComponent[] { new ScannedComponent { @@ -39,13 +39,13 @@ public void InitializeTest() var executeScanAsyncResult = new ScanResult { DetectorsInScan = new List(), - ComponentsFound = scannedComponents, + ComponentsFound = this.scannedComponents, ContainerDetailsMap = new Dictionary(), ResultCode = ProcessingResultCode.Success, SourceDirectory = "D:\\test\\directory", }; - scanExecutionServiceMock.Setup(x => x.ExecuteScanAsync(It.IsAny())) + this.scanExecutionServiceMock.Setup(x => x.ExecuteScanAsync(It.IsAny())) .ReturnsAsync(executeScanAsyncResult); } @@ -54,12 +54,12 @@ public void RunComponentDetection() { var args = new BcdeArguments(); - serviceUnderTest = new BcdeDevCommandService + this.serviceUnderTest = new BcdeDevCommandService { - BcdeScanExecutionService = scanExecutionServiceMock.Object, + BcdeScanExecutionService = this.scanExecutionServiceMock.Object, }; - var result = serviceUnderTest.Handle(args); + var result = this.serviceUnderTest.Handle(args); result.Result.ResultCode.Should().Be(ProcessingResultCode.Success); result.Result.SourceDirectory.Should().Be("D:\\test\\directory"); } diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs index 42121825c..ef73f7554 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs @@ -41,54 +41,54 @@ public class BcdeScanExecutionServiceTests [TestInitialize] public void InitializeTest() { - loggerMock = new Mock(); - detectorProcessingServiceMock = new Mock(); - detectorRegistryServiceMock = new Mock(); - detectorRestrictionServiceMock = new Mock(); - componentDetector2Mock = new Mock(); - componentDetector3Mock = new Mock(); - versionedComponentDetector1Mock = new Mock(); - sampleContainerDetails = new ContainerDetails { Id = 1 }; + this.loggerMock = new Mock(); + this.detectorProcessingServiceMock = new Mock(); + this.detectorRegistryServiceMock = new Mock(); + this.detectorRestrictionServiceMock = new Mock(); + this.componentDetector2Mock = new Mock(); + this.componentDetector3Mock = new Mock(); + this.versionedComponentDetector1Mock = new Mock(); + this.sampleContainerDetails = new ContainerDetails { Id = 1 }; var defaultGraphTranslationService = new DefaultGraphTranslationService { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; - contentByFileInfo = new Dictionary(); + this.contentByFileInfo = new Dictionary(); - detectedComponents = new[] + this.detectedComponents = new[] { new DetectedComponent(new NpmComponent("some-npm-component", "1.2.3")), new DetectedComponent(new NuGetComponent("SomeNugetComponent", "1.2.3.4")), }; - serviceUnderTest = new BcdeScanExecutionService + this.serviceUnderTest = new BcdeScanExecutionService { - DetectorProcessingService = detectorProcessingServiceMock.Object, - DetectorRegistryService = detectorRegistryServiceMock.Object, - DetectorRestrictionService = detectorRestrictionServiceMock.Object, - Logger = loggerMock.Object, + DetectorProcessingService = this.detectorProcessingServiceMock.Object, + DetectorRegistryService = this.detectorRegistryServiceMock.Object, + DetectorRestrictionService = this.detectorRestrictionServiceMock.Object, + Logger = this.loggerMock.Object, GraphTranslationServices = new List> { new Lazy(() => defaultGraphTranslationService, new GraphTranslationServiceMetadata()), }, }; - sourceDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); + this.sourceDirectory = new DirectoryInfo(Path.Combine(Path.GetTempPath(), Path.GetRandomFileName())); - sourceDirectory.Create(); + this.sourceDirectory.Create(); } [TestCleanup] public void CleanupTests() { - detectorProcessingServiceMock.VerifyAll(); - detectorRegistryServiceMock.VerifyAll(); - detectorRestrictionServiceMock.VerifyAll(); + this.detectorProcessingServiceMock.VerifyAll(); + this.detectorRegistryServiceMock.VerifyAll(); + this.detectorRestrictionServiceMock.VerifyAll(); try { - sourceDirectory.Delete(true); + this.sourceDirectory.Delete(true); } catch { @@ -99,36 +99,37 @@ public void CleanupTests() public void DetectComponents_HappyPath() { var componentRecorder = new ComponentRecorder(); - var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(sourceDirectory.FullName, "/some/file/path")); + var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(this.sourceDirectory.FullName, "/some/file/path")); - componentDetector2Mock.SetupGet(x => x.Id).Returns("Detector2"); - componentDetector2Mock.SetupGet(x => x.Version).Returns(1); - componentDetector3Mock.SetupGet(x => x.Id).Returns("Detector3"); - componentDetector3Mock.SetupGet(x => x.Version).Returns(10); + this.componentDetector2Mock.SetupGet(x => x.Id).Returns("Detector2"); + this.componentDetector2Mock.SetupGet(x => x.Version).Returns(1); + this.componentDetector3Mock.SetupGet(x => x.Id).Returns("Detector3"); + this.componentDetector3Mock.SetupGet(x => x.Version).Returns(10); - detectedComponents[0].DevelopmentDependency = true; - detectedComponents[0].ContainerDetailIds = new HashSet { sampleContainerDetails.Id }; - singleFileComponentRecorder.RegisterUsage(detectedComponents[0], isDevelopmentDependency: true); + this.detectedComponents[0].DevelopmentDependency = true; + this.detectedComponents[0].ContainerDetailIds = new HashSet { + this.sampleContainerDetails.Id }; + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0], isDevelopmentDependency: true); var parentPipComponent = new PipComponent("sample-root", "1.0"); - detectedComponents[1].DependencyRoots = new HashSet(new[] { parentPipComponent }); - detectedComponents[1].DevelopmentDependency = null; + this.detectedComponents[1].DependencyRoots = new HashSet(new[] { parentPipComponent }); + this.detectedComponents[1].DevelopmentDependency = null; singleFileComponentRecorder.RegisterUsage(new DetectedComponent(parentPipComponent, detector: new PipComponentDetector()), isExplicitReferencedDependency: true); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1], parentComponentId: parentPipComponent.Id); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1], parentComponentId: parentPipComponent.Id); var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; - var result = DetectComponentsHappyPath(args, restrictions => + var result = this.DetectComponentsHappyPath(args, restrictions => { restrictions.AllowedDetectorCategories.Should().BeNull(); restrictions.AllowedDetectorIds.Should().BeNull(); }, new List { componentRecorder }); result.Result.Should().Be(ProcessingResultCode.Success); - ValidateDetectedComponents(result.DetectedComponents); + this.ValidateDetectedComponents(result.DetectedComponents); result.DetectorsInRun.Count().Should().Be(2); var detector2 = result.DetectorsInRun.Single(x => x.DetectorId == "Detector2"); detector2.Version.Should().Be(1); @@ -155,22 +156,22 @@ public void DetectComponents_DetectOnlyWithIdAndCategoryRestrictions() DetectorCategories = new[] { "Category1", "Category2" }, DetectorsFilter = new[] { "Detector1", "Detector2" }, AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/location"); - singleFileComponentRecorder.RegisterUsage(detectedComponents[0]); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1]); - var result = DetectComponentsHappyPath(args, restrictions => + var result = this.DetectComponentsHappyPath(args, restrictions => { restrictions.AllowedDetectorCategories.Should().Contain(args.DetectorCategories); restrictions.AllowedDetectorIds.Should().Contain(args.DetectorsFilter); }, new List { componentRecorder }); result.Result.Should().Be(ProcessingResultCode.Success); - ValidateDetectedComponents(result.DetectedComponents); + this.ValidateDetectedComponents(result.DetectedComponents); } [TestMethod] @@ -179,43 +180,43 @@ public void DetectComponents_DetectOnlyWithNoUrl() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/location"); - singleFileComponentRecorder.RegisterUsage(detectedComponents[0]); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1]); - var result = DetectComponentsHappyPath(args, restrictions => + var result = this.DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); result.Result.Should().Be(ProcessingResultCode.Success); - ValidateDetectedComponents(result.DetectedComponents); + this.ValidateDetectedComponents(result.DetectedComponents); } [TestMethod] public void DetectComponents_ReturnsExperimentalDetectorInformation() { - componentDetector2Mock.As(); - componentDetector3Mock.As(); + this.componentDetector2Mock.As(); + this.componentDetector3Mock.As(); var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("/location"); - singleFileComponentRecorder.RegisterUsage(detectedComponents[0]); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0]); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1]); - var result = DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); + var result = this.DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); result.Result.Should().Be(ProcessingResultCode.Success); - ValidateDetectedComponents(result.DetectedComponents); + this.ValidateDetectedComponents(result.DetectedComponents); result.DetectorsInRun.All(x => x.IsExperimental).Should().BeTrue(); } @@ -227,26 +228,28 @@ public void DetectComponents_Graph_Happy_Path() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(mockGraphLocation); - singleFileComponentRecorder.RegisterUsage(detectedComponents[0], isExplicitReferencedDependency: true, isDevelopmentDependency: true); - singleFileComponentRecorder.RegisterUsage(detectedComponents[1], isDevelopmentDependency: false, parentComponentId: detectedComponents[0].Component.Id); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0], isExplicitReferencedDependency: true, isDevelopmentDependency: true); + singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1], isDevelopmentDependency: false, parentComponentId: this.detectedComponents[0].Component.Id); Mock mockDependencyGraphA = new Mock(); - mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] { detectedComponents[0].Component.Id, detectedComponents[1].Component.Id }); - mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(detectedComponents[0].Component.Id)) - .Returns(new[] { detectedComponents[1].Component.Id }); - mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(detectedComponents[0].Component.Id)).Returns(true); - mockDependencyGraphA.Setup(x => x.IsDevelopmentDependency(detectedComponents[0].Component.Id)).Returns(true); - mockDependencyGraphA.Setup(x => x.IsDevelopmentDependency(detectedComponents[1].Component.Id)).Returns(false); + mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] { + this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id }); + mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[0].Component.Id)) + .Returns(new[] { + this.detectedComponents[1].Component.Id }); + mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(this.detectedComponents[0].Component.Id)).Returns(true); + mockDependencyGraphA.Setup(x => x.IsDevelopmentDependency(this.detectedComponents[0].Component.Id)).Returns(true); + mockDependencyGraphA.Setup(x => x.IsDevelopmentDependency(this.detectedComponents[1].Component.Id)).Returns(false); - var result = DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); + var result = this.DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); result.SourceDirectory.Should().NotBeNull(); - result.SourceDirectory.Should().Be(sourceDirectory.ToString()); + result.SourceDirectory.Should().Be(this.sourceDirectory.ToString()); result.Result.Should().Be(ProcessingResultCode.Success); result.DependencyGraphs.Count.Should().Be(1); @@ -254,19 +257,19 @@ public void DetectComponents_Graph_Happy_Path() matchingGraph.Key.Should().Be(mockGraphLocation); var explicitlyReferencedComponents = matchingGraph.Value.ExplicitlyReferencedComponentIds; explicitlyReferencedComponents.Count.Should().Be(1); - explicitlyReferencedComponents.Should().Contain(detectedComponents[0].Component.Id); + explicitlyReferencedComponents.Should().Contain(this.detectedComponents[0].Component.Id); var actualGraph = matchingGraph.Value.Graph; actualGraph.Keys.Count.Should().Be(2); - actualGraph[detectedComponents[0].Component.Id].Count.Should().Be(1); - actualGraph[detectedComponents[0].Component.Id].Should().Contain(detectedComponents[1].Component.Id); - actualGraph[detectedComponents[1].Component.Id].Should().BeNull(); + actualGraph[this.detectedComponents[0].Component.Id].Count.Should().Be(1); + actualGraph[this.detectedComponents[0].Component.Id].Should().Contain(this.detectedComponents[1].Component.Id); + actualGraph[this.detectedComponents[1].Component.Id].Should().BeNull(); - matchingGraph.Value.DevelopmentDependencies.Should().Contain(detectedComponents[0].Component.Id); - matchingGraph.Value.DevelopmentDependencies.Should().NotContain(detectedComponents[1].Component.Id); + matchingGraph.Value.DevelopmentDependencies.Should().Contain(this.detectedComponents[0].Component.Id); + matchingGraph.Value.DevelopmentDependencies.Should().NotContain(this.detectedComponents[1].Component.Id); - matchingGraph.Value.Dependencies.Should().Contain(detectedComponents[1].Component.Id); - matchingGraph.Value.Dependencies.Should().NotContain(detectedComponents[0].Component.Id); + matchingGraph.Value.Dependencies.Should().Contain(this.detectedComponents[1].Component.Id); + matchingGraph.Value.Dependencies.Should().NotContain(this.detectedComponents[0].Component.Id); } [TestMethod] @@ -277,35 +280,39 @@ public void DetectComponents_Graph_AccumulatesGraphsOnSameLocation() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var componentRecorder = new ComponentRecorder(); Mock mockDependencyGraphA = new Mock(); - mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] { detectedComponents[0].Component.Id, detectedComponents[1].Component.Id }); - mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(detectedComponents[0].Component.Id)) - .Returns(new[] { detectedComponents[1].Component.Id }); - mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(detectedComponents[0].Component.Id)).Returns(true); + mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] { + this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id }); + mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[0].Component.Id)) + .Returns(new[] { + this.detectedComponents[1].Component.Id }); + mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(this.detectedComponents[0].Component.Id)).Returns(true); var singleFileComponentRecorderA = componentRecorder.CreateSingleFileComponentRecorder(mockGraphLocation); - singleFileComponentRecorderA.RegisterUsage(detectedComponents[0], isExplicitReferencedDependency: true); - singleFileComponentRecorderA.RegisterUsage(detectedComponents[1], parentComponentId: detectedComponents[0].Component.Id); + singleFileComponentRecorderA.RegisterUsage(this.detectedComponents[0], isExplicitReferencedDependency: true); + singleFileComponentRecorderA.RegisterUsage(this.detectedComponents[1], parentComponentId: this.detectedComponents[0].Component.Id); Mock mockDependencyGraphB = new Mock(); - mockDependencyGraphB.Setup(x => x.GetComponents()).Returns(new[] { detectedComponents[0].Component.Id, detectedComponents[1].Component.Id }); - mockDependencyGraphB.Setup(x => x.GetDependenciesForComponent(detectedComponents[1].Component.Id)) - .Returns(new[] { detectedComponents[0].Component.Id }); - mockDependencyGraphB.Setup(x => x.IsComponentExplicitlyReferenced(detectedComponents[1].Component.Id)).Returns(true); + mockDependencyGraphB.Setup(x => x.GetComponents()).Returns(new[] { + this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id }); + mockDependencyGraphB.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[1].Component.Id)) + .Returns(new[] { + this.detectedComponents[0].Component.Id }); + mockDependencyGraphB.Setup(x => x.IsComponentExplicitlyReferenced(this.detectedComponents[1].Component.Id)).Returns(true); var singleFileComponentRecorderB = componentRecorder.CreateSingleFileComponentRecorder(mockGraphLocation); - singleFileComponentRecorderB.RegisterUsage(detectedComponents[1], isExplicitReferencedDependency: true); - singleFileComponentRecorderB.RegisterUsage(detectedComponents[0], parentComponentId: detectedComponents[1].Component.Id); + singleFileComponentRecorderB.RegisterUsage(this.detectedComponents[1], isExplicitReferencedDependency: true); + singleFileComponentRecorderB.RegisterUsage(this.detectedComponents[0], parentComponentId: this.detectedComponents[1].Component.Id); - var result = DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); + var result = this.DetectComponentsHappyPath(args, restrictions => { }, new List { componentRecorder }); result.SourceDirectory.Should().NotBeNull(); - result.SourceDirectory.Should().Be(sourceDirectory.ToString()); + result.SourceDirectory.Should().Be(this.sourceDirectory.ToString()); result.Result.Should().Be(ProcessingResultCode.Success); result.DependencyGraphs.Count.Should().Be(1); @@ -313,15 +320,15 @@ public void DetectComponents_Graph_AccumulatesGraphsOnSameLocation() matchingGraph.Key.Should().Be(mockGraphLocation); var explicitlyReferencedComponents = matchingGraph.Value.ExplicitlyReferencedComponentIds; explicitlyReferencedComponents.Count.Should().Be(2); - explicitlyReferencedComponents.Should().Contain(detectedComponents[0].Component.Id); - explicitlyReferencedComponents.Should().Contain(detectedComponents[1].Component.Id); + explicitlyReferencedComponents.Should().Contain(this.detectedComponents[0].Component.Id); + explicitlyReferencedComponents.Should().Contain(this.detectedComponents[1].Component.Id); var actualGraph = matchingGraph.Value.Graph; actualGraph.Keys.Count.Should().Be(2); - actualGraph[detectedComponents[0].Component.Id].Count.Should().Be(1); - actualGraph[detectedComponents[0].Component.Id].Should().Contain(detectedComponents[1].Component.Id); - actualGraph[detectedComponents[1].Component.Id].Count.Should().Be(1); - actualGraph[detectedComponents[1].Component.Id].Should().Contain(detectedComponents[0].Component.Id); + actualGraph[this.detectedComponents[0].Component.Id].Count.Should().Be(1); + actualGraph[this.detectedComponents[0].Component.Id].Should().Contain(this.detectedComponents[1].Component.Id); + actualGraph[this.detectedComponents[1].Component.Id].Count.Should().Be(1); + actualGraph[this.detectedComponents[1].Component.Id].Should().Contain(this.detectedComponents[0].Component.Id); } [TestMethod] @@ -332,7 +339,7 @@ public void VerifyTranslation_ComponentsAreReturnedWithDevDependencyInfo() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); @@ -344,7 +351,7 @@ public void VerifyTranslation_ComponentsAreReturnedWithDevDependencyInfo() singleFileComponentRecorder.RegisterUsage(detectedComponent2, isDevelopmentDependency: false); singleFileComponentRecorder.RegisterUsage(detectedComponent3); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var detectedComponents = results.ComponentsFound; @@ -366,7 +373,7 @@ public void VerifyTranslation_RootsFromMultipleLocationsAreAgregated() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location1"); @@ -380,7 +387,7 @@ public void VerifyTranslation_RootsFromMultipleLocationsAreAgregated() var detectedComponent2NewLocation = new DetectedComponent(new NpmComponent("test", "2.0.0"), detector: npmDetector); singleFileComponentRecorder.RegisterUsage(detectedComponent2NewLocation, isExplicitReferencedDependency: true); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var detectedComponents = results.ComponentsFound; @@ -402,7 +409,7 @@ public void VerifyTranslation_ComponentsAreReturnedWithRoots() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); @@ -412,7 +419,7 @@ public void VerifyTranslation_ComponentsAreReturnedWithRoots() singleFileComponentRecorder.RegisterUsage(detectedComponent1, isExplicitReferencedDependency: true); singleFileComponentRecorder.RegisterUsage(detectedComponent2, parentComponentId: detectedComponent1.Component.Id); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var detectedComponents = results.ComponentsFound; @@ -433,7 +440,7 @@ public void VerifyTranslation_DevDependenciesAreMergedWhenSameComponentInDiffere var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var firstRecorder = componentRecorder.CreateSingleFileComponentRecorder("FileA"); @@ -469,7 +476,7 @@ public void VerifyTranslation_DevDependenciesAreMergedWhenSameComponentInDiffere firstRecorder.RegisterUsage(component.component, isDevelopmentDependency: component.isDevDep); } - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var components = results.ComponentsFound; @@ -487,13 +494,13 @@ public void VerifyTranslation_LocationsAreMergedWhenSameComponentInDifferentFile var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; - var firstRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(sourceDirectory.FullName, "/some/file/path")); - firstRecorder.AddAdditionalRelatedFile(Path.Join(sourceDirectory.FullName, "/some/related/file/1")); - var secondRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(sourceDirectory.FullName, "/some/other/file/path")); - secondRecorder.AddAdditionalRelatedFile(Path.Join(sourceDirectory.FullName, "/some/related/file/2")); + var firstRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(this.sourceDirectory.FullName, "/some/file/path")); + firstRecorder.AddAdditionalRelatedFile(Path.Join(this.sourceDirectory.FullName, "/some/related/file/1")); + var secondRecorder = componentRecorder.CreateSingleFileComponentRecorder(Path.Join(this.sourceDirectory.FullName, "/some/other/file/path")); + secondRecorder.AddAdditionalRelatedFile(Path.Join(this.sourceDirectory.FullName, "/some/related/file/2")); var firstComponent = new DetectedComponent(new NpmComponent("test", "1.0.0"), detector: npmDetector); var secondComponent = new DetectedComponent(new NpmComponent("test", "1.0.0"), detector: npmDetector); @@ -501,7 +508,7 @@ public void VerifyTranslation_LocationsAreMergedWhenSameComponentInDifferentFile firstRecorder.RegisterUsage(firstComponent); secondRecorder.RegisterUsage(secondComponent); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var actualComponent = results.ComponentsFound.Single(); @@ -528,7 +535,7 @@ public void VerifyTranslation_RootsAreMergedWhenSameComponentInDifferentFiles() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var firstRecorder = componentRecorder.CreateSingleFileComponentRecorder("FileA"); @@ -546,7 +553,7 @@ public void VerifyTranslation_RootsAreMergedWhenSameComponentInDifferentFiles() secondRecorder.RegisterUsage(root2, isExplicitReferencedDependency: true); secondRecorder.RegisterUsage(secondComponent, parentComponentId: root2.Component.Id); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); var actualComponent = results.ComponentsFound.First(c => c.Component.Id == firstComponent.Component.Id); actualComponent.TopLevelReferrers.Count().Should().Be(2); @@ -566,7 +573,7 @@ public void VerifyTranslation_DetectedComponentExist_UpdateFunctionIsApplied() var args = new BcdeArguments { AdditionalPluginDirectories = Enumerable.Empty(), - SourceDirectory = sourceDirectory, + SourceDirectory = this.sourceDirectory, }; var singleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder("location"); @@ -574,12 +581,12 @@ public void VerifyTranslation_DetectedComponentExist_UpdateFunctionIsApplied() singleFileComponentRecorder.RegisterUsage(detectedComponent, isDevelopmentDependency: true); - var results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + var results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); results.ComponentsFound.Where(component => component.Component.Id == detectedComponent.Component.Id).Single().IsDevelopmentDependency.Should().BeTrue(); singleFileComponentRecorder.RegisterUsage(detectedComponent, isDevelopmentDependency: false); - results = SetupRecorderBasedScanning(args, new List { componentRecorder }); + results = this.SetupRecorderBasedScanning(args, new List { componentRecorder }); results.ComponentsFound.Where(component => component.Component.Id == detectedComponent.Component.Id).Single().IsDevelopmentDependency.Should().BeFalse(); } @@ -588,11 +595,14 @@ private TestOutput DetectComponentsHappyPath( Action restrictionAsserter = null, IEnumerable componentRecorders = null) { - var registeredDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object, versionedComponentDetector1Mock.Object }; - var restrictedDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object }; - detectorRegistryServiceMock.Setup(x => x.GetDetectors(Enumerable.Empty(), It.IsAny>())) + var registeredDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, + this.versionedComponentDetector1Mock.Object }; + var restrictedDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object }; + this.detectorRegistryServiceMock.Setup(x => x.GetDetectors(Enumerable.Empty(), It.IsAny>())) .Returns(registeredDetectors); - detectorRestrictionServiceMock.Setup( + this.detectorRestrictionServiceMock.Setup( x => x.ApplyRestrictions( It.IsAny(), It.Is>(inputDetectors => registeredDetectors.Intersect(inputDetectors).Count() == registeredDetectors.Length))) @@ -601,27 +611,28 @@ private TestOutput DetectComponentsHappyPath( (restrictions, detectors) => restrictionAsserter?.Invoke(restrictions)); // We initialize detected component's DetectedBy here because of a Moq constraint -- certain operations (Adding interfaces) have to happen before .Object - detectedComponents[0].DetectedBy = componentDetector2Mock.Object; - detectedComponents[1].DetectedBy = componentDetector3Mock.Object; + this.detectedComponents[0].DetectedBy = this.componentDetector2Mock.Object; + this.detectedComponents[1].DetectedBy = this.componentDetector3Mock.Object; var processingResult = new DetectorProcessingResult { ResultCode = ProcessingResultCode.Success, ContainersDetailsMap = new Dictionary { - { sampleContainerDetails.Id, sampleContainerDetails }, + { + this.sampleContainerDetails.Id, this.sampleContainerDetails }, }, - ComponentRecorders = componentRecorders.Select(componentRecorder => (componentDetector2Mock.Object, componentRecorder)), + ComponentRecorders = componentRecorders.Select(componentRecorder => (this.componentDetector2Mock.Object, componentRecorder)), }; - detectorProcessingServiceMock.Setup(x => + this.detectorProcessingServiceMock.Setup(x => x.ProcessDetectorsAsync( args, It.Is>(inputDetectors => restrictedDetectors.Intersect(inputDetectors).Count() == restrictedDetectors.Length), Match.Create(restriction => true))) .ReturnsAsync(processingResult); - var result = serviceUnderTest.ExecuteScanAsync(args).Result; + var result = this.serviceUnderTest.ExecuteScanAsync(args).Result; result.ResultCode.Should().Be(ProcessingResultCode.Success); result.SourceDirectory.Should().NotBeNull(); result.SourceDirectory.Should().Be(args.SourceDirectorySerialized); @@ -635,38 +646,42 @@ private ScanResult SetupRecorderBasedScanning( BcdeArguments args, IEnumerable componentRecorders) { - var registeredDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object, versionedComponentDetector1Mock.Object }; - var restrictedDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object }; - detectorRegistryServiceMock.Setup(x => x.GetDetectors(Enumerable.Empty(), It.IsAny>())) + var registeredDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, + this.versionedComponentDetector1Mock.Object }; + var restrictedDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object }; + this.detectorRegistryServiceMock.Setup(x => x.GetDetectors(Enumerable.Empty(), It.IsAny>())) .Returns(registeredDetectors); - detectorRestrictionServiceMock.Setup( + this.detectorRestrictionServiceMock.Setup( x => x.ApplyRestrictions( It.IsAny(), It.Is>(inputDetectors => registeredDetectors.Intersect(inputDetectors).Count() == registeredDetectors.Length))) .Returns(restrictedDetectors); // We initialize detected component's DetectedBy here because of a Moq constraint -- certain operations (Adding interfaces) have to happen before .Object - detectedComponents[0].DetectedBy = componentDetector2Mock.Object; - detectedComponents[1].DetectedBy = componentDetector3Mock.Object; + this.detectedComponents[0].DetectedBy = this.componentDetector2Mock.Object; + this.detectedComponents[1].DetectedBy = this.componentDetector3Mock.Object; var processingResult = new DetectorProcessingResult { ResultCode = ProcessingResultCode.Success, ContainersDetailsMap = new Dictionary { - { sampleContainerDetails.Id, sampleContainerDetails }, + { + this.sampleContainerDetails.Id, this.sampleContainerDetails }, }, - ComponentRecorders = componentRecorders.Select(componentRecorder => (componentDetector2Mock.Object, componentRecorder)), + ComponentRecorders = componentRecorders.Select(componentRecorder => (this.componentDetector2Mock.Object, componentRecorder)), }; - detectorProcessingServiceMock.Setup(x => + this.detectorProcessingServiceMock.Setup(x => x.ProcessDetectorsAsync( args, It.Is>(inputDetectors => restrictedDetectors.Intersect(inputDetectors).Count() == restrictedDetectors.Length), Match.Create(restriction => true))) .ReturnsAsync(processingResult); - var result = serviceUnderTest.ExecuteScanAsync(args).Result; + var result = this.serviceUnderTest.ExecuteScanAsync(args).Result; result.ResultCode.Should().Be(ProcessingResultCode.Success); result.SourceDirectory.Should().NotBeNull(); result.SourceDirectory.Should().Be(args.SourceDirectorySerialized); @@ -678,21 +693,21 @@ private void ValidateDetectedComponents(IEnumerable scannedCom { var npmComponent = scannedComponents.Where(x => x.Component.Type == ComponentType.Npm).Select(x => x.Component as NpmComponent).FirstOrDefault(); npmComponent.Should().NotBeNull(); - npmComponent.Name.Should().Be(((NpmComponent)detectedComponents[0].Component).Name); + npmComponent.Name.Should().Be(((NpmComponent)this.detectedComponents[0].Component).Name); var nugetComponent = scannedComponents.Where(x => x.Component.Type == ComponentType.NuGet).Select(x => x.Component as NuGetComponent).FirstOrDefault(); nugetComponent.Should().NotBeNull(); - nugetComponent.Name.Should().Be(((NuGetComponent)detectedComponents[1].Component).Name); + nugetComponent.Name.Should().Be(((NuGetComponent)this.detectedComponents[1].Component).Name); } private class TestOutput { public TestOutput(DefaultGraphScanResult result) { - Result = result.ResultCode; - DetectedComponents = result.ComponentsFound; - DetectorsInRun = result.DetectorsInScan; - DependencyGraphs = result.DependencyGraphs; - SourceDirectory = result.SourceDirectory; + this.Result = result.ResultCode; + this.DetectedComponents = result.ComponentsFound; + this.DetectorsInRun = result.DetectorsInScan; + this.DependencyGraphs = result.DependencyGraphs; + this.SourceDirectory = result.SourceDirectory; } internal ProcessingResultCode Result { get; set; } diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorListingCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorListingCommandServiceTests.cs index c5e3958b6..d1d76c376 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorListingCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorListingCommandServiceTests.cs @@ -28,48 +28,50 @@ public class DetectorListingCommandServiceTests [TestInitialize] public void InitializeTest() { - loggerMock = new Mock(); - detectorRegistryServiceMock = new Mock(); - componentDetector2Mock = new Mock(); - componentDetector3Mock = new Mock(); - versionedComponentDetector1Mock = new Mock(); + this.loggerMock = new Mock(); + this.detectorRegistryServiceMock = new Mock(); + this.componentDetector2Mock = new Mock(); + this.componentDetector3Mock = new Mock(); + this.versionedComponentDetector1Mock = new Mock(); - serviceUnderTest = new DetectorListingCommandService + this.serviceUnderTest = new DetectorListingCommandService { - DetectorRegistryService = detectorRegistryServiceMock.Object, - Logger = loggerMock.Object, + DetectorRegistryService = this.detectorRegistryServiceMock.Object, + Logger = this.loggerMock.Object, }; - logOutput = new List(); - loggerMock.Setup(x => x.LogInfo(It.IsAny())).Callback(loggedString => + this.logOutput = new List(); + this.loggerMock.Setup(x => x.LogInfo(It.IsAny())).Callback(loggedString => { - logOutput.Add(loggedString); + this.logOutput.Add(loggedString); }); - componentDetector2Mock.SetupGet(x => x.Id).Returns("ComponentDetector2"); - componentDetector3Mock.SetupGet(x => x.Id).Returns("ComponentDetector3"); - versionedComponentDetector1Mock.SetupGet(x => x.Id).Returns("VersionedComponentDetector"); + this.componentDetector2Mock.SetupGet(x => x.Id).Returns("ComponentDetector2"); + this.componentDetector3Mock.SetupGet(x => x.Id).Returns("ComponentDetector3"); + this.versionedComponentDetector1Mock.SetupGet(x => x.Id).Returns("VersionedComponentDetector"); - var registeredDetectors = new[] { componentDetector2Mock.Object, componentDetector3Mock.Object, versionedComponentDetector1Mock.Object }; - detectorRegistryServiceMock.Setup(x => x.GetDetectors(It.IsAny>(), It.IsAny>())) + var registeredDetectors = new[] { + this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, + this.versionedComponentDetector1Mock.Object }; + this.detectorRegistryServiceMock.Setup(x => x.GetDetectors(It.IsAny>(), It.IsAny>())) .Returns(registeredDetectors); } [TestCleanup] public void CleanupTests() { - detectorRegistryServiceMock.VerifyAll(); + this.detectorRegistryServiceMock.VerifyAll(); } [TestMethod] public async Task DetectorListingCommandService_ListsDetectors() { - var result = await serviceUnderTest.Handle(new ListDetectionArgs()); + var result = await this.serviceUnderTest.Handle(new ListDetectionArgs()); result.ResultCode.Should().Be(ProcessingResultCode.Success); - logOutput.Should().Contain("ComponentDetector2"); - logOutput.Should().Contain("ComponentDetector3"); - logOutput.Should().Contain("VersionedComponentDetector"); + this.logOutput.Should().Contain("ComponentDetector2"); + this.logOutput.Should().Contain("ComponentDetector3"); + this.logOutput.Should().Contain("VersionedComponentDetector"); } } } diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs index a433af0c5..e0a26844d 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs @@ -58,29 +58,29 @@ private IndividualDetectorScanResult ExpectedResultForDetector(string detectorId [TestInitialize] public void TestInit() { - loggerMock = new Mock(); - serviceUnderTest = new DetectorProcessingService + this.loggerMock = new Mock(); + this.serviceUnderTest = new DetectorProcessingService { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, }; - directoryWalkerFactory = new FastDirectoryWalkerFactory() + this.directoryWalkerFactory = new FastDirectoryWalkerFactory() { - Logger = loggerMock.Object, + Logger = this.loggerMock.Object, PathUtilityService = new PathUtilityService(), }; - serviceUnderTest.Scanner = directoryWalkerFactory; + this.serviceUnderTest.Scanner = this.directoryWalkerFactory; - firstFileComponentDetectorMock = SetupFileDetectorMock("firstFileDetectorId"); - secondFileComponentDetectorMock = SetupFileDetectorMock("secondFileDetectorId"); - experimentalFileComponentDetectorMock = SetupFileDetectorMock("experimentalFileDetectorId"); - experimentalFileComponentDetectorMock.As(); + this.firstFileComponentDetectorMock = this.SetupFileDetectorMock("firstFileDetectorId"); + this.secondFileComponentDetectorMock = this.SetupFileDetectorMock("secondFileDetectorId"); + this.experimentalFileComponentDetectorMock = this.SetupFileDetectorMock("experimentalFileDetectorId"); + this.experimentalFileComponentDetectorMock.As(); - firstCommandComponentDetectorMock = SetupCommandDetectorMock("firstCommandDetectorId"); - secondCommandComponentDetectorMock = SetupCommandDetectorMock("secondCommandDetectorId"); + this.firstCommandComponentDetectorMock = this.SetupCommandDetectorMock("firstCommandDetectorId"); + this.secondCommandComponentDetectorMock = this.SetupCommandDetectorMock("secondCommandDetectorId"); - isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); + this.isWin = RuntimeInformation.IsOSPlatform(OSPlatform.Windows); } private Mock SetupFileDetectorMock(string id) @@ -90,9 +90,9 @@ private Mock SetupFileDetectorMock(string id) mockFileDetector.SetupGet(x => x.Id).Returns(id); var sourceDirectory = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "Some", "Source", "Directory")); - componentDictionary.Should().ContainKey(id, $"MockDetector id:{id}, should be in mock dictionary"); + this.componentDictionary.Should().ContainKey(id, $"MockDetector id:{id}, should be in mock dictionary"); - var expectedResult = ExpectedResultForDetector(id); + var expectedResult = this.ExpectedResultForDetector(id); mockFileDetector.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory && request.ComponentRecorder != null))).ReturnsAsync( (ScanRequest request) => @@ -102,8 +102,8 @@ private Mock SetupFileDetectorMock(string id) mockFileDetector.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory && request.ComponentRecorder != null))).ReturnsAsync( (ScanRequest request) => { - serviceUnderTest.Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1); - FillComponentRecorder(request.ComponentRecorder, id); + this.serviceUnderTest.Scanner.Initialize(request.SourceDirectory, request.DirectoryExclusionPredicate, 1); + this.FillComponentRecorder(request.ComponentRecorder, id); return expectedResult; }).Verifiable(); @@ -121,14 +121,14 @@ private IEnumerable GetDiscoveredComponentsFromDetectorProces private void FillComponentRecorder(IComponentRecorder componentRecorder, string id) { var singleFileRecorder = componentRecorder.CreateSingleFileComponentRecorder("/mock/location"); - singleFileRecorder.RegisterUsage(componentDictionary[id], false); + singleFileRecorder.RegisterUsage(this.componentDictionary[id], false); } private void ValidateExpectedComponents(DetectorProcessingResult result, IEnumerable detectorsRan) { var shouldBePresent = detectorsRan.Where(detector => !(detector is IExperimentalDetector)) - .Select(detector => componentDictionary[detector.Id]); - var isPresent = GetDiscoveredComponentsFromDetectorProcessingResult(result); + .Select(detector => this.componentDictionary[detector.Id]); + var isPresent = this.GetDiscoveredComponentsFromDetectorProcessingResult(result); var check = isPresent.Select(i => i.GetType()); @@ -142,13 +142,13 @@ private Mock SetupCommandDetectorMock(string id) mockCommandDetector.SetupAllProperties(); mockCommandDetector.SetupGet(x => x.Id).Returns(id); - componentDictionary.Should().ContainKey(id, $"MockDetector id:{id}, should be in mock dictionary"); + this.componentDictionary.Should().ContainKey(id, $"MockDetector id:{id}, should be in mock dictionary"); mockCommandDetector.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory && !request.DetectorArgs.Any()))).ReturnsAsync( (ScanRequest request) => { - FillComponentRecorder(request.ComponentRecorder, id); - return ExpectedResultForDetector(id); + this.FillComponentRecorder(request.ComponentRecorder, id); + return this.ExpectedResultForDetector(id); }).Verifiable(); return mockCommandDetector; @@ -157,17 +157,18 @@ private Mock SetupCommandDetectorMock(string id) [TestMethod] public void ProcessDetectorsAsync_HappyPathReturnsDetectedComponents() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object }; - var results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object }; + var results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - ValidateExpectedComponents(results, detectorsToUse); - GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => x.Component?.Type == ComponentType.Npm).Component - .Should().Be(componentDictionary[firstFileComponentDetectorMock.Object.Id].Component); - GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => x.Component?.Type == ComponentType.NuGet).Component - .Should().Be(componentDictionary[secondFileComponentDetectorMock.Object.Id].Component); + this.ValidateExpectedComponents(results, this.detectorsToUse); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => x.Component?.Type == ComponentType.Npm).Component + .Should().Be(this.componentDictionary[this.firstFileComponentDetectorMock.Object.Id].Component); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => x.Component?.Type == ComponentType.NuGet).Component + .Should().Be(this.componentDictionary[this.secondFileComponentDetectorMock.Object.Id].Component); results.ResultCode.Should().Be(ProcessingResultCode.Success); } @@ -189,8 +190,8 @@ public void ProcessDetectorsAsync_NullDetectedComponentsReturnIsCoalesced() }; }); - detectorsToUse = new[] { mockComponentDetector.Object }; - var results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + this.detectorsToUse = new[] { mockComponentDetector.Object }; + var results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; results.ResultCode.Should().Be(ProcessingResultCode.Success); } @@ -198,13 +199,14 @@ public void ProcessDetectorsAsync_NullDetectedComponentsReturnIsCoalesced() [TestMethod] public void ProcessDetectorsAsync_HappyPathReturns_DependencyGraph() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object }; - var results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object }; + var results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - foreach (var discoveredComponent in GetDiscoveredComponentsFromDetectorProcessingResult(results)) + foreach (var discoveredComponent in this.GetDiscoveredComponentsFromDetectorProcessingResult(results)) { var componentId = discoveredComponent.Component.Id; bool isMatched = false; @@ -220,10 +222,11 @@ public void ProcessDetectorsAsync_HappyPathReturns_DependencyGraph() [TestMethod] public void ProcessDetectorsAsync_AdditionalTelemetryDetailsAreReturned() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object }; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Wait(); }); foreach (var record in records) @@ -236,16 +239,18 @@ public void ProcessDetectorsAsync_AdditionalTelemetryDetailsAreReturned() [TestMethod] public void ProcessDetectorsAsync_ExperimentalDetectorsDoNotReturnComponents() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object, experimentalFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, + this.experimentalFileComponentDetectorMock.Object }; DetectorProcessingResult results = null; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; }); - var experimentalDetectorRecord = records.FirstOrDefault(x => x.DetectorId == experimentalFileComponentDetectorMock.Object.Id); - var experimentalComponent = componentDictionary[experimentalFileComponentDetectorMock.Object.Id].Component as NuGetComponent; + var experimentalDetectorRecord = records.FirstOrDefault(x => x.DetectorId == this.experimentalFileComponentDetectorMock.Object.Id); + var experimentalComponent = this.componentDictionary[this.experimentalFileComponentDetectorMock.Object.Id].Component as NuGetComponent; // protect against test code changes. experimentalComponent.Name.Should().NotBeNullOrEmpty("Experimental component should be nuget and have a name"); @@ -255,54 +260,58 @@ public void ProcessDetectorsAsync_ExperimentalDetectorsDoNotReturnComponents() experimentalDetectorRecord.IsExperimental.Should().BeTrue(); // We should have all components except the ones that came from our experimental detector - GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount) - experimentalDetectorRecord.DetectedComponentCount); - GetDiscoveredComponentsFromDetectorProcessingResult(results).All(x => (x.Component as NuGetComponent)?.Name != experimentalComponent.Name) + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount) - experimentalDetectorRecord.DetectedComponentCount); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).All(x => (x.Component as NuGetComponent)?.Name != experimentalComponent.Name) .Should().BeTrue("Experimental component should not be in component list"); results.ResultCode.Should().Be(ProcessingResultCode.Success); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - experimentalFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.experimentalFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_ExperimentalDetectorsDoNormalStuffIfExplicitlyEnabled() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object, experimentalFileComponentDetectorMock.Object }; - var experimentalDetectorId = experimentalFileComponentDetectorMock.Object.Id; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, + this.experimentalFileComponentDetectorMock.Object }; + var experimentalDetectorId = this.experimentalFileComponentDetectorMock.Object.Id; DetectorProcessingResult results = null; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions { ExplicitlyEnabledDetectorIds = new[] { experimentalDetectorId } }).Result; + results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions { ExplicitlyEnabledDetectorIds = new[] { experimentalDetectorId } }).Result; }); // We should have all components except the ones that came from our experimental detector - GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount)); - GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => (x.Component as NuGetComponent)?.Name == (componentDictionary[experimentalDetectorId].Component as NuGetComponent).Name) + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount)); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).FirstOrDefault(x => (x.Component as NuGetComponent)?.Name == (this.componentDictionary[experimentalDetectorId].Component as NuGetComponent).Name) .Should().NotBeNull(); results.ResultCode.Should().Be(ProcessingResultCode.Success); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - experimentalFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.experimentalFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_ExperimentalDetectorsThrowingDoesntKillDetection() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object, experimentalFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, + this.experimentalFileComponentDetectorMock.Object }; - experimentalFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))) + this.experimentalFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))) .Throws(new InvalidOperationException("Simulated experimental failure")); DetectorProcessingResult results = null; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; }); - var experimentalDetectorRecord = records.FirstOrDefault(x => x.DetectorId == experimentalFileComponentDetectorMock.Object.Id); + var experimentalDetectorRecord = records.FirstOrDefault(x => x.DetectorId == this.experimentalFileComponentDetectorMock.Object.Id); experimentalDetectorRecord.Should().NotBeNull(); experimentalDetectorRecord.DetectedComponentCount.Should().Be(0); experimentalDetectorRecord.IsExperimental.Should().BeTrue(); @@ -310,17 +319,18 @@ public void ProcessDetectorsAsync_ExperimentalDetectorsThrowingDoesntKillDetecti experimentalDetectorRecord.ExperimentalInformation.Contains("Simulated experimental failure"); // We should have all components except the ones that came from our experimental detector - GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount)); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results).Count().Should().Be(records.Sum(x => x.DetectedComponentCount)); results.ResultCode.Should().Be(ProcessingResultCode.Success); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpected() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object }; if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Inconclusive("Test is platform specific and fails on non-windows"); @@ -330,13 +340,13 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpected() var d2 = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "shouldNotExclude", "stuff")); ScanRequest capturedRequest = null; - firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) - .ReturnsAsync(ExpectedResultForDetector(firstFileComponentDetectorMock.Object.Id)) + this.firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) + .ReturnsAsync(this.ExpectedResultForDetector(this.firstFileComponentDetectorMock.Object.Id)) .Callback(request => capturedRequest = request); - serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Wait(); - directoryWalkerFactory.Reset(); + this.directoryWalkerFactory.Reset(); // Base case should match all directories. capturedRequest.DirectoryExclusionPredicate(defaultArgs.SourceDirectory.Name, defaultArgs.SourceDirectory.Parent.Name).Should().BeFalse(); @@ -350,9 +360,9 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpected() }; // Now exercise the exclusion code - serviceUnderTest.ProcessDetectorsAsync(argsWithExclusion, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(argsWithExclusion, this.detectorsToUse, new DetectorRestrictions()).Wait(); - directoryWalkerFactory.Reset(); + this.directoryWalkerFactory.Reset(); // Previous two tests should now exclude capturedRequest.DirectoryExclusionPredicate(defaultArgs.SourceDirectory.Name, defaultArgs.SourceDirectory.Parent.FullName).Should().BeTrue(); @@ -385,46 +395,47 @@ public void GenerateDirectoryExclusionPredicate_IgnoreCaseAndAllowWindowsPathsWo // This unit test previously depended on defaultArgs. But the author assumed that \Source\ was in the default source path, which may not be true on all developers machines. // control this more explicitly. - BcdeArguments args = new BcdeArguments { SourceDirectory = new System.IO.DirectoryInfo(isWin ? @"C:\Some\Source\Directory" : "/c/Some/Source/Directory"), DetectorArgs = Enumerable.Empty() }; + BcdeArguments args = new BcdeArguments { SourceDirectory = new DirectoryInfo(this.isWin ? @"C:\Some\Source\Directory" : "/c/Some/Source/Directory"), DetectorArgs = Enumerable.Empty() }; var dn = args.SourceDirectory.Name.AsSpan(); var dp = args.SourceDirectory.Parent.FullName.AsSpan(); // Exclusion predicate is case sensitive and allow windows path, the exclusion list follow the windows path structure and has a case mismatch with the directory path, should not exclude args.DirectoryExclusionList = new[] { @"**\source\**" }; - var exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); + var exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); Assert.IsFalse(exclusionPredicate(dn, dp)); // Exclusion predicate is case sensitive and allow windows path, the exclusion list follow the windows path structure and match directory path case, should exclude args.DirectoryExclusionList = new[] { @"**\Source\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); Assert.IsTrue(exclusionPredicate(dn, dp)); // Exclusion predicate is not case sensitive and allow windows path, the exclusion list follow the windows path, should exclude args.DirectoryExclusionList = new[] { @"**\sOuRce\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); Assert.IsTrue(exclusionPredicate(dn, dp)); // Exclusion predicate does not support windows path and the exclusion list define the path as a windows path, should not exclude args.DirectoryExclusionList = new[] { @"**\Source\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: true); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: true); Assert.IsFalse(exclusionPredicate(dn, dp)); // Exclusion predicate support windows path and the exclusion list define the path as a windows path, should exclude args.DirectoryExclusionList = new[] { @"**\Source\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); Assert.IsTrue(exclusionPredicate(dn, dp)); // Exclusion predicate support windows path and the exclusion list does not define a windows path, should exclude args.DirectoryExclusionList = new[] { @"**/Source/**", @"**/Source\**" }; - exclusionPredicate = serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); + exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); Assert.IsTrue(exclusionPredicate(dn, dp)); } [TestMethod] public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForObsolete() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object }; var sourceDirectory = defaultSourceDirectory; var args = defaultArgs; var d1 = new DirectoryInfo(Path.Combine(sourceDirectory.FullName, "Child")); @@ -442,13 +453,13 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForO Environment.CurrentDirectory = sourceDirectory.FullName; ScanRequest capturedRequest = null; - firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) - .ReturnsAsync(ExpectedResultForDetector(firstFileComponentDetectorMock.Object.Id)) + this.firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) + .ReturnsAsync(this.ExpectedResultForDetector(this.firstFileComponentDetectorMock.Object.Id)) .Callback(request => capturedRequest = request); - serviceUnderTest.ProcessDetectorsAsync(args, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(args, this.detectorsToUse, new DetectorRestrictions()).Wait(); - directoryWalkerFactory.Reset(); + this.directoryWalkerFactory.Reset(); // Base case should match all directories. capturedRequest.DirectoryExclusionPredicate(args.SourceDirectory.Name.AsSpan(), args.SourceDirectory.Parent.FullName.AsSpan()).Should().BeFalse(); @@ -456,9 +467,10 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForO // Now exercise the exclusion code args.DirectoryExclusionListObsolete = new[] { Path.Combine("Child"), Path.Combine("..", "bin") }; - serviceUnderTest.ProcessDetectorsAsync(args, new[] { firstFileComponentDetectorMock.Object }, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(args, new[] { + this.firstFileComponentDetectorMock.Object }, new DetectorRestrictions()).Wait(); - directoryWalkerFactory.Reset(); + this.directoryWalkerFactory.Reset(); // Previous two tests should now exclude capturedRequest.DirectoryExclusionPredicate(d1.Name.AsSpan(), d1.Parent.FullName.AsSpan()).Should().BeTrue(); @@ -472,36 +484,40 @@ public void ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForO public void ProcessDetectorsAsync_CapturesTelemetry() { BcdeArguments args = defaultArgs; - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object }; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - serviceUnderTest.ProcessDetectorsAsync(args, detectorsToUse, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(args, this.detectorsToUse, new DetectorRestrictions()).Wait(); }); records.Should().Contain(x => x is DetectorExecutionTelemetryRecord); records.Count(x => x is DetectorExecutionTelemetryRecord) .Should().Be(2); - var firstDetectorRecord = records.FirstOrDefault(x => x.DetectorId == firstFileComponentDetectorMock.Object.Id); + var firstDetectorRecord = records.FirstOrDefault(x => x.DetectorId == this.firstFileComponentDetectorMock.Object.Id); firstDetectorRecord.Should().NotBeNull(); firstDetectorRecord.ExecutionTime.Should().BePositive(); - var secondDetectorRecord = records.FirstOrDefault(x => x.DetectorId == secondFileComponentDetectorMock.Object.Id); + var secondDetectorRecord = records.FirstOrDefault(x => x.DetectorId == this.secondFileComponentDetectorMock.Object.Id); secondDetectorRecord.Should().NotBeNull(); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_ExecutesMixedCommandAndFileDetectors() { - detectorsToUse = new[] { firstFileComponentDetectorMock.Object, secondFileComponentDetectorMock.Object, firstCommandComponentDetectorMock.Object, secondCommandComponentDetectorMock.Object }; + this.detectorsToUse = new[] { + this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, + this.firstCommandComponentDetectorMock.Object, + this.secondCommandComponentDetectorMock.Object }; DetectorProcessingResult results = null; var records = TelemetryHelper.ExecuteWhileCapturingTelemetry(() => { - results = serviceUnderTest.ProcessDetectorsAsync(defaultArgs, detectorsToUse, new DetectorRestrictions()).Result; + results = this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, this.detectorsToUse, new DetectorRestrictions()).Result; }); results.Should().NotBeNull("Detector processing failed"); @@ -511,26 +527,27 @@ public void ProcessDetectorsAsync_ExecutesMixedCommandAndFileDetectors() records.Count(x => x is DetectorExecutionTelemetryRecord) .Should().Be(4); - ValidateExpectedComponents(results, detectorsToUse); + this.ValidateExpectedComponents(results, this.detectorsToUse); - firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - firstCommandComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); - secondCommandComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.firstCommandComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); + this.secondCommandComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == defaultArgs.SourceDirectory))); } [TestMethod] public void ProcessDetectorsAsync_HandlesDetectorArgs() { ScanRequest capturedRequest = null; - firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) - .ReturnsAsync(ExpectedResultForDetector(firstFileComponentDetectorMock.Object.Id)) + this.firstFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.IsAny())) + .ReturnsAsync(this.ExpectedResultForDetector(this.firstFileComponentDetectorMock.Object.Id)) .Callback(request => capturedRequest = request); var args = defaultArgs; args.DetectorArgs = new string[] { "arg1=val1", "arg2", "arg3=val3" }; - serviceUnderTest.ProcessDetectorsAsync(defaultArgs, new[] { firstFileComponentDetectorMock.Object }, new DetectorRestrictions()).Wait(); + this.serviceUnderTest.ProcessDetectorsAsync(defaultArgs, new[] { + this.firstFileComponentDetectorMock.Object }, new DetectorRestrictions()).Wait(); capturedRequest.DetectorArgs .Should().Contain("arg1", "val1") diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs index ca6e99487..2485584c6 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs @@ -40,34 +40,38 @@ private Mock GenerateDetector(string detectorName, string[] [TestInitialize] public void TestInitialize() { - logger = new Mock(); - firstDetectorMock = GenerateDetector("FirstDetector"); - secondDetectorMock = GenerateDetector("SecondDetector"); - thirdDetectorMock = GenerateDetector("ThirdDetector"); - retiredNpmDetector = GenerateDetector("MSLicenseDevNpm"); - newNpmDetector = GenerateDetector("NpmWithRoots"); - - detectors = new[] { firstDetectorMock.Object, secondDetectorMock.Object, thirdDetectorMock.Object, retiredNpmDetector.Object, newNpmDetector.Object }; - serviceUnderTest = new DetectorRestrictionService() { Logger = logger.Object }; + this.logger = new Mock(); + this.firstDetectorMock = this.GenerateDetector("FirstDetector"); + this.secondDetectorMock = this.GenerateDetector("SecondDetector"); + this.thirdDetectorMock = this.GenerateDetector("ThirdDetector"); + this.retiredNpmDetector = this.GenerateDetector("MSLicenseDevNpm"); + this.newNpmDetector = this.GenerateDetector("NpmWithRoots"); + + this.detectors = new[] { + this.firstDetectorMock.Object, this.secondDetectorMock.Object, + this.thirdDetectorMock.Object, + this.retiredNpmDetector.Object, + this.newNpmDetector.Object }; + this.serviceUnderTest = new DetectorRestrictionService() { Logger = this.logger.Object }; } [TestMethod] public void WithRestrictions_BaseCaseReturnsAll() { DetectorRestrictions r = new DetectorRestrictions(); - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(detectors); + .Should().Contain(this.detectors); } [TestMethod] public void WithRestrictions_RemovesDefaultOff() { DetectorRestrictions r = new DetectorRestrictions(); - var detectorMock = GenerateDetector("defaultOffDetector"); + var detectorMock = this.GenerateDetector("defaultOffDetector"); var defaultOffDetectorMock = detectorMock.As(); - detectors = detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + this.detectors = this.detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().NotContain(defaultOffDetectorMock.Object as IComponentDetector); } @@ -76,11 +80,11 @@ public void WithRestrictions_RemovesDefaultOff() public void WithRestrictions_AllowsDefaultOffWithDetectorRestriction() { DetectorRestrictions r = new DetectorRestrictions(); - var detectorMock = GenerateDetector("defaultOffDetector"); + var detectorMock = this.GenerateDetector("defaultOffDetector"); var defaultOffDetectorMock = detectorMock.As(); - detectors = detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); + this.detectors = this.detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); r.ExplicitlyEnabledDetectorIds = new[] { "defaultOffDetector" }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().Contain(defaultOffDetectorMock.Object as IComponentDetector); } @@ -92,13 +96,13 @@ public void WithRestrictions_FiltersBasedOnDetectorId() { AllowedDetectorIds = new[] { "FirstDetector", "SecondDetector" }, }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(firstDetectorMock.Object).And.Contain(secondDetectorMock.Object) - .And.NotContain(thirdDetectorMock.Object); + .Should().Contain(this.firstDetectorMock.Object).And.Contain(this.secondDetectorMock.Object) + .And.NotContain(this.thirdDetectorMock.Object); r.AllowedDetectorIds = new[] { "NotARealDetector" }; - Action shouldThrow = () => serviceUnderTest.ApplyRestrictions(r, detectors); + Action shouldThrow = () => this.serviceUnderTest.ApplyRestrictions(r, this.detectors); shouldThrow.Should().Throw(); } @@ -109,19 +113,19 @@ public void WithRestrictions_CorrectsRetiredDetector() { AllowedDetectorIds = new[] { "MSLicenseDevNpm" }, }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(newNpmDetector.Object); + .Should().Contain(this.newNpmDetector.Object); r.AllowedDetectorIds = new[] { "mslicensenpm" }; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(newNpmDetector.Object); + .Should().Contain(this.newNpmDetector.Object); r.AllowedDetectorIds = new[] { "mslicensenpm", "NpmWithRoots" }; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().OnlyContain(item => item == newNpmDetector.Object); + .Should().OnlyContain(item => item == this.newNpmDetector.Object); } [TestMethod] @@ -131,20 +135,20 @@ public void WithRestrictions_FiltersBasedOnCategory() { AllowedDetectorCategories = new[] { "FirstDetectorCategory", "ThirdDetectorCategory" }, }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(firstDetectorMock.Object).And.Contain(thirdDetectorMock.Object) - .And.NotContain(secondDetectorMock.Object); + .Should().Contain(this.firstDetectorMock.Object).And.Contain(this.thirdDetectorMock.Object) + .And.NotContain(this.secondDetectorMock.Object); r.AllowedDetectorCategories = new[] { "AllCategory" }; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors - .Should().Contain(firstDetectorMock.Object) - .And.Contain(thirdDetectorMock.Object) - .And.Contain(secondDetectorMock.Object); + .Should().Contain(this.firstDetectorMock.Object) + .And.Contain(this.thirdDetectorMock.Object) + .And.Contain(this.secondDetectorMock.Object); r.AllowedDetectorCategories = new[] { "NoCategory" }; - Action shouldThrow = () => serviceUnderTest.ApplyRestrictions(r, detectors); + Action shouldThrow = () => this.serviceUnderTest.ApplyRestrictions(r, this.detectors); shouldThrow.Should().Throw(); } @@ -153,30 +157,30 @@ public void WithRestrictions_AlwaysIncludesDetectorsThatSpecifyAllCategory() { var detectors = new[] { - GenerateDetector("1", new[] { "Cat1" }).Object, - GenerateDetector("2", new[] { "Cat2" }).Object, - GenerateDetector("3", new[] { nameof(DetectorClass.All) }).Object, + this.GenerateDetector("1", new[] { "Cat1" }).Object, + this.GenerateDetector("2", new[] { "Cat2" }).Object, + this.GenerateDetector("3", new[] { nameof(DetectorClass.All) }).Object, }; var r = new DetectorRestrictions { AllowedDetectorCategories = new[] { "ACategoryWhichDoesntMatch" }, }; - var restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, detectors); restrictedDetectors .Should().Contain(detectors[2]) .And.NotContain(detectors[0]) .And.NotContain(detectors[1]); r.AllowedDetectorCategories = new[] { "Cat1" }; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, detectors); restrictedDetectors .Should().Contain(detectors[0]) .And.Contain(detectors[2]) .And.NotContain(detectors[1]); r.AllowedDetectorCategories = null; - restrictedDetectors = serviceUnderTest.ApplyRestrictions(r, detectors); + restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, detectors); restrictedDetectors .Should().Contain(detectors[0]) .And.Contain(detectors[1]) diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs b/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs index a740dab49..b2bf5bdc8 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs +++ b/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtility.cs @@ -30,23 +30,23 @@ public class DetectorTestUtility public async Task<(IndividualDetectorScanResult, IComponentRecorder)> ExecuteDetector() { - if (scanRequest == null) + if (this.scanRequest == null) { - scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, componentRecorder); + this.scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), null, null, new Dictionary(), null, this.componentRecorder); } else { - componentRecorder = scanRequest.ComponentRecorder; + this.componentRecorder = this.scanRequest.ComponentRecorder; } - InitializeFileRelatedMocksUsingDefaultImplementationIfNecessary(); + this.InitializeFileRelatedMocksUsingDefaultImplementationIfNecessary(); - detector.Scanner = mockObservableDirectoryWalkerFactory.Object; - detector.ComponentStreamEnumerableFactory = mockComponentStreamEnumerableFactory.Object; - detector.Logger = mockLogger.Object; + this.detector.Scanner = this.mockObservableDirectoryWalkerFactory.Object; + this.detector.ComponentStreamEnumerableFactory = this.mockComponentStreamEnumerableFactory.Object; + this.detector.Logger = this.mockLogger.Object; - var scanResult = await detector.ExecuteDetectorAsync(scanRequest); - return (scanResult, componentRecorder); + var scanResult = await this.detector.ExecuteDetectorAsync(this.scanRequest); + return (scanResult, this.componentRecorder); } /// @@ -75,7 +75,7 @@ public DetectorTestUtility WithScanRequest(ScanRequest scanRequest) public DetectorTestUtility WithFile(string fileName, string fileContents, IEnumerable searchPatterns = null, string fileLocation = null) { - return WithFile(fileName, fileContents.ToStream(), searchPatterns, fileLocation); + return this.WithFile(fileName, fileContents.ToStream(), searchPatterns, fileLocation); } public DetectorTestUtility WithFile(string fileName, Stream fileContents, IEnumerable searchPatterns = null, string fileLocation = null) @@ -87,23 +87,23 @@ public DetectorTestUtility WithFile(string fileName, Stream fileContents, IEn if (searchPatterns == null || !searchPatterns.Any()) { - searchPatterns = detector.SearchPatterns; + searchPatterns = this.detector.SearchPatterns; } - filesToAdd.Add((fileName, fileContents, fileLocation, searchPatterns)); + this.filesToAdd.Add((fileName, fileContents, fileLocation, searchPatterns)); return this; } public DetectorTestUtility WithComponentStreamEnumerableFactory(Mock mock) { - mockComponentStreamEnumerableFactory = mock; + this.mockComponentStreamEnumerableFactory = mock; return this; } public DetectorTestUtility WithObservableDirectoryWalkerFactory(Mock mock) { - mockObservableDirectoryWalkerFactory = mock; + this.mockObservableDirectoryWalkerFactory = mock; return this; } @@ -111,7 +111,7 @@ private ProcessRequest CreateProcessRequest(string pattern, string filePath, Str { return new ProcessRequest { - SingleFileComponentRecorder = componentRecorder.CreateSingleFileComponentRecorder(filePath), + SingleFileComponentRecorder = this.componentRecorder.CreateSingleFileComponentRecorder(filePath), ComponentStream = CreateComponentStreamForFile(pattern, filePath, content), }; } @@ -130,33 +130,33 @@ private void InitializeFileRelatedMocksUsingDefaultImplementationIfNecessary() { bool useDefaultObservableDirectoryWalkerFactory = false, useDefaultComponentStreamEnumerableFactory = false; - if (mockObservableDirectoryWalkerFactory == null) + if (this.mockObservableDirectoryWalkerFactory == null) { useDefaultObservableDirectoryWalkerFactory = true; - mockObservableDirectoryWalkerFactory = new Mock(); + this.mockObservableDirectoryWalkerFactory = new Mock(); } - if (mockComponentStreamEnumerableFactory == null) + if (this.mockComponentStreamEnumerableFactory == null) { useDefaultComponentStreamEnumerableFactory = true; - mockComponentStreamEnumerableFactory = new Mock(); + this.mockComponentStreamEnumerableFactory = new Mock(); } - if (!filesToAdd.Any() && useDefaultObservableDirectoryWalkerFactory) + if (!this.filesToAdd.Any() && useDefaultObservableDirectoryWalkerFactory) { - mockObservableDirectoryWalkerFactory.Setup(x => - x.GetFilteredComponentStreamObservable(It.IsAny(), detector.SearchPatterns, It.IsAny())) + this.mockObservableDirectoryWalkerFactory.Setup(x => + x.GetFilteredComponentStreamObservable(It.IsAny(), this.detector.SearchPatterns, It.IsAny())) .Returns(Enumerable.Empty().ToObservable()); } - if (!filesToAdd.Any() && useDefaultComponentStreamEnumerableFactory) + if (!this.filesToAdd.Any() && useDefaultComponentStreamEnumerableFactory) { - mockComponentStreamEnumerableFactory.Setup(x => - x.GetComponentStreams(It.IsAny(), detector.SearchPatterns, It.IsAny(), It.IsAny())) + this.mockComponentStreamEnumerableFactory.Setup(x => + x.GetComponentStreams(It.IsAny(), this.detector.SearchPatterns, It.IsAny(), It.IsAny())) .Returns(Enumerable.Empty()); } - var filesGroupedBySearchPattern = filesToAdd.GroupBy(filesToAdd => filesToAdd.searchPatterns, new EnumerableStringComparer()); + var filesGroupedBySearchPattern = this.filesToAdd.GroupBy(filesToAdd => filesToAdd.searchPatterns, new EnumerableStringComparer()); foreach (var group in filesGroupedBySearchPattern) { var searchPatterns = group.Key; @@ -164,48 +164,48 @@ private void InitializeFileRelatedMocksUsingDefaultImplementationIfNecessary() if (useDefaultObservableDirectoryWalkerFactory) { - mockObservableDirectoryWalkerFactory.Setup(x => + this.mockObservableDirectoryWalkerFactory.Setup(x => x.GetFilteredComponentStreamObservable(It.IsAny(), searchPatterns, It.IsAny())) .Returns, IComponentRecorder>((directoryInfo, searchPatterns, componentRecorder) => { return filesToSend - .Select(fileToSend => CreateProcessRequest(FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).ToObservable(); + .Select(fileToSend => this.CreateProcessRequest(this.FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).ToObservable(); }); } if (useDefaultComponentStreamEnumerableFactory) { - mockComponentStreamEnumerableFactory.Setup(x => + this.mockComponentStreamEnumerableFactory.Setup(x => x.GetComponentStreams(It.IsAny(), searchPatterns, It.IsAny(), It.IsAny())) .Returns, ExcludeDirectoryPredicate, bool>((directoryInfo, searchPatterns, excludeDirectoryPredicate, recurse) => { if (recurse) { return filesToSend - .Select(fileToSend => CreateProcessRequest(FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).Select(pr => pr.ComponentStream); + .Select(fileToSend => this.CreateProcessRequest(this.FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).Select(pr => pr.ComponentStream); } else { return filesToSend .Where(fileToSend => Directory.GetParent(fileToSend.Location).FullName == directoryInfo.FullName) - .Select(fileToSend => CreateProcessRequest(FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).Select(pr => pr.ComponentStream); + .Select(fileToSend => this.CreateProcessRequest(this.FindMatchingPattern(fileToSend.Name, searchPatterns), fileToSend.Location, fileToSend.Contents)).Select(pr => pr.ComponentStream); } }); } } - var providedDetectorSearchPatterns = filesGroupedBySearchPattern.Any(group => group.Key.SequenceEqual(detector.SearchPatterns)); + var providedDetectorSearchPatterns = filesGroupedBySearchPattern.Any(group => group.Key.SequenceEqual(this.detector.SearchPatterns)); if (!providedDetectorSearchPatterns && useDefaultObservableDirectoryWalkerFactory) { - mockObservableDirectoryWalkerFactory.Setup(x => - x.GetFilteredComponentStreamObservable(It.IsAny(), detector.SearchPatterns, It.IsAny())) + this.mockObservableDirectoryWalkerFactory.Setup(x => + x.GetFilteredComponentStreamObservable(It.IsAny(), this.detector.SearchPatterns, It.IsAny())) .Returns(new List().ToObservable()); } if (!providedDetectorSearchPatterns && useDefaultComponentStreamEnumerableFactory) { - mockComponentStreamEnumerableFactory.Setup(x => - x.GetComponentStreams(It.IsAny(), detector.SearchPatterns, It.IsAny(), It.IsAny())) + this.mockComponentStreamEnumerableFactory.Setup(x => + x.GetComponentStreams(It.IsAny(), this.detector.SearchPatterns, It.IsAny(), It.IsAny())) .Returns(new List()); } }