diff --git a/src/BenchmarkDotNet/Analysers/BaselineCustomAnalyzer.cs b/src/BenchmarkDotNet/Analysers/BaselineCustomAnalyzer.cs index 51663e4085..300d520f15 100644 --- a/src/BenchmarkDotNet/Analysers/BaselineCustomAnalyzer.cs +++ b/src/BenchmarkDotNet/Analysers/BaselineCustomAnalyzer.cs @@ -25,7 +25,7 @@ protected override IEnumerable AnalyseSummary(Summary summary) foreach (var benchmarkCase in summary.BenchmarksCases) { - string logicalGroupKey = summary.GetLogicalGroupKey(benchmarkCase); + string? logicalGroupKey = summary.GetLogicalGroupKey(benchmarkCase); var baseline = summary.GetBaseline(logicalGroupKey); if (BaselineCustomColumn.ResultsAreInvalid(summary, benchmarkCase, baseline) == false) continue; diff --git a/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs b/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs index c5c54f8c91..e9f14a7625 100644 --- a/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs +++ b/src/BenchmarkDotNet/Analysers/OutliersAnalyser.cs @@ -53,7 +53,7 @@ string Format(int n, string verb) return $"{n} {words} {verb}"; } - var rangeMessages = new List { GetRangeMessage(lowerOutliers, cultureInfo), GetRangeMessage(upperOutliers, cultureInfo) }; + var rangeMessages = new List { GetRangeMessage(lowerOutliers, cultureInfo), GetRangeMessage(upperOutliers, cultureInfo) }; rangeMessages.RemoveAll(string.IsNullOrEmpty); string rangeMessage = rangeMessages.Any() ? " (" + string.Join(", ", rangeMessages) + ")" diff --git a/src/BenchmarkDotNet/Columns/BaselineCustomColumn.cs b/src/BenchmarkDotNet/Columns/BaselineCustomColumn.cs index b808d988d8..4dabe8e502 100644 --- a/src/BenchmarkDotNet/Columns/BaselineCustomColumn.cs +++ b/src/BenchmarkDotNet/Columns/BaselineCustomColumn.cs @@ -43,7 +43,7 @@ public abstract string GetValue(Summary summary, BenchmarkCase benchmarkCase, St public override string ToString() => ColumnName; public bool IsDefault(Summary summary, BenchmarkCase benchmarkCase) => false; - internal static bool ResultsAreInvalid(Summary summary, BenchmarkCase benchmarkCase, BenchmarkCase baseline) + internal static bool ResultsAreInvalid(Summary summary, BenchmarkCase benchmarkCase, BenchmarkCase? baseline) { return baseline == null || summary[baseline] == null || diff --git a/src/BenchmarkDotNet/Columns/TagColumn.cs b/src/BenchmarkDotNet/Columns/TagColumn.cs index e4300f037c..425b4d2ad8 100644 --- a/src/BenchmarkDotNet/Columns/TagColumn.cs +++ b/src/BenchmarkDotNet/Columns/TagColumn.cs @@ -19,7 +19,7 @@ public TagColumn(string columnName, Func getTag) } public bool IsDefault(Summary summary, BenchmarkCase benchmarkCase) => false; - public string GetValue(Summary summary, BenchmarkCase benchmarkCase) => getTag(benchmarkCase.Descriptor.WorkloadMethod.Name); + public string GetValue(Summary summary, BenchmarkCase benchmarkCase) => getTag(benchmarkCase.Descriptor?.WorkloadMethod?.Name ?? ""); public bool IsAvailable(Summary summary) => true; public bool AlwaysShow => true; diff --git a/src/BenchmarkDotNet/Configs/ImmutableConfig.cs b/src/BenchmarkDotNet/Configs/ImmutableConfig.cs index 1216ef3b16..b6e03126fd 100644 --- a/src/BenchmarkDotNet/Configs/ImmutableConfig.cs +++ b/src/BenchmarkDotNet/Configs/ImmutableConfig.cs @@ -119,7 +119,7 @@ internal ImmutableConfig( public bool HasExtraStatsDiagnoser() => HasMemoryDiagnoser() || HasThreadingDiagnoser() || HasExceptionDiagnoser(); - public IDiagnoser GetCompositeDiagnoser(BenchmarkCase benchmarkCase, RunMode runMode) + public IDiagnoser? GetCompositeDiagnoser(BenchmarkCase benchmarkCase, RunMode runMode) { var diagnosersForGivenMode = diagnosers.Where(diagnoser => diagnoser.GetRunMode(benchmarkCase) == runMode).ToImmutableHashSet(); diff --git a/src/BenchmarkDotNet/Diagnosers/DiagnoserActionParameters.cs b/src/BenchmarkDotNet/Diagnosers/DiagnoserActionParameters.cs index a403e170f5..c7d957b385 100644 --- a/src/BenchmarkDotNet/Diagnosers/DiagnoserActionParameters.cs +++ b/src/BenchmarkDotNet/Diagnosers/DiagnoserActionParameters.cs @@ -6,7 +6,7 @@ namespace BenchmarkDotNet.Diagnosers { public class DiagnoserActionParameters { - public DiagnoserActionParameters(Process process, BenchmarkCase benchmarkCase, BenchmarkId benchmarkId) + public DiagnoserActionParameters(Process? process, BenchmarkCase benchmarkCase, BenchmarkId benchmarkId) { Process = process; BenchmarkCase = benchmarkCase; diff --git a/src/BenchmarkDotNet/Exporters/Json/SimpleJson.cs b/src/BenchmarkDotNet/Exporters/Json/SimpleJson.cs index 5aa3ebe1c4..5670d64588 100644 --- a/src/BenchmarkDotNet/Exporters/Json/SimpleJson.cs +++ b/src/BenchmarkDotNet/Exporters/Json/SimpleJson.cs @@ -1,3 +1,4 @@ +#nullable disable // ReSharper disable All //----------------------------------------------------------------------- // diff --git a/src/BenchmarkDotNet/Extensions/CommonExtensions.cs b/src/BenchmarkDotNet/Extensions/CommonExtensions.cs index a753787c53..65d0f7e3fd 100644 --- a/src/BenchmarkDotNet/Extensions/CommonExtensions.cs +++ b/src/BenchmarkDotNet/Extensions/CommonExtensions.cs @@ -32,10 +32,12 @@ public static string GetColumnTitle(this IColumn column, SummaryStyle style) } } - public static bool IsNullOrEmpty(this IReadOnlyCollection value) => value == null || value.Count == 0; + public static bool IsNullOrEmpty(this IReadOnlyCollection? value) => value == null || value.Count == 0; public static bool IsEmpty(this IReadOnlyCollection value) => value.Count == 0; public static bool IsEmpty(this IEnumerable value) => !value.Any(); + public static IEnumerable WhereNotNull(this IEnumerable values) => values.Where(value => value != null).Cast(); + public static void AddRange(this HashSet hashSet, IEnumerable collection) { foreach (var item in collection) @@ -43,7 +45,7 @@ public static void AddRange(this HashSet hashSet, IEnumerable collectio } #if NETSTANDARD2_0 - public static TValue GetValueOrDefault(this IDictionary dictionary, TKey key) + public static TValue? GetValueOrDefault(this IDictionary dictionary, TKey key) => dictionary.TryGetValue(key, out var value) ? value : default; #endif @@ -97,7 +99,9 @@ internal static string DeleteFileIfExists(this string filePath) internal static string EnsureFolderExists(this string filePath) { - string directoryPath = Path.GetDirectoryName(filePath); + string? directoryPath = Path.GetDirectoryName(filePath); + if (directoryPath == null) + throw new ArgumentException($"Can't get directory path from '{filePath}'"); if (!Directory.Exists(directoryPath)) Directory.CreateDirectory(directoryPath); @@ -105,7 +109,7 @@ internal static string EnsureFolderExists(this string filePath) return filePath; } - internal static bool IsNotNullButDoesNotExist(this FileSystemInfo fileInfo) + internal static bool IsNotNullButDoesNotExist(this FileSystemInfo? fileInfo) => fileInfo != null && !fileInfo.Exists; } } \ No newline at end of file diff --git a/src/BenchmarkDotNet/Helpers/Assertion.cs b/src/BenchmarkDotNet/Helpers/Assertion.cs new file mode 100644 index 0000000000..44e8b36e46 --- /dev/null +++ b/src/BenchmarkDotNet/Helpers/Assertion.cs @@ -0,0 +1,14 @@ +using System; +using JetBrains.Annotations; + +namespace BenchmarkDotNet.Helpers; + +internal static class Assertion +{ + [AssertionMethod] + public static void NotNull(string name, object? value) + { + if (value == null) + throw new ArgumentNullException(name, $"{name} can't be null"); + } +} \ No newline at end of file diff --git a/src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs b/src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs index a16e15f653..0921b7d1d6 100644 --- a/src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs +++ b/src/BenchmarkDotNet/Helpers/DirtyAssemblyResolveHelper.cs @@ -28,7 +28,7 @@ internal class DirtyAssemblyResolveHelper : IDisposable /// "the handler is invoked whenever the runtime fails to bind to an assembly by name." /// /// not null when we find it manually, null when can't help - private Assembly HelpTheFrameworkToResolveTheAssembly(object sender, ResolveEventArgs args) + private Assembly? HelpTheFrameworkToResolveTheAssembly(object sender, ResolveEventArgs args) { var fullName = new AssemblyName(args.Name); string simpleName = fullName.Name; diff --git a/src/BenchmarkDotNet/Reports/Summary.cs b/src/BenchmarkDotNet/Reports/Summary.cs index 680ded2d5b..3822ed8acb 100644 --- a/src/BenchmarkDotNet/Reports/Summary.cs +++ b/src/BenchmarkDotNet/Reports/Summary.cs @@ -75,7 +75,7 @@ public Summary( /// /// Returns a report for the given benchmark or null if there is no a corresponded report. /// - public BenchmarkReport this[BenchmarkCase benchmarkCase] => ReportMap.GetValueOrDefault(benchmarkCase); + public BenchmarkReport? this[BenchmarkCase benchmarkCase] => ReportMap.GetValueOrDefault(benchmarkCase); public bool HasCriticalValidationErrors => ValidationErrors.Any(validationError => validationError.IsCritical); @@ -108,7 +108,7 @@ internal static string BuildAllRuntimes(HostEnvironmentInfo hostEnvironmentInfo, foreach (var benchmarkReport in reports) { - string runtime = benchmarkReport.GetRuntimeInfo(); + string? runtime = benchmarkReport.GetRuntimeInfo(); if (runtime != null) { string jobId = benchmarkReport.BenchmarkCase.Job.ResolvedId; @@ -135,7 +135,7 @@ internal static string BuildAllRuntimes(HostEnvironmentInfo hostEnvironmentInfo, public bool IsBaseline(BenchmarkCase benchmarkCase) => BaseliningStrategy.IsBaseline(benchmarkCase); - public BenchmarkCase? GetBaseline(string logicalGroupKey) + public BenchmarkCase? GetBaseline(string? logicalGroupKey) => BenchmarksCases .Where(b => GetLogicalGroupKey(b) == logicalGroupKey) .FirstOrDefault(IsBaseline); @@ -158,7 +158,11 @@ private static IOrderer GetConfiguredOrdererOrDefaultOne(IEnumerable benchmarkCases) => benchmarkCases .Where(benchmark => benchmark.Config.SummaryStyle != SummaryStyle.Default - && benchmark.Config.SummaryStyle != null) // Paranoid +#nullable disable + // ReSharper disable once ConditionIsAlwaysTrueOrFalseAccordingToNullableAPIContract ConditionIsAlwaysTrueOrFalse + // TODO: remove this check once the nullability migration is finished + && benchmark.Config.SummaryStyle != null) // Paranoid +#nullable enable .Select(benchmark => benchmark.Config.SummaryStyle) .Distinct() .SingleOrDefault() diff --git a/src/BenchmarkDotNet/Reports/SummaryStyle.cs b/src/BenchmarkDotNet/Reports/SummaryStyle.cs index 23451442df..ebe727ba81 100644 --- a/src/BenchmarkDotNet/Reports/SummaryStyle.cs +++ b/src/BenchmarkDotNet/Reports/SummaryStyle.cs @@ -20,9 +20,9 @@ public class SummaryStyle : IEquatable public bool PrintUnitsInContent { get; } public bool PrintZeroValuesInContent { get; } public int MaxParameterColumnWidth { get; } - public SizeUnit SizeUnit { get; } + public SizeUnit? SizeUnit { get; } internal SizeUnit CodeSizeUnit { get; } - public TimeUnit TimeUnit { get; } + public TimeUnit? TimeUnit { get; } public CultureInfo CultureInfo { get; } public RatioStyle RatioStyle { get; } @@ -30,7 +30,7 @@ public class SummaryStyle : IEquatable public TextJustification TextColumnJustification { get; } public TextJustification NumericColumnJustification { get; } - public SummaryStyle(CultureInfo? cultureInfo, bool printUnitsInHeader, SizeUnit sizeUnit, TimeUnit timeUnit, bool printUnitsInContent = true, + public SummaryStyle(CultureInfo? cultureInfo, bool printUnitsInHeader, SizeUnit? sizeUnit, TimeUnit? timeUnit, bool printUnitsInContent = true, bool printZeroValuesInContent = false, int maxParameterColumnWidth = DefaultMaxParameterColumnWidth, RatioStyle ratioStyle = RatioStyle.Value, TextJustification textColumnJustification = TextJustification.Left, TextJustification numericColumnJustification = TextJustification.Right) { diff --git a/src/BenchmarkDotNet/Running/Descriptor.cs b/src/BenchmarkDotNet/Running/Descriptor.cs index a38b1a13d9..4ff74fced7 100644 --- a/src/BenchmarkDotNet/Running/Descriptor.cs +++ b/src/BenchmarkDotNet/Running/Descriptor.cs @@ -11,10 +11,10 @@ public class Descriptor : IEquatable { public Type Type { get; } public MethodInfo WorkloadMethod { get; } - public MethodInfo GlobalSetupMethod { get; } - public MethodInfo GlobalCleanupMethod { get; } - public MethodInfo IterationSetupMethod { get; } - public MethodInfo IterationCleanupMethod { get; } + public MethodInfo? GlobalSetupMethod { get; } + public MethodInfo? GlobalCleanupMethod { get; } + public MethodInfo? IterationSetupMethod { get; } + public MethodInfo? IterationCleanupMethod { get; } public string AdditionalLogic { get; } public int OperationsPerInvoke { get; } public string WorkloadMethodDisplayInfo { get; } @@ -22,10 +22,10 @@ public class Descriptor : IEquatable public bool Baseline { get; } public string[] Categories { get; } - internal string TypeInfo => Type?.GetDisplayName() ?? "Untitled"; - private string MethodFolderInfo => WorkloadMethod?.Name ?? "Untitled"; + internal string TypeInfo => Type.GetDisplayName(); + private string MethodFolderInfo => WorkloadMethod.Name; - public string FolderInfo => (Type != null ? FolderNameHelper.ToFolderName(Type) : "Untitled") + "_" + MethodFolderInfo; + public string FolderInfo => $"{FolderNameHelper.ToFolderName(Type)}_{MethodFolderInfo}"; public string DisplayInfo => TypeInfo + "." + WorkloadMethodDisplayInfo; public Descriptor( @@ -42,6 +42,9 @@ public Descriptor( int operationsPerInvoke = 1, int methodIndex = 0) { + Assertion.NotNull(nameof(type), type); + Assertion.NotNull(nameof(workloadMethod), workloadMethod); + Type = type; WorkloadMethod = workloadMethod; GlobalSetupMethod = globalSetupMethod; @@ -58,9 +61,9 @@ public Descriptor( public override string ToString() => DisplayInfo; - private static string FormatDescription(string? description) + private static string? FormatDescription(string? description) { - var specialSymbols = new[] { ' ', '\'', '[', ']' }; + char[] specialSymbols = { ' ', '\'', '[', ']' }; return description != null && specialSymbols.Any(description.Contains) ? "'" + description + "'" : description; @@ -70,9 +73,9 @@ private static string FormatDescription(string? description) public string GetFilterName() => $"{Type.GetCorrectCSharpTypeName(includeGenericArgumentsNamespace: false)}.{WorkloadMethod.Name}"; - public bool Equals(Descriptor other) => GetFilterName().Equals(other.GetFilterName()); + public bool Equals(Descriptor? other) => GetFilterName().Equals(other?.GetFilterName()); - public override bool Equals(object obj) => obj is Descriptor && Equals((Descriptor)obj); + public override bool Equals(object? obj) => obj is Descriptor descriptor && Equals(descriptor); public override int GetHashCode() => GetFilterName().GetHashCode(); } diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs index 3532fa1e07..4348685369 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliCommandExecutor.cs @@ -54,7 +54,7 @@ public static DotNetCliCommandResult Execute(DotNetCliCommand parameters) } } - internal static string GetDotNetSdkVersion() + internal static string? GetDotNetSdkVersion() { using (var process = new Process { StartInfo = BuildStartInfo(customDotNetCliPath: null, workingDirectory: string.Empty, arguments: "--version") }) using (new ConsoleExitHandler(process, NullLogger.Instance)) @@ -98,7 +98,7 @@ internal static void LogEnvVars(DotNetCliCommand command) } } - internal static ProcessStartInfo BuildStartInfo(string customDotNetCliPath, string workingDirectory, string arguments, + internal static ProcessStartInfo BuildStartInfo(string? customDotNetCliPath, string workingDirectory, string arguments, IReadOnlyList? environmentVariables = null, bool redirectStandardInput = false, bool redirectStandardError = true, bool redirectStandardOutput = true) { const string dotnetMultiLevelLookupEnvVarName = "DOTNET_MULTILEVEL_LOOKUP"; diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs index 960558d5c0..83158e0b1e 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/DotNetCliPublisher.cs @@ -8,18 +8,21 @@ namespace BenchmarkDotNet.Toolchains.DotNetCli { public class DotNetCliPublisher : IBuilder { - public DotNetCliPublisher(string? customDotNetCliPath = null, string? extraArguments = null, IReadOnlyList environmentVariables = null) + public DotNetCliPublisher( + string? customDotNetCliPath = null, + string? extraArguments = null, + IReadOnlyList? environmentVariables = null) { CustomDotNetCliPath = customDotNetCliPath; ExtraArguments = extraArguments; EnvironmentVariables = environmentVariables; } - private string CustomDotNetCliPath { get; } + private string? CustomDotNetCliPath { get; } - private string ExtraArguments { get; } + private string? ExtraArguments { get; } - private IReadOnlyList EnvironmentVariables { get; } + private IReadOnlyList? EnvironmentVariables { get; } public BuildResult Build(GenerateResult generateResult, BuildPartition buildPartition, ILogger logger) => new DotNetCliCommand( diff --git a/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs b/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs index 664d1333f1..6f48698cb9 100644 --- a/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs +++ b/src/BenchmarkDotNet/Toolchains/DotNetCli/NetCoreAppSettings.cs @@ -43,7 +43,7 @@ public class NetCoreAppSettings [PublicAPI] public NetCoreAppSettings( string targetFrameworkMoniker, - string runtimeFrameworkVersion, + string? runtimeFrameworkVersion, string name, string? customDotNetCliPath = null, string? packagesPath = null, @@ -68,29 +68,29 @@ public NetCoreAppSettings( /// public string TargetFrameworkMoniker { get; } - public string RuntimeFrameworkVersion { get; } + public string? RuntimeFrameworkVersion { get; } /// /// display name used for showing the results /// public string Name { get; } - public string CustomDotNetCliPath { get; } + public string? CustomDotNetCliPath { get; } /// /// The directory to restore packages to. /// - public string PackagesPath { get; } + public string? PackagesPath { get; } /// /// Path to a custom runtime pack. /// - public string CustomRuntimePack { get; } + public string? CustomRuntimePack { get; } /// /// Path to the Mono AOT Compiler /// - public string AOTCompilerPath { get; } + public string? AOTCompilerPath { get; } /// /// Mono AOT Compiler mode, either 'mini' or 'llvm' diff --git a/src/BenchmarkDotNet/Validators/ParamsValidator.cs b/src/BenchmarkDotNet/Validators/ParamsValidator.cs index 630811b62b..5a503148d5 100644 --- a/src/BenchmarkDotNet/Validators/ParamsValidator.cs +++ b/src/BenchmarkDotNet/Validators/ParamsValidator.cs @@ -24,19 +24,19 @@ private IEnumerable Validate(Type type) BindingFlags.FlattenHierarchy; foreach (var memberInfo in type.GetMembers(reflectionFlags)) { - var attributes = new Attribute[] + var attributes = new Attribute?[] { memberInfo.ResolveAttribute(), memberInfo.ResolveAttribute(), memberInfo.ResolveAttribute() } - .Where(attribute => attribute != null) + .WhereNotNull() .ToList(); if (attributes.IsEmpty()) continue; string name = $"{type.Name}.{memberInfo.Name}"; - string? attributeString = string.Join(", ", attributes.Select(attribute => $"[{attribute.GetType().Name.Replace(nameof(Attribute), "")}]")); + string attributeString = string.Join(", ", attributes.Select(attribute => $"[{attribute.GetType().Name.Replace(nameof(Attribute), "")}]")); if (attributes.Count > 1) yield return new ValidationError(TreatsWarningsAsErrors, diff --git a/src/BenchmarkDotNet/Validators/ValidationError.cs b/src/BenchmarkDotNet/Validators/ValidationError.cs index 23faff5a54..9bec081479 100644 --- a/src/BenchmarkDotNet/Validators/ValidationError.cs +++ b/src/BenchmarkDotNet/Validators/ValidationError.cs @@ -15,11 +15,11 @@ public ValidationError(bool isCritical, string message, BenchmarkCase? benchmark [PublicAPI] public bool IsCritical { get; } [PublicAPI] public string Message { get; } - [PublicAPI] public BenchmarkCase BenchmarkCase { get; } + [PublicAPI] public BenchmarkCase? BenchmarkCase { get; } public override string ToString() => Message; - public bool Equals(ValidationError other) + public bool Equals(ValidationError? other) { if (ReferenceEquals(null, other)) return false; @@ -28,13 +28,13 @@ public bool Equals(ValidationError other) return IsCritical == other.IsCritical && string.Equals(Message, other.Message) && Equals(BenchmarkCase, other.BenchmarkCase); } - public override bool Equals(object obj) + public override bool Equals(object? obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; - if (obj.GetType() != this.GetType()) + if (obj.GetType() != GetType()) return false; return Equals((ValidationError)obj); } diff --git a/tests/BenchmarkDotNet.Tests/Columns/MetricColumnTests.cs b/tests/BenchmarkDotNet.Tests/Columns/MetricColumnTests.cs index f16c4bd7f6..4c7678ba67 100644 --- a/tests/BenchmarkDotNet.Tests/Columns/MetricColumnTests.cs +++ b/tests/BenchmarkDotNet.Tests/Columns/MetricColumnTests.cs @@ -11,6 +11,7 @@ using BenchmarkDotNet.Parameters; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; +using BenchmarkDotNet.Tests.Mocks; using BenchmarkDotNet.Validators; using Perfolizer.Horology; using Xunit; @@ -37,7 +38,7 @@ private static Summary CreateMockSummary(bool printUnitsInContent, bool printUni var summaryStyle = new SummaryStyle(TestCultureInfo.Instance, printUnitsInHeader, null, timeUnit, printUnitsInContent); var config = new ManualConfig().WithSummaryStyle(summaryStyle); var benchmarkCase = new BenchmarkCase( - new Descriptor(null, null), + new Descriptor(MockFactory.MockType, MockFactory.MockMethodInfo), Job.Dry, new ParameterInstances(ImmutableArray.Empty), ImmutableConfigBuilder.Create(config)); diff --git a/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs b/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs index 323da8ddba..706e74b561 100644 --- a/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs +++ b/tests/BenchmarkDotNet.Tests/CsProjGeneratorTests.cs @@ -186,19 +186,13 @@ public void TheDefaultFilePathShouldBeUsedWhenAnAssemblyLocationIsEmpty() { const string programName = "testProgram"; var config = ManualConfig.CreateEmpty().CreateImmutableConfig(); - var benchmarkMethod = - typeof(MockFactory.MockBenchmarkClass) - .GetTypeInfo() - .GetMethods() - .Single(method => method.Name == nameof(MockFactory.MockBenchmarkClass.Foo)); - //Simulate loading an assembly from a stream var benchmarkDotNetAssembly = typeof(MockFactory.MockBenchmarkClass).GetTypeInfo().Assembly; var streamLoadedAssembly = Assembly.Load(File.ReadAllBytes(benchmarkDotNetAssembly.Location)); - var assemblyType = streamLoadedAssembly.GetRunnableBenchmarks().Select(type => type).FirstOrDefault(); + var assemblyType = streamLoadedAssembly.GetRunnableBenchmarks().Select(type => type).First(); - var target = new Descriptor(assemblyType, benchmarkMethod); + var target = new Descriptor(assemblyType, MockFactory.MockMethodInfo); var benchmarkCase = BenchmarkCase.Create(target, Job.Default, null, config); var benchmarks = new[] { new BenchmarkBuildInfo(benchmarkCase, config.CreateImmutableConfig(), 999) }; @@ -213,12 +207,7 @@ public void TheDefaultFilePathShouldBeUsedWhenAnAssemblyLocationIsEmpty() public void TestAssemblyFilePathIsUsedWhenTheAssemblyLocationIsNotEmpty() { const string programName = "testProgram"; - var benchmarkMethod = - typeof(MockFactory.MockBenchmarkClass) - .GetTypeInfo() - .GetMethods() - .Single(method => method.Name == nameof(MockFactory.MockBenchmarkClass.Foo)); - var target = new Descriptor(typeof(MockFactory.MockBenchmarkClass), benchmarkMethod); + var target = new Descriptor(MockFactory.MockType, MockFactory.MockMethodInfo); var benchmarkCase = BenchmarkCase.Create(target, Job.Default, null, ManualConfig.CreateEmpty().CreateImmutableConfig()); var benchmarks = new[] { new BenchmarkBuildInfo(benchmarkCase, ManualConfig.CreateEmpty().CreateImmutableConfig(), 0) }; var projectGenerator = new SteamLoadedBuildPartition("netcoreapp3.0", null, null, null, true); diff --git a/tests/BenchmarkDotNet.Tests/Mocks/MockFactory.cs b/tests/BenchmarkDotNet.Tests/Mocks/MockFactory.cs index ce54b83bbb..ac8d770c22 100644 --- a/tests/BenchmarkDotNet.Tests/Mocks/MockFactory.cs +++ b/tests/BenchmarkDotNet.Tests/Mocks/MockFactory.cs @@ -2,9 +2,11 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using System.Reflection; using BenchmarkDotNet.Attributes; using BenchmarkDotNet.Columns; using BenchmarkDotNet.Configs; +using BenchmarkDotNet.Disassemblers; using BenchmarkDotNet.Engines; using BenchmarkDotNet.Helpers; using BenchmarkDotNet.Reports; @@ -15,6 +17,7 @@ using BenchmarkDotNet.Validators; using Perfolizer.Horology; using static BenchmarkDotNet.Reports.SummaryTable.SummaryTableColumn; +using MethodInfo = System.Reflection.MethodInfo; namespace BenchmarkDotNet.Tests.Mocks { @@ -123,5 +126,10 @@ [Benchmark] public void Foo() { } [Benchmark] public void Bar() { } } + + public static readonly Type MockType = typeof(MockBenchmarkClass); + + public static readonly MethodInfo MockMethodInfo = MockType.GetTypeInfo().GetMethods() + .Single(method => method.Name == nameof(MockBenchmarkClass.Foo)); } } \ No newline at end of file diff --git a/tests/BenchmarkDotNet.Tests/Order/DefaultOrdererTests.cs b/tests/BenchmarkDotNet.Tests/Order/DefaultOrdererTests.cs index 04cff38e30..d9d2e7490e 100644 --- a/tests/BenchmarkDotNet.Tests/Order/DefaultOrdererTests.cs +++ b/tests/BenchmarkDotNet.Tests/Order/DefaultOrdererTests.cs @@ -11,6 +11,7 @@ using BenchmarkDotNet.Parameters; using BenchmarkDotNet.Reports; using BenchmarkDotNet.Running; +using BenchmarkDotNet.Tests.Mocks; using BenchmarkDotNet.Validators; using Xunit; @@ -22,7 +23,7 @@ public class DefaultOrdererTests "", "", TimeSpan.Zero, CultureInfo.InvariantCulture, ImmutableArray.Empty, ImmutableArray.Empty); private static BenchmarkCase CreateBenchmarkCase(string category, int parameter, params BenchmarkLogicalGroupRule[] rules) => new ( - new Descriptor(null, null, categories: new[] { category }), + new Descriptor(MockFactory.MockType, MockFactory.MockMethodInfo, categories: new[] { category }), new Job(), new ParameterInstances(new[] { diff --git a/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs b/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs index 18d947acea..632875d52b 100644 --- a/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs +++ b/tests/BenchmarkDotNet.Tests/Validators/CompilationValidatorTests.cs @@ -22,9 +22,7 @@ public void BenchmarkedMethodNameMustNotContainWhitespaces() new[] { BenchmarkCase.Create( - new Descriptor( - typeof(CompilationValidatorTests), - method.Method), + new Descriptor(typeof(CompilationValidatorTests), method.Method), Job.Dry, null, config @@ -48,9 +46,7 @@ public void BenchmarkedMethodNameMustNotUseCsharpKeywords() new[] { BenchmarkCase.Create( - new Descriptor( - typeof(CompilationValidatorTests), - method.Method), + new Descriptor(typeof(CompilationValidatorTests), method.Method), Job.Dry, null, config)