diff --git a/Directory.Packages.props b/Directory.Packages.props index 37c5d28d..5f279626 100644 --- a/Directory.Packages.props +++ b/Directory.Packages.props @@ -52,7 +52,6 @@ - diff --git a/src/Microsoft.ComponentDetection.Common/Column.cs b/src/Microsoft.ComponentDetection.Common/Column.cs index 4554f71c..4ce0cac2 100644 --- a/src/Microsoft.ComponentDetection.Common/Column.cs +++ b/src/Microsoft.ComponentDetection.Common/Column.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; public class Column { diff --git a/src/Microsoft.ComponentDetection.Common/ComponentComparer.cs b/src/Microsoft.ComponentDetection.Common/ComponentComparer.cs index fcb9485c..8e03c910 100644 --- a/src/Microsoft.ComponentDetection.Common/ComponentComparer.cs +++ b/src/Microsoft.ComponentDetection.Common/ComponentComparer.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using System.Collections.Generic; using Microsoft.ComponentDetection.Contracts.TypedComponent; diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStream.cs b/src/Microsoft.ComponentDetection.Common/ComponentStream.cs index f9f0d9e8..8c18db62 100644 --- a/src/Microsoft.ComponentDetection.Common/ComponentStream.cs +++ b/src/Microsoft.ComponentDetection.Common/ComponentStream.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using System.IO; using Microsoft.ComponentDetection.Contracts; diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs index 7afd066f..ade05d0e 100644 --- a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs +++ b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerable.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using System; using System.Collections; diff --git a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs index 18030d77..318394f2 100644 --- a/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs +++ b/src/Microsoft.ComponentDetection.Common/ComponentStreamEnumerableFactory.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs b/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs index 0ebbe87f..8f58b3bc 100644 --- a/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs +++ b/src/Microsoft.ComponentDetection.Common/DependencyGraph/ComponentRecorder.cs @@ -172,12 +172,12 @@ public class ComponentRecorder : IComponentRecorder #if DEBUG if (detectedComponent.DependencyRoots is null || detectedComponent.DependencyRoots.Count == 0) { - this.logger.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!"); + this.logger?.LogWarning("Detector should not populate DetectedComponent.DependencyRoots!"); } if (detectedComponent.DevelopmentDependency.HasValue) { - this.logger.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!"); + this.logger?.LogWarning("Detector should not populate DetectedComponent.DevelopmentDependency!"); } #endif diff --git a/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs b/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs index 6cf6fafe..79a0090a 100644 --- a/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs +++ b/src/Microsoft.ComponentDetection.Common/DependencyScopeComparer.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using Microsoft.ComponentDetection.Contracts.BcdeModels; diff --git a/src/Microsoft.ComponentDetection.Common/DirectoryItemFacade.cs b/src/Microsoft.ComponentDetection.Common/DirectoryItemFacade.cs index 13e388f6..06dc4115 100644 --- a/src/Microsoft.ComponentDetection.Common/DirectoryItemFacade.cs +++ b/src/Microsoft.ComponentDetection.Common/DirectoryItemFacade.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using System.Collections.Generic; using System.Diagnostics; diff --git a/src/Microsoft.ComponentDetection.Common/IConsoleWritingService.cs b/src/Microsoft.ComponentDetection.Common/IConsoleWritingService.cs index 4a62593f..83d70634 100644 --- a/src/Microsoft.ComponentDetection.Common/IConsoleWritingService.cs +++ b/src/Microsoft.ComponentDetection.Common/IConsoleWritingService.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; public interface IConsoleWritingService { diff --git a/src/Microsoft.ComponentDetection.Common/ISafeFileEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Common/ISafeFileEnumerableFactory.cs index 98588d34..5cd277f4 100644 --- a/src/Microsoft.ComponentDetection.Common/ISafeFileEnumerableFactory.cs +++ b/src/Microsoft.ComponentDetection.Common/ISafeFileEnumerableFactory.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using System.Collections.Generic; using System.IO; diff --git a/src/Microsoft.ComponentDetection.Common/MatchedFile.cs b/src/Microsoft.ComponentDetection.Common/MatchedFile.cs index ec66ea8e..8b8b6cc6 100644 --- a/src/Microsoft.ComponentDetection.Common/MatchedFile.cs +++ b/src/Microsoft.ComponentDetection.Common/MatchedFile.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using System.IO; diff --git a/src/Microsoft.ComponentDetection.Common/ScanType.cs b/src/Microsoft.ComponentDetection.Common/ScanType.cs index b61f7c87..b3a2d696 100644 --- a/src/Microsoft.ComponentDetection.Common/ScanType.cs +++ b/src/Microsoft.ComponentDetection.Common/ScanType.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; public enum ScanType { diff --git a/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs b/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs index 07ad56fc..d60f5647 100644 --- a/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs +++ b/src/Microsoft.ComponentDetection.Common/TabularStringFormat.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/MetricAttribute.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/MetricAttribute.cs index 6a8f1b90..e6ee53a2 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/MetricAttribute.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Attributes/MetricAttribute.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes; +namespace Microsoft.ComponentDetection.Common.Telemetry.Attributes; using System; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs index 0d537c52..7fc21dc2 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/CommandLineTelemetryService.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry; +namespace Microsoft.ComponentDetection.Common.Telemetry; using System; using System.Collections.Concurrent; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/ITelemetryService.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/ITelemetryService.cs index e6251350..370c13d4 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/ITelemetryService.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/ITelemetryService.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry; +namespace Microsoft.ComponentDetection.Common.Telemetry; using Microsoft.ComponentDetection.Common.Telemetry.Records; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs index 8ba43a9e..be340269 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BaseDetectionTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; using System; using System.Diagnostics; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BcdeExecutionTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BcdeExecutionTelemetryRecord.cs index ab67b8d2..69aefc6a 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BcdeExecutionTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/BcdeExecutionTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; using System; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs index a26f840b..e4745f7f 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/CommandLineInvocationTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; using System; using Microsoft.ComponentDetection.Contracts; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs index 4a2aaa8e..94c43727 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectedComponentScopeRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; using System.Runtime.CompilerServices; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectorExecutionTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectorExecutionTelemetryRecord.cs index 4c9060b5..cbed3d3b 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectorExecutionTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/DetectorExecutionTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class DetectorExecutionTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/GoGraphTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/GoGraphTelemetryRecord.cs index bef83e60..1edaf2a1 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/GoGraphTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/GoGraphTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class GoGraphTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/IDetectionTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/IDetectionTelemetryRecord.cs index 27d072bc..2056aff1 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/IDetectionTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/IDetectionTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; using System; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorImageDetectionFailed.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorImageDetectionFailed.cs index 774706cf..5da8f7e9 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorImageDetectionFailed.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorImageDetectionFailed.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class LinuxContainerDetectorImageDetectionFailed : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingRepoNameAndTagRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingRepoNameAndTagRecord.cs index 132c30c6..6d64ae1a 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingRepoNameAndTagRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingRepoNameAndTagRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class LinuxContainerDetectorMissingRepoNameAndTagRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs index abe41459..d4133c8a 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorMissingVersion.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class LinuxContainerDetectorMissingVersion : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorTimeout.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorTimeout.cs index 9ddc38a8..4e91d612 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorTimeout.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorTimeout.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class LinuxContainerDetectorTimeout : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorUnsupportedOs.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorUnsupportedOs.cs index d6758426..59b61bd0 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorUnsupportedOs.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxContainerDetectorUnsupportedOs.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class LinuxContainerDetectorUnsupportedOs : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs index 46d343ee..b5d7ab5d 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LinuxScannerTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class LinuxScannerTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs index f85d80e2..019ac304 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/LoadComponentDetectorsTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class LoadComponentDetectorsTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs index fd2c16e6..3759a402 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/NuGetProjectAssetsTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; using System; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs index 28093d45..ff0a5920 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PyPiCacheTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class PypiCacheTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiFailureTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiFailureTelemetryRecord.cs index 5f78a246..834d02d1 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiFailureTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiFailureTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; using System.Net; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiMaxRetriesReachedTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiMaxRetriesReachedTelemetryRecord.cs index 5b0fd92f..e49973c5 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiMaxRetriesReachedTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiMaxRetriesReachedTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class PypiMaxRetriesReachedTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiRetryTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiRetryTelemetryRecord.cs index 15552b8e..d60d18a0 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiRetryTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/PypiRetryTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; using System.Net; diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/RustCrateDetectorTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/RustCrateDetectorTelemetryRecord.cs index 08d3c8e4..9ee6ef2c 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/RustCrateDetectorTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/RustCrateDetectorTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class RustCrateDetectorTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/RustGraphTelemetryRecord.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/RustGraphTelemetryRecord.cs index 0b09cc9e..92d92ef5 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/Records/RustGraphTelemetryRecord.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/Records/RustGraphTelemetryRecord.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry.Records; +namespace Microsoft.ComponentDetection.Common.Telemetry.Records; public class RustGraphTelemetryRecord : BaseDetectionTelemetryRecord { diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/TelemetryConstants.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/TelemetryConstants.cs index 96c1c76b..1ba30666 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/TelemetryConstants.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/TelemetryConstants.cs @@ -1,4 +1,4 @@ -using System; +using System; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("Microsoft.ComponentDetection.Orchestrator")] diff --git a/src/Microsoft.ComponentDetection.Common/Telemetry/TelemetryMode.cs b/src/Microsoft.ComponentDetection.Common/Telemetry/TelemetryMode.cs index 1d628596..f68cc670 100644 --- a/src/Microsoft.ComponentDetection.Common/Telemetry/TelemetryMode.cs +++ b/src/Microsoft.ComponentDetection.Common/Telemetry/TelemetryMode.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Telemetry; +namespace Microsoft.ComponentDetection.Common.Telemetry; public enum TelemetryMode { diff --git a/src/Microsoft.ComponentDetection.Common/WarnOnAlertSeverity.cs b/src/Microsoft.ComponentDetection.Common/WarnOnAlertSeverity.cs index 65ceab80..a66601bf 100644 --- a/src/Microsoft.ComponentDetection.Common/WarnOnAlertSeverity.cs +++ b/src/Microsoft.ComponentDetection.Common/WarnOnAlertSeverity.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common; +namespace Microsoft.ComponentDetection.Common; public enum WarnOnAlertSeverity { diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs index 331830cb..ac3ea4ed 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/ContainerDetails.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.BcdeModels; +namespace Microsoft.ComponentDetection.Contracts.BcdeModels; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DefaultGraphScanResult.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DefaultGraphScanResult.cs index 7e07692d..e009f2ee 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DefaultGraphScanResult.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DefaultGraphScanResult.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.BcdeModels; +namespace Microsoft.ComponentDetection.Contracts.BcdeModels; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraph.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraph.cs index 06ebbf31..c98abf0c 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraph.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraph.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.BcdeModels; +namespace Microsoft.ComponentDetection.Contracts.BcdeModels; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraphCollection.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraphCollection.cs index b1ccaced..f384d97d 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraphCollection.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraphCollection.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.BcdeModels; +namespace Microsoft.ComponentDetection.Contracts.BcdeModels; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraphWithMetadata.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraphWithMetadata.cs index 2358cb9e..b850ff67 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraphWithMetadata.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyGraphWithMetadata.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.BcdeModels; +namespace Microsoft.ComponentDetection.Contracts.BcdeModels; using System.Collections.Generic; using Newtonsoft.Json; diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs index 6fa95e39..bbb56ab9 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/DependencyScope.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.BcdeModels; +namespace Microsoft.ComponentDetection.Contracts.BcdeModels; /// Used to communicate Dependency Scope of Component. /// Currently only populated for Maven component. diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/Detector.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/Detector.cs index f350eb56..b2636cf0 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/Detector.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/Detector.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.BcdeModels; +namespace Microsoft.ComponentDetection.Contracts.BcdeModels; using System.Collections.Generic; using Microsoft.ComponentDetection.Contracts.TypedComponent; diff --git a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs index 0ed8aa09..4e15e897 100644 --- a/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs +++ b/src/Microsoft.ComponentDetection.Contracts/BcdeModels/TypedComponentConverter.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.BcdeModels; +namespace Microsoft.ComponentDetection.Contracts.BcdeModels; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs b/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs index 3da44b17..cde85fd5 100644 --- a/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs +++ b/src/Microsoft.ComponentDetection.Contracts/DetectorClass.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts; +namespace Microsoft.ComponentDetection.Contracts; /// Class of detector, the names of which are converted into categories for all default detectors. public enum DetectorClass diff --git a/src/Microsoft.ComponentDetection.Contracts/IComponentStream.cs b/src/Microsoft.ComponentDetection.Contracts/IComponentStream.cs index 2660e18d..c5abf722 100644 --- a/src/Microsoft.ComponentDetection.Contracts/IComponentStream.cs +++ b/src/Microsoft.ComponentDetection.Contracts/IComponentStream.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts; +namespace Microsoft.ComponentDetection.Contracts; using System.IO; diff --git a/src/Microsoft.ComponentDetection.Contracts/IComponentStreamEnumerableFactory.cs b/src/Microsoft.ComponentDetection.Contracts/IComponentStreamEnumerableFactory.cs index 66de20f7..9f317442 100644 --- a/src/Microsoft.ComponentDetection.Contracts/IComponentStreamEnumerableFactory.cs +++ b/src/Microsoft.ComponentDetection.Contracts/IComponentStreamEnumerableFactory.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts; +namespace Microsoft.ComponentDetection.Contracts; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Contracts/IObservableDirectoryWalkerFactory.cs b/src/Microsoft.ComponentDetection.Contracts/IObservableDirectoryWalkerFactory.cs index 50db2a92..45a06fbc 100644 --- a/src/Microsoft.ComponentDetection.Contracts/IObservableDirectoryWalkerFactory.cs +++ b/src/Microsoft.ComponentDetection.Contracts/IObservableDirectoryWalkerFactory.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts; +namespace Microsoft.ComponentDetection.Contracts; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs b/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs index e421fa35..7dd6ab3b 100644 --- a/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs +++ b/src/Microsoft.ComponentDetection.Contracts/Internal/NpmAuthor.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.Internal; +namespace Microsoft.ComponentDetection.Contracts.Internal; using System; diff --git a/src/Microsoft.ComponentDetection.Contracts/Internal/ProcessRequest.cs b/src/Microsoft.ComponentDetection.Contracts/Internal/ProcessRequest.cs index d878396f..1a727f80 100644 --- a/src/Microsoft.ComponentDetection.Contracts/Internal/ProcessRequest.cs +++ b/src/Microsoft.ComponentDetection.Contracts/Internal/ProcessRequest.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.Internal; +namespace Microsoft.ComponentDetection.Contracts.Internal; public class ProcessRequest { diff --git a/src/Microsoft.ComponentDetection.Contracts/KillSwitchConfiguration.cs b/src/Microsoft.ComponentDetection.Contracts/KillSwitchConfiguration.cs index 04fe243e..107539ec 100644 --- a/src/Microsoft.ComponentDetection.Contracts/KillSwitchConfiguration.cs +++ b/src/Microsoft.ComponentDetection.Contracts/KillSwitchConfiguration.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts; +namespace Microsoft.ComponentDetection.Contracts; /// /// Represents the configuration for the kill switch. diff --git a/src/Microsoft.ComponentDetection.Contracts/ProcessingResultCode.cs b/src/Microsoft.ComponentDetection.Contracts/ProcessingResultCode.cs index 4d2e9c8a..9836d635 100644 --- a/src/Microsoft.ComponentDetection.Contracts/ProcessingResultCode.cs +++ b/src/Microsoft.ComponentDetection.Contracts/ProcessingResultCode.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts; +namespace Microsoft.ComponentDetection.Contracts; /// Code used to communicate the state of a scan after completion. public enum ProcessingResultCode diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComponentType.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComponentType.cs index 371ad836..3d3593c7 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComponentType.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/ComponentType.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; using System.Runtime.Serialization; diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs index 3ffc1956..04edb3f7 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/CondaComponent.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; public class CondaComponent : TypedComponent { diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs index d41cf5cf..aeee1683 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GitComponent.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; using System; diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs index dcb9066a..6246ef70 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/GoComponent.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; using System; using PackageUrl; diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs index 0e77a77b..b0273065 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/MavenComponent.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; using PackageUrl; diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs index 427370b4..e758eeda 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NpmComponent.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Contracts.Internal; using PackageUrl; diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs index 8ba4dfd5..dad78752 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/NugetComponent.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; using PackageUrl; diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs index ca02e5cc..63b00d3c 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/PodComponent.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; using System.Collections.Generic; using PackageUrl; diff --git a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs index 6fa8475e..c4328bfb 100644 --- a/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs +++ b/src/Microsoft.ComponentDetection.Contracts/TypedComponent/SpdxComponent.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.TypedComponent; +namespace Microsoft.ComponentDetection.Contracts.TypedComponent; using System; diff --git a/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs index ecd6091a..491a3a0c 100644 --- a/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/cocoapods/PodComponentDetector.cs @@ -29,11 +29,11 @@ public class PodComponentDetector : FileComponentDetector public override string Id { get; } = "CocoaPods"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.CocoaPods) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.CocoaPods)]; - public override IList SearchPatterns { get; } = new List { "Podfile.lock" }; + public override IList SearchPatterns { get; } = ["Podfile.lock"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Pod, ComponentType.Git }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Pod, ComponentType.Git]; public override int Version { get; } = 2; @@ -225,7 +225,7 @@ public class PodComponentDetector : FileComponentDetector foreach (var pod in podDependencies) { // Add all the dependencies to the map, without duplicates - dependenciesMap.TryAdd(pod.Key, new HashSet()); + dependenciesMap.TryAdd(pod.Key, []); foreach (var dependency in pod.Value) { diff --git a/src/Microsoft.ComponentDetection.Detectors/conan/ConanLockComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/conan/ConanLockComponentDetector.cs index 232615b4..21d622d5 100644 --- a/src/Microsoft.ComponentDetection.Detectors/conan/ConanLockComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/conan/ConanLockComponentDetector.cs @@ -26,13 +26,13 @@ public class ConanLockComponentDetector : FileComponentDetector, IDefaultOffComp public override string Id => "ConanLock"; - public override IList SearchPatterns => new List { "conan.lock" }; + public override IList SearchPatterns => ["conan.lock"]; - public override IEnumerable SupportedComponentTypes => new[] { ComponentType.Conan }; + public override IEnumerable SupportedComponentTypes => [ComponentType.Conan]; public override int Version { get; } = 1; - public override IEnumerable Categories => new List { "Conan" }; + public override IEnumerable Categories => ["Conan"]; protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) { @@ -52,9 +52,8 @@ public class ConanLockComponentDetector : FileComponentDetector, IDefaultOffComp var packagesDictionary = conanLock.GraphLock.Nodes; var explicitReferencedDependencies = new HashSet(); var developmentDependencies = new HashSet(); - if (packagesDictionary.ContainsKey("0")) + if (packagesDictionary.Remove("0", out var rootNode)) { - packagesDictionary.Remove("0", out var rootNode); if (rootNode?.Requires != null) { explicitReferencedDependencies = new HashSet(rootNode.Requires); diff --git a/src/Microsoft.ComponentDetection.Detectors/conda/CondaDependencyResolver.cs b/src/Microsoft.ComponentDetection.Detectors/conda/CondaDependencyResolver.cs index 60ffb84b..64a442fc 100644 --- a/src/Microsoft.ComponentDetection.Detectors/conda/CondaDependencyResolver.cs +++ b/src/Microsoft.ComponentDetection.Detectors/conda/CondaDependencyResolver.cs @@ -28,7 +28,7 @@ public static class CondaDependencyResolver public static void UpdateDirectlyReferencedPackages(ISingleFileComponentRecorder singleFileComponentRecorder) => singleFileComponentRecorder.GetDetectedComponents().Keys.ForEach(componentId => { - if (!singleFileComponentRecorder.DependencyGraph.GetAncestors(componentId).Any()) + if (singleFileComponentRecorder.DependencyGraph.GetAncestors(componentId).Count == 0) { singleFileComponentRecorder.RegisterUsage( singleFileComponentRecorder.GetComponent(componentId), @@ -100,7 +100,7 @@ public static class CondaDependencyResolver /// A list of packages without dependencies. private static List GetPackages(CondaLock condaLock) => condaLock?.Package == null - ? new List() + ? [] : condaLock.Package; /// diff --git a/src/Microsoft.ComponentDetection.Detectors/conda/CondaLockComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/conda/CondaLockComponentDetector.cs index db0a1269..6a5ab362 100644 --- a/src/Microsoft.ComponentDetection.Detectors/conda/CondaLockComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/conda/CondaLockComponentDetector.cs @@ -27,13 +27,13 @@ public class CondaLockComponentDetector : FileComponentDetector, IDefaultOffComp public override string Id => "CondaLock"; - public override IList SearchPatterns { get; } = new List { "conda-lock.yml", "*.conda-lock.yml" }; + public override IList SearchPatterns { get; } = ["conda-lock.yml", "*.conda-lock.yml"]; - public override IEnumerable SupportedComponentTypes => new[] { ComponentType.Conda, ComponentType.Pip }; + public override IEnumerable SupportedComponentTypes => [ComponentType.Conda, ComponentType.Pip]; public override int Version { get; } = 2; - public override IEnumerable Categories => new List { "Python" }; + public override IEnumerable Categories => ["Python"]; /// protected override Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) diff --git a/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs index 65921192..7826a382 100644 --- a/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/dockerfile/DockerfileComponentDetector.cs @@ -35,11 +35,11 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom public override string Id { get; } = "DockerReference"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.DockerReference) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.DockerReference)]; - public override IList SearchPatterns { get; } = new List { "dockerfile", "dockerfile.*", "*.dockerfile" }; + public override IList SearchPatterns { get; } = ["dockerfile", "dockerfile.*", "*.dockerfile"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.DockerReference }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.DockerReference]; public override int Version => 1; @@ -55,7 +55,7 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom string contents; using (var reader = new StreamReader(file.Stream)) { - contents = await reader.ReadToEndAsync(); + contents = await reader.ReadToEndAsync(cancellationToken); } var stageNameMap = new Dictionary(); @@ -69,7 +69,7 @@ public class DockerfileComponentDetector : FileComponentDetector, IDefaultOffCom private Task ParseDockerFileAsync(string fileContents, string fileLocation, ISingleFileComponentRecorder singleFileComponentRecorder, Dictionary stageNameMap) { - var dockerfileModel = Valleysoft.DockerfileModel.Dockerfile.Parse(fileContents); + var dockerfileModel = Dockerfile.Parse(fileContents); var instructions = dockerfileModel.Items; foreach (var instruction in instructions) { diff --git a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs index 523a784c..abfd9b70 100644 --- a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentDetector.cs @@ -23,7 +23,7 @@ public class GoComponentDetector : FileComponentDetector @"(?.*)\s+(?.*?)(/go\.mod)?\s+(?.*)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase); - private readonly HashSet projectRoots = new(); + private readonly HashSet projectRoots = []; private readonly ICommandLineInvocationService commandLineInvocationService; private readonly IEnvironmentVariableService envVarService; @@ -44,11 +44,11 @@ public class GoComponentDetector : FileComponentDetector public override string Id => "Go"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod)]; - public override IList SearchPatterns { get; } = new List { "go.mod", "go.sum" }; + public override IList SearchPatterns { get; } = ["go.mod", "go.sum"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Go }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Go]; public override int Version => 7; @@ -90,7 +90,7 @@ public class GoComponentDetector : FileComponentDetector private IEnumerable FindAdjacentGoModComponentStreams(ProcessRequest processRequest) => this.ComponentStreamEnumerableFactory.GetComponentStreams( new FileInfo(processRequest.ComponentStream.Location).Directory, - new[] { "go.mod" }, + ["go.mod"], (_, _) => false, false) .Select(x => @@ -224,7 +224,7 @@ public class GoComponentDetector : FileComponentDetector var projectRootDirectory = Directory.GetParent(location); record.ProjectRoot = projectRootDirectory.FullName; - var isGoAvailable = await this.commandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, new[] { "version" }); + var isGoAvailable = await this.commandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, ["version"]); record.IsGoAvailable = isGoAvailable; if (!isGoAvailable) @@ -236,7 +236,7 @@ public class GoComponentDetector : FileComponentDetector this.Logger.LogInformation("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.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-mod=readonly", "-m", "-json", "all" }); + var goDependenciesProcess = await this.commandLineInvocationService.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, ["list", "-mod=readonly", "-m", "-json", "all"]); if (goDependenciesProcess.ExitCode != 0) { this.Logger.LogError("Go CLI command \"go list -m -json all\" failed with error: {GoDependenciesProcessStdErr}", goDependenciesProcess.StdErr); @@ -308,7 +308,7 @@ public class GoComponentDetector : FileComponentDetector } // Stopping at the first ) restrict the detection to only the require section. - while ((line = await reader.ReadLineAsync()) != null && !line.EndsWith(")")) + while ((line = await reader.ReadLineAsync()) != null && !line.EndsWith(')')) { this.TryRegisterDependencyFromModLine(line, singleFileComponentRecorder); } diff --git a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentWithReplaceDetector.cs b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentWithReplaceDetector.cs index eed69fba..12849535 100644 --- a/src/Microsoft.ComponentDetection.Detectors/go/GoComponentWithReplaceDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/go/GoComponentWithReplaceDetector.cs @@ -23,7 +23,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment @"(?.*)\s+(?.*?)(/go\.mod)?\s+(?.*)", RegexOptions.Compiled | RegexOptions.ExplicitCapture | RegexOptions.IgnoreCase); - private readonly HashSet projectRoots = new(); + private readonly HashSet projectRoots = []; private readonly ICommandLineInvocationService commandLineInvocationService; private readonly IEnvironmentVariableService envVarService; @@ -44,11 +44,11 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment public override string Id => "GoWithReplace"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.GoMod)]; - public override IList SearchPatterns { get; } = new List { "go.mod", "go.sum" }; + public override IList SearchPatterns { get; } = ["go.mod", "go.sum"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Go }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Go]; public override int Version => 1; @@ -90,7 +90,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment private IEnumerable FindAdjacentGoModComponentStreams(ProcessRequest processRequest) => this.ComponentStreamEnumerableFactory.GetComponentStreams( new FileInfo(processRequest.ComponentStream.Location).Directory, - new[] { "go.mod" }, + ["go.mod"], (_, _) => false, false) .Select(x => @@ -224,7 +224,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment var projectRootDirectory = Directory.GetParent(location); record.ProjectRoot = projectRootDirectory.FullName; - var isGoAvailable = await this.commandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, new[] { "version" }); + var isGoAvailable = await this.commandLineInvocationService.CanCommandBeLocatedAsync("go", null, workingDirectory: projectRootDirectory, ["version"]); record.IsGoAvailable = isGoAvailable; if (!isGoAvailable) @@ -236,7 +236,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment this.Logger.LogInformation("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.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, new[] { "list", "-mod=readonly", "-m", "-json", "all" }); + var goDependenciesProcess = await this.commandLineInvocationService.ExecuteCommandAsync("go", null, workingDirectory: projectRootDirectory, ["list", "-mod=readonly", "-m", "-json", "all"]); if (goDependenciesProcess.ExitCode != 0) { this.Logger.LogError("Go CLI command \"go list -m -json all\" failed with error: {GoDependenciesProcessStdErr}", goDependenciesProcess.StdErr); @@ -309,7 +309,7 @@ public class GoComponentWithReplaceDetector : FileComponentDetector, IExperiment } // Stopping at the first ) restrict the detection to only the require section. - while ((line = await reader.ReadLineAsync()) != null && !line.EndsWith(")")) + while ((line = await reader.ReadLineAsync()) != null && !line.EndsWith(')')) { this.TryRegisterDependencyFromModLine(line, singleFileComponentRecorder); } diff --git a/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs index 9a7fb9b3..f01f9f94 100644 --- a/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/gradle/GradleComponentDetector.cs @@ -31,19 +31,19 @@ public class GradleComponentDetector : FileComponentDetector, IComponentDetector this.Scanner = walkerFactory; this.Logger = logger; - this.devLockfiles = envVarService.GetListEnvironmentVariable(DevLockfilesEnvVar) ?? new List(); - this.devConfigurations = envVarService.GetListEnvironmentVariable(DevConfigurationsEnvVar) ?? new List(); + this.devLockfiles = envVarService.GetListEnvironmentVariable(DevLockfilesEnvVar) ?? []; + this.devConfigurations = envVarService.GetListEnvironmentVariable(DevConfigurationsEnvVar) ?? []; this.Logger.LogDebug("Gradle dev-only lockfiles {Lockfiles}", string.Join(", ", this.devLockfiles)); this.Logger.LogDebug("Gradle dev-only configurations {Configurations}", string.Join(", ", this.devConfigurations)); } public override string Id { get; } = "Gradle"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Maven) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Maven)]; - public override IList SearchPatterns { get; } = new List { "*.lockfile" }; + public override IList SearchPatterns { get; } = ["*.lockfile"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Maven }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Maven]; public override int Version { get; } = 3; diff --git a/src/Microsoft.ComponentDetection.Detectors/ivy/IvyDetector.cs b/src/Microsoft.ComponentDetection.Detectors/ivy/IvyDetector.cs index 2ff6f4d1..0e9b8cb7 100644 --- a/src/Microsoft.ComponentDetection.Detectors/ivy/IvyDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/ivy/IvyDetector.cs @@ -43,7 +43,7 @@ public class IvyDetector : FileComponentDetector, IExperimentalDetector internal const string AntVersionArgument = "-version"; - internal static readonly string[] AdditionalValidCommands = { "ant" }; + internal static readonly string[] AdditionalValidCommands = ["ant"]; private readonly ICommandLineInvocationService commandLineInvocationService; @@ -61,13 +61,13 @@ public class IvyDetector : FileComponentDetector, IExperimentalDetector public override string Id => "Ivy"; - public override IList SearchPatterns => new List { "ivy.xml" }; + public override IList SearchPatterns => ["ivy.xml"]; - public override IEnumerable SupportedComponentTypes => new[] { ComponentType.Maven }; + public override IEnumerable SupportedComponentTypes => [ComponentType.Maven]; public override int Version => 2; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Maven) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Maven)]; protected override async Task> OnPrepareDetectionAsync( IObservable processRequests, diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/Exceptions/MissingContainerDetailException.cs b/src/Microsoft.ComponentDetection.Detectors/linux/Exceptions/MissingContainerDetailException.cs index 8f820cf1..0b85170a 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/Exceptions/MissingContainerDetailException.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/Exceptions/MissingContainerDetailException.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Linux.Exceptions; +namespace Microsoft.ComponentDetection.Detectors.Linux.Exceptions; using System; diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/ILinuxScanner.cs b/src/Microsoft.ComponentDetection.Detectors/linux/ILinuxScanner.cs index 2defc6f4..5b3e3ef9 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/ILinuxScanner.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/ILinuxScanner.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Linux; +namespace Microsoft.ComponentDetection.Detectors.Linux; using System.Collections.Generic; using System.Threading; diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs index 9dabf30c..fcd655ba 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxContainerDetector.cs @@ -31,9 +31,9 @@ public class LinuxContainerDetector : IComponentDetector public string Id => "Linux"; - public IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Linux) }; + public IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Linux)]; - public IEnumerable SupportedComponentTypes => new[] { ComponentType.Linux }; + public IEnumerable SupportedComponentTypes => [ComponentType.Linux]; public int Version => 4; @@ -47,7 +47,7 @@ public class LinuxContainerDetector : IComponentDetector .ToList(); #pragma warning restore CA1308 - if (imagesToProcess == null || !imagesToProcess.Any()) + if (imagesToProcess == null || imagesToProcess.Count == 0) { this.logger.LogInformation("No instructions received to scan docker images."); return EmptySuccessfulScan(); @@ -110,7 +110,7 @@ public class LinuxContainerDetector : IComponentDetector return new ImageScanningResult { ContainerDetails = null, - Components = Enumerable.Empty(), + Components = [], }; } @@ -135,13 +135,7 @@ public class LinuxContainerDetector : IComponentDetector null); } - var imageDetails = await this.dockerService.InspectImageAsync(image, cancellationToken); - - // Unable to fetch image details - if (imageDetails == null) - { - throw new MissingContainerDetailException(image); - } + var imageDetails = await this.dockerService.InspectImageAsync(image, cancellationToken) ?? throw new MissingContainerDetailException(image); processedImages.TryAdd(imageDetails.ImageId, imageDetails); } diff --git a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs index 84fca195..e49cfc03 100644 --- a/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs +++ b/src/Microsoft.ComponentDetection.Detectors/linux/LinuxScanner.cs @@ -17,12 +17,16 @@ public class LinuxScanner : ILinuxScanner { private const string ScannerImage = "governancecontainerregistry.azurecr.io/syft:v0.100.0@sha256:df7b07bfadff45e0135d74f22478f47b16ac6aff4e8dbd93133fcae3bbbb790d"; - private static readonly IList CmdParameters = new List - { - "--quiet", "--scope", "all-layers", "--output", "json", - }; + private static readonly IList CmdParameters = + [ + "--quiet", + "--scope", + "all-layers", + "--output", + "json", + ]; - private static readonly IEnumerable AllowedArtifactTypes = new[] { "apk", "deb", "rpm" }; + private static readonly IEnumerable AllowedArtifactTypes = ["apk", "deb", "rpm"]; private static readonly SemaphoreSlim DockerSemaphore = new SemaphoreSlim(2); @@ -163,7 +167,7 @@ public class LinuxScanner : ILinuxScanner } var licenses = artifact.Licenses; - if (licenses != null && licenses.Any()) + if (licenses != null && licenses.Length != 0) { return string.Join(", ", licenses.Select(l => l.Value)); } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs b/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs index faf14864..0355d203 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/GraphNode.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Maven; +namespace Microsoft.ComponentDetection.Detectors.Maven; using System.Collections.Generic; @@ -12,7 +12,7 @@ public class GraphNode public T Value { get; set; } - public List> Children { get; } = new List>(); + public List> Children { get; } = []; - public List> Parents { get; } = new List>(); + public List> Parents { get; } = []; } diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs index b36bb53a..6d075656 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenCommandService.cs @@ -16,7 +16,7 @@ public class MavenCommandService : IMavenCommandService internal const string MvnVersionArgument = "--version"; - internal static readonly string[] AdditionalValidCommands = new[] { "mvn.cmd" }; + internal static readonly string[] AdditionalValidCommands = ["mvn.cmd"]; private readonly ICommandLineInvocationService commandLineInvocationService; private readonly IMavenStyleDependencyGraphParserService parserService; diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs index 1517a70f..cd4127fa 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenParsingUtilities.cs @@ -47,7 +47,7 @@ public static class MavenParsingUtilities { // Six part versions have an entry in their 4th index. We remove it to normalize. E.g.: // var mysteriousSixPartVersionPart = results[3]; - results = new[] { results[0], results[1], results[2], results[4], results[5] }; + results = [results[0], results[1], results[2], results[4], results[5]]; } // 'MavenCompile' is a default scope for maven dependencies. diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs index 3598bece..3883e03d 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MavenStyleDependencyGraphParser.cs @@ -8,9 +8,9 @@ using Microsoft.Extensions.Logging; public class MavenStyleDependencyGraphParser { - private static readonly char[] TrimCharacters = new char[] { '|', ' ' }; + private static readonly char[] TrimCharacters = ['|', ' ']; - private static readonly string[] ComponentSplitters = new[] { "+-", "\\-" }; + private static readonly string[] ComponentSplitters = ["+-", "\\-"]; private readonly Stack> stack = new Stack>(); diff --git a/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs index 93195c3e..871f9c7e 100644 --- a/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/maven/MvnCliComponentDetector.cs @@ -36,13 +36,13 @@ public class MvnCliComponentDetector : FileComponentDetector public override string Id => "MvnCli"; - public override IList SearchPatterns => new List { MavenManifest }; + public override IList SearchPatterns => [MavenManifest]; - public override IEnumerable SupportedComponentTypes => new[] { ComponentType.Maven }; + public override IEnumerable SupportedComponentTypes => [ComponentType.Maven]; public override int Version => 4; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Maven) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Maven)]; private void LogDebugWithId(string message) { @@ -70,7 +70,7 @@ public class MvnCliComponentDetector : FileComponentDetector this.LogDebugWithId($"Nested {MavenManifest} files processed successfully, retrieving generated dependency graphs."); - return this.ComponentStreamEnumerableFactory.GetComponentStreams(this.CurrentScanRequest.SourceDirectory, new[] { this.mavenCommandService.BcdeMvnDependencyFileName }, this.CurrentScanRequest.DirectoryExclusionPredicate) + return this.ComponentStreamEnumerableFactory.GetComponentStreams(this.CurrentScanRequest.SourceDirectory, [this.mavenCommandService.BcdeMvnDependencyFileName], this.CurrentScanRequest.DirectoryExclusionPredicate) .Select(componentStream => { // The file stream is going to be disposed after the iteration is finished @@ -137,7 +137,7 @@ public class MvnCliComponentDetector : FileComponentDetector var current = directoryItemFacades.GetOrAdd(currentDir, _ => new DirectoryItemFacadeOptimized { Name = currentDir, - FileNames = new HashSet(), + FileNames = [], }); // If we didn't come from a directory, it's because we're just getting started. Our current directory should include the file that led to it showing up in the graph. diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV1.cs b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV1.cs index ac4139ba..f519629f 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV1.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV1.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable namespace Microsoft.ComponentDetection.Detectors.Npm.Contracts; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV1Dependency.cs b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV1Dependency.cs index b06259d3..92c47e71 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV1Dependency.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV1Dependency.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable namespace Microsoft.ComponentDetection.Detectors.Npm.Contracts; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2.cs b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2.cs index 45652bda..bef57a87 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable namespace Microsoft.ComponentDetection.Detectors.Npm.Contracts; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2Dependency.cs b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2Dependency.cs index fe5ce5eb..f0522ef2 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2Dependency.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2Dependency.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable namespace Microsoft.ComponentDetection.Detectors.Npm.Contracts; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2Package.cs b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2Package.cs index ccb308f0..d668f0b3 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2Package.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV2Package.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable namespace Microsoft.ComponentDetection.Detectors.Npm.Contracts; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV3.cs b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV3.cs index 27d7b924..714f1920 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV3.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV3.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable namespace Microsoft.ComponentDetection.Detectors.Npm.Contracts; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV3Package.cs b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV3Package.cs index f56bc5fd..274e169d 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV3Package.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/Contracts/PackageLockV3Package.cs @@ -1,4 +1,4 @@ -#nullable enable +#nullable enable namespace Microsoft.ComponentDetection.Detectors.Npm.Contracts; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs index dc4c643f..1ed41a72 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentDetector.cs @@ -34,11 +34,11 @@ public class NpmComponentDetector : FileComponentDetector public override string Id { get; } = "Npm"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Npm) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Npm)]; - public override IList SearchPatterns { get; } = new List { "package.json" }; + public override IList SearchPatterns { get; } = ["package.json"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Npm }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Npm]; public override int Version { get; } = 2; @@ -52,7 +52,7 @@ public class NpmComponentDetector : FileComponentDetector string contents; using (var reader = new StreamReader(file.Stream)) { - contents = await reader.ReadToEndAsync(); + contents = await reader.ReadToEndAsync(cancellationToken); } await this.SafeProcessAllPackageJTokensAsync(filePath, contents, (token) => diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentUtilities.cs index 1f3859f2..b65c108c 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmComponentUtilities.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Npm; +namespace Microsoft.ComponentDetection.Detectors.Npm; using System; using System.Collections.Generic; @@ -95,7 +95,7 @@ public static class NpmComponentUtilities public static IDictionary> TryGetAllPackageJsonDependencies(Stream stream, out IList yarnWorkspaces) { - yarnWorkspaces = new List(); + yarnWorkspaces = []; using var file = new StreamReader(stream); using var reader = new JsonTextReader(file); diff --git a/src/Microsoft.ComponentDetection.Detectors/npm/NpmLockfileDetectorBase.cs b/src/Microsoft.ComponentDetection.Detectors/npm/NpmLockfileDetectorBase.cs index 5e7ea264..39026ad7 100644 --- a/src/Microsoft.ComponentDetection.Detectors/npm/NpmLockfileDetectorBase.cs +++ b/src/Microsoft.ComponentDetection.Detectors/npm/NpmLockfileDetectorBase.cs @@ -47,16 +47,16 @@ public abstract class NpmLockfileDetectorBase : FileComponentDetector /// Used in scenarios where one file path creates multiple JTokens, a false value indicates processing additional JTokens should be halted, proceed otherwise. protected delegate bool JTokenProcessingDelegate(JToken token); - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Npm) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Npm)]; - public override IList SearchPatterns { get; } = new List { "package-lock.json", "npm-shrinkwrap.json", LernaSearchPattern }; + public override IList SearchPatterns { get; } = ["package-lock.json", "npm-shrinkwrap.json", LernaSearchPattern]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Npm }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Npm]; - private List LernaFiles { get; } = new(); + private List LernaFiles { get; } = []; /// - protected override IList SkippedFolders => new List { "node_modules", "pnpm-store" }; + protected override IList SkippedFolders => ["node_modules", "pnpm-store"]; protected abstract bool IsSupportedLockfileVersion(int lockfileVersion); @@ -98,7 +98,7 @@ public abstract class NpmLockfileDetectorBase : FileComponentDetector protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) { - IEnumerable packageJsonPattern = new List { "package.json" }; + IEnumerable packageJsonPattern = ["package.json"]; var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; @@ -243,8 +243,8 @@ public abstract class NpmLockfileDetectorBase : FileComponentDetector directoryItemFacadesByPath[currentDir] = current = new DirectoryItemFacade { Name = currentDir, - Files = new List(), - Directories = new List(), + Files = [], + Directories = [], }; } diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs index e8337040..eba09e5c 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetComponentDetector.cs @@ -18,11 +18,11 @@ using Microsoft.Extensions.Logging; public class NuGetComponentDetector : FileComponentDetector { - private static readonly IEnumerable LowConfidencePackages = new[] { "Newtonsoft.Json" }; + private static readonly IEnumerable LowConfidencePackages = ["Newtonsoft.Json"]; public const string NugetConfigFileName = "nuget.config"; - private readonly IList repositoryPathKeyNames = new List { "repositorypath", "globalpackagesfolder" }; + private readonly IList repositoryPathKeyNames = ["repositorypath", "globalpackagesfolder"]; public NuGetComponentDetector( IComponentStreamEnumerableFactory componentStreamEnumerableFactory, @@ -36,11 +36,11 @@ public class NuGetComponentDetector : FileComponentDetector public override string Id { get; } = "NuGet"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.NuGet) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.NuGet)]; - public override IList SearchPatterns { get; } = new List { "*.nupkg", "*.nuspec", NugetConfigFileName, "paket.lock" }; + public override IList SearchPatterns { get; } = ["*.nupkg", "*.nuspec", NugetConfigFileName, "paket.lock"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.NuGet }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.NuGet]; public override int Version { get; } = 2; diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetNuspecUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetNuspecUtilities.cs index b0c054e2..cff3b98b 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetNuspecUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetNuspecUtilities.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.NuGet; +namespace Microsoft.ComponentDetection.Detectors.NuGet; using System; using System.IO; @@ -27,20 +27,15 @@ public static class NuGetNuspecUtilities var nuspecEntry = archive.Entries.FirstOrDefault(x => x.Name.EndsWith(".nuspec", StringComparison.OrdinalIgnoreCase) - && !x.FullName.Contains('/')); - - if (nuspecEntry == null) - { - throw new FileNotFoundException("No nuspec file was found"); - } + && !x.FullName.Contains('/')) ?? throw new FileNotFoundException("No nuspec file was found"); using var nuspecStream = nuspecEntry.Open(); return await GetNuspecBytesFromNuspecStreamAsync(nuspecStream, nuspecEntry.Length); } - catch (InvalidDataException ex) + catch (InvalidDataException) { - throw ex; + throw; } finally { diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetPackagesConfigDetector.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetPackagesConfigDetector.cs index 78101338..44a899c2 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetPackagesConfigDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetPackagesConfigDetector.cs @@ -33,17 +33,17 @@ public sealed class NuGetPackagesConfigDetector : FileComponentDetector } /// - public override IList SearchPatterns => new[] { "packages.config" }; + public override IList SearchPatterns => ["packages.config"]; /// public override string Id => "NuGetPackagesConfig"; /// public override IEnumerable Categories => - new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.NuGet) }; + [Enum.GetName(typeof(DetectorClass), DetectorClass.NuGet)]; /// - public override IEnumerable SupportedComponentTypes => new[] { ComponentType.NuGet }; + public override IEnumerable SupportedComponentTypes => [ComponentType.NuGet]; /// public override int Version => 1; diff --git a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs index 33232d87..162f1b3d 100644 --- a/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/nuget/NuGetProjectModelProjectCentricComponentDetector.cs @@ -24,13 +24,13 @@ public class NuGetProjectModelProjectCentricComponentDetector : FileComponentDet private readonly ConcurrentDictionary frameworkComponentsThatWereOmmittedWithCount = new ConcurrentDictionary(); - private readonly List netCoreFrameworkNames = new List { "Microsoft.AspNetCore.App", "Microsoft.AspNetCore.Razor.Design", "Microsoft.NETCore.App" }; + private readonly List netCoreFrameworkNames = ["Microsoft.AspNetCore.App", "Microsoft.AspNetCore.Razor.Design", "Microsoft.NETCore.App"]; // This list is meant to encompass all net standard dependencies, but likely contains some net core app 1.x ones, too. // The specific guidance we got around populating this list is to do so based on creating a dotnet core 1.x app to make sure we had the complete // set of netstandard.library files that could show up in later sdk versions. - private readonly string[] netStandardDependencies = new[] - { + private readonly string[] netStandardDependencies = + [ "Libuv", "Microsoft.CodeAnalysis.Analyzers", "Microsoft.CodeAnalysis.Common", @@ -183,7 +183,7 @@ public class NuGetProjectModelProjectCentricComponentDetector : FileComponentDet "System.Xml.XmlSerializer", "System.Xml.XPath", "System.Xml.XPath.XDocument", - }; + ]; private readonly IFileUtilityService fileUtilityService; @@ -201,11 +201,11 @@ public class NuGetProjectModelProjectCentricComponentDetector : FileComponentDet public override string Id { get; } = "NuGetProjectCentric"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.NuGet) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.NuGet)]; - public override IList SearchPatterns { get; } = new List { "project.assets.json" }; + public override IList SearchPatterns { get; } = ["project.assets.json"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.NuGet }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.NuGet]; public override int Version { get; } = 1; @@ -273,7 +273,7 @@ public class NuGetProjectModelProjectCentricComponentDetector : FileComponentDet return; } - visited ??= new HashSet(); + visited ??= []; var libraryComponent = new DetectedComponent(new NuGetComponent(library.Name, library.Version.ToNormalizedString())); singleFileComponentRecorder.RegisterUsage(libraryComponent, explicitlyReferencedComponentIds.Contains(libraryComponent.Component.Id), parentComponentId); @@ -427,7 +427,7 @@ public class NuGetProjectModelProjectCentricComponentDetector : FileComponentDet private HashSet GetDependencyComponentIds(LockFile lockFile, LockFileTarget target, IList dependencies, HashSet visited = null) { - visited ??= new HashSet(); + visited ??= []; var currentComponents = new HashSet(); foreach (var dependency in dependencies) { diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/IPythonResolver.cs b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/IPythonResolver.cs index 8a34b4bc..a1a3a62b 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/IPythonResolver.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/IPythonResolver.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Pip; +namespace Microsoft.ComponentDetection.Detectors.Pip; using System.Collections.Generic; using System.Threading.Tasks; diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipDependencySpecification.cs b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipDependencySpecification.cs index c0d3b08a..e1093cb5 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipDependencySpecification.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipDependencySpecification.cs @@ -26,8 +26,8 @@ public class PipDependencySpecification /// /// These are packages that we don't want to evaluate in our graph as they are generally python builtins. /// - public static readonly HashSet PackagesToIgnore = new HashSet - { + public static readonly HashSet PackagesToIgnore = + [ "-markerlib", "pip", "pip-tools", @@ -35,7 +35,7 @@ public class PipDependencySpecification "pkg-resources", "setuptools", "wheel", - }; + ]; // Extracts abcd from a string like abcd==1.*,!=1.3 private static readonly Regex PipNameExtractionRegex = new Regex( @@ -82,9 +82,9 @@ public class PipDependencySpecification /// /// Gets or sets the set of dependency specifications that constrain the overall dependency request (ex: ==1.0, >=2.0). /// - public IList DependencySpecifiers { get; set; } = new List(); + public IList DependencySpecifiers { get; set; } = []; - public IList ConditionalDependencySpecifiers { get; set; } = new List(); + public IList ConditionalDependencySpecifiers { get; set; } = []; private string DebuggerDisplay => $"{this.Name} ({string.Join(';', this.DependencySpecifiers)})"; @@ -186,15 +186,12 @@ public class PipDependencySpecification var conditionalSpec = $"{conditionalOperator}{conditionalValue}"; try { - conditionMet = PythonVersionUtilities.VersionValidForSpec(pythonEnvironmentVariables[conditionalVar], new List { conditionalSpec }); + conditionMet = PythonVersionUtilities.VersionValidForSpec(pythonEnvironmentVariables[conditionalVar], [conditionalSpec]); } catch (ArgumentException ae) { conditionMet = false; - if (this.Logger != null) - { - this.Logger.LogDebug("Could not create pip dependency: {ErrorMessage}", ae.Message); - } + this.Logger?.LogDebug("Could not create pip dependency: {ErrorMessage}", ae.Message); } } else @@ -256,10 +253,7 @@ public class PipDependencySpecification } catch (ArgumentException ae) { - if (this.Logger != null) - { - this.Logger.LogDebug("Could not create pip dependency: {ErrorMessage}", ae.Message); - } + this.Logger?.LogDebug("Could not create pip dependency: {ErrorMessage}", ae.Message); return null; } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipGraphNode.cs b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipGraphNode.cs index 15f7383f..c08576ad 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipGraphNode.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipGraphNode.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Pip; +namespace Microsoft.ComponentDetection.Detectors.Pip; using System.Collections.Generic; using Microsoft.ComponentDetection.Contracts.TypedComponent; @@ -13,7 +13,7 @@ public class PipGraphNode public PipComponent Value { get; set; } - public List Children { get; } = new List(); + public List Children { get; } = []; - public List Parents { get; } = new List(); + public List Parents { get; } = []; } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipReportGraphNode.cs b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipReportGraphNode.cs index 8b689000..690e4426 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipReportGraphNode.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PipReportGraphNode.cs @@ -17,9 +17,9 @@ public sealed record PipReportGraphNode public PipComponent Value { get; set; } - public List Children { get; } = new List(); + public List Children { get; } = []; - public List Parents { get; } = new List(); + public List Parents { get; } = []; public bool Requested { get; set; } } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PythonResolverState.cs b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PythonResolverState.cs index 0f0ea516..adae76e7 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PythonResolverState.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PythonResolverState.cs @@ -12,5 +12,5 @@ public class PythonResolverState public IDictionary NodeReferences { get; } = new Dictionary(StringComparer.OrdinalIgnoreCase); - public IList Roots { get; } = new List(); + public IList Roots { get; } = []; } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PythonVersion.cs b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PythonVersion.cs index a16fbdb0..8564a6f9 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PythonVersion.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/Contracts/PythonVersion.cs @@ -111,10 +111,7 @@ public class PythonVersion : IComparable public static PythonVersion Create(string version) { - if (version == null) - { - throw new ArgumentNullException(nameof(version)); - } + ArgumentNullException.ThrowIfNull(version); if (Cache.TryGetValue(version, out var cachedVersion)) { diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs index f50175c0..46cc33de 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PipComponentDetector.cs @@ -32,11 +32,11 @@ public class PipComponentDetector : FileComponentDetector, IDefaultOffComponentD public override string Id => "Pip"; - public override IList SearchPatterns => new List { "setup.py", "requirements.txt" }; + public override IList SearchPatterns => ["setup.py", "requirements.txt"]; - public override IEnumerable Categories => new List { "Python" }; + public override IEnumerable Categories => ["Python"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Pip }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Pip]; public override int Version { get; } = 13; diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PipReportComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PipReportComponentDetector.cs index 0a24d9fa..9e8d01c5 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PipReportComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PipReportComponentDetector.cs @@ -24,7 +24,7 @@ public class PipReportComponentDetector : FileComponentDetector private const string PipReportFileLevelTimeoutSecondsEnvVar = "PipReportFileLevelTimeoutSeconds"; private const string PipReportPersistReportsEnvVar = "PipReportPersistReports"; - private static readonly IList PipReportPreGeneratedFilePatterns = new List { "*.component-detection-pip-report.json", "component-detection-pip-report.json" }; + private static readonly IList PipReportPreGeneratedFilePatterns = ["*.component-detection-pip-report.json", "component-detection-pip-report.json"]; /// /// The maximum version of the report specification that this detector can handle. @@ -71,11 +71,11 @@ public class PipReportComponentDetector : FileComponentDetector public override string Id => "PipReport"; - public override IList SearchPatterns => new List { "setup.py", "requirements.txt" }; + public override IList SearchPatterns => ["setup.py", "requirements.txt"]; - public override IEnumerable Categories => new List { "Python" }; + public override IEnumerable Categories => ["Python"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Pip }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Pip]; public override int Version { get; } = 8; @@ -127,7 +127,7 @@ public class PipReportComponentDetector : FileComponentDetector var singleFileComponentRecorder = processRequest.SingleFileComponentRecorder; var file = processRequest.ComponentStream; - List reportFiles = new(); + List reportFiles = []; try { var pipOverride = this.GetPipReportOverrideBehavior(); @@ -186,8 +186,8 @@ public class PipReportComponentDetector : FileComponentDetector .ToList(); } - List reports = new(); - if (preGeneratedReportFiles is not null && preGeneratedReportFiles.Any()) + List reports = []; + if (preGeneratedReportFiles is not null && preGeneratedReportFiles.Count != 0) { this.Logger.LogInformation("PipReport: Found pre-generated pip report(s) for {File}.", file.Location); @@ -211,7 +211,7 @@ public class PipReportComponentDetector : FileComponentDetector } } - var foundPreGeneratedReport = reports.Any(); + var foundPreGeneratedReport = reports.Count != 0; pipReportTypeRecord.PreGenerated = foundPreGeneratedReport; if (!foundPreGeneratedReport) { @@ -233,7 +233,7 @@ public class PipReportComponentDetector : FileComponentDetector reportFiles.Add(reportFile); } - if (!reports.Any()) + if (reports.Count == 0) { this.Logger.LogWarning("PipReport: Failed to generate or find pip installation report for {File}.", file.Location); return; @@ -388,7 +388,7 @@ public class PipReportComponentDetector : FileComponentDetector } else { - dependenciesByPkg.Add(normalizedPkgName, new List { dependencySpec }); + dependenciesByPkg.Add(normalizedPkgName, [dependencySpec]); } } } @@ -440,7 +440,7 @@ public class PipReportComponentDetector : FileComponentDetector // parentComponentId is guaranteed to exist in the graph or an exception will be thrown. foreach (var node in graph.Values) { - if (!node.Parents.Any()) + if (node.Parents.Count == 0) { continue; } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs index 26ce6979..8e0890ed 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonCommandService.cs @@ -81,7 +81,7 @@ public class PythonCommandService : IPythonCommandService if (command.ExitCode != 0) { this.logger.LogDebug("Python: Failed distutils setup with error: {StdErr}", command.StdErr); - return new List(); + return []; } var result = command.StdOut; @@ -91,7 +91,7 @@ public class PythonCommandService : IPythonCommandService // For Python2 if there are no packages (Result: "None") skip any parsing if (result.Equals("None", StringComparison.OrdinalIgnoreCase) && !command.StdOut.StartsWith('[')) { - return new List(); + return []; } return result.Split(new string[] { "'," }, StringSplitOptions.RemoveEmptyEntries).Select(x => x.Trim().Trim('\'').Trim()).ToList(); @@ -102,7 +102,7 @@ public class PythonCommandService : IPythonCommandService var items = new List<(string, GitComponent)>(); foreach (var line in File.ReadAllLines(path) .Select(x => x.Trim().TrimEnd('\\')) - .Where(x => !x.StartsWith("#") && !x.StartsWith("-") && !string.IsNullOrWhiteSpace(x))) + .Where(x => !x.StartsWith('#') && !x.StartsWith('-') && !string.IsNullOrWhiteSpace(x))) { // We technically shouldn't be ignoring information after the ; // It's used to indicate environment markers like specific python versions @@ -170,13 +170,13 @@ public class PythonCommandService : IPythonCommandService private async Task CanCommandBeLocatedAsync(string pythonPath) { - return await this.commandLineInvocationService.CanCommandBeLocatedAsync(pythonPath, new List { "python3", "python2" }, "--version"); + return await this.commandLineInvocationService.CanCommandBeLocatedAsync(pythonPath, ["python3", "python2"], "--version"); } public async Task GetPythonVersionAsync(string pythonPath) { var pythonCommand = await this.ResolvePythonAsync(pythonPath); - var versionResult = await this.commandLineInvocationService.ExecuteCommandAsync(pythonCommand, new List { "python3", "python2" }, "--version"); + var versionResult = await this.commandLineInvocationService.ExecuteCommandAsync(pythonCommand, ["python3", "python2"], "--version"); var version = new Regex("Python ([\\d.]+)"); var match = version.Match(versionResult.StdOut); return match.Success ? match.Groups[1].Value : null; @@ -185,7 +185,7 @@ public class PythonCommandService : IPythonCommandService public async Task GetOsTypeAsync(string pythonPath) { var pythonCommand = await this.ResolvePythonAsync(pythonPath); - var versionResult = await this.commandLineInvocationService.ExecuteCommandAsync(pythonCommand, new List { "python3", "python2" }, "-c", "\"import sys; print(sys.platform);\""); + var versionResult = await this.commandLineInvocationService.ExecuteCommandAsync(pythonCommand, ["python3", "python2"], "-c", "\"import sys; print(sys.platform);\""); return versionResult.ExitCode == 0 && string.IsNullOrEmpty(versionResult.StdErr) ? versionResult.StdOut.Trim() : null; } } diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonNotFoundException.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonNotFoundException.cs index f9fc313c..1f1aa0ed 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonNotFoundException.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonNotFoundException.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Pip; +namespace Microsoft.ComponentDetection.Detectors.Pip; using System; diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs index 7154cab4..22535544 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolver.cs @@ -14,7 +14,7 @@ public class PythonResolver : PythonResolverBase, IPythonResolver { private readonly IPyPiClient pypiClient; private readonly ILogger logger; - private readonly Dictionary pythonEnvironmentVariables = new Dictionary(); + private readonly Dictionary pythonEnvironmentVariables = []; private readonly int maxLicenseFieldLength = 100; private readonly string classifierFieldSeparator = " :: "; @@ -47,12 +47,12 @@ public class PythonResolver : PythonResolverBase, IPythonResolver var result = project.Releases; - if (result is not null && result.Keys.Any()) + if (result is not null && result.Keys.Count != 0) { state.ValidVersionMap[rootPackage.Name] = result; // Grab the latest version as our candidate version - var candidateVersion = state.ValidVersionMap[rootPackage.Name].Keys.Any() + var candidateVersion = state.ValidVersionMap[rootPackage.Name].Keys.Count != 0 ? state.ValidVersionMap[rootPackage.Name].Keys.Last() : null; var node = new PipGraphNode(new PipComponent(rootPackage.Name, candidateVersion, license: this.GetLicenseFromProject(project), author: this.GetSupplierFromProject(project))); @@ -75,7 +75,7 @@ public class PythonResolver : PythonResolverBase, IPythonResolver } // Now queue packages for processing - return await this.ProcessQueueAsync(singleFileComponentRecorder, state) ?? new List(); + return await this.ProcessQueueAsync(singleFileComponentRecorder, state) ?? []; } private async Task> ProcessQueueAsync(ISingleFileComponentRecorder singleFileComponentRecorder, PythonResolverState state) @@ -120,10 +120,10 @@ public class PythonResolver : PythonResolverBase, IPythonResolver var result = project.Releases; - if (result is not null && result.Keys.Any()) + if (result is not null && result.Keys.Count != 0) { state.ValidVersionMap[dependencyNode.Name] = result; - var candidateVersion = state.ValidVersionMap[dependencyNode.Name].Keys.Any() + var candidateVersion = state.ValidVersionMap[dependencyNode.Name].Keys.Count != 0 ? state.ValidVersionMap[dependencyNode.Name].Keys.Last() : null; this.AddGraphNode(state, state.NodeReferences[currentNode.Name], dependencyNode.Name, candidateVersion, license: this.GetLicenseFromProject(project), author: this.GetSupplierFromProject(project)); @@ -163,7 +163,7 @@ public class PythonResolver : PythonResolverBase, IPythonResolver state.ValidVersionMap[spec.Name][candidateVersion].FirstOrDefault(x => string.Equals("bdist_egg", x.PackageType, StringComparison.OrdinalIgnoreCase)); if (packageToFetch == null) { - return new List(); + return []; } return await this.pypiClient.FetchPackageDependenciesAsync(spec.Name, candidateVersion, packageToFetch); diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolverBase.cs b/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolverBase.cs index e501d8ff..efc5aa5e 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolverBase.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/PythonResolverBase.cs @@ -42,7 +42,7 @@ public abstract class PythonResolverBase return false; } - var candidateVersion = state.ValidVersionMap[pipComponent.Name].Keys.Any() ? state.ValidVersionMap[pipComponent.Name].Keys.Last() : null; + var candidateVersion = state.ValidVersionMap[pipComponent.Name].Keys.Count != 0 ? state.ValidVersionMap[pipComponent.Name].Keys.Last() : null; node.Value = new PipComponent(pipComponent.Name, candidateVersion, author: pipComponent.Author, license: pipComponent.License); diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/SimplePipComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/pip/SimplePipComponentDetector.cs index 47baf7f2..0d697ced 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/SimplePipComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/SimplePipComponentDetector.cs @@ -32,11 +32,11 @@ public class SimplePipComponentDetector : FileComponentDetector, IDefaultOffComp public override string Id => "SimplePip"; - public override IList SearchPatterns => new List { "setup.py", "requirements.txt" }; + public override IList SearchPatterns => ["setup.py", "requirements.txt"]; - public override IEnumerable Categories => new List { "Python" }; + public override IEnumerable Categories => ["Python"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Pip }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Pip]; public override int Version { get; } = 3; diff --git a/src/Microsoft.ComponentDetection.Detectors/pip/SimplePythonResolver.cs b/src/Microsoft.ComponentDetection.Detectors/pip/SimplePythonResolver.cs index d013b47e..5cda7b22 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pip/SimplePythonResolver.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pip/SimplePythonResolver.cs @@ -118,12 +118,12 @@ public class SimplePythonResolver : PythonResolverBase, ISimplePythonResolver { var pythonProject = this.ConvertSimplePypiProjectToSortedDictionary(simplePythonProject, rootPackage); - if (pythonProject.Keys.Any()) + if (pythonProject.Keys.Count != 0) { state.ValidVersionMap[rootPackage.Name] = pythonProject; // Grab the latest version as our candidate version - var candidateVersion = state.ValidVersionMap[rootPackage.Name].Keys.Any() + var candidateVersion = state.ValidVersionMap[rootPackage.Name].Keys.Count != 0 ? state.ValidVersionMap[rootPackage.Name].Keys.Last() : null; @@ -147,7 +147,7 @@ public class SimplePythonResolver : PythonResolverBase, ISimplePythonResolver }); // Now queue packages for processing - return await this.ProcessQueueAsync(singleFileComponentRecorder, state) ?? new List(); + return await this.ProcessQueueAsync(singleFileComponentRecorder, state) ?? []; } private async Task> ProcessQueueAsync(ISingleFileComponentRecorder singleFileComponentRecorder, PythonResolverState state) @@ -199,10 +199,10 @@ public class SimplePythonResolver : PythonResolverBase, ISimplePythonResolver } var result = this.ConvertSimplePypiProjectToSortedDictionary(newProject, dependencyNode); - if (result.Keys.Any()) + if (result.Keys.Count != 0) { state.ValidVersionMap[dependencyNode.Name] = result; - var candidateVersion = state.ValidVersionMap[dependencyNode.Name].Keys.Any() + var candidateVersion = state.ValidVersionMap[dependencyNode.Name].Keys.Count != 0 ? state.ValidVersionMap[dependencyNode.Name].Keys.Last() : null; AddGraphNode(state, state.NodeReferences[currentNode.Name], dependencyNode.Name, candidateVersion); @@ -261,7 +261,7 @@ public class SimplePythonResolver : PythonResolverBase, ISimplePythonResolver var pythonProjectRelease = new PythonProjectRelease { PythonVersion = version, PackageType = packageType, Size = file.Size, Url = file.Url }; if (!sortedProjectVersions.ContainsKey(version)) { - sortedProjectVersions.Add(version, new List()); + sortedProjectVersions.Add(version, []); } sortedProjectVersions[version].Add(pythonProjectRelease); @@ -295,14 +295,14 @@ public class SimplePythonResolver : PythonResolverBase, ISimplePythonResolver state.ValidVersionMap[spec.Name][candidateVersion].FirstOrDefault(x => string.Equals("bdist_egg", x.PackageType, StringComparison.OrdinalIgnoreCase)); if (packageToFetch == null) { - return new List(); + return []; } var packageFileStream = await this.simplePypiClient.FetchPackageFileStreamAsync(packageToFetch.Url); if (packageFileStream.Length == 0) { - return new List(); + return []; } return await this.FetchDependenciesFromPackageStreamAsync(spec.Name, candidateVersion, packageFileStream); diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetectorFactory.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetectorFactory.cs index ece1656e..a4cd8824 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetectorFactory.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmComponentDetectorFactory.cs @@ -35,11 +35,11 @@ public class PnpmComponentDetectorFactory : FileComponentDetector public override string Id { get; } = "Pnpm"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Npm) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Npm)]; - public override IList SearchPatterns { get; } = new List { "shrinkwrap.yaml", "pnpm-lock.yaml" }; + public override IList SearchPatterns { get; } = ["shrinkwrap.yaml", "pnpm-lock.yaml"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Npm }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Npm]; public override int Version { get; } = 6; @@ -58,7 +58,7 @@ public class PnpmComponentDetectorFactory : FileComponentDetector try { - var fileContent = await new StreamReader(file.Stream).ReadToEndAsync(); + var fileContent = await new StreamReader(file.Stream).ReadToEndAsync(cancellationToken); var detector = this.GetPnpmComponentDetector(fileContent, out var detectedVersion); if (detector == null) { diff --git a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmParsingUtilities.cs b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmParsingUtilities.cs index 729f287c..fe107d9e 100644 --- a/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmParsingUtilities.cs +++ b/src/Microsoft.ComponentDetection.Detectors/pnpm/PnpmParsingUtilities.cs @@ -21,10 +21,7 @@ public static class PnpmParsingUtilities public static bool IsPnpmPackageDevDependency(Package pnpmPackage) { - if (pnpmPackage == null) - { - throw new ArgumentNullException(nameof(pnpmPackage)); - } + ArgumentNullException.ThrowIfNull(pnpmPackage); return string.Equals(bool.TrueString, pnpmPackage.Dev, StringComparison.InvariantCultureIgnoreCase); } @@ -136,7 +133,7 @@ public static class PnpmParsingUtilities var packageVersion = packageNameParts[^1]; // Check for leading `/` from pnpm. - if (!fullPackageName.StartsWith("/")) + if (!fullPackageName.StartsWith('/')) { throw new FormatException("Found pnpm dependency path not starting with `/`. This case is currently unhandled."); } @@ -158,7 +155,7 @@ public static class PnpmParsingUtilities /// A pnpm dependency path for the specified version of the named package. public static string ReconstructPnpmDependencyPathV6(string dependencyName, string dependencyVersion) { - if (dependencyVersion.StartsWith("/")) + if (dependencyVersion.StartsWith('/')) { return dependencyVersion; } diff --git a/src/Microsoft.ComponentDetection.Detectors/poetry/Contracts/PoetryLock.cs b/src/Microsoft.ComponentDetection.Detectors/poetry/Contracts/PoetryLock.cs index 34b47f2b..389d9d90 100644 --- a/src/Microsoft.ComponentDetection.Detectors/poetry/Contracts/PoetryLock.cs +++ b/src/Microsoft.ComponentDetection.Detectors/poetry/Contracts/PoetryLock.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Poetry.Contracts; +namespace Microsoft.ComponentDetection.Detectors.Poetry.Contracts; using System.Collections.Generic; using System.Runtime.Serialization; diff --git a/src/Microsoft.ComponentDetection.Detectors/poetry/Contracts/PoetryPackage.cs b/src/Microsoft.ComponentDetection.Detectors/poetry/Contracts/PoetryPackage.cs index ebd26506..d7ddff13 100644 --- a/src/Microsoft.ComponentDetection.Detectors/poetry/Contracts/PoetryPackage.cs +++ b/src/Microsoft.ComponentDetection.Detectors/poetry/Contracts/PoetryPackage.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Poetry.Contracts; +namespace Microsoft.ComponentDetection.Detectors.Poetry.Contracts; using System.Collections.Generic; using System.Runtime.Serialization; diff --git a/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs index 41b075b9..946f1cae 100644 --- a/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/poetry/PoetryComponentDetector.cs @@ -27,13 +27,13 @@ public class PoetryComponentDetector : FileComponentDetector, IExperimentalDetec public override string Id => "Poetry"; - public override IList SearchPatterns { get; } = new List { "poetry.lock" }; + public override IList SearchPatterns { get; } = ["poetry.lock"]; - public override IEnumerable SupportedComponentTypes => new[] { ComponentType.Pip }; + public override IEnumerable SupportedComponentTypes => [ComponentType.Pip]; public override int Version { get; } = 3; - public override IEnumerable Categories => new List { "Python" }; + public override IEnumerable Categories => ["Python"]; protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) { @@ -46,7 +46,7 @@ public class PoetryComponentDetector : FileComponentDetector, IExperimentalDetec { IgnoreMissingProperties = true, }; - var poetryLock = Toml.ToModel(await reader.ReadToEndAsync(), options: options); + var poetryLock = Toml.ToModel(await reader.ReadToEndAsync(cancellationToken), options: options); if (poetryLock.Metadata != null && poetryLock.Metadata.TryGetValue("lock-version", out var lockVersion)) { diff --git a/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs index f4a4abf7..b2021dfb 100644 --- a/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/ruby/RubyComponentDetector.cs @@ -63,11 +63,11 @@ public class RubyComponentDetector : FileComponentDetector public override string Id { get; } = "Ruby"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.RubyGems) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.RubyGems)]; - public override IList SearchPatterns { get; } = new List { "Gemfile.lock" }; + public override IList SearchPatterns { get; } = ["Gemfile.lock"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.RubyGems }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.RubyGems]; public override int Version { get; } = 3; @@ -136,7 +136,7 @@ public class RubyComponentDetector : FileComponentDetector // Nothing in the lockfile tells us where bundler came from var addComponent = new DetectedComponent(new RubyGemsComponent(name, line, "unknown")); components.TryAdd(string.Format("{0}:{1}", name, file.Location), addComponent); - dependencies.TryAdd(string.Format("{0}:{1}", name, file.Location), new List()); + dependencies.TryAdd(string.Format("{0}:{1}", name, file.Location), []); break; default: // We ignore other sections @@ -249,7 +249,7 @@ public class RubyComponentDetector : FileComponentDetector else { components.TryAdd(lookupKey, addComponent); - dependencies.Add(lookupKey, new List()); + dependencies.Add(lookupKey, []); } } } @@ -259,7 +259,7 @@ public class RubyComponentDetector : FileComponentDetector private bool IsVersionRelative(string version) { - return version.StartsWith("~") || version.StartsWith("="); + return version.StartsWith('~') || version.StartsWith('='); } private class Dependency diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs b/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs index 9ce72884..44dd43f5 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/CargoDependencyData.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Rust; +namespace Microsoft.ComponentDetection.Detectors.Rust; using System.Collections.Generic; @@ -6,10 +6,10 @@ public class CargoDependencyData { public CargoDependencyData() { - this.CargoWorkspaces = new HashSet(); - this.CargoWorkspaceExclusions = new HashSet(); - this.NonDevDependencies = new List(); - this.DevDependencies = new List(); + this.CargoWorkspaces = []; + this.CargoWorkspaceExclusions = []; + this.NonDevDependencies = []; + this.DevDependencies = []; } public HashSet CargoWorkspaces { get; set; } diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoLock.cs b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoLock.cs index 8dbdbe05..39338f91 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoLock.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoLock.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Rust.Contracts; +namespace Microsoft.ComponentDetection.Detectors.Rust.Contracts; using System.Collections.Generic; using System.Runtime.Serialization; diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs index 35595b24..e2558a27 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoPackage.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Rust.Contracts; +namespace Microsoft.ComponentDetection.Detectors.Rust.Contracts; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoToml.cs b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoToml.cs index 00261619..845cb25b 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoToml.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/Contracts/CargoToml.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Rust.Contracts; +namespace Microsoft.ComponentDetection.Detectors.Rust.Contracts; using System.Runtime.Serialization; diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs b/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs index 1ca08047..200ac50b 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/DependencySpecification.cs @@ -16,7 +16,7 @@ public class DependencySpecification public void Add(string name, string cargoVersionSpecifier) { ISet ranges = new HashSet(); - var specifiers = cargoVersionSpecifier.Split(new char[] { ',' }); + var specifiers = cargoVersionSpecifier.Split([',']); foreach (var specifier in specifiers) { ranges.Add(new Range(specifier.Trim())); diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/RustCliDetector.cs b/src/Microsoft.ComponentDetection.Detectors/rust/RustCliDetector.cs index 582ae062..276dc79f 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/RustCliDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/RustCliDetector.cs @@ -62,16 +62,16 @@ public class RustCliDetector : FileComponentDetector public override string Id => "RustCli"; /// - public override IEnumerable Categories { get; } = new[] { "Rust" }; + public override IEnumerable Categories { get; } = ["Rust"]; /// - public override IEnumerable SupportedComponentTypes => new[] { ComponentType.Cargo }; + public override IEnumerable SupportedComponentTypes => [ComponentType.Cargo]; /// public override int Version => 4; /// - public override IList SearchPatterns { get; } = new[] { "Cargo.toml" }; + public override IList SearchPatterns { get; } = ["Cargo.toml"]; /// protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) @@ -129,12 +129,12 @@ public class RustCliDetector : FileComponentDetector x => new CargoComponent( x.Name, x.Version, - (x.Authors == null || x.Authors.Any(a => string.IsNullOrWhiteSpace(a)) || !x.Authors.Any()) ? null : string.Join(", ", x.Authors), + (x.Authors == null || x.Authors.Any(a => string.IsNullOrWhiteSpace(a)) || x.Authors.Length == 0) ? null : string.Join(", ", x.Authors), string.IsNullOrWhiteSpace(x.License) ? null : x.License, x.Source)); var root = metadata.Resolve.Root; - HashSet visitedDependencies = new(); + HashSet visitedDependencies = []; // A cargo.toml can be used to declare a workspace and not a package (A Virtual Manifest). // In this case, the root will be null as it will not be pulling in dependencies itself. @@ -146,9 +146,8 @@ public class RustCliDetector : FileComponentDetector foreach (var dep in metadata.Resolve.Nodes) { var componentKey = $"{dep.Id}"; - if (!visitedDependencies.Contains(componentKey)) + if (visitedDependencies.Add(componentKey)) { - visitedDependencies.Add(componentKey); this.TraverseAndRecordComponents(processRequest.SingleFileComponentRecorder, componentStream.Location, graph, dep.Id, null, null, packages, visitedDependencies, explicitlyReferencedDependency: false); } } @@ -272,9 +271,8 @@ public class RustCliDetector : FileComponentDetector { // include isTomlRoot to ensure that the roots present in the toml are marked as such in circular dependency cases var componentKey = $"{detectedComponent.Component.Id}{dep.Pkg} {isTomlRoot}"; - if (!visitedDependencies.Contains(componentKey)) + if (visitedDependencies.Add(componentKey)) { - visitedDependencies.Add(componentKey); this.TraverseAndRecordComponents(recorder, location, graph, dep.Pkg, shouldRegister ? detectedComponent : null, dep, packagesMetadata, visitedDependencies, explicitlyReferencedDependency: isTomlRoot && explicitlyReferencedDependency); } } @@ -289,7 +287,7 @@ public class RustCliDetector : FileComponentDetector private IComponentStream FindCorrespondingCargoLock(IComponentStream cargoToml, ISingleFileComponentRecorder singleFileComponentRecorder) { var cargoLockLocation = Path.Combine(Path.GetDirectoryName(cargoToml.Location), "Cargo.lock"); - var cargoLockStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(cargoToml.Location).Directory, new List { "Cargo.lock" }, (name, directoryName) => false, recursivelyScanDirectories: false).FirstOrDefault(); + var cargoLockStream = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(cargoToml.Location).Directory, ["Cargo.lock"], (name, directoryName) => false, recursivelyScanDirectories: false).FirstOrDefault(); if (cargoLockStream == null) { return null; @@ -345,7 +343,7 @@ public class RustCliDetector : FileComponentDetector if (!packagesByName.TryGetValue(cargoPackage.Name, out var packageList)) { // First package with this name - packageList = new List<(CargoPackage, CargoComponent)>(); + packageList = []; packagesByName.Add(cargoPackage.Name, packageList); } else if (packageList.Any(p => p.Package.Equals(cargoPackage))) diff --git a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs index 38b30f2b..779435ca 100644 --- a/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/rust/RustCrateDetector.cs @@ -36,13 +36,13 @@ public class RustCrateDetector : FileComponentDetector public override string Id => "RustCrateDetector"; - public override IList SearchPatterns => new List { CargoLockSearchPattern }; + public override IList SearchPatterns => [CargoLockSearchPattern]; - public override IEnumerable SupportedComponentTypes => new[] { ComponentType.Cargo }; + public override IEnumerable SupportedComponentTypes => [ComponentType.Cargo]; public override int Version { get; } = 8; - public override IEnumerable Categories => new List { "Rust" }; + public override IEnumerable Categories => ["Rust"]; private static bool ParseDependency(string dependency, out string packageName, out string version, out string source) { @@ -74,7 +74,7 @@ public class RustCrateDetector : FileComponentDetector { IgnoreMissingProperties = true, }; - var cargoLock = Toml.ToModel(await reader.ReadToEndAsync(), options: options); + var cargoLock = Toml.ToModel(await reader.ReadToEndAsync(cancellationToken), options: options); this.RecordLockfileVersion(cargoLock.Version); this.ProcessCargoLock(cargoLock, singleFileComponentRecorder, cargoLockFile); } @@ -95,7 +95,7 @@ public class RustCrateDetector : FileComponentDetector if (!packagesByName.TryGetValue(cargoPackage.Name, out var packageList)) { // First package with this name - packageList = new List<(CargoPackage, CargoComponent)>(); + packageList = []; packagesByName.Add(cargoPackage.Name, packageList); } else if (packageList.Any(p => p.Package.Equals(cargoPackage))) diff --git a/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs index 5df967a2..ccede688 100644 --- a/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/spdx/Spdx22ComponentDetector.cs @@ -20,7 +20,7 @@ using Newtonsoft.Json.Linq; /// public class Spdx22ComponentDetector : FileComponentDetector, IDefaultOffComponentDetector { - private readonly IEnumerable supportedSPDXVersions = new List { "SPDX-2.2" }; + private readonly IEnumerable supportedSPDXVersions = ["SPDX-2.2"]; public Spdx22ComponentDetector( IComponentStreamEnumerableFactory componentStreamEnumerableFactory, @@ -33,15 +33,15 @@ public class Spdx22ComponentDetector : FileComponentDetector, IDefaultOffCompone } public override IEnumerable Categories => - new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Spdx) }; + [Enum.GetName(typeof(DetectorClass), DetectorClass.Spdx)]; public override string Id => "SPDX22SBOM"; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Spdx }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Spdx]; public override int Version => 1; - public override IList SearchPatterns => new List { "*.spdx.json" }; + public override IList SearchPatterns => ["*.spdx.json"]; protected override Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) { @@ -106,7 +106,7 @@ public class Spdx22ComponentDetector : FileComponentDetector, IDefaultOffCompone this.Logger.LogWarning("SPDX file at {ManifestLocation} has more than one element in documentDescribes, first will be selected as root element.", processRequest.ComponentStream.Location); } - if (rootElements != null && !rootElements.Any()) + if (rootElements != null && rootElements.Length == 0) { this.Logger.LogWarning("SPDX file at {ManifestLocation} does not have root elements in documentDescribes section, considering SPDXRef-Document as a root element.", processRequest.ComponentStream.Location); } diff --git a/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs index 0901a25b..393e1087 100644 --- a/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/vcpkg/VcpkgComponentDetector.cs @@ -15,7 +15,7 @@ using Newtonsoft.Json; public class VcpkgComponentDetector : FileComponentDetector { - private readonly HashSet projectRoots = new HashSet(); + private readonly HashSet projectRoots = []; private readonly ICommandLineInvocationService commandLineInvocationService; private readonly IEnvironmentVariableService envVarService; @@ -36,11 +36,11 @@ public class VcpkgComponentDetector : FileComponentDetector public override string Id { get; } = "Vcpkg"; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Vcpkg) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Vcpkg)]; - public override IList SearchPatterns { get; } = new List { "vcpkg.spdx.json" }; + public override IList SearchPatterns { get; } = ["vcpkg.spdx.json"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Vcpkg }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Vcpkg]; public override int Version => 2; diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Contracts/YarnBerryLockfile.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Contracts/YarnBerryLockfile.cs index 052c1434..b5d49bfc 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Contracts/YarnBerryLockfile.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Contracts/YarnBerryLockfile.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Yarn.Contracts; +namespace Microsoft.ComponentDetection.Detectors.Yarn.Contracts; using System.Collections.Generic; using YamlDotNet.Serialization; diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Contracts/YarnBerryTypeConverter.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Contracts/YarnBerryTypeConverter.cs index eeb85bf6..16192a99 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Contracts/YarnBerryTypeConverter.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Contracts/YarnBerryTypeConverter.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Yarn.Contracts; +namespace Microsoft.ComponentDetection.Detectors.Yarn.Contracts; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/IYarnLockParser.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/IYarnLockParser.cs index a8b67fcf..c3fc9295 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/IYarnLockParser.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/IYarnLockParser.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Yarn; +namespace Microsoft.ComponentDetection.Detectors.Yarn; using Microsoft.ComponentDetection.Contracts; using Microsoft.ComponentDetection.Detectors.Yarn.Parsers; diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlock.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlock.cs index c0b91612..49c42207 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlock.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlock.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Yarn.Parsers; +namespace Microsoft.ComponentDetection.Detectors.Yarn.Parsers; using System.Collections.Generic; @@ -17,5 +17,5 @@ public class YarnBlock /// /// Gets child blocks, as dentoed by "{child}:". /// - public IList Children { get; } = new List(); + public IList Children { get; } = []; } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs index 5257acf6..dcfe8dc5 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnBlockFile.cs @@ -45,7 +45,7 @@ public class YarnBlockFile : IYarnBlockFile private static readonly Regex YarnV2Regex = new Regex("(.*):\\s\"?(.*)", RegexOptions.Compiled); - private readonly IList fileLines = new List(); + private readonly IList fileLines = []; private int fileLineIndex; @@ -73,10 +73,7 @@ public class YarnBlockFile : IYarnBlockFile public static async Task CreateBlockFileAsync(Stream stream) { - if (stream == null) - { - throw new ArgumentNullException(nameof(stream)); - } + ArgumentNullException.ThrowIfNull(stream); var fileLines = new List(); using (var reader = new StreamReader(stream)) @@ -111,7 +108,7 @@ public class YarnBlockFile : IYarnBlockFile do { - if (this.fileLines[this.fileLineIndex].StartsWith("#")) + if (this.fileLines[this.fileLineIndex].StartsWith('#')) { if (this.fileLines[this.fileLineIndex].Contains("yarn lockfile")) { @@ -174,7 +171,7 @@ public class YarnBlockFile : IYarnBlockFile break; } - if (this.fileLines[this.fileLineIndex].EndsWith(":")) + if (this.fileLines[this.fileLineIndex].EndsWith(':')) { block.Children.Add(this.ParseBlock(level + 1)); this.fileLineIndex--; @@ -223,7 +220,7 @@ public class YarnBlockFile : IYarnBlockFile line = this.fileLines[this.fileLineIndex]; } } - while (string.IsNullOrWhiteSpace(line) || line.StartsWith(" ") || line.StartsWith("\t") || line.StartsWith("#")); + while (string.IsNullOrWhiteSpace(line) || line.StartsWith(' ') || line.StartsWith('\t') || line.StartsWith('#')); return true; } diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs index 51742d65..eb5bfc77 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/Parsers/YarnLockParser.cs @@ -18,7 +18,7 @@ public class YarnLockParser : IYarnLockParser private const string OptionalDependencies = "optionalDependencies"; - private static readonly List SupportedVersions = new List { YarnLockVersion.V1, YarnLockVersion.Berry }; + private static readonly List SupportedVersions = [YarnLockVersion.V1, YarnLockVersion.Berry]; private readonly ILogger logger; @@ -36,13 +36,10 @@ public class YarnLockParser : IYarnLockParser public YarnLockFile Parse(ISingleFileComponentRecorder singleFileComponentRecorder, IYarnBlockFile fileLines, ILogger logger) { - if (fileLines == null) - { - throw new ArgumentNullException(nameof(fileLines)); - } + ArgumentNullException.ThrowIfNull(fileLines); var file = new YarnLockFile { LockVersion = fileLines.YarnLockVersion, LockfileVersion = fileLines.LockfileVersion }; - IList entries = new List(); + IList entries = []; foreach (var block in fileLines) { diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs index 496c4695..780afaa2 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnDependency.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Yarn; +namespace Microsoft.ComponentDetection.Detectors.Yarn; public class YarnDependency { diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs index cb02c5dc..e758cd65 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnEntry.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Yarn; +namespace Microsoft.ComponentDetection.Detectors.Yarn; using System.Collections.Generic; @@ -24,17 +24,17 @@ public class YarnEntry /// /// Gets the satisfied version strings of this entry. /// - public IList Satisfied { get; } = new List(); + public IList Satisfied { get; } = []; /// /// Gets the name@version dependencies that this package requires. /// - public IList Dependencies { get; } = new List(); + public IList Dependencies { get; } = []; /// /// Gets the name@version dependencies that this package requires. /// - public IList OptionalDependencies { get; } = new List(); + public IList OptionalDependencies { get; } = []; /// /// Gets or sets a value indicating whether or not the component is a dev dependency. diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs index 10170418..30407ff4 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockComponentDetector.cs @@ -32,17 +32,17 @@ public class YarnLockComponentDetector : FileComponentDetector public override string Id { get; } = "Yarn"; - public override IList SearchPatterns { get; } = new List { "yarn.lock" }; + public override IList SearchPatterns { get; } = ["yarn.lock"]; - public override IEnumerable SupportedComponentTypes { get; } = new[] { ComponentType.Npm }; + public override IEnumerable SupportedComponentTypes { get; } = [ComponentType.Npm]; public override int Version => 8; - public override IEnumerable Categories => new[] { Enum.GetName(typeof(DetectorClass), DetectorClass.Npm) }; + public override IEnumerable Categories => [Enum.GetName(typeof(DetectorClass), DetectorClass.Npm)]; /// /// "Package" is a more common substring, enclose it with \ to verify it is a folder. - protected override IList SkippedFolders => new List { "node_modules", "pnpm-store", "\\package\\" }; + protected override IList SkippedFolders => ["node_modules", "pnpm-store", "\\package\\"]; protected override async Task OnFileFoundAsync(ProcessRequest processRequest, IDictionary detectorArgs, CancellationToken cancellationToken = default) { @@ -194,15 +194,15 @@ public class YarnLockComponentDetector : FileComponentDetector /// False if no package.json file was found at location, otherwise it returns true. private bool TryReadPeerPackageJsonRequestsAsYarnEntries(ISingleFileComponentRecorder singleFileComponentRecorder, string location, Dictionary yarnEntries, out List yarnRoots) { - yarnRoots = new List(); + yarnRoots = []; - var pkgJsons = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(location).Directory, new List { "package.json" }, (name, directoryName) => false, recursivelyScanDirectories: false); + var pkgJsons = this.ComponentStreamEnumerableFactory.GetComponentStreams(new FileInfo(location).Directory, ["package.json"], (name, directoryName) => false, recursivelyScanDirectories: false); IDictionary> combinedDependencies = new Dictionary>(); var pkgJsonCount = 0; - IList yarnWorkspaces = new List(); + IList yarnWorkspaces = []; foreach (var pkgJson in pkgJsons) { combinedDependencies = NpmComponentUtilities.TryGetAllPackageJsonDependencies(pkgJson.Stream, out yarnWorkspaces); diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockFileFactory.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockFileFactory.cs index 763399ef..c122eec7 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockFileFactory.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockFileFactory.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Yarn; +namespace Microsoft.ComponentDetection.Detectors.Yarn; using System.Collections.Generic; using System.IO; diff --git a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockVersion.cs b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockVersion.cs index 9c928d49..ec1f997a 100644 --- a/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockVersion.cs +++ b/src/Microsoft.ComponentDetection.Detectors/yarn/YarnLockVersion.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Yarn; +namespace Microsoft.ComponentDetection.Detectors.Yarn; public enum YarnLockVersion { diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Commands/ListDetectorsCommand.cs b/src/Microsoft.ComponentDetection.Orchestrator/Commands/ListDetectorsCommand.cs index aeec8e43..c2b24e73 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Commands/ListDetectorsCommand.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Commands/ListDetectorsCommand.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Commands; +namespace Microsoft.ComponentDetection.Orchestrator.Commands; using System.Collections.Generic; using Microsoft.ComponentDetection.Contracts; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/DetectorRunResult.cs b/src/Microsoft.ComponentDetection.Orchestrator/DetectorRunResult.cs index 5a710f4c..539dec49 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/DetectorRunResult.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/DetectorRunResult.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator; +namespace Microsoft.ComponentDetection.Orchestrator; using System; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Exceptions/InvalidDetectorCategoriesException.cs b/src/Microsoft.ComponentDetection.Orchestrator/Exceptions/InvalidDetectorCategoriesException.cs index 61bd9764..deadd7f7 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Exceptions/InvalidDetectorCategoriesException.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Exceptions/InvalidDetectorCategoriesException.cs @@ -1,7 +1,6 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Exceptions; +namespace Microsoft.ComponentDetection.Orchestrator.Exceptions; using System; -using System.Runtime.Serialization; [Serializable] public class InvalidDetectorCategoriesException : Exception @@ -19,9 +18,4 @@ public class InvalidDetectorCategoriesException : Exception : base(message, innerException) { } - - protected InvalidDetectorCategoriesException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Exceptions/InvalidDetectorFilterException.cs b/src/Microsoft.ComponentDetection.Orchestrator/Exceptions/InvalidDetectorFilterException.cs index a00d7966..b5f58680 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Exceptions/InvalidDetectorFilterException.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Exceptions/InvalidDetectorFilterException.cs @@ -1,7 +1,6 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Exceptions; +namespace Microsoft.ComponentDetection.Orchestrator.Exceptions; using System; -using System.Runtime.Serialization; [Serializable] public class InvalidDetectorFilterException : Exception @@ -19,9 +18,4 @@ public class InvalidDetectorFilterException : Exception : base(message, innerException) { } - - protected InvalidDetectorFilterException(SerializationInfo info, StreamingContext context) - : base(info, context) - { - } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/DefaultExperimentProcessor.cs b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/DefaultExperimentProcessor.cs index dbe47107..7172d786 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/DefaultExperimentProcessor.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/DefaultExperimentProcessor.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Experiments; +namespace Microsoft.ComponentDetection.Orchestrator.Experiments; using System; using System.Text.Json; @@ -13,6 +13,11 @@ using Microsoft.Extensions.Logging; /// public class DefaultExperimentProcessor : IExperimentProcessor { + private static readonly JsonSerializerOptions JsonOptions = new JsonSerializerOptions + { + WriteIndented = true, + }; + private readonly IFileWritingService fileWritingService; private readonly ILogger logger; @@ -34,7 +39,7 @@ public class DefaultExperimentProcessor : IExperimentProcessor this.logger.LogInformation("Writing experiment {Name} results to {Filename}", config.Name, this.fileWritingService.ResolveFilePath(filename)); - var serializedDiff = JsonSerializer.Serialize(diff, new JsonSerializerOptions { WriteIndented = true }); + var serializedDiff = JsonSerializer.Serialize(diff, JsonOptions); await this.fileWritingService.WriteFileAsync(filename, serializedDiff); } } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/ExperimentService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/ExperimentService.cs index f372255e..d21433ba 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/ExperimentService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/ExperimentService.cs @@ -7,7 +7,6 @@ using System.Linq; using System.Threading.Tasks; using Microsoft.ComponentDetection.Common.DependencyGraph; using Microsoft.ComponentDetection.Contracts; -using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Orchestrator.Commands; using Microsoft.ComponentDetection.Orchestrator.Experiments.Configs; using Microsoft.ComponentDetection.Orchestrator.Experiments.Models; @@ -77,8 +76,8 @@ public class ExperimentService : IExperimentService var scanResult = this.graphTranslationService.GenerateScanResultFromProcessingResult( new DetectorProcessingResult() { - ComponentRecorders = new[] { (detector, componentRecorder) }, - ContainersDetailsMap = new Dictionary(), + ComponentRecorders = [(detector, componentRecorder)], + ContainersDetailsMap = [], ResultCode = ProcessingResultCode.Success, }, settings, diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/IExperimentProcessor.cs b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/IExperimentProcessor.cs index 0762affc..90430c98 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/IExperimentProcessor.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/IExperimentProcessor.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Experiments; +namespace Microsoft.ComponentDetection.Orchestrator.Experiments; using System.Threading.Tasks; using Microsoft.ComponentDetection.Orchestrator.Experiments.Configs; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentComponent.cs b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentComponent.cs index 9e07fa63..8ba4a4d6 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentComponent.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentComponent.cs @@ -17,7 +17,7 @@ public record ExperimentComponent { this.Id = detectedComponent.Component.Id; this.DevelopmentDependency = detectedComponent.IsDevelopmentDependency ?? false; - this.RootIds = detectedComponent.TopLevelReferrers?.Select(x => x.Id).ToHashSet() ?? new HashSet(); + this.RootIds = detectedComponent.TopLevelReferrers?.Select(x => x.Id).ToHashSet() ?? []; } /// diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentDiff.cs b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentDiff.cs index 1896d376..e0fe879e 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentDiff.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentDiff.cs @@ -27,7 +27,7 @@ public class ExperimentDiff { var oldComponentDictionary = controlGroupComponents.DistinctBy(x => x.Id).ToDictionary(x => x.Id); var newComponentDictionary = experimentGroupComponents.DistinctBy(x => x.Id).ToDictionary(x => x.Id); - additionalProperties ??= Array.Empty<(string PropertyKey, string PropertyValue)>(); + additionalProperties ??= []; this.AdditionalProperties = additionalProperties?.Select(kv => new KeyValuePair(kv.PropertyKey, kv.PropertyValue)).ToImmutableList(); this.AddedIds = newComponentDictionary.Keys.Except(oldComponentDictionary.Keys).ToImmutableList(); diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentResults.cs b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentResults.cs index b3d655f4..d66df5e2 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentResults.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Experiments/Models/ExperimentResults.cs @@ -23,7 +23,7 @@ public class ExperimentResults private readonly ConcurrentDictionary experimentalDetectors = new(); - private readonly ConcurrentBag<(string, string)> additionalProperties = new(); + private readonly ConcurrentBag<(string, string)> additionalProperties = []; /// /// The set of components in the control group. diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/CommaDelimitedConverter.cs b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/CommaDelimitedConverter.cs index e197438f..e616de4e 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/CommaDelimitedConverter.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/CommaDelimitedConverter.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Extensions; +namespace Microsoft.ComponentDetection.Orchestrator.Extensions; using System; using System.ComponentModel; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/KeyValueDelimitedConverter.cs b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/KeyValueDelimitedConverter.cs index e0f147a0..f1ac7c28 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/KeyValueDelimitedConverter.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/KeyValueDelimitedConverter.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Extensions; +namespace Microsoft.ComponentDetection.Orchestrator.Extensions; using System; using System.Collections.Generic; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/SemicolonDelimitedConverter.cs b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/SemicolonDelimitedConverter.cs index ecefa39c..e382d26b 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/SemicolonDelimitedConverter.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/SemicolonDelimitedConverter.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Extensions; +namespace Microsoft.ComponentDetection.Orchestrator.Extensions; using System; using System.ComponentModel; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/TypeRegistrar.cs b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/TypeRegistrar.cs index 853795ee..79299a74 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/TypeRegistrar.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/TypeRegistrar.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Extensions; +namespace Microsoft.ComponentDetection.Orchestrator.Extensions; using System; using System.Collections.Generic; @@ -15,7 +15,7 @@ public sealed class TypeRegistrar : ITypeRegistrar, IDisposable public TypeRegistrar(IServiceCollection services) { this.Services = services; - this.BuiltProviders = new List(); + this.BuiltProviders = []; } private IServiceCollection Services { get; } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/TypeResolver.cs b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/TypeResolver.cs index 6bc7956c..90630207 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Extensions/TypeResolver.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Extensions/TypeResolver.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Extensions; +namespace Microsoft.ComponentDetection.Orchestrator.Extensions; using System; using Microsoft.Extensions.DependencyInjection; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/IArgumentHelper.cs b/src/Microsoft.ComponentDetection.Orchestrator/IArgumentHelper.cs index b49fbf46..587b8a27 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/IArgumentHelper.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/IArgumentHelper.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator; +namespace Microsoft.ComponentDetection.Orchestrator; using CommandLine; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingResult.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingResult.cs index 9078de01..b77fad27 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingResult.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingResult.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Services; +namespace Microsoft.ComponentDetection.Orchestrator.Services; using System.Collections.Generic; using Microsoft.ComponentDetection.Common.DependencyGraph; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs index a5d03b8d..c2c28c90 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorProcessingService.cs @@ -291,7 +291,7 @@ public class DetectorProcessingService : IDetectorProcessingService { individualDetectorScanResult ??= new IndividualDetectorScanResult(); - individualDetectorScanResult.ContainerDetails ??= Enumerable.Empty(); + individualDetectorScanResult.ContainerDetails ??= []; // Additional telemetry details can safely be null return individualDetectorScanResult; @@ -374,13 +374,13 @@ public class DetectorProcessingService : IDetectorProcessingService AnsiConsole.Write(table); - var tsf = new TabularStringFormat(new Column[] - { + var tsf = new TabularStringFormat( + [ new Column { Header = "Component Detector Id", Width = 30 }, new Column { Header = "Detection Time", Width = 30, Format = "{0:g2} seconds" }, new Column { Header = "# Components Found", Width = 30, }, new Column { Header = "# Explicitly Referenced", Width = 40 }, - }); + ]); var rows = providerElapsedTime.OrderBy(a => a.Key).Select(x => { @@ -394,13 +394,13 @@ public class DetectorProcessingService : IDetectorProcessingService }; }).ToList(); - rows.Add(new object[] - { + rows.Add( + [ "Total", totalElapsedTime, providerElapsedTime.Sum(x => x.Value.ComponentsFoundCount), providerElapsedTime.Sum(x => x.Value.ExplicitlyReferencedComponentCount), - }); + ]); foreach (var line in tsf.GenerateString(rows).Split(new[] { NewLine }, StringSplitOptions.None)) { diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs index 7f5d8a0d..958a5668 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/DetectorRestrictionService.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Services; +namespace Microsoft.ComponentDetection.Orchestrator.Services; using System; using System.Collections.Generic; @@ -9,7 +9,7 @@ using Microsoft.Extensions.Logging; public class DetectorRestrictionService : IDetectorRestrictionService { - private readonly IList oldDetectorIds = new List { "MSLicenseDevNpm", "MSLicenseDevNpmList", "MSLicenseNpm", "MSLicenseNpmList" }; + private readonly IList oldDetectorIds = ["MSLicenseDevNpm", "MSLicenseDevNpmList", "MSLicenseNpm", "MSLicenseNpmList"]; private readonly string newDetectorId = "NpmWithRoots"; private readonly ILogger logger; @@ -30,10 +30,9 @@ public class DetectorRestrictionService : IDetectorRestrictionService // If we have retired detectors in the arg specified list and don't have the new detector, add the new detector if (allowedIds.Any(a => this.oldDetectorIds.Contains(a, StringComparer.OrdinalIgnoreCase)) && !allowedIds.Contains(this.newDetectorId, StringComparer.OrdinalIgnoreCase)) { - allowedIds = allowedIds.Concat(new string[] - { + allowedIds = allowedIds.Concat([ this.newDetectorId, - }); + ]); } detectors = detectors.Where(d => allowedIds.Contains(d.Id, StringComparer.OrdinalIgnoreCase)).ToList(); diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs index a3fa0f60..07780b9d 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/DefaultGraphTranslationService.cs @@ -76,7 +76,7 @@ public class DefaultGraphTranslationService : IGraphTranslationService foreach (var component in detectedComponents) { // clone custom locations and make them relative to root. - var declaredRawFilePaths = component.FilePaths ?? new HashSet(); + var declaredRawFilePaths = component.FilePaths ?? []; var componentCustomLocations = JsonConvert.DeserializeObject>(JsonConvert.SerializeObject(declaredRawFilePaths)); component.FilePaths?.Clear(); @@ -242,7 +242,7 @@ public class DefaultGraphTranslationService : IGraphTranslationService try { var relativePath = rootUri.MakeRelativeUri(new Uri(path)).ToString(); - if (!relativePath.StartsWith("/")) + if (!relativePath.StartsWith('/')) { relativePath = "/" + relativePath; } diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/GraphTranslationUtility.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/GraphTranslationUtility.cs index 7fb2834d..8259f262 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/GraphTranslationUtility.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/GraphTranslation/GraphTranslationUtility.cs @@ -23,10 +23,10 @@ public static class GraphTranslationUtility { model[graphByLocation.Key] = graphWithMetadata = new DependencyGraphWithMetadata { - ExplicitlyReferencedComponentIds = new HashSet(), - Graph = new DependencyGraph(), - DevelopmentDependencies = new HashSet(), - Dependencies = new HashSet(), + ExplicitlyReferencedComponentIds = [], + Graph = [], + DevelopmentDependencies = [], + Dependencies = [], }; } @@ -37,13 +37,13 @@ public static class GraphTranslationUtility // We set dependencies to null basically to make the serialized output look more consistent (instead of empty arrays). If another location gets merged that has dependencies, it needs to create and set the key to non-null. if (!graphWithMetadata.Graph.TryGetValue(componentId, out var dependencies)) { - dependencies = componentDependencies != null && componentDependencies.Any() ? new HashSet() : null; + dependencies = componentDependencies != null && componentDependencies.Any() ? [] : null; graphWithMetadata.Graph[componentId] = dependencies; } else if (dependencies == null && componentDependencies != null && componentDependencies.Any()) { // The explicit case where new data is found in a later graph for a given component at a location, and it is adding dependencies. - graphWithMetadata.Graph[componentId] = dependencies = new HashSet(); + graphWithMetadata.Graph[componentId] = dependencies = []; } foreach (var dependentComponentId in componentDependencies) diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/IDetectorRestrictionService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/IDetectorRestrictionService.cs index 218a7074..e3f78838 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/IDetectorRestrictionService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/IDetectorRestrictionService.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Services; +namespace Microsoft.ComponentDetection.Orchestrator.Services; using System.Collections.Generic; using Microsoft.ComponentDetection.Contracts; diff --git a/src/Microsoft.ComponentDetection.Orchestrator/Services/IScanExecutionService.cs b/src/Microsoft.ComponentDetection.Orchestrator/Services/IScanExecutionService.cs index de19f038..6132b062 100644 --- a/src/Microsoft.ComponentDetection.Orchestrator/Services/IScanExecutionService.cs +++ b/src/Microsoft.ComponentDetection.Orchestrator/Services/IScanExecutionService.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Services; +namespace Microsoft.ComponentDetection.Orchestrator.Services; using System.Threading.Tasks; using Microsoft.ComponentDetection.Contracts.BcdeModels; diff --git a/src/Microsoft.ComponentDetection/Program.cs b/src/Microsoft.ComponentDetection/Program.cs index 2c9134ae..1b044ad3 100644 --- a/src/Microsoft.ComponentDetection/Program.cs +++ b/src/Microsoft.ComponentDetection/Program.cs @@ -62,7 +62,7 @@ app.Configure( config.AddCommand("scan") .WithDescription("Initiates a scan"); - config.SetExceptionHandler((e) => + config.SetExceptionHandler((e, _) => { logger.LogError(e, "An error occurred while executing the command"); }); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/AsyncExceptionTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/AsyncExceptionTests.cs index 7bd941c4..82e323e9 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/AsyncExceptionTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/AsyncExceptionTests.cs @@ -24,13 +24,13 @@ public class AsyncExceptionTests [TestMethod] public async Task ExecuteWithoutTimeAsync_ThrowsTimeoutExceptionAsync() { - var toExecute = async () => + static async Task ToExecuteAsync() { await Task.Delay(5000); return 0; - }; + } - var func = async () => await AsyncExecution.ExecuteWithTimeoutAsync(toExecute, TimeSpan.FromSeconds(1), CancellationToken.None); + var func = async () => await AsyncExecution.ExecuteWithTimeoutAsync(ToExecuteAsync, TimeSpan.FromSeconds(1), CancellationToken.None); await func.Should().ThrowAsync(); } @@ -48,9 +48,9 @@ public class AsyncExceptionTests [TestMethod] public async Task ExecuteVoidWithTimeoutAsync_ThrowsTimeoutExceptionAsync() { - var toExecute = () => Task.Delay(5000).Wait(); + static void ToExecute() => Task.Delay(5000).Wait(); - var func = async () => await AsyncExecution.ExecuteVoidWithTimeoutAsync(toExecute, TimeSpan.FromSeconds(1), CancellationToken.None); + var func = async () => await AsyncExecution.ExecuteVoidWithTimeoutAsync(ToExecute, TimeSpan.FromSeconds(1), CancellationToken.None); await func.Should().ThrowAsync(); } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs index c8709e01..55fa6733 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/BaseDetectionTelemetryRecordTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.Collections.Generic; @@ -41,22 +41,17 @@ public class BaseDetectionTelemetryRecordTests recordName.Should().NotBeNullOrEmpty($"RecordName not set for {type.FullName}!"); - if (dic.TryGetValue(recordName, out var value)) - { - Assert.Fail($"Duplicate RecordName:`{recordName}` found for {type.FullName} and {value.FullName}!"); - } - else - { - dic.Add(recordName, type); - } + dic.Should().NotContainKey(recordName, "Duplicate RecordName:`{RecordName}` found for {TypeName}!", recordName, type.FullName); + + dic.Add(recordName, type); } } [TestMethod] public void SerializableProperties() { - var serializableTypes = new HashSet(new[] - { + var serializableTypes = new HashSet( + [ typeof(string), typeof(string[]), typeof(bool), @@ -64,7 +59,7 @@ public class BaseDetectionTelemetryRecordTests typeof(int?), typeof(TimeSpan?), typeof(HttpStatusCode), - }); + ]); foreach (var type in this.recordTypes) { @@ -73,7 +68,7 @@ public class BaseDetectionTelemetryRecordTests if (!serializableTypes.Contains(property.PropertyType) && Attribute.GetCustomAttribute(property.PropertyType, typeof(DataContractAttribute)) == null) { - Assert.Fail( + Attribute.GetCustomAttribute(property.PropertyType, typeof(DataContractAttribute)).Should().NotBeNull( $"Type {property.PropertyType} on {type.Name}.{property.Name} is not allowed! " + "Add it to the list if it serializes properly to JSON!"); } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs index 913248af..b12b05af 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/CommandLineInvocationServiceTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.IO; @@ -31,14 +31,14 @@ public class CommandLineInvocationServiceTests [SkipTestIfNotWindows] public async Task FallbackWorksIfBadCommandsAreFirstAsync() { - var result = await this.commandLineService.CanCommandBeLocatedAsync("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe", "cmd.exe" }, "/C"); + var result = await this.commandLineService.CanCommandBeLocatedAsync("57AB44A4-885A-47F4-866C-41417133B983", ["fakecommandexecutable.exe", "cmd.exe"], "/C"); result.Should().BeTrue(); } [SkipTestIfNotWindows] public async Task ReturnsFalseIfNoValidCommandIsFoundAsync() { - var result = await this.commandLineService.CanCommandBeLocatedAsync("57AB44A4-885A-47F4-866C-41417133B983", new[] { "fakecommandexecutable.exe" }, "/C"); + var result = await this.commandLineService.CanCommandBeLocatedAsync("57AB44A4-885A-47F4-866C-41417133B983", ["fakecommandexecutable.exe"], "/C"); result.Should().BeFalse(); } diff --git a/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs index 4dab2cb3..38f0a2cc 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/ComponentStreamEnumerableTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.IO; @@ -27,8 +27,7 @@ public class ComponentStreamEnumerableTests var tempFileOne = Path.GetTempFileName(); var tempFileTwo = Path.GetTempFileName(); var enumerable = new ComponentStreamEnumerable( - new[] - { + [ new MatchedFile { File = new FileInfo(tempFileOne), @@ -39,7 +38,7 @@ public class ComponentStreamEnumerableTests File = new FileInfo(tempFileTwo), Pattern = "Some Pattern", }, - }, + ], this.loggerMock.Object); enumerable.Should().HaveCount(2); @@ -68,8 +67,7 @@ public class ComponentStreamEnumerableTests It.IsAny(), It.IsAny>())); var enumerable = new ComponentStreamEnumerable( - new[] - { + [ new MatchedFile { File = new FileInfo(tempFileOne), @@ -80,7 +78,7 @@ public class ComponentStreamEnumerableTests File = new FileInfo(tempFileTwo), Pattern = "Some Pattern", }, - }, + ], this.loggerMock.Object).ToList(); enumerable.Should().ContainSingle(); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/ConsoleWritingServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/ConsoleWritingServiceTests.cs index 19ed27af..6ff4bb84 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/ConsoleWritingServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/ConsoleWritingServiceTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.IO; diff --git a/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs index 04e8de56..200f03c5 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/DependencyGraphTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using FluentAssertions; diff --git a/test/Microsoft.ComponentDetection.Common.Tests/DependencyScopeComparerTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/DependencyScopeComparerTests.cs index 14897e75..e9080932 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/DependencyScopeComparerTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/DependencyScopeComparerTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using FluentAssertions; using Microsoft.ComponentDetection.Contracts.BcdeModels; diff --git a/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs index 80ce9232..b203be82 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/DockerServiceTests.cs @@ -1,7 +1,6 @@ namespace Microsoft.ComponentDetection.Common.Tests; using System; -using System.Collections.Generic; using System.Threading.Tasks; using Docker.DotNet.Models; using FluentAssertions; @@ -77,7 +76,7 @@ public class DockerServiceTests [SkipTestOnWindows] public async Task DockerService_CanCreateAndRunImageAsync() { - var (stdout, stderr) = await this.dockerService.CreateAndRunContainerAsync(TestImage, new List()); + var (stdout, stderr) = await this.dockerService.CreateAndRunContainerAsync(TestImage, []); stdout.Should().StartWith("\nHello from Docker!"); stderr.Should().BeEmpty(); } @@ -89,13 +88,13 @@ public class DockerServiceTests { Config = new Config { - Env = new List - { + Env = + [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "MARATHON_APP_RESOURCE_CPU=1", "REGION=local", "PIP_INDEX_URL=https://user:aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa@someregistry.localhost.com", - }, + ], }, }; @@ -103,13 +102,13 @@ public class DockerServiceTests { Config = new Config { - Env = new List - { + Env = + [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "MARATHON_APP_RESOURCE_CPU=1", "REGION=local", $"PIP_INDEX_URL=https://{StringUtilities.SensitivePlaceholder}@someregistry.localhost.com", - }, + ], }, }; @@ -120,12 +119,12 @@ public class DockerServiceTests { Config = new Config { - Env = new List - { + Env = + [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "MARATHON_APP_RESOURCE_CPU=1", "REGION=local", - }, + ], }, }; @@ -133,12 +132,12 @@ public class DockerServiceTests { Config = new Config { - Env = new List - { + Env = + [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "MARATHON_APP_RESOURCE_CPU=1", "REGION=local", - }, + ], }, }; @@ -149,13 +148,13 @@ public class DockerServiceTests { Config = new Config { - Env = new List - { + Env = + [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "MARATHON_APP_RESOURCE_CPU=1", "REGION=local", "PIP_INDEX_URL=https://someregistry.localhost.com", - }, + ], }, }; @@ -163,13 +162,13 @@ public class DockerServiceTests { Config = new Config { - Env = new List - { + Env = + [ "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin", "MARATHON_APP_RESOURCE_CPU=1", "REGION=local", "PIP_INDEX_URL=https://someregistry.localhost.com", - }, + ], }, }; @@ -211,7 +210,7 @@ public class DockerServiceTests { Config = new Config { - Env = new List(), + Env = [], }, }; diff --git a/test/Microsoft.ComponentDetection.Common.Tests/FileEnumerationTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/FileEnumerationTests.cs index c8420d9e..ed88ef6a 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/FileEnumerationTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/FileEnumerationTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.Collections.Generic; @@ -20,13 +20,14 @@ public class FileEnumerationTests var testDirectory = Environment.GetEnvironmentVariable("COMPONENT_DETECTION_SYMLINK_TEST"); if (string.IsNullOrWhiteSpace(testDirectory)) { - Assert.Inconclusive("Test directory environment variable isn't set. Not testing"); + // Test directory environment variable isn't set. Not testing + return; } var loggerMock = new Mock>(); var pathUtility = new PathUtilityService(loggerMock.Object); - var sfe = new SafeFileEnumerable(new DirectoryInfo(Path.Combine(testDirectory, "root")), new[] { "*" }, loggerMock.Object, pathUtility, (name, directoryName) => false, true); + var sfe = new SafeFileEnumerable(new DirectoryInfo(Path.Combine(testDirectory, "root")), ["*"], loggerMock.Object, pathUtility, (name, directoryName) => false, true); var foundFiles = new List(); foreach (var f in sfe) diff --git a/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs index dcc1014a..eb0965c8 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/FileWritingServiceTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.Collections.Generic; diff --git a/test/Microsoft.ComponentDetection.Common.Tests/PatternMatchingUtilityTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/PatternMatchingUtilityTests.cs index 574863c7..4779fdaf 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/PatternMatchingUtilityTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/PatternMatchingUtilityTests.cs @@ -14,7 +14,7 @@ public class PatternMatchingUtilityTests var pattern = "test*"; var input = "test123"; - var matcher = PatternMatchingUtility.GetFilePatternMatcher(new[] { pattern }); + var matcher = PatternMatchingUtility.GetFilePatternMatcher([pattern]); matcher(input).Should().BeTrue(); matcher("123test").Should().BeFalse(); @@ -26,7 +26,7 @@ public class PatternMatchingUtilityTests var pattern = "*test"; var input = "123test"; - var matcher = PatternMatchingUtility.GetFilePatternMatcher(new[] { pattern }); + var matcher = PatternMatchingUtility.GetFilePatternMatcher([pattern]); matcher(input).Should().BeTrue(); matcher("test123").Should().BeFalse(); @@ -38,7 +38,7 @@ public class PatternMatchingUtilityTests var pattern = "test"; var input = "test"; - var matcher = PatternMatchingUtility.GetFilePatternMatcher(new[] { pattern }); + var matcher = PatternMatchingUtility.GetFilePatternMatcher([pattern]); matcher(input).Should().BeTrue(); matcher("123test").Should().BeFalse(); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs index 632217c8..1579128c 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/SafeFileEnumerableTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.Collections.Generic; @@ -47,7 +47,7 @@ public class SafeFileEnumerableTests File.Create(file0).Close(); File.Create(subFile0).Close(); - IEnumerable searchPatterns = new List { name }; + IEnumerable searchPatterns = [name]; this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(It.IsAny())).Returns((s) => s); this.pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); @@ -75,7 +75,7 @@ public class SafeFileEnumerableTests File.Create(file0).Close(); File.Create(Path.Combine(this.temporaryDirectory, "SubDir", name)).Close(); - IEnumerable searchPatterns = new List { name }; + IEnumerable searchPatterns = [name]; this.pathUtilityServiceMock.Setup(x => x.MatchesPattern(name, name)).Returns(true); @@ -101,7 +101,7 @@ public class SafeFileEnumerableTests File.Create(Path.Combine(this.temporaryDirectory, name)).Close(); File.Create(Path.Combine(this.temporaryDirectory, "SubDir", name)).Close(); - IEnumerable searchPatterns = new List { name }; + IEnumerable searchPatterns = [name]; this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(subDir.FullName)).Returns(subDir.FullName); var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, true); @@ -132,7 +132,7 @@ public class SafeFileEnumerableTests this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(subDir.FullName)).Returns(subDir.FullName); this.pathUtilityServiceMock.Setup(x => x.ResolvePhysicalPath(symlink)).Returns(subDir.FullName); - IEnumerable searchPatterns = new List { name }; + IEnumerable searchPatterns = [name]; var enumerable = new SafeFileEnumerable(new DirectoryInfo(this.temporaryDirectory), searchPatterns, this.loggerMock.Object, this.pathUtilityServiceMock.Object, (directoryName, span) => false, true); diff --git a/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs b/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs index 08457b4f..8d08dbb6 100644 --- a/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs +++ b/test/Microsoft.ComponentDetection.Common.Tests/TabularStringFormatTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Common.Tests; +namespace Microsoft.ComponentDetection.Common.Tests; using System; using System.Linq; @@ -17,18 +17,18 @@ public class TabularStringFormatTests [TestInitialize] public void TestInitialize() { - this.columns = new Column[] - { + this.columns = + [ 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 }, - }; + ]; - this.rows = new[] - { - // One row - new[] { "a", "b", "c" }, - }; + // One row + this.rows = + [ + ["a", "b", "c"], + ]; this.tsf = new TabularStringFormat(this.columns); } @@ -82,7 +82,7 @@ public class TabularStringFormatTests public void GenerateString_ThrowsInvalidOperationException() { // add an extra row - this.rows = this.rows.Concat(new[] { new[] { "a", "b", "c", "d" } }).ToArray(); + this.rows = this.rows.Concat([["a", "b", "c", "d"]]).ToArray(); var action = () => this.tsf.GenerateString(this.rows); diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/DetectedComponentTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/DetectedComponentTests.cs index 0ea06320..823442d0 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/DetectedComponentTests.cs +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/DetectedComponentTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.Tests; +namespace Microsoft.ComponentDetection.Contracts.Tests; using FluentAssertions; using Microsoft.ComponentDetection.Contracts.TypedComponent; diff --git a/test/Microsoft.ComponentDetection.Contracts.Tests/PurlGenerationTests.cs b/test/Microsoft.ComponentDetection.Contracts.Tests/PurlGenerationTests.cs index 1268745a..a0834f7b 100644 --- a/test/Microsoft.ComponentDetection.Contracts.Tests/PurlGenerationTests.cs +++ b/test/Microsoft.ComponentDetection.Contracts.Tests/PurlGenerationTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Contracts.Tests; +namespace Microsoft.ComponentDetection.Contracts.Tests; using FluentAssertions; using Microsoft.ComponentDetection.Contracts.TypedComponent; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/ConanLockComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/ConanLockComponentDetectorTests.cs index 69208325..b509188d 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/ConanLockComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/ConanLockComponentDetectorTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System; using System.Collections.Generic; @@ -142,7 +142,7 @@ public class ConanLockComponentDetectorTests : BaseDetectorTest packageVersions = new Dictionary() { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs index 91525474..aa5df714 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentDetectorTests.cs @@ -178,7 +178,7 @@ require ( .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(4); + componentRecorder.GetDetectedComponents().Should().HaveCount(4); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); dependencyGraphs.Keys.Should().HaveCount(2); @@ -203,7 +203,7 @@ $#26^#25%4"; .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -222,7 +222,7 @@ github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("go.mod", goMod) - .WithFile("go.mod", goMod, new[] { "go.mod" }) + .WithFile("go.mod", goMod, ["go.mod"]) .WithFile("go.sum", goSum) .ExecuteDetectorAsync(); @@ -405,14 +405,16 @@ replace ( this.commandLineMock.Setup(x => x.CanCommandBeLocatedAsync("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "list", "-mod=readonly", "-m", "-json", "all" })) + string[] cmdParams = ["list", "-mod=readonly", "-m", "-json", "all"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "mod", "graph" })) + cmdParams = ["mod", "graph"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, @@ -467,14 +469,16 @@ github.com/prometheus/client_golang@v1.12.1 github.com/prometheus/common@v0.32.1 this.commandLineMock.Setup(x => x.CanCommandBeLocatedAsync("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "list", "-mod=readonly", "-m", "-json", "all" })) + string[] cmdParams = ["list", "-mod=readonly", "-m", "-json", "all"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "mod", "graph" })) + cmdParams = ["mod", "graph"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentWithReplaceDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentWithReplaceDetectorTests.cs index c8e9c5f5..67789938 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentWithReplaceDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GoComponentWithReplaceDetectorTests.cs @@ -178,7 +178,7 @@ require ( .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(4); + componentRecorder.GetDetectedComponents().Should().HaveCount(4); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); dependencyGraphs.Keys.Should().HaveCount(2); @@ -203,7 +203,7 @@ $#26^#25%4"; .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -222,7 +222,7 @@ github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5y var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("go.mod", goMod) - .WithFile("go.mod", goMod, new[] { "go.mod" }) + .WithFile("go.mod", goMod, ["go.mod"]) .WithFile("go.sum", goSum) .ExecuteDetectorAsync(); @@ -413,14 +413,16 @@ replace ( this.commandLineMock.Setup(x => x.CanCommandBeLocatedAsync("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "list", "-mod=readonly", "-m", "-json", "all" })) + string[] cmdParams = ["list", "-mod=readonly", "-m", "-json", "all"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "mod", "graph" })) + cmdParams = ["mod", "graph"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, @@ -481,14 +483,16 @@ replace ( this.commandLineMock.Setup(x => x.CanCommandBeLocatedAsync("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "list", "-mod=readonly", "-m", "-json", "all" })) + string[] cmdParams = ["list", "-mod=readonly", "-m", "-json", "all"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "mod", "graph" })) + cmdParams = ["mod", "graph"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, @@ -543,14 +547,16 @@ github.com/prometheus/client_golang@v1.12.1 github.com/prometheus/common@v0.32.1 this.commandLineMock.Setup(x => x.CanCommandBeLocatedAsync("go", null, It.IsAny(), It.IsAny())) .ReturnsAsync(true); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "list", "-mod=readonly", "-m", "-json", "all" })) + string[] cmdParams = ["list", "-mod=readonly", "-m", "-json", "all"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, StdOut = buildDependencies, }); - this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), new[] { "mod", "graph" })) + cmdParams = ["mod", "graph"]; + this.commandLineMock.Setup(x => x.ExecuteCommandAsync("go", null, It.IsAny(), cmdParams)) .ReturnsAsync(new CommandLineExecutionResult { ExitCode = 0, diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs index dbe7b175..2a70a467 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleComponentDetectorTests.cs @@ -34,7 +34,7 @@ public class GradleComponentDetectorTests : BaseDetectorTest { @@ -204,7 +204,7 @@ $#26^#25%4"; .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(5); + componentRecorder.GetDetectedComponents().Should().HaveCount(5); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); dependencyGraphs.Keys.Should().ContainSingle(); @@ -294,7 +294,7 @@ org.springframework:spring-core:5.0.5.RELEASE"; var devLockfile2 = @"org.jacoco:org.jacoco.agent:0.8.8"; - this.envVarService.Setup(x => x.GetListEnvironmentVariable("CD_GRADLE_DEV_LOCKFILES", ",")).Returns(new List { "dev1\\gradle.lockfile", "dev2\\gradle.lockfile" }); + this.envVarService.Setup(x => x.GetListEnvironmentVariable("CD_GRADLE_DEV_LOCKFILES", ",")).Returns(["dev1\\gradle.lockfile", "dev2\\gradle.lockfile"]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("dev1\\gradle.lockfile", devLockfile1) @@ -347,7 +347,7 @@ org.springframework:spring-core:5.0.5.RELEASE"; org.springframework:spring-core:5.0.5.RELEASE=assembleRelease,testDebugUnitTest org.hamcrest:hamcrest-core:2.2=testReleaseUnitTest"; - this.envVarService.Setup(x => x.GetListEnvironmentVariable("CD_GRADLE_DEV_CONFIGURATIONS", ",")).Returns(new List { "testDebugUnitTest", "testReleaseUnitTest" }); + this.envVarService.Setup(x => x.GetListEnvironmentVariable("CD_GRADLE_DEV_CONFIGURATIONS", ",")).Returns(["testDebugUnitTest", "testReleaseUnitTest"]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("gradle.lockfile", lockfile) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleTestUtilities.cs index 5771b4be..ab22f15f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/GradleTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/GradleTestUtilities.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Collections.Generic; using System.IO; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs index 03f4236b..077c209c 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/IvyDetectorTests.cs @@ -34,7 +34,7 @@ public class IvyDetectorTests : BaseDetectorTest var (detectorResult, componentRecorder) = await this.DetectorTestUtility.ExecuteDetectorAsync(); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); } @@ -110,16 +110,16 @@ public class IvyDetectorTests : BaseDetectorTest // There is only one graph var dependencyGraph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); - dependencyGraph.GetDependenciesForComponent(d1Id).Should().HaveCount(0); + dependencyGraph.GetDependenciesForComponent(d1Id).Should().BeEmpty(); dependencyGraph.IsComponentExplicitlyReferenced(d1Id).Should().BeTrue(); dependencyGraph.IsDevelopmentDependency(d1Id).Should().BeTrue(); - dependencyGraph.GetDependenciesForComponent(d2Id).Should().HaveCount(1); + dependencyGraph.GetDependenciesForComponent(d2Id).Should().ContainSingle(); dependencyGraph.GetDependenciesForComponent(d2Id).Should().Contain(d3Id); dependencyGraph.IsComponentExplicitlyReferenced(d2Id).Should().BeTrue(); dependencyGraph.IsDevelopmentDependency(d2Id).Should().BeFalse(); - dependencyGraph.GetDependenciesForComponent(d3Id).Should().HaveCount(0); + dependencyGraph.GetDependenciesForComponent(d3Id).Should().BeEmpty(); dependencyGraph.IsComponentExplicitlyReferenced(d3Id).Should().BeFalse(); dependencyGraph.IsDevelopmentDependency(d3Id).Should().BeFalse(); } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs index 73150957..94c2287f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxContainerDetectorTests.cs @@ -25,14 +25,14 @@ public class LinuxContainerDetectorTests private const string NodeLatestDigest = "2a22e4a1a550"; private const string BashPackageId = "Ubuntu 20.04 bash 5.0-6ubuntu1 - Linux"; - private static readonly IEnumerable LinuxComponents = new List - { + private static readonly IEnumerable LinuxComponents = + [ new LayerMappedLinuxComponents { DockerLayer = new DockerLayer(), - LinuxComponents = new List { new LinuxComponent("Ubuntu", "20.04", "bash", "5.0-6ubuntu1") }, + LinuxComponents = [new LinuxComponent("Ubuntu", "20.04", "bash", "5.0-6ubuntu1")], }, - }; + ]; private readonly Mock mockDockerService; private readonly Mock mockLogger; @@ -47,7 +47,7 @@ public class LinuxContainerDetectorTests this.mockDockerService.Setup(service => service.TryPullImageAsync(It.IsAny(), It.IsAny())) .ReturnsAsync(true); this.mockDockerService.Setup(service => service.InspectImageAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(new ContainerDetails { Id = 1, ImageId = NodeLatestDigest, Layers = Enumerable.Empty() }); + .ReturnsAsync(new ContainerDetails { Id = 1, ImageId = NodeLatestDigest, Layers = [] }); this.mockLogger = new Mock(); this.mockLinuxContainerDetectorLogger = new Mock>(); @@ -62,7 +62,7 @@ public class LinuxContainerDetectorTests { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage }, componentRecorder); + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, [NodeLatestImage], componentRecorder); var linuxContainerDetector = new LinuxContainerDetector( this.mockSyftLinuxScanner.Object, @@ -87,7 +87,7 @@ public class LinuxContainerDetectorTests { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage }, componentRecorder); + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, [NodeLatestImage], componentRecorder); this.mockDockerService.Setup(service => service.CanRunLinuxContainersAsync(It.IsAny())) .ReturnsAsync(false); @@ -144,7 +144,7 @@ public class LinuxContainerDetectorTests { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { "UPPERCASE" }, componentRecorder); + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, ["UPPERCASE"], componentRecorder); var linuxContainerDetector = new LinuxContainerDetector( this.mockSyftLinuxScanner.Object, @@ -167,7 +167,7 @@ public class LinuxContainerDetectorTests { var componentRecorder = new ComponentRecorder(); - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, new List { NodeLatestImage, NodeLatestDigest }, componentRecorder); + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, null, [NodeLatestImage, NodeLatestDigest], componentRecorder); var linuxContainerDetector = new LinuxContainerDetector( this.mockSyftLinuxScanner.Object, @@ -190,7 +190,7 @@ public class LinuxContainerDetectorTests public async Task TestLinuxContainerDetector_TimeoutParameterSpecifiedAsync() { var detectorArgs = new Dictionary { { "Linux.ScanningTimeoutSec", "2" } }; - var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, detectorArgs, new List { NodeLatestImage }, new ComponentRecorder()); + var scanRequest = new ScanRequest(new DirectoryInfo(Path.GetTempPath()), (_, __) => false, this.mockLogger.Object, detectorArgs, [NodeLatestImage], new ComponentRecorder()); var linuxContainerDetector = new LinuxContainerDetector( this.mockSyftLinuxScanner.Object, @@ -212,7 +212,7 @@ public class LinuxContainerDetectorTests 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" }); + .ReturnsAsync(new ContainerDetails { Id = 1, ImageId = NodeLatestDigest, Layers = [], BaseImageRef = "scratch" }); await this.TestLinuxContainerDetectorAsync(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs index 97ec67fa..48b1d7f4 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/LinuxScannerTests.cs @@ -119,7 +119,7 @@ public class LinuxScannerTests this.mockDockerService.Setup(service => service.CreateAndRunContainerAsync(It.IsAny(), It.IsAny>(), It.IsAny())) .ReturnsAsync((syftOutput, string.Empty)); - var result = (await this.linuxScanner.ScanLinuxAsync("fake_hash", new[] { new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" } }, 0)).First().LinuxComponents; + var result = (await this.linuxScanner.ScanLinuxAsync("fake_hash", [new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" }], 0)).First().LinuxComponents; result.Should().ContainSingle(); var package = result.First(); @@ -138,7 +138,7 @@ public class LinuxScannerTests this.mockDockerService.Setup(service => service.CreateAndRunContainerAsync(It.IsAny(), It.IsAny>(), It.IsAny())) .ReturnsAsync((syftOutput, string.Empty)); - var result = (await this.linuxScanner.ScanLinuxAsync("fake_hash", new[] { new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" } }, 0)).First().LinuxComponents; + var result = (await this.linuxScanner.ScanLinuxAsync("fake_hash", [new DockerLayer { LayerIndex = 0, DiffId = "sha256:f95fc50d21d981f1efe1f04109c2c3287c271794f5d9e4fdf9888851a174a971" }], 0)).First().LinuxComponents; result.Should().ContainSingle(); var package = result.First(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs index 78fda3b0..21623003 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenCommandServiceTests.cs @@ -110,7 +110,7 @@ public class MavenCommandServiceTests }, }; - cts.Cancel(); + await cts.CancelAsync(); var bcdeMvnFileName = "bcde.mvndeps"; var cliParameters = new[] { "dependency:tree", "-B", $"-DoutputFile={bcdeMvnFileName}", "-DoutputType=text", $"-f{pomLocation}" }; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs index 21147bbb..5c7791fc 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenParsingUtilitiesTests.cs @@ -1,6 +1,5 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; -using System; using FluentAssertions; using Microsoft.ComponentDetection.Contracts.BcdeModels; using Microsoft.ComponentDetection.Contracts.TypedComponent; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs index 2fa78805..7612f5cd 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenStyleDependencyGraphParserTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System.IO; using System.Linq; @@ -80,6 +80,6 @@ public class MavenStyleDependencyGraphParserTests guavaDependencies.Should().HaveCount(5); guavaDependencies.Should().Contain(animalSnifferAnnotations.Component.Id); - dependencyGraph.GetDependenciesForComponent(animalSnifferAnnotations.Component.Id).Should().HaveCount(0); + dependencyGraph.GetDependenciesForComponent(animalSnifferAnnotations.Component.Id).Should().BeEmpty(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenTestUtilities.cs index 997c683c..38d6c9a3 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MavenTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MavenTestUtilities.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; public static class MavenTestUtilities { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj b/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj index efcd7733..66c23ceb 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/Microsoft.ComponentDetection.Detectors.Tests.csproj @@ -14,8 +14,8 @@ - - + + diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs index f74e5c20..7adf0fee 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/MvnCliDetectorTests.cs @@ -36,7 +36,7 @@ public class MvnCliDetectorTests : BaseDetectorTest var (detectorResult, componentRecorder) = await this.DetectorTestUtility .ExecuteDetectorAsync(); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); detectorResult.ResultCode.Should().Be(ProcessingResultCode.Success); } @@ -167,21 +167,21 @@ public class MvnCliDetectorTests : BaseDetectorTest // There is only one graph var dependencyGraph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); - dependencyGraph.GetDependenciesForComponent(explicitReferencedComponentId).Should().HaveCount(1); + dependencyGraph.GetDependenciesForComponent(explicitReferencedComponentId).Should().ContainSingle(); dependencyGraph.GetDependenciesForComponent(explicitReferencedComponentId).Should().Contain(intermediateParentComponentId); dependencyGraph.IsComponentExplicitlyReferenced(explicitReferencedComponentId).Should().BeTrue(); - dependencyGraph.GetDependenciesForComponent(intermediateParentComponentId).Should().HaveCount(1); + dependencyGraph.GetDependenciesForComponent(intermediateParentComponentId).Should().ContainSingle(); dependencyGraph.GetDependenciesForComponent(intermediateParentComponentId).Should().Contain(leafComponentId); dependencyGraph.IsComponentExplicitlyReferenced(intermediateParentComponentId).Should().BeFalse(); - dependencyGraph.GetDependenciesForComponent(leafComponentId).Should().HaveCount(0); + dependencyGraph.GetDependenciesForComponent(leafComponentId).Should().BeEmpty(); dependencyGraph.IsComponentExplicitlyReferenced(leafComponentId).Should().BeFalse(); } protected bool ShouldBeEquivalentTo(IEnumerable result, IEnumerable expected) { - result.Should().BeEquivalentTo(expected); + result.Should().BeEquivalentTo(expected); return true; } @@ -194,6 +194,6 @@ public class MvnCliDetectorTests : BaseDetectorTest this.mavenCommandServiceMock.Setup(x => x.MavenCLIExistsAsync()) .ReturnsAsync(true); this.DetectorTestUtility.WithFile("pom.xml", content) - .WithFile("pom.xml", content, searchPatterns: new[] { bcdeMvnFileName }); + .WithFile("pom.xml", content, searchPatterns: [bcdeMvnFileName]); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs index ccfb6eba..bce143d4 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Collections.Generic; using System.Linq; @@ -16,7 +16,7 @@ using static Microsoft.ComponentDetection.Detectors.Tests.Utilities.TestUtilityE [TestCategory("Governance/ComponentDetection")] public class NpmDetectorTests : BaseDetectorTest { - private readonly List packageJsonSearchPattern = new List { "package.json" }; + private readonly List packageJsonSearchPattern = ["package.json"]; [TestMethod] public async Task TestNpmDetector_NameAndVersionDetectedAsync() diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs index 0b9434b3..f39fe83e 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmDetectorWithRootsTests.cs @@ -22,8 +22,8 @@ public class NpmDetectorWithRootsTests : BaseDetectorTest packageJsonSearchPattern = new() { "package.json" }; - private readonly List packageLockJsonSearchPatterns = new() { "package-lock.json", "npm-shrinkwrap.json", "lerna.json" }; + private readonly List packageJsonSearchPattern = ["package.json"]; + private readonly List packageLockJsonSearchPatterns = ["package-lock.json", "npm-shrinkwrap.json", "lerna.json"]; private readonly Mock mockPathUtilityService; public NpmDetectorWithRootsTests() @@ -102,7 +102,7 @@ public class NpmDetectorWithRootsTests : BaseDetectorTest { private readonly string packageLockJsonFileName = "package-lock.json"; private readonly string packageJsonFileName = "package.json"; - private readonly List packageJsonSearchPattern = new() { "package.json" }; - private readonly List packageLockJsonSearchPatterns = new() { "package-lock.json", "npm-shrinkwrap.json", "lerna.json" }; + private readonly List packageJsonSearchPattern = ["package.json"]; + private readonly List packageLockJsonSearchPatterns = ["package-lock.json", "npm-shrinkwrap.json", "lerna.json"]; private readonly Mock mockPathUtilityService; public NpmLockfile3DetectorTests() @@ -280,8 +280,8 @@ public class NpmLockfile3DetectorTests : BaseDetectorTest var dependencyGraph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); - dependencyGraph.GetDependenciesForComponent(componentAId).Should().HaveCount(1); + dependencyGraph.GetDependenciesForComponent(componentAId).Should().ContainSingle(); dependencyGraph.GetDependenciesForComponent(componentAId).Should().Contain(componentBId); - dependencyGraph.GetDependenciesForComponent(componentBId).Should().HaveCount(0); + dependencyGraph.GetDependenciesForComponent(componentBId).Should().BeEmpty(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs index ca355115..580a970c 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NpmUtilitiesTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Linq; using FluentAssertions; @@ -173,14 +173,14 @@ public class NpmUtilitiesTests NpmComponentUtilities.TraverseAndRecordComponents(currentDependency, singleFileComponentRecorder1, typedComponent, typedComponent); NpmComponentUtilities.TraverseAndRecordComponents(currentDependency, singleFileComponentRecorder2, typedComponent, typedComponent); - componentRecorder.GetDetectedComponents().Count().Should().Be(1); + componentRecorder.GetDetectedComponents().Should().ContainSingle(); componentRecorder.GetComponent(typedComponent.Id).Should().NotBeNull(); var graph1 = componentRecorder.GetDependencyGraphsByLocation()["/this/is/a/test/path/"]; var graph2 = componentRecorder.GetDependencyGraphsByLocation()["/this/is/a/different/path/"]; - graph1.GetExplicitReferencedDependencyIds(typedComponent.Id).Contains(typedComponent.Id).Should().BeTrue(); - graph2.GetExplicitReferencedDependencyIds(typedComponent.Id).Contains(typedComponent.Id).Should().BeTrue(); + graph1.GetExplicitReferencedDependencyIds(typedComponent.Id).Should().Contain(typedComponent.Id); + graph2.GetExplicitReferencedDependencyIds(typedComponent.Id).Should().Contain(typedComponent.Id); componentRecorder.GetEffectiveDevDependencyValue(typedComponent.Id).GetValueOrDefault(true).Should().BeFalse(); var json1 = @"{ @@ -200,14 +200,14 @@ public class NpmUtilitiesTests NpmComponentUtilities.TraverseAndRecordComponents(currentDependency1, singleFileComponentRecorder2, typedComponent1, typedComponent1); - componentRecorder.GetDetectedComponents().Count().Should().Be(2); + componentRecorder.GetDetectedComponents().Should().HaveCount(2); - graph2.GetExplicitReferencedDependencyIds(typedComponent1.Id).Contains(typedComponent1.Id).Should().BeTrue(); + graph2.GetExplicitReferencedDependencyIds(typedComponent1.Id).Should().Contain(typedComponent1.Id); componentRecorder.GetEffectiveDevDependencyValue(typedComponent1.Id).GetValueOrDefault(false).Should().BeTrue(); NpmComponentUtilities.TraverseAndRecordComponents(currentDependency1, singleFileComponentRecorder2, typedComponent, typedComponent1, parentComponentId: typedComponent1.Id); - componentRecorder.GetDetectedComponents().Count().Should().Be(2); + componentRecorder.GetDetectedComponents().Should().HaveCount(2); var explicitlyReferencedDependencyIds = graph2.GetExplicitReferencedDependencyIds(typedComponent.Id); explicitlyReferencedDependencyIds.Should().Contain(typedComponent.Id); explicitlyReferencedDependencyIds.Should().Contain(typedComponent1.Id); @@ -231,7 +231,7 @@ public class NpmUtilitiesTests addedComponent1.Should().BeEquivalentTo(expectedDetectedComponent, options => options.Excluding(obj => obj.DependencyRoots)); addedComponent2.Should().BeEquivalentTo(expectedDetectedDevComponent, options => options.Excluding(obj => obj.DependencyRoots)); - componentRecorder.GetDetectedComponents().Count().Should().Be(2); + componentRecorder.GetDetectedComponents().Should().HaveCount(2); var nonDevComponent = componentRecorder.GetComponent(expectedDetectedComponent.Component.Id); nonDevComponent.Should().BeEquivalentTo(expectedDetectedComponent.Component); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs index 7fab4333..c58d74bc 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetComponentDetectorTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System; using System.Collections.Generic; @@ -23,7 +23,7 @@ using Moq; public class NuGetComponentDetectorTests : BaseDetectorTest { private static readonly IEnumerable DetectorSearchPattern = - new List { "*.nupkg", "*.nuspec", "nuget.config", "paket.lock" }; + ["*.nupkg", "*.nuspec", "nuget.config", "paket.lock"]; private readonly Mock> mockLogger; @@ -39,7 +39,7 @@ public class NuGetComponentDetectorTests : BaseDetectorTest)It.IsAny())); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(2); + componentRecorder.GetDetectedComponents().Should().HaveCount(2); } [TestMethod] @@ -232,7 +232,7 @@ NUGET Match.Create>(stuff => DetectorSearchPattern.Intersect(stuff).Count() == DetectorSearchPattern.Count()), It.IsAny(), It.IsAny())) - .Returns(Enumerable.Empty()); + .Returns([]); // This is matching the additional directory that is ONLY sourced in the nuget.config. If this works, we would see the component in our results. componentStreamEnumerableFactoryMock.Setup( @@ -268,13 +268,13 @@ NUGET directoryWalkerMock.VerifyAll(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(1); + componentRecorder.GetDetectedComponents().Should().ContainSingle(); } [TestMethod] public async Task TestNugetDetector_LowConfidencePackagesAsync() { - var nupkg = await NugetTestUtilities.ZipNupkgComponentAsync("Newtonsoft.Json.nupkg", NugetTestUtilities.GetValidNuspec("Newtonsoft.Json", "9.0.1", new[] { "JamesNK" })); + var nupkg = await NugetTestUtilities.ZipNupkgComponentAsync("Newtonsoft.Json.nupkg", NugetTestUtilities.GetValidNuspec("Newtonsoft.Json", "9.0.1", ["JamesNK"])); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("Newtonsoft.Json.nupkg", nupkg) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs index 880923b8..81a3c85f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetNuspecUtilitiesTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System; using System.IO; @@ -18,9 +18,8 @@ public class NuGetNuspecUtilitiesTests { using var stream = new MemoryStream(); - async Task ShouldThrow() => await NuGetNuspecUtilities.GetNuspecBytesAsync(stream); - - await Assert.ThrowsExceptionAsync(ShouldThrow); + var action = async () => await NuGetNuspecUtilities.GetNuspecBytesAsync(stream); + await action.Should().ThrowAsync(); // The position should always be reset to 0 stream.Position.Should().Be(0); @@ -38,9 +37,8 @@ public class NuGetNuspecUtilitiesTests stream.Seek(0, SeekOrigin.Begin); - async Task ShouldThrow() => await NuGetNuspecUtilities.GetNuspecBytesAsync(stream); - - await Assert.ThrowsExceptionAsync(ShouldThrow); + var action = async () => await NuGetNuspecUtilities.GetNuspecBytesAsync(stream); + await action.Should().ThrowAsync(); // The position should always be reset to 0 stream.Position.Should().Be(0); @@ -58,10 +56,10 @@ public class NuGetNuspecUtilitiesTests stream.Seek(0, SeekOrigin.Begin); - async Task ShouldThrow() => await NuGetNuspecUtilities.GetNuspecBytesAsync(stream); + var action = async () => await NuGetNuspecUtilities.GetNuspecBytesAsync(stream); // No Nuspec File is in the archive - await Assert.ThrowsExceptionAsync(ShouldThrow); + await action.Should().ThrowAsync(); // The position should always be reset to 0 stream.Position.Should().Be(0); @@ -70,7 +68,7 @@ public class NuGetNuspecUtilitiesTests [TestMethod] public async Task GetNuspecBytes_ReadsNuspecBytesAsync() { - byte[] randomBytes = { 0xDE, 0xAD, 0xC0, 0xDE }; + byte[] randomBytes = [0xDE, 0xAD, 0xC0, 0xDE]; using var stream = new MemoryStream(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs index ad25eb1a..04ce211f 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NuGetProjectModelProjectCentricComponentDetectorTests.cs @@ -52,7 +52,7 @@ public class NuGetProjectModelProjectCentricComponentDetectorTests : BaseDetecto x.Component.Id, y => y.Id == x.Component.Id)); - componentRecorder.ForAllComponents(grouping => Assert.IsTrue(grouping.AllFileLocations.Any(location => location.Contains("Loader.csproj")))); + componentRecorder.ForAllComponents(grouping => grouping.AllFileLocations.Should().Contain(location => location.Contains("Loader.csproj"))); } [TestMethod] @@ -78,7 +78,7 @@ public class NuGetProjectModelProjectCentricComponentDetectorTests : BaseDetecto nugetVersioning.Component.Id, x => x.Name.Contains("NuGet.ProjectModel")).Should().BeTrue(); - componentRecorder.ForAllComponents(grouping => Assert.IsTrue(grouping.AllFileLocations.Any(location => location.Contains("Detectors.csproj")))); + componentRecorder.ForAllComponents(grouping => grouping.AllFileLocations.Should().Contain(location => location.Contains("Detectors.csproj"))); } [TestMethod] @@ -93,7 +93,7 @@ public class NuGetProjectModelProjectCentricComponentDetectorTests : BaseDetecto var omittedComponentsWithCount = JsonConvert.DeserializeObject>(ommittedComponentInformationJson); (omittedComponentsWithCount.Keys.Count > 5).Should().BeTrue("Ommitted framework assemblies are missing. There should be more than ten, but this is a gut check to make sure we have data."); - omittedComponentsWithCount["Microsoft.NETCore.App"].Should().Be(4, "There should be four cases of the NETCore.App library being omitted in the test data."); + omittedComponentsWithCount.Should().Contain("Microsoft.NETCore.App", 4, "There should be four cases of the NETCore.App library being omitted in the test data."); } [TestMethod] @@ -121,7 +121,7 @@ public class NuGetProjectModelProjectCentricComponentDetectorTests : BaseDetecto expectedDependencyIdsForCompositionTypedParts.Should().HaveSameCount(dependencies); - detectedComponents.Should().HaveCount(graph.GetComponents().Count()); + detectedComponents.Should().HaveSameCount(graph.GetComponents()); // Top level dependencies look like this: // (we expect all non-proj and non-framework to show up as explicit refs, so those will be absent from the check) @@ -195,7 +195,7 @@ public class NuGetProjectModelProjectCentricComponentDetectorTests : BaseDetecto systemTextJson.Component.Id, x => x.Name.Contains("Microsoft.Extensions.DependencyModel")).Should().BeTrue(); - componentRecorder.ForAllComponents(grouping => Assert.IsTrue(grouping.AllFileLocations.Any(location => location.Contains("ExtCore.WebApplication.csproj")))); + componentRecorder.ForAllComponents(grouping => grouping.AllFileLocations.Should().Contain(location => location.Contains("ExtCore.WebApplication.csproj"))); } [TestMethod] @@ -211,7 +211,7 @@ public class NuGetProjectModelProjectCentricComponentDetectorTests : BaseDetecto // With 3.X, we don't expect there to be a lot of these, but there are still netstandard libraries present which can bring things into the graph omittedComponentsWithCount.Keys.Should().HaveCount(4, "Ommitted framework assemblies are missing. There should be more than ten, but this is a gut check to make sure we have data."); - omittedComponentsWithCount["System.Reflection"].Should().Be(1, "There should be one case of the System.Reflection library being omitted in the test data."); + omittedComponentsWithCount.Should().Contain("System.Reflection", 1, "There should be one case of the System.Reflection library being omitted in the test data."); } [TestMethod] @@ -239,7 +239,7 @@ public class NuGetProjectModelProjectCentricComponentDetectorTests : BaseDetecto dependencies.Should().Contain(expectedId); } - detectedComponents.Should().HaveCount(graph.GetComponents().Count()); + detectedComponents.Should().HaveSameCount(graph.GetComponents()); // Top level dependencies look like this: // (we expect all non-proj and non-framework to show up as explicit refs, so those will be absent from the check) diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/NugetTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/NugetTestUtilities.cs index 37fa45ce..913aae83 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/NugetTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/NugetTestUtilities.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System.IO; using System.IO.Compression; @@ -16,7 +16,7 @@ public static class NugetTestUtilities var componentName = GetRandomString(); var componentSpecFileName = $"{componentName}.nuspec"; var componentSpecPath = Path.Combine(Path.GetTempPath(), componentSpecFileName); - var template = GetTemplatedNuspec(componentName, NewRandomVersion(), new string[] { GetRandomString(), GetRandomString() }); + var template = GetTemplatedNuspec(componentName, NewRandomVersion(), [GetRandomString(), GetRandomString()]); return template; } @@ -26,7 +26,7 @@ public static class NugetTestUtilities var componentName = GetRandomString(); var componentSpecFileName = $"{componentName}.nuspec"; var componentSpecPath = Path.Combine(Path.GetTempPath(), componentSpecFileName); - var template = GetTemplatedNuspec(componentName, NewRandomVersion(), new string[] { GetRandomString(), GetRandomString() }); + var template = GetTemplatedNuspec(componentName, NewRandomVersion(), [GetRandomString(), GetRandomString()]); var mock = new Mock(); mock.SetupGet(x => x.Stream).Returns(template.ToStream()); @@ -51,7 +51,7 @@ public static class NugetTestUtilities public static string GetRandomValidNuspec() { var componentName = GetRandomString(); - var template = GetTemplatedNuspec(componentName, NewRandomVersion(), new string[] { GetRandomString(), GetRandomString() }); + var template = GetTemplatedNuspec(componentName, NewRandomVersion(), [GetRandomString(), GetRandomString()]); return template; } @@ -81,7 +81,7 @@ public static class NugetTestUtilities public static string GetRandomMalformedNuPkgComponent() { var componentName = GetRandomString(); - var template = GetTemplatedNuspec(componentName, NewRandomVersion(), new string[] { GetRandomString(), GetRandomString() }); + var template = GetTemplatedNuspec(componentName, NewRandomVersion(), [GetRandomString(), GetRandomString()]); template = template.Replace("", ""); return template; } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipCommandServiceTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipCommandServiceTests.cs index 2ecf7611..56de7743 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipCommandServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipCommandServiceTests.cs @@ -698,7 +698,7 @@ public class PipCommandServiceTests .ReturnsAsync(TestResources.pip_report_single_pkg); var cts = new CancellationTokenSource(); - cts.Cancel(); + await cts.CancelAsync(); var action = async () => await service.GenerateInstallationReportAsync(testPath, cancellationToken: cts.Token); await action.Should().ThrowAsync().WithMessage("PipReport: Cancelled*"); } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs index 8374abd5..944e47c3 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipComponentDetectorTests.cs @@ -69,8 +69,8 @@ public class PipComponentDetectorTests : BaseDetectorTest { this.pythonCommandService.Setup(x => x.PythonExistsAsync(It.IsAny())).ReturnsAsync(true); - 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" }); + var baseSetupPyDependencies = this.ToGitTuple(["a==1.0", "b>=2.0,!=2.1", "c!=1.1"]); + var baseRequirementsTextDependencies = this.ToGitTuple(["d~=1.0", "e<=2.0", "f===1.1"]); baseRequirementsTextDependencies.Add((null, new GitComponent(new Uri("https://github.com/example/example"), "deadbee"))); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); @@ -128,8 +128,8 @@ public class PipComponentDetectorTests : BaseDetectorTest { this.pythonCommandService.Setup(x => x.PythonExistsAsync(It.IsAny())).ReturnsAsync(true); - 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" }); + var baseRequirementsTextDependencies = this.ToGitTuple(["d~=1.0", "e<=2.0", "f===1.1", "h==1.3"]); + var baseRequirementsTextDependencies2 = this.ToGitTuple(["D~=1.0", "E<=2.0", "F===1.1", "g==2"]); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "TEST", "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies2); @@ -157,7 +157,7 @@ public class PipComponentDetectorTests : BaseDetectorTest .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(5); + componentRecorder.GetDetectedComponents().Should().HaveCount(5); } [TestMethod] @@ -168,8 +168,8 @@ public class PipComponentDetectorTests : BaseDetectorTest const string file1 = "c:\\repo\\setup.py"; const string file2 = "c:\\repo\\lib\\requirements.txt"; - 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" }); + var baseReqs = this.ToGitTuple(["a~=1.0", "b<=2.0",]); + var altReqs = this.ToGitTuple(["c~=1.0", "d<=2.0", "e===1.1"]); this.pythonCommandService.Setup(x => x.ParseFileAsync(file1, null)).ReturnsAsync(baseReqs); this.pythonCommandService.Setup(x => x.ParseFileAsync(file2, null)).ReturnsAsync(altReqs); @@ -189,7 +189,7 @@ public class PipComponentDetectorTests : BaseDetectorTest rootA.Children.Add(red); rootB.Children.Add(green); - rootC.Children.AddRange(new[] { red, blue, }); + rootC.Children.AddRange([red, blue,]); rootD.Children.Add(cat); green.Children.Add(cat); cat.Children.Add(lion); @@ -198,11 +198,11 @@ public class PipComponentDetectorTests : BaseDetectorTest this.pythonResolver.Setup(x => x.ResolveRootsAsync(It.IsAny(), It.Is>(p => p.Any(d => d.Name == "a")))) - .ReturnsAsync(new List { rootA, rootB, }); + .ReturnsAsync([rootA, rootB,]); this.pythonResolver.Setup(x => x.ResolveRootsAsync(It.IsAny(), It.Is>(p => p.Any(d => d.Name == "c")))) - .ReturnsAsync(new List { rootC, rootD, rootE, }); + .ReturnsAsync([rootC, rootD, rootE,]); var (result, componentRecorder) = await this.DetectorTestUtility .WithFile("setup.py", string.Empty, fileLocation: file1) @@ -230,12 +230,12 @@ public class PipComponentDetectorTests : BaseDetectorTest x => x.Id == rootId); } - ComponentRecorderTestUtilities.CheckChild(componentRecorder, "red 0.2 - pip", new[] { "a 1.0 - pip", "c 1.0 - pip", }); - ComponentRecorderTestUtilities.CheckChild(componentRecorder, "green 1.3 - pip", new[] { "b 2.1 - pip", }); - ComponentRecorderTestUtilities.CheckChild(componentRecorder, "blue 0.4 - pip", new[] { "c 1.0 - pip", }); - ComponentRecorderTestUtilities.CheckChild(componentRecorder, "cat 1.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); - ComponentRecorderTestUtilities.CheckChild(componentRecorder, "lion 3.8 - pip", new[] { "b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip", }); - ComponentRecorderTestUtilities.CheckChild(componentRecorder, "dog 2.1 - pip", new[] { "c 1.0 - pip", }); + ComponentRecorderTestUtilities.CheckChild(componentRecorder, "red 0.2 - pip", ["a 1.0 - pip", "c 1.0 - pip",]); + ComponentRecorderTestUtilities.CheckChild(componentRecorder, "green 1.3 - pip", ["b 2.1 - pip",]); + ComponentRecorderTestUtilities.CheckChild(componentRecorder, "blue 0.4 - pip", ["c 1.0 - pip",]); + ComponentRecorderTestUtilities.CheckChild(componentRecorder, "cat 1.8 - pip", ["b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip",]); + ComponentRecorderTestUtilities.CheckChild(componentRecorder, "lion 3.8 - pip", ["b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip",]); + ComponentRecorderTestUtilities.CheckChild(componentRecorder, "dog 2.1 - pip", ["c 1.0 - pip",]); var graphsByLocations = componentRecorder.GetDependencyGraphsByLocation(); graphsByLocations.Should().HaveCount(2); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs index d7717f30..b9340e8c 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipDependencySpecifierTests.cs @@ -66,10 +66,10 @@ public class PipDependencySpecifierTests { var specs = new List<(string, PipDependencySpecification)> { - ("TestPackage==1.0", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { "==1.0" } }), - ("TestPackage>=1.0,!=1.1", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=1.0", "!=1.1" } }), - ("OtherPackage!=1.2,>=1.0,<=1.9,~=1.4", new PipDependencySpecification { Name = "OtherPackage", DependencySpecifiers = new List { "!=1.2", ">=1.0", "<=1.9", "~=1.4" } }), - ("TestPackage[Optional]<3,>=1.0.0", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { "<3", ">=1.0.0" } }), + ("TestPackage==1.0", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = ["==1.0"] }), + ("TestPackage>=1.0,!=1.1", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=1.0", "!=1.1"] }), + ("OtherPackage!=1.2,>=1.0,<=1.9,~=1.4", new PipDependencySpecification { Name = "OtherPackage", DependencySpecifiers = ["!=1.2", ">=1.0", "<=1.9", "~=1.4"] }), + ("TestPackage[Optional]<3,>=1.0.0", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = ["<3", ">=1.0.0"] }), }; VerifyPipDependencyParsing(specs); @@ -80,12 +80,12 @@ public class PipDependencySpecifierTests { var specs = new List<(string, PipDependencySpecification)> { - ("Requires-Dist: TestPackage<1.27.0,>=1.19.5", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { "<1.27.0", ">=1.19.5" } }), - ("Requires-Dist: TestPackage (>=1.0.0) ; sys_platform == \"win32\"", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=1.0.0" }, ConditionalDependencySpecifiers = new List { "sys_platform == \"win32\"" } }), - ("Requires-Dist: OtherPackage[Optional] (<3,>=1.0.0)", new PipDependencySpecification { Name = "OtherPackage", DependencySpecifiers = new List { "<3", ">=1.0.0" } }), - ("Requires-Dist: TestPackage (>=3.7.4.3) ; python_version < \"3.8\"", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=3.7.4.3" }, ConditionalDependencySpecifiers = new List { "python_version < \"3.8\"" } }), - ("Requires-Dist: TestPackage ; python_version < \"3.8\"", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List(), ConditionalDependencySpecifiers = new List { "python_version < \"3.8\"" } }), - ("Requires-Dist: SpacePackage >=1.16.0", new PipDependencySpecification() { Name = "SpacePackage", DependencySpecifiers = new List() { ">=1.16.0" } }), + ("Requires-Dist: TestPackage<1.27.0,>=1.19.5", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = ["<1.27.0", ">=1.19.5"] }), + ("Requires-Dist: TestPackage (>=1.0.0) ; sys_platform == \"win32\"", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=1.0.0"], ConditionalDependencySpecifiers = ["sys_platform == \"win32\""] }), + ("Requires-Dist: OtherPackage[Optional] (<3,>=1.0.0)", new PipDependencySpecification { Name = "OtherPackage", DependencySpecifiers = ["<3", ">=1.0.0"] }), + ("Requires-Dist: TestPackage (>=3.7.4.3) ; python_version < \"3.8\"", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=3.7.4.3"], ConditionalDependencySpecifiers = ["python_version < \"3.8\""] }), + ("Requires-Dist: TestPackage ; python_version < \"3.8\"", new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [], ConditionalDependencySpecifiers = ["python_version < \"3.8\""] }), + ("Requires-Dist: SpacePackage >=1.16.0", new PipDependencySpecification() { Name = "SpacePackage", DependencySpecifiers = [">=1.16.0"] }), }; VerifyPipDependencyParsing(specs, true); @@ -96,21 +96,21 @@ public class PipDependencySpecifierTests { var specs = new List<(string, bool, PipDependencySpecification)> { - ("Requires-Dist: TestPackage (>=1.0.0) ; sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=1.0.0" }, ConditionalDependencySpecifiers = new List { "sys_platform == \"win32\"" } }), - ("Requires-Dist: TestPackage (>=3.7.4.3) ; python_version < \"3.8\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=3.7.4.3" }, ConditionalDependencySpecifiers = new List { "python_version < \"3.8\"" } }), - ("Requires-Dist: TestPackage ; python_version == \"3.8\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List(), ConditionalDependencySpecifiers = new List { "python_version == \"3.8\"" } }), - ("Requires-Dist: TestPackage (>=3.0.1) ; python_version < \"3.5\" or sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=3.0.1" }, ConditionalDependencySpecifiers = new List { "python_version < \"3.5\"", "or sys_platform == \"win32\"" } }), - ("Requires-Dist: TestPackage (>=2.0.1) ; python_version == \"3.8\" and sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=2.0.1" }, ConditionalDependencySpecifiers = new List { "python_version == \"3.8\"", "and sys_platform == \"win32\"" } }), - ("Requires-Dist: TestPackage (>=2.0.1) ; python_version == \"3.8\" and sys_platform == \"linux\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=2.0.1" }, ConditionalDependencySpecifiers = new List { "python_version == \"3.8\"", "and sys_platform == \"linux\"" } }), - ("Requires-Dist: TestPackage (>=4.0.1) ; python_version < \"3.6\" and sys_platform == \"win32\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=4.0.1" }, ConditionalDependencySpecifiers = new List { "python_version < \"3.6\"", "and sys_platform == \"win32\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; python_version > \"3.7\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "python_version > \"3.7\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; python_version >= \"3.7\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "python_version >= \"3.7\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; python_version < \"3.9\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "python_version < \"3.9\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; python_version <= \"3.9\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "python_version <= \"3.9\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; python_version == \"3.8\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "python_version == \"3.8\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; python_version === \"3.8\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "python_version === \"3.8\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; python_version ~= \"3.8\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "python_version ~= \"3.8\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; python_version != \"3.8\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "python_version != \"3.8\"" } }), + ("Requires-Dist: TestPackage (>=1.0.0) ; sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=1.0.0"], ConditionalDependencySpecifiers = ["sys_platform == \"win32\""] }), + ("Requires-Dist: TestPackage (>=3.7.4.3) ; python_version < \"3.8\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=3.7.4.3"], ConditionalDependencySpecifiers = ["python_version < \"3.8\""] }), + ("Requires-Dist: TestPackage ; python_version == \"3.8\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [], ConditionalDependencySpecifiers = ["python_version == \"3.8\""] }), + ("Requires-Dist: TestPackage (>=3.0.1) ; python_version < \"3.5\" or sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=3.0.1"], ConditionalDependencySpecifiers = ["python_version < \"3.5\"", "or sys_platform == \"win32\""] }), + ("Requires-Dist: TestPackage (>=2.0.1) ; python_version == \"3.8\" and sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=2.0.1"], ConditionalDependencySpecifiers = ["python_version == \"3.8\"", "and sys_platform == \"win32\""] }), + ("Requires-Dist: TestPackage (>=2.0.1) ; python_version == \"3.8\" and sys_platform == \"linux\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=2.0.1"], ConditionalDependencySpecifiers = ["python_version == \"3.8\"", "and sys_platform == \"linux\""] }), + ("Requires-Dist: TestPackage (>=4.0.1) ; python_version < \"3.6\" and sys_platform == \"win32\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=4.0.1"], ConditionalDependencySpecifiers = ["python_version < \"3.6\"", "and sys_platform == \"win32\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; python_version > \"3.7\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["python_version > \"3.7\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; python_version >= \"3.7\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["python_version >= \"3.7\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; python_version < \"3.9\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["python_version < \"3.9\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; python_version <= \"3.9\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["python_version <= \"3.9\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; python_version == \"3.8\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["python_version == \"3.8\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; python_version === \"3.8\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["python_version === \"3.8\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; python_version ~= \"3.8\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["python_version ~= \"3.8\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; python_version != \"3.8\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["python_version != \"3.8\""] }), }; var pythonEnvironmentVariables = new Dictionary { @@ -126,10 +126,10 @@ public class PipDependencySpecifierTests { var specs = new List<(string, bool, PipDependencySpecification)> { - ("Requires-Dist: TestPackage (>=2.0.1) ; python_version == \"3.8\" and sys_platform == \"linux\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=2.0.1" }, ConditionalDependencySpecifiers = new List { "python_version == \"3.8\"", "and sys_platform == \"linux\"" } }), - ("Requires-Dist: TestPackage (>=4.0.1) ; python_version == \"3.6\" and sys_platform == \"win32\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=4.0.1" }, ConditionalDependencySpecifiers = new List { "python_version == \"3.6\"", "and sys_platform == \"win32\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"linux\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "sys_platform == \"linux\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"win32\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "sys_platform == \"win32\"" } }), + ("Requires-Dist: TestPackage (>=2.0.1) ; python_version == \"3.8\" and sys_platform == \"linux\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=2.0.1"], ConditionalDependencySpecifiers = ["python_version == \"3.8\"", "and sys_platform == \"linux\""] }), + ("Requires-Dist: TestPackage (>=4.0.1) ; python_version == \"3.6\" and sys_platform == \"win32\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=4.0.1"], ConditionalDependencySpecifiers = ["python_version == \"3.6\"", "and sys_platform == \"win32\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"linux\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["sys_platform == \"linux\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"win32\"", false, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["sys_platform == \"win32\""] }), }; var pythonEnvironmentVariables = new Dictionary { @@ -145,11 +145,11 @@ public class PipDependencySpecifierTests { var specs = new List<(string, bool, PipDependencySpecification)> { - ("Requires-Dist: TestPackage (>=2.0.1) ; python_version == \"3.8\" and sys_platform == \"linux\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=2.0.1" }, ConditionalDependencySpecifiers = new List { "python_version == \"3.8\"", "and sys_platform == \"linux\"" } }), - ("Requires-Dist: TestPackage (>=4.0.1) ; python_version == \"3.6\" and sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=4.0.1" }, ConditionalDependencySpecifiers = new List { "python_version == \"3.6\"", "and sys_platform == \"win32\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"linux\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "sys_platform == \"linux\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "sys_platform == \"win32\"" } }), - ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"asdf\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = new List { ">=5.0.1" }, ConditionalDependencySpecifiers = new List { "sys_platform == \"asdf\"" } }), + ("Requires-Dist: TestPackage (>=2.0.1) ; python_version == \"3.8\" and sys_platform == \"linux\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=2.0.1"], ConditionalDependencySpecifiers = ["python_version == \"3.8\"", "and sys_platform == \"linux\""] }), + ("Requires-Dist: TestPackage (>=4.0.1) ; python_version == \"3.6\" and sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=4.0.1"], ConditionalDependencySpecifiers = ["python_version == \"3.6\"", "and sys_platform == \"win32\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"linux\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["sys_platform == \"linux\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"win32\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["sys_platform == \"win32\""] }), + ("Requires-Dist: TestPackage (>=5.0.1) ; sys_platform == \"asdf\"", true, new PipDependencySpecification { Name = "TestPackage", DependencySpecifiers = [">=5.0.1"], ConditionalDependencySpecifiers = ["sys_platform == \"asdf\""] }), }; // test null and empty cases should allow packages through @@ -168,7 +168,7 @@ public class PipDependencySpecifierTests var spec = new PipDependencySpecification { Name = "TestPackage", - DependencySpecifiers = new List { ">=1.0", "<=3.0", "!=2.0", "!=4.0" }, + DependencySpecifiers = [">=1.0", "<=3.0", "!=2.0", "!=4.0"], }; var highestVersion = spec.GetHighestExplicitPackageVersion(); @@ -181,7 +181,7 @@ public class PipDependencySpecifierTests var spec = new PipDependencySpecification { Name = "TestPackage", - DependencySpecifiers = new List { ">=1.0", "info", "!=2.0", "!=4.0" }, + DependencySpecifiers = [">=1.0", "info", "!=2.0", "!=4.0"], }; var highestVersion = spec.GetHighestExplicitPackageVersion(); @@ -194,7 +194,7 @@ public class PipDependencySpecifierTests var spec = new PipDependencySpecification { Name = "TestPackage", - DependencySpecifiers = new List { "info" }, + DependencySpecifiers = ["info"], }; var highestVersion = spec.GetHighestExplicitPackageVersion(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipReportComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipReportComponentDetectorTests.cs index 7c323334..e0a212d9 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipReportComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipReportComponentDetectorTests.cs @@ -47,7 +47,7 @@ public class PipReportComponentDetectorTests : BaseDetectorTest(); - this.pythonResolver.Setup(x => x.GetPythonEnvironmentVariables()).Returns(new Dictionary()); + this.pythonResolver.Setup(x => x.GetPythonEnvironmentVariables()).Returns([]); this.DetectorTestUtility.AddServiceMock(this.pythonResolver); this.mockLogger = new Mock>(); @@ -475,12 +475,12 @@ public class PipReportComponentDetectorTests : BaseDetectorTest( componentRecorder, "async-lru 2.0.4 - pip", - new[] { "jupyterlab 4.2.0 - pip" }); + ["jupyterlab 4.2.0 - pip"]); ComponentRecorderTestUtilities.CheckChild( componentRecorder, "tinycss2 1.3.0 - pip", - new[] { "jupyterlab 4.2.0 - pip" }); + ["jupyterlab 4.2.0 - pip"]); } [TestMethod] @@ -490,8 +490,8 @@ public class PipReportComponentDetectorTests : BaseDetectorTest x.DoesEnvironmentVariableExist("PipReportOverrideBehavior")).Returns(true); this.mockEnvVarService.Setup(x => x.GetEnvironmentVariable("PipReportOverrideBehavior")).Returns("sourcecodescan"); - var baseSetupPyDependencies = this.ToGitTuple(new List { "a==1.0", "b>=2.0,!=2.1,<3.0.0", "c!=1.1" }); - var baseRequirementsTextDependencies = this.ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1", "g<3.0", "h>=1.0,<=3.0,!=2.0,!=4.0" }); + var baseSetupPyDependencies = this.ToGitTuple(["a==1.0", "b>=2.0,!=2.1,<3.0.0", "c!=1.1"]); + var baseRequirementsTextDependencies = this.ToGitTuple(["d~=1.0", "e<=2.0", "f===1.1", "g<3.0", "h>=1.0,<=3.0,!=2.0,!=4.0"]); baseRequirementsTextDependencies.Add((null, new GitComponent(new Uri("https://github.com/example/example"), "deadbee"))); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); @@ -537,8 +537,8 @@ public class PipReportComponentDetectorTests : BaseDetectorTest x.PythonExistsAsync(It.IsAny())).ReturnsAsync(true); - var baseSetupPyDependencies = this.ToGitTuple(new List { "a==1.0", "b>=2.0,!=2.1,<3.0.0", "c!=1.1", "y==invalidversion" }); - var baseRequirementsTextDependencies = this.ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1", "g<3.0", "h>=1.0,<=3.0,!=2.0,!=4.0", "z==anotherinvalidversion" }); + var baseSetupPyDependencies = this.ToGitTuple(["a==1.0", "b>=2.0,!=2.1,<3.0.0", "c!=1.1", "y==invalidversion"]); + var baseRequirementsTextDependencies = this.ToGitTuple(["d~=1.0", "e<=2.0", "f===1.1", "g<3.0", "h>=1.0,<=3.0,!=2.0,!=4.0", "z==anotherinvalidversion"]); baseRequirementsTextDependencies.Add((null, new GitComponent(new Uri("https://github.com/example/example"), "deadbee"))); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); @@ -597,8 +597,8 @@ public class PipReportComponentDetectorTests : BaseDetectorTest x.DoesEnvironmentVariableExist("PipReportOverrideBehavior")).Returns(true); this.mockEnvVarService.Setup(x => x.GetEnvironmentVariable("PipReportOverrideBehavior")).Returns("skip"); - var baseSetupPyDependencies = this.ToGitTuple(new List { "a==1.0", "b>=2.0,!=2.1,<3.0.0", "c!=1.1" }); - var baseRequirementsTextDependencies = this.ToGitTuple(new List { "d~=1.0", "e<=2.0", "f===1.1", "g<3.0", "h>=1.0,<=3.0,!=2.0,!=4.0" }); + var baseSetupPyDependencies = this.ToGitTuple(["a==1.0", "b>=2.0,!=2.1,<3.0.0", "c!=1.1"]); + var baseRequirementsTextDependencies = this.ToGitTuple(["d~=1.0", "e<=2.0", "f===1.1", "g<3.0", "h>=1.0,<=3.0,!=2.0,!=4.0"]); baseRequirementsTextDependencies.Add((null, new GitComponent(new Uri("https://github.com/example/example"), "deadbee"))); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); @@ -627,7 +627,7 @@ public class PipReportComponentDetectorTests : BaseDetectorTest x.ParseFileAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(new List<(string PackageString, GitComponent Component)> { ("requests", null) }); + .ReturnsAsync([("requests", null)]); var file1 = Path.Join(Directory.GetCurrentDirectory(), "Mocks", "requirements.txt"); var pregeneratedFile = Path.Join(Directory.GetCurrentDirectory(), "Mocks", "test.component-detection-pip-report.json"); @@ -663,7 +663,7 @@ public class PipReportComponentDetectorTests : BaseDetectorTest x.ParseFileAsync(It.IsAny(), It.IsAny())) - .ReturnsAsync(new List<(string PackageString, GitComponent Component)> { ("requests", null) }); + .ReturnsAsync([("requests", null)]); var file1 = Path.Join(Directory.GetCurrentDirectory(), "Mocks", "Invalid", "requirements.txt"); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs index b3a08ed4..9dcb1997 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PipResolverTests.cs @@ -58,7 +58,7 @@ public class PipResolverTests Info = new PythonProjectInfo { AuthorEmail = "Microsoft ", - Classifiers = new List { "License :: OSI Approved :: MIT License" }, + Classifiers = ["License :: OSI Approved :: MIT License"], }, }; @@ -68,7 +68,7 @@ public class PipResolverTests Info = new PythonProjectInfo { Maintainer = "Microsoft", - Classifiers = new List { "License :: OSI Approved :: MIT License", "License :: OSI Approved :: BSD License" }, + Classifiers = ["License :: OSI Approved :: MIT License", "License :: OSI Approved :: BSD License"], }, }; @@ -76,9 +76,9 @@ public class PipResolverTests this.pyPiClient.Setup(x => x.GetProjectAsync(b)).ReturnsAsync(bProject); this.pyPiClient.Setup(x => x.GetProjectAsync(c)).ReturnsAsync(cProject); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync([b]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync([c]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync([]); var dependencies = new List { a }; @@ -135,7 +135,7 @@ public class PipResolverTests var dneProject = new PythonProject { - Releases = new SortedDictionary>(), + Releases = [], }; this.pyPiClient.Setup(x => x.GetProjectAsync(a)).ReturnsAsync(aProject); @@ -143,9 +143,9 @@ public class PipResolverTests this.pyPiClient.Setup(x => x.GetProjectAsync(c)).ReturnsAsync(cProject); this.pyPiClient.Setup(x => x.GetProjectAsync(doesNotExist)).ReturnsAsync(dneProject); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync([b]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync([c]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync([]); var dependencies = new List { a, doesNotExist }; @@ -202,7 +202,7 @@ public class PipResolverTests var dneProject = new PythonProject { - Releases = new SortedDictionary>(), + Releases = [], }; this.pyPiClient.Setup(x => x.GetProjectAsync(a)).ReturnsAsync(aProject); @@ -210,9 +210,9 @@ public class PipResolverTests this.pyPiClient.Setup(x => x.GetProjectAsync(c)).ReturnsAsync(cProject); this.pyPiClient.Setup(x => x.GetProjectAsync(doesNotExist)).ReturnsAsync(dneProject); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync([b]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync([c]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync([]); var dependencies = new List { a, doesNotExist }; @@ -266,15 +266,15 @@ public class PipResolverTests var dneProject = new PythonProject { - Releases = new SortedDictionary>(), + Releases = [], }; this.pyPiClient.Setup(x => x.GetProjectAsync(a)).ReturnsAsync(aProject); this.pyPiClient.Setup(x => x.GetProjectAsync(b)).ReturnsAsync(bProject); this.pyPiClient.Setup(x => x.GetProjectAsync(c)).ReturnsAsync(dneProject); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c }); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync([b]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync([c]); var dependencies = new List { a }; @@ -329,10 +329,10 @@ public class PipResolverTests this.pyPiClient.Setup(x => x.GetProjectAsync(b)).ReturnsAsync(bProject); this.pyPiClient.Setup(x => x.GetProjectAsync(c)).ReturnsAsync(cProject); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b, c }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { cAlt }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.1", cReleases["1.1"].First())).ReturnsAsync(new List { }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync([b, c]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync([cAlt]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.1", cReleases["1.1"].First())).ReturnsAsync([]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync([]); var dependencies = new List { a }; @@ -387,7 +387,7 @@ public class PipResolverTests Info = new PythonProjectInfo { AuthorEmail = "Microsoft ", - Classifiers = new List { "License :: OSI Approved :: MIT License" }, + Classifiers = ["License :: OSI Approved :: MIT License"], }, }; @@ -397,7 +397,7 @@ public class PipResolverTests Info = new PythonProjectInfo { Maintainer = "Microsoft", - Classifiers = new List { "License :: OSI Approved :: MIT License", "License :: OSI Approved :: BSD License" }, + Classifiers = ["License :: OSI Approved :: MIT License", "License :: OSI Approved :: BSD License"], }, }; @@ -405,9 +405,9 @@ public class PipResolverTests this.pyPiClient.Setup(x => x.GetProjectAsync(b)).ReturnsAsync(bProject); this.pyPiClient.Setup(x => x.GetProjectAsync(c)).ReturnsAsync(cProject); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync(new List { b }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync(new List { c, c2 }); - this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync(new List { }); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("a", "1.0", aReleases["1.0"].First())).ReturnsAsync([b]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("b", "1.0", bReleases["1.0"].First())).ReturnsAsync([c, c2]); + this.pyPiClient.Setup(x => x.FetchPackageDependenciesAsync("c", "1.0", cReleases["1.0"].First())).ReturnsAsync([]); var dependencies = new List { a }; @@ -470,10 +470,11 @@ public class PipResolverTests foreach (var version in versions) { - toReturn.Add(version, new List - { - this.CreatePythonProjectRelease(), - }); + toReturn.Add( + version, + [ + this.CreatePythonProjectRelease(), + ]); } return toReturn; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs index c43b019b..6f94f34a 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PnpmDetectorTests.cs @@ -192,7 +192,7 @@ shrinkwrapVersion: 3"; parentComponent => parentComponent.Name == "some-other-root", parentComponent => parentComponent.Name == "query-string"); - componentRecorder.ForOneComponent(strictUriEncodeComponent.Component.Id, grouping => Assert.AreEqual(2, grouping.AllFileLocations.Count())); + componentRecorder.ForOneComponent(strictUriEncodeComponent.Component.Id, grouping => grouping.AllFileLocations.Should().HaveCount(2)); } [TestMethod] @@ -300,7 +300,7 @@ shrinkwrapVersion: 3"; .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -330,7 +330,7 @@ packages: .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(4); + componentRecorder.GetDetectedComponents().Should().HaveCount(4); var queryStringComponentId = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPathV5("/query-string/4.3.4").Component.Id; var objectAssignComponentId = PnpmParsingUtilities.CreateDetectedComponentFromPnpmPathV5("/object-assign/4.1.1").Component.Id; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs index 5e9afda1..82142065 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PodDetectorTest.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System; using System.Collections.Generic; @@ -30,7 +30,7 @@ COCOAPODS: 1.4.0.beta.1"; .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -688,7 +688,7 @@ COCOAPODS: 1.8.4"; detectedComponents.Should().ContainSingle(); var firstComponent = detectedComponents.First(); - componentRecorder.ForOneComponent(firstComponent.Component.Id, grouping => Assert.AreEqual(2, Enumerable.Count(grouping.AllFileLocations))); + componentRecorder.ForOneComponent(firstComponent.Component.Id, grouping => grouping.AllFileLocations.Should().HaveCount(2)); } private void AssertPodComponentNameAndVersion(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 045e8b2f..08529c4e 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PyPiClientTests.cs @@ -30,7 +30,7 @@ public class PyPiClientTests [TestMethod] public async Task GetReleases_InvalidSpecVersion_NotThrowAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0", "==1.0.0notvalid" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0", "==1.0.0notvalid"] }; var pythonProject = new PythonProject { @@ -52,7 +52,7 @@ public class PyPiClientTests public async Task GetProject_SupportsReleaseCandidatesDependenciesAsync() { const string version = "1.0.0rc4"; - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { $"=={version}" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = [$"=={version}"] }; var pythonProject = new PythonProject { @@ -74,7 +74,7 @@ public class PyPiClientTests [TestMethod] public async Task GetReleases_DuplicateEntries_CallsGetAsync_OnceAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var pythonProject = new PythonProject { Releases = new SortedDictionary> @@ -102,7 +102,7 @@ public class PyPiClientTests [TestMethod] public async Task GetReleases_DifferentEntries_CallsGetAsync_OnceAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var pythonProject = new PythonProject { Releases = new SortedDictionary> @@ -172,7 +172,7 @@ public class PyPiClientTests [TestMethod] public async Task GetReleases_MaxEntriesVariable_CreatesNewCacheAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var pythonProject = new PythonProject { Releases = new SortedDictionary> @@ -212,7 +212,7 @@ public class PyPiClientTests [TestMethod] public async Task GetReleases_AddsUserAgentHeadersAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var pythonProject = new PythonProject { Releases = new SortedDictionary> diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs index 17ed3d2f..3b57b6fb 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/PythonVersionTests.cs @@ -83,8 +83,8 @@ public class PythonVersionTests [TestMethod] public void TestVersionValidForSpec() { - IList<(IList, IList, IList)> testCases = new List<(IList, IList, IList)> - { + IList<(IList, IList, IList)> testCases = + [ (new List { "==1.0" }, new List { "1.0" }, new List { "1.0.1", "2.0", "0.1" }), (new List { "== 1.0 " }, new List { "1.0" }, new List { "1.0.1", "2.0", "0.1" }), (new List { "==1.4.*" }, new List { "1.4", "1.4.1", "1.4.2", "1.4.3" }, new List { "1.0.1", "2.0", "0.1", "1.5", "1.5.0" }), @@ -93,7 +93,7 @@ public class PythonVersionTests (new List { ">1.0", "<1.4" }, new List { "1.1", "1.3" }, new List { "0.9", "1.5", "1.0", "1.4" }), (new List { ">1.0", "<1.4", "!=1.2" }, new List { "1.1", "1.3" }, new List { "0.9", "1.5", "1.0", "1.4", "1.2" }), (new List { "==1.1.1.dev17+gcae73d8.d20200403" }, new List { "1.1.1.dev17", "v1.1.1.dev17", "1.1.1.dev17+gcae73d8.d20200403" }, new List { "1.1.1.dev18", "1.0.1", "1.1.1" }), - }; + ]; foreach (var (specs, validVersions, invalidVersions) in testCases) { @@ -105,17 +105,17 @@ public class PythonVersionTests [TestMethod] public void TestVersionValidForSpec_VersionIsNotValid_ArgumentExceptionIsThrown() { - Action action = () => PythonVersionUtilities.VersionValidForSpec("notvalid", new List { "==1.0" }); + Action action = () => PythonVersionUtilities.VersionValidForSpec("notvalid", ["==1.0"]); action.Should().Throw(); } [TestMethod] public void TestVersionValidForSpec_SomeSpecIsNotValid_ArgumentExceptionIsThrown() { - Action action = () => PythonVersionUtilities.VersionValidForSpec("1.0.0", new List { "==notvalid" }); + Action action = () => PythonVersionUtilities.VersionValidForSpec("1.0.0", ["==notvalid"]); action.Should().Throw(); - action = () => PythonVersionUtilities.VersionValidForSpec("1.0.0", new List { "==1.1+gcae73d8.d20200403+1.0" }); + action = () => PythonVersionUtilities.VersionValidForSpec("1.0.0", ["==1.1+gcae73d8.d20200403+1.0"]); action.Should().Throw(); } } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs index 37bfce52..b35379bd 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RubyDetectorTest.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Collections.Generic; using System.IO; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCliDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCliDetectorTests.cs index 7932f90c..790a4801 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCliDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCliDetectorTests.cs @@ -598,7 +598,7 @@ dependencies = [ await writer.FlushAsync(); stream.Position = 0; this.mockComponentStreamEnumerableFactory.Setup(x => x.GetComponentStreams(It.IsAny(), new List { "Cargo.lock" }, It.IsAny(), false)) - .Returns(new[] { new ComponentStream() { Location = "Cargo.toml", Stream = stream } }); + .Returns([new ComponentStream() { Location = "Cargo.toml", Stream = stream }]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("Cargo.toml", string.Empty) @@ -712,7 +712,7 @@ dependencies = [ .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Should().HaveCount(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -762,7 +762,7 @@ dependencies = [ .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Should().HaveCount(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -945,7 +945,7 @@ dependencies = [ .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Should().HaveCount(1); + componentRecorder.GetDetectedComponents().Should().ContainSingle(); componentRecorder .GetDetectedComponents() @@ -1006,7 +1006,7 @@ dependencies = [ .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Should().HaveCount(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -1052,7 +1052,7 @@ dependencies = [ await writer.FlushAsync(); stream.Position = 0; this.mockComponentStreamEnumerableFactory.Setup(x => x.GetComponentStreams(It.IsAny(), new List { "Cargo.lock" }, It.IsAny(), false)) - .Returns(new[] { new ComponentStream() { Location = "Cargo.toml", Stream = stream } }); + .Returns([new ComponentStream() { Location = "Cargo.toml", Stream = stream }]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("Cargo.toml", string.Empty) @@ -1124,7 +1124,7 @@ dependencies = [ await writer.FlushAsync(); stream.Position = 0; this.mockComponentStreamEnumerableFactory.Setup(x => x.GetComponentStreams(It.IsAny(), new List { "Cargo.lock" }, It.IsAny(), false)) - .Returns(new[] { new ComponentStream() { Location = "Cargo.toml", Stream = stream } }); + .Returns([new ComponentStream() { Location = "Cargo.toml", Stream = stream }]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("Cargo.toml", string.Empty) @@ -1195,14 +1195,14 @@ dependencies = [ await writer.FlushAsync(); stream.Position = 0; this.mockComponentStreamEnumerableFactory.Setup(x => x.GetComponentStreams(It.IsAny(), new List { "Cargo.lock" }, It.IsAny(), false)) - .Returns(new[] { new ComponentStream() { Location = "Cargo.toml", Stream = stream } }); + .Returns([new ComponentStream() { Location = "Cargo.toml", Stream = stream }]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("Cargo.toml", string.Empty) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Should().HaveCount(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); return; } diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs index 1339f1ef..07e7abdc 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RustCrateDetectorTests.cs @@ -238,7 +238,7 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(6); + componentRecorder.GetDetectedComponents().Should().HaveCount(6); var graph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); // There should only be 1 @@ -315,7 +315,7 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" graph1.GetComponents().Should().BeEquivalentTo(graph2.GetComponents()); // The graphs should have detected the same components // Two Cargo.lock files - componentRecorder.ForAllComponents(x => Enumerable.Count(x.AllFileLocations).Should().Be(2)); + componentRecorder.ForAllComponents(x => x.AllFileLocations.Should().HaveCount(2)); } [TestMethod] @@ -338,7 +338,7 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" graph1.GetComponents().Should().BeEquivalentTo(graph2.GetComponents()); // The graphs should have detected the same components // Two Cargo.lock files - componentRecorder.ForAllComponents(x => x.AllFileLocations.Count().Should().Be(2)); + componentRecorder.ForAllComponents(x => x.AllFileLocations.Should().HaveCount(2)); } [TestMethod] @@ -349,7 +349,7 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(6); + componentRecorder.GetDetectedComponents().Should().HaveCount(6); IDictionary packageVersions = new Dictionary() { @@ -405,7 +405,7 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(7); + componentRecorder.GetDetectedComponents().Should().HaveCount(7); var packageVersions = new List() { @@ -530,7 +530,7 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(7); + componentRecorder.GetDetectedComponents().Should().HaveCount(7); var graph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); // There should only be 1 @@ -629,7 +629,7 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(7); + componentRecorder.GetDetectedComponents().Should().HaveCount(7); var packageVersions = new List() { @@ -696,7 +696,7 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(6); + componentRecorder.GetDetectedComponents().Should().HaveCount(6); } [TestMethod] @@ -720,12 +720,12 @@ source = ""registry+https://github.com/rust-lang/crates.io-index"" var componentGraphs = componentRecorder.GetDependencyGraphsByLocation(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(6); + componentRecorder.GetDetectedComponents().Should().HaveCount(6); componentGraphs.Should().ContainSingle(); // Only 1 Cargo.lock is specified // A root Cargo.lock - componentRecorder.ForAllComponents(x => x.AllFileLocations.Count().Should().Be(1)); + componentRecorder.ForAllComponents(x => x.AllFileLocations.Should().ContainSingle()); } [TestMethod] @@ -759,7 +759,7 @@ dependencies = [ .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(2); + componentRecorder.GetDetectedComponents().Should().HaveCount(2); var graph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); // There should only be 1 @@ -797,7 +797,7 @@ source = ""git+https://github.com/microsoft/component-detection/?branch=main#abc .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(1); + componentRecorder.GetDetectedComponents().Should().ContainSingle(); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); dependencyGraphs.Should().ContainSingle(); @@ -835,7 +835,7 @@ source = ""registry+sparse+https://other.registry/index/"" result.ResultCode.Should().Be(ProcessingResultCode.Success); // If registries have identity, this should be 2 - componentRecorder.GetDetectedComponents().Count().Should().Be(1); + componentRecorder.GetDetectedComponents().Should().ContainSingle(); var dependencyGraphs = componentRecorder.GetDependencyGraphsByLocation(); dependencyGraphs.Should().ContainSingle(); @@ -875,7 +875,7 @@ dependencies = [] .ExecuteDetectorAsync(); result.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(1); + componentRecorder.GetDetectedComponents().Should().ContainSingle(); var graph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); // There should only be 1 diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs index 464ec40c..54e79451 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/RustDependencySpecifierTest.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System.Collections.Generic; using FluentAssertions; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs index 164e32a3..eccbd419 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/SPDX22ComponentDetectorTests.cs @@ -111,10 +111,7 @@ public class Spdx22ComponentDetectorTests : BaseDetectorTest x.PythonExistsAsync(It.IsAny())).ReturnsAsync(true); - 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" }); + var baseSetupPyDependencies = this.ToGitTuple(["a==1.0", "b>=2.0,!=2.1", "c!=1.1"]); + var baseRequirementsTextDependencies = this.ToGitTuple(["d~=1.0", "e<=2.0", "f===1.1"]); baseRequirementsTextDependencies.Add((null, new GitComponent(new Uri("https://github.com/example/example"), "deadbee"))); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "setup.py"), null)).ReturnsAsync(baseSetupPyDependencies); @@ -129,8 +129,8 @@ public class SimplePipComponentDetectorTests : BaseDetectorTest x.PythonExistsAsync(It.IsAny())).ReturnsAsync(true); - 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" }); + var baseRequirementsTextDependencies = this.ToGitTuple(["d~=1.0", "e<=2.0", "f===1.1", "h==1.3"]); + var baseRequirementsTextDependencies2 = this.ToGitTuple(["D~=1.0", "E<=2.0", "F===1.1", "g==2"]); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies); this.pythonCommandService.Setup(x => x.ParseFileAsync(Path.Join(Path.GetTempPath(), "TEST", "requirements.txt"), null)).ReturnsAsync(baseRequirementsTextDependencies2); @@ -158,7 +158,7 @@ public class SimplePipComponentDetectorTests : BaseDetectorTest { "a~=1.0", "b<=2.0", }); - var altReqs = this.ToGitTuple(new List { "c~=1.0", "d<=2.0", "e===1.1" }); + var baseReqs = this.ToGitTuple(["a~=1.0", "b<=2.0",]); + var altReqs = this.ToGitTuple(["c~=1.0", "d<=2.0", "e===1.1"]); this.pythonCommandService.Setup(x => x.ParseFileAsync(file1, null)).ReturnsAsync(baseReqs); this.pythonCommandService.Setup(x => x.ParseFileAsync(file2, null)).ReturnsAsync(altReqs); @@ -190,7 +190,7 @@ public class SimplePipComponentDetectorTests : BaseDetectorTest x.ResolveRootsAsync(It.IsAny(), It.Is>(p => p.Any(d => d.Name == "a")))) - .ReturnsAsync(new List { rootA, rootB, }); + .ReturnsAsync([rootA, rootB,]); this.pythonResolver.Setup(x => x.ResolveRootsAsync(It.IsAny(), It.Is>(p => p.Any(d => d.Name == "c")))) - .ReturnsAsync(new List { rootC, rootD, rootE, }); + .ReturnsAsync([rootC, rootD, rootE,]); var (result, componentRecorder) = await this.DetectorTestUtility .WithFile("setup.py", string.Empty, fileLocation: file1) @@ -231,12 +231,12 @@ public class SimplePipComponentDetectorTests : BaseDetectorTest x.Id == rootId); } - 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", }); + this.CheckChild(componentRecorder, "red 0.2 - pip", ["a 1.0 - pip", "c 1.0 - pip",]); + this.CheckChild(componentRecorder, "green 1.3 - pip", ["b 2.1 - pip",]); + this.CheckChild(componentRecorder, "blue 0.4 - pip", ["c 1.0 - pip",]); + this.CheckChild(componentRecorder, "cat 1.8 - pip", ["b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip",]); + this.CheckChild(componentRecorder, "lion 3.8 - pip", ["b 2.1 - pip", "c 1.0 - pip", "d 1.9 - pip",]); + this.CheckChild(componentRecorder, "dog 2.1 - pip", ["c 1.0 - pip",]); var graphsByLocations = componentRecorder.GetDependencyGraphsByLocation(); graphsByLocations.Should().HaveCount(2); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePypiClientTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePypiClientTests.cs index e1b91127..f46ccb74 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePypiClientTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePypiClientTests.cs @@ -1,7 +1,6 @@ namespace Microsoft.ComponentDetection.Detectors.Tests; using System; -using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; @@ -46,7 +45,7 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_DuplicateEntries_CallsGetAsync_OnceAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" }, Name = "boto3" }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"], Name = "boto3" }; var pythonProject = this.SampleValidApiJsonResponse("boto3", "0.0.1"); var mockHandler = this.MockHttpMessageHandler(pythonProject, HttpStatusCode.OK); @@ -67,10 +66,10 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_DifferentEntries_CallsGetAsync_TwiceAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var pythonProject = new SimplePypiProject() { - Files = new List { new SimplePypiProjectRelease() }, + Files = [new SimplePypiProjectRelease()], }; var mockHandler = this.MockHttpMessageHandler(JsonConvert.SerializeObject(pythonProject), HttpStatusCode.OK); @@ -96,15 +95,15 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_ReturnsValidSimplePypiProjectAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" }, Name = "boto3" }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"], Name = "boto3" }; var sampleApiResponse = this.SampleValidApiJsonResponse("boto3", "0.0.1"); var expectedResult = new SimplePypiProject() { - Files = new List - { + Files = + [ new SimplePypiProjectRelease() { FileName = "boto3-0.0.1-py2.py3-none-any.whl", Url = new Uri("https://files.pythonhosted.org/packages/3f/95/a24847c245befa8c50a9516cbdca309880bd21b5879e7c895e953217e947/boto3-0.0.1-py2.py3-none-any.whl"), Size = 45469 }, new SimplePypiProjectRelease() { FileName = "boto3-0.0.1.tar.gz", Url = new Uri("https://files.pythonhosted.org/packages/df/18/4e36b93f6afb79b5f67b38f7d235773a21831b193602848c590f8a008608/boto3-0.0.1.tar.gz"), Size = 33415 }, - }, + ], }; var mockHandler = this.MockHttpMessageHandler(sampleApiResponse, HttpStatusCode.OK); @@ -117,7 +116,7 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_InvalidSpec_NotThrowAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" }, Name = "randomName" }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"], Name = "randomName" }; var mockHandler = this.MockHttpMessageHandler("404 Not Found", HttpStatusCode.NotFound); var simplePypiClient = this.CreateSimplePypiClient(mockHandler.Object, new Mock().Object, new Mock>().Object); @@ -130,7 +129,7 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_UnexpectedContentTypeReturnedByApi_NotThrowAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var content = "\r\n\t

Links for boto3

\r\n\tboto3-0.0.1-py2.py3-none-any.whl
"; var mockHandler = this.MockHttpMessageHandler(content, HttpStatusCode.OK); @@ -144,7 +143,7 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_ShouldRetryAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var mockHandler = this.MockHttpMessageHandler(string.Empty, HttpStatusCode.InternalServerError); var simplePypiClient = this.CreateSimplePypiClient(mockHandler.Object, new Mock().Object, new Mock>().Object); @@ -164,7 +163,7 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_ShouldNotRetryAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var mockHandler = this.MockHttpMessageHandler("some content", HttpStatusCode.MultipleChoices); var simplePypiClient = this.CreateSimplePypiClient(mockHandler.Object, new Mock().Object, new Mock>().Object); @@ -182,7 +181,7 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_AddsCorrectHeadersAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var pythonProject = this.SampleValidApiJsonResponse("boto3", "0.0.1"); var mockHandler = this.MockHttpMessageHandler(pythonProject, HttpStatusCode.OK); @@ -206,7 +205,7 @@ public class SimplePyPiClientTests [TestMethod] public async Task GetSimplePypiProject_MaxEntriesVariable_CreatesNewCacheAsync() { - var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = new List { "==1.0.0" } }; + var pythonSpecs = new PipDependencySpecification { DependencySpecifiers = ["==1.0.0"] }; var pythonProject = this.SampleValidApiJsonResponse("boto3", "0.0.1"); var mockHandler = this.MockHttpMessageHandler(pythonProject, HttpStatusCode.OK); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePythonResolverTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePythonResolverTests.cs index 63216029..71201aa8 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePythonResolverTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/SimplePythonResolverTests.cs @@ -49,8 +49,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("b")))).ReturnsAsync(bReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c")))).ReturnsAsync(cReleases); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString(new List() { b }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString(new List() { c }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString([b]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString([c]))); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.First().Url)).ReturnsAsync(new MemoryStream()); var dependencies = new List { specA }; @@ -95,8 +95,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c")))).ReturnsAsync(cReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("dne")))).ReturnsAsync(this.CreateSimplePypiProject(new List<(string, string)>())); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString(new List() { b }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString(new List() { c }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString([b]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString([c]))); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.First().Url)).ReturnsAsync(new MemoryStream()); var dependencies = new List { specA, specDne }; @@ -137,8 +137,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("b")))).ReturnsAsync(bReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c")))).ReturnsAsync(cReleases); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString(new List() { b }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString(new List() { c }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString([b]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString([c]))); var dependencies = new List { specA }; @@ -179,8 +179,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("b")))).ReturnsAsync(bReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c") && x.DependencySpecifiers.First().Equals("<=1.1")))).ReturnsAsync(cReleases); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString(new List() { b, c }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString(new List() { cAlt }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString([b, c]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString([cAlt]))); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.First().Url)).ReturnsAsync(new MemoryStream()); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.Last().Url)).ReturnsAsync(new MemoryStream()); @@ -228,8 +228,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("b")))).ReturnsAsync(bReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c") && x.DependencySpecifiers.First().Equals("<=1.1")))).ReturnsAsync(cReleases); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString(new List() { b, c }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString(new List() { cAlt }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString([b, c]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString([cAlt]))); var dependencies = new List { specA }; @@ -275,8 +275,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("b")))).ReturnsAsync(bReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c")))).ReturnsAsync(cReleases); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.15.0", this.CreateMetadataString(new List() { b }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.19", this.CreateMetadataString(new List() { c }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.15.0", this.CreateMetadataString([b]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.19", this.CreateMetadataString([c]))); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.First().Url)).ReturnsAsync(new MemoryStream()); var dependencies = new List { specA }; @@ -318,8 +318,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("b")))).ReturnsAsync(bReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c")))).ReturnsAsync(cReleases); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.20", this.CreateMetadataString(new List() { b }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0.0", this.CreateMetadataString(new List() { c }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.20", this.CreateMetadataString([b]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0.0", this.CreateMetadataString([c]))); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.First().Url)).ReturnsAsync(new MemoryStream()); var dependencies = new List { specA }; @@ -360,8 +360,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("b")))).ReturnsAsync(bReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c")))).ReturnsAsync(cReleases); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString(new List() { b }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString(new List() { c, c2 }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "1.0", this.CreateMetadataString([b]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString([c, c2]))); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.First().Url)).ReturnsAsync(new MemoryStream()); var dependencies = new List { specA }; @@ -437,7 +437,7 @@ public class SimplePythonResolverTests .ReturnsAsync(releases); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(releases.Files.First().Url)) - .ReturnsAsync(this.CreatePypiZip(componentName, versions[i], this.CreateMetadataString(new List()))); + .ReturnsAsync(this.CreatePypiZip(componentName, versions[i], this.CreateMetadataString([]))); } var resolver = new SimplePythonResolver(this.simplePyPiClient.Object, this.loggerMock.Object); @@ -477,8 +477,8 @@ public class SimplePythonResolverTests this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("b")))).ReturnsAsync(bReleases); this.simplePyPiClient.Setup(x => x.GetSimplePypiProjectAsync(It.Is(x => x.Name.Equals("c")))).ReturnsAsync(cReleases); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "10.0.0", this.CreateMetadataString(new List() { b }))); - this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString(new List() { c }))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(aReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("a", "10.0.0", this.CreateMetadataString([b]))); + this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(bReleases.Files.First().Url)).ReturnsAsync(this.CreatePypiZip("b", "1.0", this.CreateMetadataString([c]))); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.First().Url)).ReturnsAsync(new MemoryStream()); this.simplePyPiClient.Setup(x => x.FetchPackageFileStreamAsync(cReleases.Files.Last().Url)).ReturnsAsync(new MemoryStream()); @@ -530,7 +530,7 @@ public class SimplePythonResolverTests private SimplePypiProject CreateSimplePypiProject(IList<(string Version, string PackageTypes)> versionAndTypes) { - var toReturn = new SimplePypiProject() { Files = new List() }; + var toReturn = new SimplePypiProject() { Files = [] }; foreach ((var version, var packagetype) in versionAndTypes) { diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/EnumerableStringComparer.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/EnumerableStringComparer.cs index bd03ea9e..e2b79a14 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/EnumerableStringComparer.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/EnumerableStringComparer.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests.Utilities; +namespace Microsoft.ComponentDetection.Detectors.Tests.Utilities; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/TestUtilityExtensions.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/TestUtilityExtensions.cs index 0b409885..63569435 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/TestUtilityExtensions.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/Utilities/TestUtilityExtensions.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests.Utilities; +namespace Microsoft.ComponentDetection.Detectors.Tests.Utilities; using System; using System.Security.Cryptography; diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs index 8256b298..f149aec1 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/VcpkgComponentDetectorTests.cs @@ -73,10 +73,7 @@ public class VcpkgComponentDetectorTests : BaseDetectorTest await YarnBlockFile.CreateBlockFileAsync(null); - - await Assert.ThrowsExceptionAsync(Action); + var action = async () => await YarnBlockFile.CreateBlockFileAsync(null); + await action.Should().ThrowAsync(); } [TestMethod] @@ -29,9 +28,8 @@ public class YarnBlockFileTests stream.Close(); - async Task Action() => await YarnBlockFile.CreateBlockFileAsync(stream); - - await Assert.ThrowsExceptionAsync(Action); + var action = async () => await YarnBlockFile.CreateBlockFileAsync(stream); + await action.Should().ThrowAsync(); } [TestMethod] diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs index d4553504..e8d1cd7e 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnLockDetectorTests.cs @@ -33,7 +33,7 @@ public class YarnLockDetectorTests : BaseDetectorTest // TODO: Mock all of this correctly var loggerMock = new Mock>(); this.yarnLockParser = new YarnLockParser(loggerMock.Object); - this.yarnLockFileFactory = new YarnLockFileFactory(new[] { this.yarnLockParser }); + this.yarnLockFileFactory = new YarnLockFileFactory([this.yarnLockParser]); var yarnLockFileFactoryMock = new Mock(); var recorderMock = new Mock(); @@ -52,11 +52,11 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJson, new List { "package.json" }) + .WithFile("package.json", packageJson, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -67,11 +67,11 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJson, new List { "package.json" }) + .WithFile("package.json", packageJson, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -96,11 +96,11 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJsonContent, new List { "package.json" }) + .WithFile("package.json", packageJsonContent, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -113,7 +113,7 @@ public class YarnLockDetectorTests : BaseDetectorTest var builder = new StringBuilder(); - builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent([])); builder.AppendLine($"{componentName0}@{providedVersion0}"); builder.AppendLine($" version {version0}"); builder.AppendLine($" resolved {resolved0}"); @@ -123,11 +123,11 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJsonContent, new List { "package.json" }) + .WithFile("package.json", packageJsonContent, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); - componentRecorder.GetDetectedComponents().Count().Should().Be(0); + componentRecorder.GetDetectedComponents().Should().BeEmpty(); } [TestMethod] @@ -142,12 +142,12 @@ public class YarnLockDetectorTests : BaseDetectorTest ResolvedVersion = "https://resolved0/a/resolved", }; - var yarnLock = this.CreateYarnLockV1FileContent(new List { componentA }); + var yarnLock = this.CreateYarnLockV1FileContent([componentA]); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJsonContent, new List { "package.json" }) + .WithFile("package.json", packageJsonContent, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -174,12 +174,12 @@ public class YarnLockDetectorTests : BaseDetectorTest ResolvedVersion = "https://resolved0/a/resolved", }; - var yarnLock = this.CreateYarnLockV2FileContent(new List { componentA }); + var yarnLock = this.CreateYarnLockV2FileContent([componentA]); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJsonContent, new List { "package.json" }) + .WithFile("package.json", packageJsonContent, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -208,7 +208,7 @@ public class YarnLockDetectorTests : BaseDetectorTest Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent([componentA])); var workspaceJson = new { @@ -224,8 +224,8 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", componentStream.Stream) - .WithFile("package.json", packageStream.Stream, new[] { "package.json" }) - .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) + .WithFile("package.json", packageStream.Stream, ["package.json"]) + .WithFile("package.json", workspaceJsonComponentStream.Stream, ["package.json"], Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -254,7 +254,7 @@ public class YarnLockDetectorTests : BaseDetectorTest Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent([componentA])); var workspaceJson = new { @@ -270,8 +270,8 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", componentStream.Stream) - .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "package.json")) - .WithFile("package.json", packageStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) + .WithFile("package.json", workspaceJsonComponentStream.Stream, ["package.json"], Path.Combine(Path.GetTempPath(), "package.json")) + .WithFile("package.json", packageStream.Stream, ["package.json"], Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -300,7 +300,7 @@ public class YarnLockDetectorTests : BaseDetectorTest Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV2FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV2FileContent([componentA])); var workspaceJson = new { @@ -316,8 +316,8 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", componentStream.Stream) - .WithFile("package.json", packageStream.Stream, new[] { "package.json" }) - .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) + .WithFile("package.json", packageStream.Stream, ["package.json"]) + .WithFile("package.json", workspaceJsonComponentStream.Stream, ["package.json"], Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -346,7 +346,7 @@ public class YarnLockDetectorTests : BaseDetectorTest Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV1FileContent([componentA])); var workspaceJson = new { @@ -362,8 +362,8 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", componentStream.Stream) - .WithFile("package.json", packageStream.Stream, new[] { "package.json" }) - .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) + .WithFile("package.json", packageStream.Stream, ["package.json"]) + .WithFile("package.json", workspaceJsonComponentStream.Stream, ["package.json"], Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -392,7 +392,7 @@ public class YarnLockDetectorTests : BaseDetectorTest Name = Guid.NewGuid().ToString("N"), }; - var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV2FileContent(new List { componentA })); + var componentStream = YarnTestUtilities.GetMockedYarnLockStream("yarn.lock", this.CreateYarnLockV2FileContent([componentA])); var workspaceJson = new { @@ -408,8 +408,8 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", componentStream.Stream) - .WithFile("package.json", packageStream.Stream, new[] { "package.json" }) - .WithFile("package.json", workspaceJsonComponentStream.Stream, new[] { "package.json" }, Path.Combine(Path.GetTempPath(), "workspace", "package.json")) + .WithFile("package.json", packageStream.Stream, ["package.json"]) + .WithFile("package.json", workspaceJsonComponentStream.Stream, ["package.json"], Path.Combine(Path.GetTempPath(), "workspace", "package.json")) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -447,12 +447,12 @@ public class YarnLockDetectorTests : BaseDetectorTest componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; - var yarnLock = this.CreateYarnLockV1FileContent(new List { componentA, componentB }); + var yarnLock = this.CreateYarnLockV1FileContent([componentA, componentB]); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJsonContent, new List { "package.json" }) + .WithFile("package.json", packageJsonContent, ["package.json"]) .ExecuteDetectorAsync(); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -494,12 +494,12 @@ public class YarnLockDetectorTests : BaseDetectorTest componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; - var yarnLock = this.CreateYarnLockV2FileContent(new List { componentA, componentB }); + var yarnLock = this.CreateYarnLockV2FileContent([componentA, componentB]); var (packageJsonName, packageJsonContent, packageJsonPath) = NpmTestUtilities.GetPackageJsonOneRoot(componentA.Name, componentA.RequestedVersion); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJsonContent, new List { "package.json" }) + .WithFile("package.json", packageJsonContent, ["package.json"]) .ExecuteDetectorAsync(); var detectedComponents = componentRecorder.GetDetectedComponents(); @@ -572,7 +572,7 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJsonContent, new List { "package.json" }) + .WithFile("package.json", packageJsonContent, ["package.json"]) .ExecuteDetectorAsync(); var detectedComponentes = componentRecorder.GetDetectedComponents(); @@ -632,7 +632,7 @@ public class YarnLockDetectorTests : BaseDetectorTest var builder = new StringBuilder(); - builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent([])); builder.AppendLine($"{componentNameA}@{requestedVersionA}:"); builder.AppendLine($" version: {actualVersionA}"); builder.AppendLine($" resolved: {resolvedA}"); @@ -648,7 +648,7 @@ public class YarnLockDetectorTests : BaseDetectorTest var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLock) - .WithFile("package.json", packageJsonContent, new List { "package.json" }) + .WithFile("package.json", packageJsonContent, ["package.json"]) .ExecuteDetectorAsync(); var detectedComponentes = componentRecorder.GetDetectedComponents(); @@ -702,12 +702,12 @@ public class YarnLockDetectorTests : BaseDetectorTest componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; componentB.Dependencies = new List<(string, string)> { (componentC.Name, componentC.RequestedVersion) }; - var yarnLockFileContent = this.CreateYarnLockV1FileContent(new List { componentA, componentB, componentC }); - var packageJsonFileContent = this.CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); + var yarnLockFileContent = this.CreateYarnLockV1FileContent([componentA, componentB, componentC]); + var packageJsonFileContent = this.CreatePackageJsonFileContent([componentA, componentB, componentC]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) - .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) + .WithFile("package.json", packageJsonFileContent, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -719,13 +719,13 @@ public class YarnLockDetectorTests : BaseDetectorTest var dependencyGraph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); - dependencyGraph.GetDependenciesForComponent(componentAId).Should().HaveCount(1); + dependencyGraph.GetDependenciesForComponent(componentAId).Should().ContainSingle(); dependencyGraph.GetDependenciesForComponent(componentAId).Should().Contain(componentBId); - dependencyGraph.GetDependenciesForComponent(componentBId).Should().HaveCount(1); + dependencyGraph.GetDependenciesForComponent(componentBId).Should().ContainSingle(); dependencyGraph.GetDependenciesForComponent(componentBId).Should().Contain(componentCId); - dependencyGraph.GetDependenciesForComponent(componentCId).Should().HaveCount(0); + dependencyGraph.GetDependenciesForComponent(componentCId).Should().BeEmpty(); } [TestMethod] @@ -758,12 +758,12 @@ public class YarnLockDetectorTests : BaseDetectorTest componentA.Dependencies = new List<(string, string)> { (componentB.Name, componentB.RequestedVersion) }; componentB.Dependencies = new List<(string, string)> { (componentC.Name, componentC.RequestedVersion) }; - var yarnLockFileContent = this.CreateYarnLockV2FileContent(new List { componentA, componentB, componentC }); - var packageJsonFileContent = this.CreatePackageJsonFileContent(new List { componentA, componentB, componentC }); + var yarnLockFileContent = this.CreateYarnLockV2FileContent([componentA, componentB, componentC]); + var packageJsonFileContent = this.CreatePackageJsonFileContent([componentA, componentB, componentC]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) - .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) + .WithFile("package.json", packageJsonFileContent, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -775,13 +775,13 @@ public class YarnLockDetectorTests : BaseDetectorTest var dependencyGraph = componentRecorder.GetDependencyGraphsByLocation().Values.First(); - dependencyGraph.GetDependenciesForComponent(componentAId).Should().HaveCount(1); + dependencyGraph.GetDependenciesForComponent(componentAId).Should().ContainSingle(); dependencyGraph.GetDependenciesForComponent(componentAId).Should().Contain(componentBId); - dependencyGraph.GetDependenciesForComponent(componentBId).Should().HaveCount(1); + dependencyGraph.GetDependenciesForComponent(componentBId).Should().ContainSingle(); dependencyGraph.GetDependenciesForComponent(componentBId).Should().Contain(componentCId); - dependencyGraph.GetDependenciesForComponent(componentCId).Should().HaveCount(0); + dependencyGraph.GetDependenciesForComponent(componentCId).Should().BeEmpty(); } [TestMethod] @@ -795,17 +795,17 @@ public class YarnLockDetectorTests : BaseDetectorTest var builder = new StringBuilder(); - builder.AppendLine(this.CreateYarnLockV2FileContent(new List())); + builder.AppendLine(this.CreateYarnLockV2FileContent([])); builder.AppendLine($"\"{componentNameA}@{requestedVersionA}\", \"{componentNameB}@{requestedVersionB}\":"); builder.AppendLine($" version: {actualVersion}"); builder.AppendLine(); var yarnLockFileContent = builder.ToString(); - var packageJsonFileContent = this.CreatePackageJsonFileContent(new List()); + var packageJsonFileContent = this.CreatePackageJsonFileContent([]); var (scanResult, componentRecorder) = await this.DetectorTestUtility .WithFile("yarn.lock", yarnLockFileContent) - .WithFile("package.json", packageJsonFileContent, new List { "package.json" }) + .WithFile("package.json", packageJsonFileContent, ["package.json"]) .ExecuteDetectorAsync(); scanResult.ResultCode.Should().Be(ProcessingResultCode.Success); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs index a144c597..f4e83540 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnParserTests.cs @@ -92,21 +92,19 @@ public class YarnParserTests "a@^1.0.0", "1.0.0", "https://a", - new List - { + [ this.CreateDependencyBlock(new Dictionary { { "xyz", "2" } }), - }, + ], yarnLockFileVersion), this.CreateBlock( "b@2.4.6", "2.4.6", "https://b", - new List - { + [ this.CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }), - }, + ], yarnLockFileVersion), - this.CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", Enumerable.Empty(), yarnLockFileVersion), + this.CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", [], yarnLockFileVersion), }; var blockFile = new Mock(); @@ -139,21 +137,19 @@ public class YarnParserTests "a@^1.0.0", "1.0.0", "https://a", - new List - { + [ this.CreateDependencyBlock(new Dictionary { { "xyz", "2" } }), - }, + ], yarnLockFileVersion), this.CreateBlock( "b@2.4.6", "2.4.6", "https://b", - new List - { + [ this.CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }), - }, + ], yarnLockFileVersion), - this.CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", Enumerable.Empty(), yarnLockFileVersion), + this.CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", [], yarnLockFileVersion), }; var blockFile = new Mock(); @@ -186,12 +182,11 @@ public class YarnParserTests "internal-package@npm:0.0.0, internal-package@workspace:packages/internal-package", "0.0.0-use.local", "internal-package@workspace:packages/internal-package", - new List - { + [ this.CreateDependencyBlock(new Dictionary { { "xyz", "2" } }), - }, + ], yarnLockFileVersion), - this.CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", Enumerable.Empty(), yarnLockFileVersion), + this.CreateBlock("xyz@2, xyz@2.4", "2.4.3", "https://xyz", [], yarnLockFileVersion), }; var blockFile = new Mock(); @@ -220,14 +215,12 @@ public class YarnParserTests var blocks = new List { - this.CreateBlock("a", "1.0.0", "https://a", new List - { + this.CreateBlock("a", "1.0.0", "https://a", [ this.CreateDependencyBlock(new Dictionary { { "xyz", "2" } }), - }), - this.CreateBlock("b", "2.4.6", "https://b", new List - { + ]), + this.CreateBlock("b", "2.4.6", "https://b", [ this.CreateDependencyBlock(new Dictionary { { "xyz", "2.4" }, { "a", "^1.0.0" } }), - }), + ]), }; var blockFile = new Mock(); diff --git a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnTestUtilities.cs b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnTestUtilities.cs index 345d0db6..7a0a56a1 100644 --- a/test/Microsoft.ComponentDetection.Detectors.Tests/YarnTestUtilities.cs +++ b/test/Microsoft.ComponentDetection.Detectors.Tests/YarnTestUtilities.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Detectors.Tests; +namespace Microsoft.ComponentDetection.Detectors.Tests; using System.IO; using System.Text; diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/DefaultExperimentProcessorTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/DefaultExperimentProcessorTests.cs index e5898552..139e1b0a 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/DefaultExperimentProcessorTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/DefaultExperimentProcessorTests.cs @@ -16,6 +16,8 @@ using Moq; [TestCategory("Governance/ComponentDetection")] public class DefaultExperimentProcessorTests { + private static readonly JsonSerializerOptions TestJsonOptions = new JsonSerializerOptions { WriteIndented = true }; + private readonly Mock fileWritingServiceMock; private readonly DefaultExperimentProcessor processor; @@ -36,7 +38,7 @@ public class DefaultExperimentProcessorTests ExperimentTestUtils.CreateRandomExperimentComponents(), ExperimentTestUtils.CreateRandomExperimentComponents()); - var serializedDiff = JsonSerializer.Serialize(diff, new JsonSerializerOptions { WriteIndented = true }); + var serializedDiff = JsonSerializer.Serialize(diff, TestJsonOptions); await this.processor.ProcessExperimentAsync(config.Object, diff); diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentDiffTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentDiffTests.cs index 54c47abe..f1a1fffc 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentDiffTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentDiffTests.cs @@ -1,10 +1,8 @@ namespace Microsoft.ComponentDetection.Orchestrator.Tests.Experiments; -using System.Collections.Generic; using System.Linq; using FluentAssertions; using Microsoft.ComponentDetection.Contracts.BcdeModels; -using Microsoft.ComponentDetection.Contracts.TypedComponent; using Microsoft.ComponentDetection.Orchestrator.Experiments.Models; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -17,7 +15,7 @@ public class ExperimentDiffTests public void ExperimentDiff_DiffsAddedIds() { var testComponents = ExperimentTestUtils.CreateRandomExperimentComponents(); - var diff = new ExperimentDiff(Enumerable.Empty(), testComponents); + var diff = new ExperimentDiff([], testComponents); diff.AddedIds.Should().BeEquivalentTo(testComponents.Select(x => x.Id)); diff.RemovedIds.Should().BeEmpty(); @@ -31,7 +29,7 @@ public class ExperimentDiffTests public void ExperimentDiff_DiffsRemovedIds() { var testComponents = ExperimentTestUtils.CreateRandomExperimentComponents(); - var diff = new ExperimentDiff(testComponents, Enumerable.Empty()); + var diff = new ExperimentDiff(testComponents, []); diff.RemovedIds.Should().BeEquivalentTo(testComponents.Select(x => x.Id)); diff.AddedIds.Should().BeEmpty(); @@ -54,8 +52,8 @@ public class ExperimentDiffTests componentB.IsDevelopmentDependency = true; var diff = new ExperimentDiff( - new[] { new ExperimentComponent(componentA) }, - new[] { new ExperimentComponent(componentB) }); + [new ExperimentComponent(componentA)], + [new ExperimentComponent(componentB)]); diff.DevelopmentDependencyChanges.Should().ContainSingle(); @@ -79,12 +77,12 @@ public class ExperimentDiffTests var componentB = new ScannedComponent() { Component = componentA.Component, - TopLevelReferrers = new HashSet { rootComponent }, + TopLevelReferrers = [rootComponent], }; var diff = new ExperimentDiff( - new[] { new ExperimentComponent(componentA), }, - new[] { new ExperimentComponent(componentB), }); + [new ExperimentComponent(componentA),], + [new ExperimentComponent(componentB),]); diff.AddedRootIds.Should().ContainSingle(); diff.RemovedRootIds.Should().BeEmpty(); @@ -106,12 +104,12 @@ public class ExperimentDiffTests var componentB = new ScannedComponent() { Component = componentA.Component, - TopLevelReferrers = new HashSet { rootComponent }, + TopLevelReferrers = [rootComponent], }; var diff = new ExperimentDiff( - new[] { new ExperimentComponent(componentB), }, - new[] { new ExperimentComponent(componentA), }); + [new ExperimentComponent(componentB),], + [new ExperimentComponent(componentA),]); diff.RemovedRootIds.Should().ContainSingle(); diff.AddedRootIds.Should().BeEmpty(); diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentResultsTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentResultsTests.cs index c82f7470..c9a610e1 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentResultsTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentResultsTests.cs @@ -46,7 +46,7 @@ public class ExperimentResultsTests }; var experiment = new ExperimentResults(); - experiment.AddComponentsToControlGroup(new[] { componentA, componentB }); + experiment.AddComponentsToControlGroup([componentA, componentB]); experiment.ControlGroupComponents.Should().ContainSingle(); experiment.ExperimentGroupComponents.Should().BeEmpty(); diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentServiceTests.cs index 34f0bd46..5921ef03 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Experiments/ExperimentServiceTests.cs @@ -3,7 +3,6 @@ namespace Microsoft.ComponentDetection.Orchestrator.Tests.Experiments; using System; using System.Collections.Generic; using System.IO; -using System.Linq; using System.Threading.Tasks; using FluentAssertions; using Microsoft.ComponentDetection.Common.DependencyGraph; @@ -70,8 +69,8 @@ public class ExperimentServiceTests var components = ExperimentTestUtils.CreateRandomComponents(); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - Enumerable.Empty(), + [this.experimentConfigMock.Object], + [], this.graphTranslationServiceMock.Object, this.loggerMock.Object); this.SetupGraphMock(components); @@ -102,8 +101,8 @@ public class ExperimentServiceTests this.SetupGraphMock(components); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object, filterConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object, filterConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); @@ -128,8 +127,8 @@ public class ExperimentServiceTests var components = ExperimentTestUtils.CreateRandomComponents(); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object, filterConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object, filterConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); @@ -152,8 +151,8 @@ public class ExperimentServiceTests this.SetupGraphMock(components); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); service.RecordDetectorRun(this.detectorMock.Object, this.componentRecorder, this.scanSettingsMock.Object); @@ -177,8 +176,8 @@ public class ExperimentServiceTests this.SetupGraphMock(components); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); service.RecordDetectorRun(this.detectorMock.Object, this.componentRecorder, this.scanSettingsMock.Object); @@ -191,8 +190,8 @@ public class ExperimentServiceTests public async Task FinishAsync_SkipsEmptyExperimentsAsync() { var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); await service.FinishAsync(); @@ -209,8 +208,8 @@ public class ExperimentServiceTests this.SetupGraphMock(components); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); service.RecordDetectorRun(this.detectorMock.Object, this.componentRecorder, this.scanSettingsMock.Object); @@ -231,8 +230,8 @@ public class ExperimentServiceTests this.SetupGraphMock(components); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); service.RecordDetectorRun(this.detectorMock.Object, this.componentRecorder, this.scanSettingsMock.Object); @@ -253,8 +252,8 @@ public class ExperimentServiceTests this.SetupGraphMock(components); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); service.RecordDetectorRun(this.detectorMock.Object, this.componentRecorder, this.scanSettingsMock.Object); @@ -272,8 +271,8 @@ public class ExperimentServiceTests var components = ExperimentTestUtils.CreateRandomComponents(); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); this.SetupGraphMock(components); @@ -303,8 +302,8 @@ public class ExperimentServiceTests var components = ExperimentTestUtils.CreateRandomComponents(); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); this.SetupGraphMock(components); @@ -332,8 +331,8 @@ public class ExperimentServiceTests public async Task InitializeAsync_InitsConfigsAsync() { var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); @@ -348,8 +347,8 @@ public class ExperimentServiceTests this.experimentConfigMock.Setup(x => x.InitAsync()).ThrowsAsync(new InvalidOperationException()); var service = new ExperimentService( - new[] { this.experimentConfigMock.Object }, - new[] { this.experimentProcessorMock.Object }, + [this.experimentConfigMock.Object], + [this.experimentProcessorMock.Object], this.graphTranslationServiceMock.Object, this.loggerMock.Object); diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/CommaDelimitedConverterTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/CommaDelimitedConverterTests.cs index 0abd3bef..e1f5daf8 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/CommaDelimitedConverterTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/CommaDelimitedConverterTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Tests.Extensions; +namespace Microsoft.ComponentDetection.Orchestrator.Tests.Extensions; using System; using FluentAssertions; diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/KeyValueDelimitedConverterTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/KeyValueDelimitedConverterTests.cs index ac4d40c1..f71c9d64 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/KeyValueDelimitedConverterTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/KeyValueDelimitedConverterTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Tests.Extensions; +namespace Microsoft.ComponentDetection.Orchestrator.Tests.Extensions; using System; using System.Collections.Generic; diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/SemicolonDelimitedConverterTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/SemicolonDelimitedConverterTests.cs index ad60945a..38b577d5 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/SemicolonDelimitedConverterTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Extensions/SemicolonDelimitedConverterTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Tests.Extensions; +namespace Microsoft.ComponentDetection.Orchestrator.Tests.Extensions; using System; using FluentAssertions; diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/LoggingEnricherTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/LoggingEnricherTests.cs index 2d211c6a..7de2e67a 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/LoggingEnricherTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/LoggingEnricherTests.cs @@ -1,13 +1,11 @@ namespace Microsoft.ComponentDetection.Orchestrator.Tests; using System; -using System.Collections.Generic; using FluentAssertions; using Microsoft.VisualStudio.TestTools.UnitTesting; using Moq; using Serilog.Core; using Serilog.Events; -using Serilog.Parsing; [TestClass] [TestCategory("Governance/All")] @@ -48,8 +46,8 @@ public class LoggingEnricherTests DateTimeOffset.Now, LogEventLevel.Debug, null, - new MessageTemplate("test", Array.Empty()), - new List()); + new MessageTemplate("test", []), + []); this.enricher.Enrich(logEvent, this.propertyFactoryMock.Object); diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs index 62d7f849..b07d88b8 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/BcdeScanExecutionServiceTests.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.IO; using System.Linq; -using System.Threading; using System.Threading.Tasks; using FluentAssertions; using Microsoft.ComponentDetection.Common.DependencyGraph; @@ -51,11 +50,11 @@ public class BcdeScanExecutionServiceTests this.sampleContainerDetails = new ContainerDetails { Id = 1 }; this.graphTranslationService = new DefaultGraphTranslationService(new Mock>().Object); - this.detectedComponents = new[] - { + this.detectedComponents = + [ new DetectedComponent(new NpmComponent("some-npm-component", "1.2.3")), new DetectedComponent(new NuGetComponent("SomeNugetComponent", "1.2.3.4")), - }; + ]; this.serviceUnderTest = new ScanExecutionService( this.detectorsMock.Object, @@ -97,14 +96,14 @@ public class BcdeScanExecutionServiceTests this.componentDetector3Mock.SetupGet(x => x.Version).Returns(10); this.detectedComponents[0].DevelopmentDependency = true; - this.detectedComponents[0].ContainerDetailIds = new HashSet - { + this.detectedComponents[0].ContainerDetailIds = + [ this.sampleContainerDetails.Id, - }; + ]; singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0], isDevelopmentDependency: true); var parentPipComponent = new PipComponent("sample-root", "1.0"); - this.detectedComponents[1].DependencyRoots = new HashSet(new[] { parentPipComponent }); + this.detectedComponents[1].DependencyRoots = new HashSet([parentPipComponent]); this.detectedComponents[1].DevelopmentDependency = null; singleFileComponentRecorder.RegisterUsage(new DetectedComponent(parentPipComponent, detector: new Mock().Object), isExplicitReferencedDependency: true); singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1], parentComponentId: parentPipComponent.Id); @@ -120,7 +119,7 @@ public class BcdeScanExecutionServiceTests restrictions.AllowedDetectorCategories.Should().BeNull(); restrictions.AllowedDetectorIds.Should().BeNull(); }, - new List { componentRecorder }); + [componentRecorder]); result.Result.Should().Be(ProcessingResultCode.Success); this.ValidateDetectedComponents(result.DetectedComponents); @@ -147,8 +146,8 @@ public class BcdeScanExecutionServiceTests { var settings = new ScanSettings { - DetectorCategories = new[] { "Category1", "Category2" }, - DetectorsFilter = new[] { "Detector1", "Detector2" }, + DetectorCategories = ["Category1", "Category2"], + DetectorsFilter = ["Detector1", "Detector2"], SourceDirectory = this.sourceDirectory, }; @@ -164,7 +163,7 @@ public class BcdeScanExecutionServiceTests restrictions.AllowedDetectorCategories.Should().Contain(settings.DetectorCategories); restrictions.AllowedDetectorIds.Should().Contain(settings.DetectorsFilter); }, - new List { componentRecorder }); + [componentRecorder]); result.Result.Should().Be(ProcessingResultCode.Success); this.ValidateDetectedComponents(result.DetectedComponents); @@ -188,7 +187,7 @@ public class BcdeScanExecutionServiceTests restrictions => { }, - new List { componentRecorder }); + [componentRecorder]); result.Result.Should().Be(ProcessingResultCode.Success); this.ValidateDetectedComponents(result.DetectedComponents); @@ -210,7 +209,7 @@ public class BcdeScanExecutionServiceTests singleFileComponentRecorder.RegisterUsage(this.detectedComponents[0]); singleFileComponentRecorder.RegisterUsage(this.detectedComponents[1]); - var result = await this.DetectComponentsHappyPathAsync(settings, restrictions => { }, new List { componentRecorder }); + var result = await this.DetectComponentsHappyPathAsync(settings, restrictions => { }, [componentRecorder]); result.Result.Should().Be(ProcessingResultCode.Success); this.ValidateDetectedComponents(result.DetectedComponents); @@ -234,21 +233,21 @@ public class BcdeScanExecutionServiceTests var mockDependencyGraphA = new Mock(); - mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] - { + mockDependencyGraphA.Setup(x => x.GetComponents()).Returns( + [ this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id, - }); + ]); mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[0].Component.Id)) - .Returns(new[] - { + .Returns( + [ 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 = await this.DetectComponentsHappyPathAsync(settings, restrictions => { }, new List { componentRecorder }); + var result = await this.DetectComponentsHappyPathAsync(settings, restrictions => { }, [componentRecorder]); result.SourceDirectory.Should().NotBeNull(); result.SourceDirectory.Should().Be(this.sourceDirectory.ToString()); @@ -262,7 +261,7 @@ public class BcdeScanExecutionServiceTests var actualGraph = matchingGraph.Value.Graph; actualGraph.Keys.Should().HaveCount(2); - actualGraph[this.detectedComponents[0].Component.Id].Count.Should().Be(1); + actualGraph[this.detectedComponents[0].Component.Id].Should().ContainSingle(); actualGraph[this.detectedComponents[0].Component.Id].Should().Contain(this.detectedComponents[1].Component.Id); actualGraph[this.detectedComponents[1].Component.Id].Should().BeNull(); @@ -287,15 +286,15 @@ public class BcdeScanExecutionServiceTests var mockDependencyGraphA = new Mock(); - mockDependencyGraphA.Setup(x => x.GetComponents()).Returns(new[] - { + mockDependencyGraphA.Setup(x => x.GetComponents()).Returns( + [ this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id, - }); + ]); mockDependencyGraphA.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[0].Component.Id)) - .Returns(new[] - { + .Returns( + [ this.detectedComponents[1].Component.Id, - }); + ]); mockDependencyGraphA.Setup(x => x.IsComponentExplicitlyReferenced(this.detectedComponents[0].Component.Id)).Returns(true); @@ -305,15 +304,15 @@ public class BcdeScanExecutionServiceTests var mockDependencyGraphB = new Mock(); - mockDependencyGraphB.Setup(x => x.GetComponents()).Returns(new[] - { + mockDependencyGraphB.Setup(x => x.GetComponents()).Returns( + [ this.detectedComponents[0].Component.Id, this.detectedComponents[1].Component.Id, - }); + ]); mockDependencyGraphB.Setup(x => x.GetDependenciesForComponent(this.detectedComponents[1].Component.Id)) - .Returns(new[] - { + .Returns( + [ this.detectedComponents[0].Component.Id, - }); + ]); mockDependencyGraphB.Setup(x => x.IsComponentExplicitlyReferenced(this.detectedComponents[1].Component.Id)).Returns(true); @@ -321,7 +320,7 @@ public class BcdeScanExecutionServiceTests singleFileComponentRecorderB.RegisterUsage(this.detectedComponents[1], isExplicitReferencedDependency: true); singleFileComponentRecorderB.RegisterUsage(this.detectedComponents[0], parentComponentId: this.detectedComponents[1].Component.Id); - var result = await this.DetectComponentsHappyPathAsync(settings, restrictions => { }, new List { componentRecorder }); + var result = await this.DetectComponentsHappyPathAsync(settings, restrictions => { }, [componentRecorder]); result.SourceDirectory.Should().NotBeNull(); result.SourceDirectory.Should().Be(this.sourceDirectory.ToString()); @@ -337,9 +336,9 @@ public class BcdeScanExecutionServiceTests var actualGraph = matchingGraph.Value.Graph; actualGraph.Keys.Should().HaveCount(2); - actualGraph[this.detectedComponents[0].Component.Id].Count.Should().Be(1); + actualGraph[this.detectedComponents[0].Component.Id].Should().ContainSingle(); 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().ContainSingle(); actualGraph[this.detectedComponents[1].Component.Id].Should().Contain(this.detectedComponents[0].Component.Id); } @@ -362,7 +361,7 @@ public class BcdeScanExecutionServiceTests singleFileComponentRecorder.RegisterUsage(detectedComponent2, isDevelopmentDependency: false); singleFileComponentRecorder.RegisterUsage(detectedComponent3); - var results = await this.SetupRecorderBasedScanningAsync(settings, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(settings, [componentRecorder]); var detectedComponents = results.ComponentsFound; @@ -397,7 +396,7 @@ public class BcdeScanExecutionServiceTests var detectedComponent2NewLocation = new DetectedComponent(new NpmComponent("test", "2.0.0"), detector: npmDetector.Object); singleFileComponentRecorder.RegisterUsage(detectedComponent2NewLocation, isExplicitReferencedDependency: true); - var results = await this.SetupRecorderBasedScanningAsync(settings, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(settings, [componentRecorder]); var detectedComponents = results.ComponentsFound; @@ -432,7 +431,7 @@ public class BcdeScanExecutionServiceTests var detectedComponent2NewLocation = new DetectedComponent(new NpmComponent("test", "2.0.0"), detector: npmDetector.Object); singleFileComponentRecorder.RegisterUsage(detectedComponent2NewLocation, isExplicitReferencedDependency: true); - var results = await this.SetupRecorderBasedScanningAsync(settings, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(settings, [componentRecorder]); var detectedComponents = results.ComponentsFound; @@ -460,7 +459,7 @@ public class BcdeScanExecutionServiceTests singleFileComponentRecorder.RegisterUsage(detectedComponent1, isExplicitReferencedDependency: true); singleFileComponentRecorder.RegisterUsage(detectedComponent2, parentComponentId: detectedComponent1.Component.Id); - var results = await this.SetupRecorderBasedScanningAsync(settings, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(settings, [componentRecorder]); var detectedComponents = results.ComponentsFound; @@ -490,7 +489,7 @@ public class BcdeScanExecutionServiceTests singleFileComponentRecorder.RegisterUsage(detectedComponent1, isExplicitReferencedDependency: true); singleFileComponentRecorder.RegisterUsage(detectedComponent2, parentComponentId: detectedComponent1.Component.Id); - var results = await this.SetupRecorderBasedScanningAsync(settings, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(settings, [componentRecorder]); var detectedComponents = results.ComponentsFound; @@ -543,7 +542,7 @@ public class BcdeScanExecutionServiceTests firstRecorder.RegisterUsage(component, isDevelopmentDependency: isDevDep); } - var results = await this.SetupRecorderBasedScanningAsync(settings, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(settings, [componentRecorder]); var components = results.ComponentsFound; @@ -574,7 +573,7 @@ public class BcdeScanExecutionServiceTests firstRecorder.RegisterUsage(firstComponent); secondRecorder.RegisterUsage(secondComponent); - var results = await this.SetupRecorderBasedScanningAsync(settings, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(settings, [componentRecorder]); var actualComponent = results.ComponentsFound.Single(); @@ -618,7 +617,7 @@ public class BcdeScanExecutionServiceTests secondRecorder.RegisterUsage(root2, isExplicitReferencedDependency: true); secondRecorder.RegisterUsage(secondComponent, parentComponentId: root2.Component.Id); - var results = await this.SetupRecorderBasedScanningAsync(settings, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(settings, [componentRecorder]); var actualComponent = results.ComponentsFound.First(c => c.Component.Id == firstComponent.Component.Id); actualComponent.TopLevelReferrers.Should().HaveCount(2); @@ -645,12 +644,12 @@ public class BcdeScanExecutionServiceTests singleFileComponentRecorder.RegisterUsage(detectedComponent, isDevelopmentDependency: true); - var results = await this.SetupRecorderBasedScanningAsync(args, new List { componentRecorder }); + var results = await this.SetupRecorderBasedScanningAsync(args, [componentRecorder]); results.ComponentsFound.Single(component => component.Component.Id == detectedComponent.Component.Id).IsDevelopmentDependency.Should().BeTrue(); singleFileComponentRecorder.RegisterUsage(detectedComponent, isDevelopmentDependency: false); - results = await this.SetupRecorderBasedScanningAsync(args, new List { componentRecorder }); + results = await this.SetupRecorderBasedScanningAsync(args, [componentRecorder]); results.ComponentsFound.Single(component => component.Component.Id == detectedComponent.Component.Id).IsDevelopmentDependency.Should().BeFalse(); } @@ -663,12 +662,12 @@ public class BcdeScanExecutionServiceTests this.componentDetector2Mock.SetupGet(x => x.Id).Returns("Detector2"); this.componentDetector3Mock.SetupGet(x => x.Id).Returns("Detector3"); - IEnumerable registeredDetectors = new[] - { + IEnumerable registeredDetectors = + [ this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, this.versionedComponentDetector1Mock.Object, - }; + ]; var restrictedDetectors = new[] { this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, @@ -687,7 +686,7 @@ public class BcdeScanExecutionServiceTests restrictions.AllowedDetectorCategories.Should().BeNull(); restrictions.AllowedDetectorIds.Should().BeNull(); }, - new List { componentRecorder }); + [componentRecorder]); result.DetectorsNotInRun.Should().ContainSingle(); result.DetectorsNotInRun.Single(x => x.DetectorId == "Detector1"); @@ -702,10 +701,10 @@ public class BcdeScanExecutionServiceTests this.componentDetector2Mock.SetupGet(x => x.Id).Returns("Detector2"); this.componentDetector3Mock.SetupGet(x => x.Id).Returns("Detector3"); - IEnumerable registeredDetectors = new[] - { + IEnumerable registeredDetectors = + [ this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, - }; + ]; var restrictedDetectors = new[] { this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, @@ -724,7 +723,7 @@ public class BcdeScanExecutionServiceTests restrictions.AllowedDetectorCategories.Should().BeNull(); restrictions.AllowedDetectorIds.Should().BeNull(); }, - new List { componentRecorder }); + [componentRecorder]); result.DetectorsNotInRun.Should().BeEmpty(); } @@ -784,12 +783,12 @@ public class BcdeScanExecutionServiceTests Action restrictionAsserter = null, IEnumerable componentRecorders = null) { - IEnumerable registeredDetectors = new[] - { + IEnumerable registeredDetectors = + [ this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, this.versionedComponentDetector1Mock.Object, - }; + ]; var restrictedDetectors = new[] { this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, @@ -842,12 +841,12 @@ public class BcdeScanExecutionServiceTests ScanSettings settings, IEnumerable componentRecorders) { - IEnumerable registeredDetectors = new[] - { + IEnumerable registeredDetectors = + [ this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, this.versionedComponentDetector1Mock.Object, - }; + ]; var restrictedDetectors = new[] { this.componentDetector2Mock.Object, this.componentDetector3Mock.Object, diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DefaultGraphTranslationServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DefaultGraphTranslationServiceTests.cs index c2a97177..b3ed0df1 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DefaultGraphTranslationServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DefaultGraphTranslationServiceTests.cs @@ -57,7 +57,7 @@ public class DefaultGraphTranslationServiceTests this.sampleContainerDetails.Id, this.sampleContainerDetails }, }, - ComponentRecorders = new[] { (this.componentDetectorMock.Object, this.componentRecorder) }, + ComponentRecorders = [(this.componentDetectorMock.Object, this.componentRecorder)], }; var expectedNpmComponent = new NpmComponent("npm-component", "1.2.3"); @@ -88,8 +88,8 @@ public class DefaultGraphTranslationServiceTests var resultNpmComponent = result.ComponentsFound.Single(c => c.Component.Type == ComponentType.Npm); var resultNugetComponent = result.ComponentsFound.Single(c => c.Component.Type == ComponentType.NuGet); - resultNpmComponent.LocationsFoundAt.Should().BeEquivalentTo(new[] { npmCustomPath, detectedFilePath, relatedFilePath }); - resultNugetComponent.LocationsFoundAt.Should().BeEquivalentTo(new[] { nugetCustomPath, detectedFilePath, relatedFilePath }); + resultNpmComponent.LocationsFoundAt.Should().BeEquivalentTo([npmCustomPath, detectedFilePath, relatedFilePath]); + resultNugetComponent.LocationsFoundAt.Should().BeEquivalentTo([nugetCustomPath, detectedFilePath, relatedFilePath]); var actualNpmComponent = resultNpmComponent.Component as NpmComponent; var actualNugetComponent = resultNugetComponent.Component as NuGetComponent; diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs index a5d8e9d3..f0c32487 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorProcessingServiceTests.cs @@ -83,10 +83,10 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_HappyPathReturnsDetectedComponentsAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, - }; + ]; var results = await this.serviceUnderTest.ProcessDetectorsAsync(DefaultArgs, this.detectorsToUse, new DetectorRestrictions()); @@ -119,7 +119,7 @@ public class DetectorProcessingServiceTests }; }); - this.detectorsToUse = new[] { mockComponentDetector.Object }; + this.detectorsToUse = [mockComponentDetector.Object]; var results = await this.serviceUnderTest.ProcessDetectorsAsync(DefaultArgs, this.detectorsToUse, new DetectorRestrictions()); results.ResultCode.Should().Be(ProcessingResultCode.Success); @@ -128,10 +128,10 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_HappyPathReturns_DependencyGraphAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, - }; + ]; var results = await this.serviceUnderTest.ProcessDetectorsAsync(DefaultArgs, this.detectorsToUse, new DetectorRestrictions()); @@ -154,10 +154,10 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_AdditionalTelemetryDetailsAreReturnedAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, - }; + ]; var records = await TelemetryHelper.ExecuteWhileCapturingTelemetryAsync(async () => { @@ -174,12 +174,12 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_ExperimentalDetectorsDoNotReturnComponentsAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, this.experimentalFileComponentDetectorMock.Object, - }; + ]; DetectorProcessingResult results = null; var records = await TelemetryHelper.ExecuteWhileCapturingTelemetryAsync(async () => @@ -199,8 +199,11 @@ public class DetectorProcessingServiceTests // We should have all components except the ones that came from our experimental detector this.GetDiscoveredComponentsFromDetectorProcessingResult(results).Should().HaveCount(records.Sum(x => x.DetectedComponentCount ?? 0) - experimentalDetectorRecord.DetectedComponentCount ?? 0); - this.GetDiscoveredComponentsFromDetectorProcessingResult(results).All(x => (x.Component as NuGetComponent)?.Name != experimentalComponent.Name) - .Should().BeTrue("Experimental component should not be in component list"); + this.GetDiscoveredComponentsFromDetectorProcessingResult(results) + .Select(x => x.Component as NuGetComponent) + .Where(x => x != null) + .Should() + .OnlyContain(x => x.Name != experimentalComponent.Name, "Experimental component should not be in component list"); results.ResultCode.Should().Be(ProcessingResultCode.Success); this.firstFileComponentDetectorMock.Verify(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == DefaultArgs.SourceDirectory), It.IsAny())); @@ -211,18 +214,18 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_ExperimentalDetectorsDoNormalStuffIfExplicitlyEnabledAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, this.experimentalFileComponentDetectorMock.Object, - }; + ]; var experimentalDetectorId = this.experimentalFileComponentDetectorMock.Object.Id; DetectorProcessingResult results = null; var records = await TelemetryHelper.ExecuteWhileCapturingTelemetryAsync(async () => { - results = await this.serviceUnderTest.ProcessDetectorsAsync(DefaultArgs, this.detectorsToUse, new DetectorRestrictions { ExplicitlyEnabledDetectorIds = new[] { experimentalDetectorId } }); + results = await this.serviceUnderTest.ProcessDetectorsAsync(DefaultArgs, this.detectorsToUse, new DetectorRestrictions { ExplicitlyEnabledDetectorIds = [experimentalDetectorId] }); }); // We should have all components except the ones that came from our experimental detector @@ -239,11 +242,11 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_ExperimentalDetectorsThrowingDoesntKillDetectionAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, this.experimentalFileComponentDetectorMock.Object, - }; + ]; this.experimentalFileComponentDetectorMock.Setup(x => x.ExecuteDetectorAsync(It.Is(request => request.SourceDirectory == DefaultArgs.SourceDirectory), It.IsAny())) .Throws(new InvalidOperationException("Simulated experimental failure")); @@ -272,14 +275,15 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, - }; + ]; if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - Assert.Inconclusive("Test is platform specific and fails on non-windows"); + // Test is platform specific and fails on non-windows + return; } var d1 = new DirectoryInfo(Path.Combine(Environment.CurrentDirectory, "shouldExclude", "stuff")); @@ -302,7 +306,7 @@ public class DetectorProcessingServiceTests { SourceDirectory = DefaultSourceDirectory, DetectorArgs = new Dictionary(), - DirectoryExclusionList = new[] { Path.Combine("**", "SomeSource", "**"), Path.Combine("**", "shouldExclude", "**") }, + DirectoryExclusionList = [Path.Combine("**", "SomeSource", "**"), Path.Combine("**", "shouldExclude", "**")], }; // Now exercise the exclusion code @@ -336,7 +340,8 @@ public class DetectorProcessingServiceTests if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - Assert.Inconclusive("Test is inconsistent for non-windows platforms"); + // Test is inconsistent for non-windows platforms + return; } // 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. @@ -347,32 +352,32 @@ public class DetectorProcessingServiceTests 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\**" }; + args.DirectoryExclusionList = [@"**\source\**"]; var exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); exclusionPredicate(dn, dp).Should().BeFalse(); // 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\**" }; + args.DirectoryExclusionList = [@"**\Source\**"]; exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: false); exclusionPredicate(dn, dp).Should().BeTrue(); // Exclusion predicate is not case sensitive and allow windows path, the exclusion list follow the windows path, should exclude - args.DirectoryExclusionList = new[] { @"**\sOuRce\**" }; + args.DirectoryExclusionList = [@"**\sOuRce\**"]; exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); exclusionPredicate(dn, dp).Should().BeTrue(); // 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\**" }; + args.DirectoryExclusionList = [@"**\Source\**"]; exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: false, ignoreCase: true); exclusionPredicate(dn, dp).Should().BeFalse(); // Exclusion predicate support windows path and the exclusion list define the path as a windows path, should exclude - args.DirectoryExclusionList = new[] { @"**\Source\**" }; + args.DirectoryExclusionList = [@"**\Source\**"]; exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); exclusionPredicate(dn, dp).Should().BeTrue(); // Exclusion predicate support windows path and the exclusion list does not define a windows path, should exclude - args.DirectoryExclusionList = new[] { @"**/Source/**", @"**/Source\**" }; + args.DirectoryExclusionList = [@"**/Source/**", @"**/Source\**"]; exclusionPredicate = this.serviceUnderTest.GenerateDirectoryExclusionPredicate(@"C:\somefake\dir", args.DirectoryExclusionList, args.DirectoryExclusionListObsolete, allowWindowsPaths: true, ignoreCase: true); exclusionPredicate(dn, dp).Should().BeTrue(); } @@ -380,10 +385,10 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_DirectoryExclusionPredicateWorksAsExpectedForObsoleteAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, - }; + ]; var sourceDirectory = DefaultSourceDirectory; var args = DefaultArgs; @@ -415,10 +420,10 @@ public class DetectorProcessingServiceTests capturedRequest.DirectoryExclusionPredicate(d1.Name.AsSpan(), d1.Parent.FullName.AsSpan()).Should().BeFalse(); // Now exercise the exclusion code - args.DirectoryExclusionListObsolete = new[] { Path.Combine("Child"), Path.Combine("..", "bin") }; + args.DirectoryExclusionListObsolete = [Path.Combine("Child"), Path.Combine("..", "bin")]; await this.serviceUnderTest.ProcessDetectorsAsync( args, - new[] { this.firstFileComponentDetectorMock.Object }, + [this.firstFileComponentDetectorMock.Object], new DetectorRestrictions()); this.directoryWalkerFactory.Reset(); @@ -436,10 +441,10 @@ public class DetectorProcessingServiceTests { var args = DefaultArgs; - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, - }; + ]; var records = await TelemetryHelper.ExecuteWhileCapturingTelemetryAsync(async () => { @@ -463,13 +468,13 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_ExecutesMixedCommandAndFileDetectorsAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, this.firstCommandComponentDetectorMock.Object, this.secondCommandComponentDetectorMock.Object, - }; + ]; DetectorProcessingResult results = null; var records = await TelemetryHelper.ExecuteWhileCapturingTelemetryAsync(async () => @@ -495,10 +500,10 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_FinishesExperimentsAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, - }; + ]; await this.serviceUnderTest.ProcessDetectorsAsync(DefaultArgs, this.detectorsToUse, new DetectorRestrictions()); @@ -508,10 +513,10 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_RecordsDetectorRunsAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, - }; + ]; var firstComponents = new[] { this.componentDictionary[this.firstFileComponentDetectorMock.Object.Id] }; var secondComponents = new[] { this.componentDictionary[this.secondFileComponentDetectorMock.Object.Id] }; @@ -540,10 +545,10 @@ public class DetectorProcessingServiceTests [TestMethod] public async Task ProcessDetectorsAsync_InitializesExperimentsAsync() { - this.detectorsToUse = new[] - { + this.detectorsToUse = + [ this.firstFileComponentDetectorMock.Object, this.secondFileComponentDetectorMock.Object, - }; + ]; await this.serviceUnderTest.ProcessDetectorsAsync(DefaultArgs, this.detectorsToUse, new DetectorRestrictions()); diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs index d692988a..4a535550 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/Services/DetectorRestrictionServiceTests.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Tests.Services; +namespace Microsoft.ComponentDetection.Orchestrator.Tests.Services; using System; using System.Linq; @@ -34,14 +34,15 @@ public class DetectorRestrictionServiceTests this.retiredNpmDetector = this.GenerateDetector("MSLicenseDevNpm"); this.newNpmDetector = this.GenerateDetector("NpmWithRoots"); - this.detectors = new[] - { - this.firstDetectorMock.Object, this.secondDetectorMock.Object, + this.detectors = + [ + this.firstDetectorMock.Object, + this.secondDetectorMock.Object, this.thirdDetectorMock.Object, this.retiredNpmDetector.Object, this.newNpmDetector.Object, - }; + ]; this.serviceUnderTest = new DetectorRestrictionService(this.logger.Object); } @@ -61,7 +62,7 @@ public class DetectorRestrictionServiceTests var r = new DetectorRestrictions(); var detectorMock = this.GenerateDetector("defaultOffDetector"); var defaultOffDetectorMock = detectorMock.As(); - this.detectors = this.detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); + this.detectors = this.detectors.Union([defaultOffDetectorMock.Object]).ToArray(); var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().NotContain(defaultOffDetectorMock.Object); @@ -73,8 +74,8 @@ public class DetectorRestrictionServiceTests var r = new DetectorRestrictions(); var detectorMock = this.GenerateDetector("defaultOffDetector"); var defaultOffDetectorMock = detectorMock.As(); - this.detectors = this.detectors.Union(new[] { defaultOffDetectorMock.Object as IComponentDetector }).ToArray(); - r.ExplicitlyEnabledDetectorIds = new[] { "defaultOffDetector" }; + this.detectors = this.detectors.Union([defaultOffDetectorMock.Object]).ToArray(); + r.ExplicitlyEnabledDetectorIds = ["defaultOffDetector"]; var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().Contain(defaultOffDetectorMock.Object); @@ -85,14 +86,14 @@ public class DetectorRestrictionServiceTests { var r = new DetectorRestrictions { - AllowedDetectorIds = new[] { "FirstDetector", "SecondDetector" }, + AllowedDetectorIds = ["FirstDetector", "SecondDetector"], }; var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().Contain(this.firstDetectorMock.Object).And.Contain(this.secondDetectorMock.Object) .And.NotContain(this.thirdDetectorMock.Object); - r.AllowedDetectorIds = new[] { "NotARealDetector" }; + r.AllowedDetectorIds = ["NotARealDetector"]; Action shouldThrow = () => this.serviceUnderTest.ApplyRestrictions(r, this.detectors); shouldThrow.Should().Throw(); } @@ -102,18 +103,18 @@ public class DetectorRestrictionServiceTests { var r = new DetectorRestrictions { - AllowedDetectorIds = new[] { "MSLicenseDevNpm" }, + AllowedDetectorIds = ["MSLicenseDevNpm"], }; var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().Contain(this.newNpmDetector.Object); - r.AllowedDetectorIds = new[] { "mslicensenpm" }; + r.AllowedDetectorIds = ["mslicensenpm"]; restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().Contain(this.newNpmDetector.Object); - r.AllowedDetectorIds = new[] { "mslicensenpm", "NpmWithRoots" }; + r.AllowedDetectorIds = ["mslicensenpm", "NpmWithRoots"]; restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().OnlyContain(item => item == this.newNpmDetector.Object); @@ -124,21 +125,21 @@ public class DetectorRestrictionServiceTests { var r = new DetectorRestrictions { - AllowedDetectorCategories = new[] { "FirstDetectorCategory", "ThirdDetectorCategory" }, + AllowedDetectorCategories = ["FirstDetectorCategory", "ThirdDetectorCategory"], }; var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().Contain(this.firstDetectorMock.Object).And.Contain(this.thirdDetectorMock.Object) .And.NotContain(this.secondDetectorMock.Object); - r.AllowedDetectorCategories = new[] { "AllCategory" }; + r.AllowedDetectorCategories = ["AllCategory"]; restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, this.detectors); restrictedDetectors .Should().Contain(this.firstDetectorMock.Object) .And.Contain(this.thirdDetectorMock.Object) .And.Contain(this.secondDetectorMock.Object); - r.AllowedDetectorCategories = new[] { "NoCategory" }; + r.AllowedDetectorCategories = ["NoCategory"]; Action shouldThrow = () => this.serviceUnderTest.ApplyRestrictions(r, this.detectors); shouldThrow.Should().Throw(); } @@ -148,14 +149,14 @@ public class DetectorRestrictionServiceTests { var detectors = new[] { - this.GenerateDetector("1", new[] { "Cat1" }).Object, - this.GenerateDetector("2", new[] { "Cat2" }).Object, - this.GenerateDetector("3", new[] { nameof(DetectorClass.All) }).Object, + this.GenerateDetector("1", ["Cat1"]).Object, + this.GenerateDetector("2", ["Cat2"]).Object, + this.GenerateDetector("3", [nameof(DetectorClass.All)]).Object, }; var r = new DetectorRestrictions { - AllowedDetectorCategories = new[] { "ACategoryWhichDoesntMatch" }, + AllowedDetectorCategories = ["ACategoryWhichDoesntMatch"], }; var restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, detectors); restrictedDetectors @@ -163,7 +164,7 @@ public class DetectorRestrictionServiceTests .And.NotContain(detectors[0]) .And.NotContain(detectors[1]); - r.AllowedDetectorCategories = new[] { "Cat1" }; + r.AllowedDetectorCategories = ["Cat1"]; restrictedDetectors = this.serviceUnderTest.ApplyRestrictions(r, detectors); restrictedDetectors .Should().Contain(detectors[0]) @@ -182,7 +183,7 @@ public class DetectorRestrictionServiceTests { var mockDetector = new Mock(); mockDetector.SetupGet(x => x.Id).Returns($"{detectorName}"); - categories ??= new[] { $"{detectorName}Category", "AllCategory" }; + categories ??= [$"{detectorName}Category", "AllCategory"]; mockDetector.SetupGet(x => x.Categories).Returns(categories); return mockDetector; diff --git a/test/Microsoft.ComponentDetection.Orchestrator.Tests/TelemetryHelper.cs b/test/Microsoft.ComponentDetection.Orchestrator.Tests/TelemetryHelper.cs index 0ea2d1c6..25a474db 100644 --- a/test/Microsoft.ComponentDetection.Orchestrator.Tests/TelemetryHelper.cs +++ b/test/Microsoft.ComponentDetection.Orchestrator.Tests/TelemetryHelper.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.Orchestrator.Tests; +namespace Microsoft.ComponentDetection.Orchestrator.Tests; using System; using System.Collections.Concurrent; @@ -24,7 +24,7 @@ public static class TelemetryHelper records.Add(asT); } }); - TelemetryRelay.Instance.Init(new[] { telemetryServiceMock.Object }); + TelemetryRelay.Instance.Init([telemetryServiceMock.Object]); try { diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/Attributes/SkipTestIfNotWindowsAttribute.cs b/test/Microsoft.ComponentDetection.TestsUtilities/Attributes/SkipTestIfNotWindowsAttribute.cs index a9ffa486..26289d9b 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/Attributes/SkipTestIfNotWindowsAttribute.cs +++ b/test/Microsoft.ComponentDetection.TestsUtilities/Attributes/SkipTestIfNotWindowsAttribute.cs @@ -9,14 +9,14 @@ public sealed class SkipTestIfNotWindowsAttribute : TestMethodAttribute { if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - return new[] - { + return + [ new TestResult { Outcome = UnitTestOutcome.Inconclusive, TestFailureException = new AssertInconclusiveException($"Skipped on {RuntimeInformation.OSDescription}."), }, - }; + ]; } return base.Execute(testMethod); diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/Attributes/SkipTestOnWindowsAttribute.cs b/test/Microsoft.ComponentDetection.TestsUtilities/Attributes/SkipTestOnWindowsAttribute.cs index 0604b781..5a335a93 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/Attributes/SkipTestOnWindowsAttribute.cs +++ b/test/Microsoft.ComponentDetection.TestsUtilities/Attributes/SkipTestOnWindowsAttribute.cs @@ -9,14 +9,14 @@ public sealed class SkipTestOnWindowsAttribute : TestMethodAttribute { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { - return new[] - { + return + [ new TestResult { Outcome = UnitTestOutcome.Inconclusive, TestFailureException = new AssertInconclusiveException("Skipped on Windows."), }, - }; + ]; } return base.Execute(testMethod); diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtilityBuilder.cs b/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtilityBuilder.cs index 719f5dac..bb061d5e 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtilityBuilder.cs +++ b/test/Microsoft.ComponentDetection.TestsUtilities/DetectorTestUtilityBuilder.cs @@ -18,7 +18,7 @@ public class DetectorTestUtilityBuilder where T : FileComponentDetector { private readonly List<(string Name, Stream Contents, string Location, IEnumerable SearchPatterns)> - filesToAdd = new(); + filesToAdd = []; private readonly Mock mockComponentStreamEnumerableFactory; private readonly Mock mockObservableDirectoryWalkerFactory; @@ -134,7 +134,7 @@ public class DetectorTestUtilityBuilder private void InitializeFileMocks() { - if (!this.filesToAdd.Any()) + if (this.filesToAdd.Count == 0) { this.mockObservableDirectoryWalkerFactory.Setup(x => x.GetFilteredComponentStreamObservable( @@ -144,7 +144,7 @@ public class DetectorTestUtilityBuilder .Returns(Enumerable.Empty().ToObservable()); } - if (!this.filesToAdd.Any()) + if (this.filesToAdd.Count == 0) { this.mockComponentStreamEnumerableFactory.Setup(x => x.GetComponentStreams( diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/EnumerableStringComparer.cs b/test/Microsoft.ComponentDetection.TestsUtilities/EnumerableStringComparer.cs index 3f0849ef..69b93ec4 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/EnumerableStringComparer.cs +++ b/test/Microsoft.ComponentDetection.TestsUtilities/EnumerableStringComparer.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.TestsUtilities; +namespace Microsoft.ComponentDetection.TestsUtilities; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; diff --git a/test/Microsoft.ComponentDetection.TestsUtilities/ExtensionMethods.cs b/test/Microsoft.ComponentDetection.TestsUtilities/ExtensionMethods.cs index 932b8bcd..51265f10 100644 --- a/test/Microsoft.ComponentDetection.TestsUtilities/ExtensionMethods.cs +++ b/test/Microsoft.ComponentDetection.TestsUtilities/ExtensionMethods.cs @@ -1,4 +1,4 @@ -namespace Microsoft.ComponentDetection.TestsUtilities; +namespace Microsoft.ComponentDetection.TestsUtilities; using System; using System.Collections.Generic; @@ -38,7 +38,7 @@ public static class ExtensionMethods var formatter = invocation.Arguments[4]; var invokeMethod = formatter.GetType().GetMethod("Invoke"); - var logMessage = (string)invokeMethod?.Invoke(formatter, new[] { state, exception }); + var logMessage = (string)invokeMethod?.Invoke(formatter, [state, exception]); logOutput.Add(logMessage); }));