Skip to content

Commit b379f1c

Browse files
authored
Merge pull request #1664 from nunit/Issue-1590_NetAnalyzers
Enable Minimum .NET Analyzers
2 parents 0fef407 + 0bae2db commit b379f1c

File tree

58 files changed

+292
-214
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

58 files changed

+292
-214
lines changed

.editorconfig

+6-1
Original file line numberDiff line numberDiff line change
@@ -13,4 +13,9 @@ indent_size = 4
1313

1414
[*.{proj,csproj,vcxproj,xproj,json,config,nuspec,xml,yml}]
1515
indent_style = space
16-
indent_size = 2
16+
indent_size = 2
17+
18+
[*.cs]
19+
# This relates to classes that have finalizers, but we should not have any finalizer
20+
# CA1816: Dispose methods should call SuppressFinalize
21+
dotnet_diagnostic.CA1816.severity = none

src/Directory.Build.props

+3
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,9 @@
66
<LangVersion>12</LangVersion>
77
<Features>strict</Features>
88
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
9+
<EnableNETAnalyzers>true</EnableNETAnalyzers>
10+
<AnalysisMode>Minimum</AnalysisMode>
11+
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
912
<Version Condition="'$(Version)'==''">4.0.0.0</Version>
1013
<OutputPath>$(MSBuildThisFileDirectory)\..\bin\$(Configuration)\</OutputPath>
1114
<CheckEolTargetFramework>false</CheckEolTargetFramework>

src/NUnitCommon/nunit.agent.core.tests/AgentOptionTests.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@ public void DefaultOptionSettings<T>(string propertyName, T defaultValue)
2525
var options = new AgentOptions();
2626
var prop = typeof(AgentOptions).GetProperty(propertyName);
2727
Assert.That(prop, Is.Not.Null, $"Property {propertyName} does not exist");
28-
Assert.That(prop.GetValue(options, new object[0]), Is.EqualTo(defaultValue));
28+
Assert.That(prop.GetValue(options, Array.Empty<object>()), Is.EqualTo(defaultValue));
2929
}
3030

3131
static readonly Guid AGENT_GUID = Guid.NewGuid();
@@ -53,7 +53,7 @@ public void ValidOptionSettings<T>(string option, string propertyName, T expecte
5353
var options = new AgentOptions(option);
5454
var prop = typeof(AgentOptions).GetProperty(propertyName);
5555
Assert.That(prop, Is.Not.Null, $"Property {propertyName} does not exist");
56-
Assert.That(prop.GetValue(options, new object[0]), Is.EqualTo(expectedValue));
56+
Assert.That(prop.GetValue(options, Array.Empty<object>()), Is.EqualTo(expectedValue));
5757
}
5858

5959
[Test]

src/NUnitCommon/nunit.agent.core.tests/Runners/DomainManagerTests.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ public void CanCreateDomainWithApplicationBaseSpecified()
7171
public void CanUnloadDomain()
7272
{
7373
var domain = _domainManager.CreateDomain(_package);
74-
_domainManager.Unload(domain);
74+
DomainManager.Unload(domain);
7575

7676
CheckDomainIsUnloaded(domain);
7777
}
@@ -80,14 +80,14 @@ public void CanUnloadDomain()
8080
public void UnloadingTwiceThrowsNUnitEngineUnloadException()
8181
{
8282
var domain = _domainManager.CreateDomain(_package);
83-
_domainManager.Unload(domain);
83+
DomainManager.Unload(domain);
8484

85-
Assert.That(() => _domainManager.Unload(domain), Throws.TypeOf<NUnitEngineUnloadException>());
85+
Assert.That(() => DomainManager.Unload(domain), Throws.TypeOf<NUnitEngineUnloadException>());
8686

8787
CheckDomainIsUnloaded(domain);
8888
}
8989

90-
private void CheckDomainIsUnloaded(AppDomain domain)
90+
private static void CheckDomainIsUnloaded(AppDomain domain)
9191
{
9292
// HACK: Either the Assert will succeed or the
9393
// exception should be thrown.

src/NUnitCommon/nunit.agent.core.tests/Runners/TestAgentRunnerTests.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -91,26 +91,26 @@ private void CheckPackageLoading()
9191
Assert.That(_runner.IsPackageLoaded, Is.False, "Package should not be loaded automatically");
9292
}
9393

94-
private void CheckBasicResult(TestEngineResult result)
94+
private static void CheckBasicResult(TestEngineResult result)
9595
{
9696
foreach (var node in result.XmlNodes)
9797
CheckBasicResult(node);
9898
}
9999

100-
private void CheckBasicResult(XmlNode node)
100+
private static void CheckBasicResult(XmlNode node)
101101
{
102102
Assert.That(node.Name, Is.EqualTo("test-suite"));
103103
Assert.That(node.GetAttribute("testcasecount", 0), Is.EqualTo(MockAssembly.Tests));
104104
Assert.That(node.GetAttribute("runstate"), Is.EqualTo("Runnable"));
105105
}
106106

107-
private void CheckRunResult(TestEngineResult result)
107+
private static void CheckRunResult(TestEngineResult result)
108108
{
109109
foreach (var node in result.XmlNodes)
110110
CheckRunResult(node);
111111
}
112112

113-
private void CheckRunResult(XmlNode result)
113+
private static void CheckRunResult(XmlNode result)
114114
{
115115
CheckBasicResult(result);
116116
Assert.That(result.GetAttribute("passed", 0), Is.EqualTo(MockAssembly.PassedInAttribute));

src/NUnitCommon/nunit.agent.core/Agents/RemoteTestAgent.cs

-2
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,6 @@ public RemoteTestAgent(Guid agentId) : base(agentId) { }
2626

2727
public ITestAgentTransport? Transport;
2828

29-
public int ProcessId => System.Diagnostics.Process.GetCurrentProcess().Id;
30-
3129
public override bool Start()
3230
{
3331
Guard.OperationValid(Transport != null, "Transport must be set before calling Start().");

src/NUnitCommon/nunit.agent.core/Communication/Transports/Tcp/TestAgentTcpTransport.cs

+2-1
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ namespace NUnit.Engine.Communication.Transports.Tcp
1717
public class TestAgentTcpTransport : ITestAgentTransport, ITestEventListener
1818
{
1919
private static readonly Logger log = InternalTrace.GetLogger(typeof(TestAgentTcpTransport));
20+
private static readonly char[] PortSeparator = [':'];
2021

2122
private readonly string _agencyUrl;
2223
private Socket? _clientSocket;
@@ -30,7 +31,7 @@ public TestAgentTcpTransport(RemoteTestAgent agent, string serverUrl)
3031
Guard.ArgumentNotNullOrEmpty(serverUrl, nameof(serverUrl));
3132
_agencyUrl = serverUrl;
3233

33-
var parts = serverUrl.Split(new char[] { ':' });
34+
var parts = serverUrl.Split(PortSeparator);
3435
Guard.ArgumentValid(parts.Length == 2, "Invalid server address specified. Must be a valid endpoint including the port number", nameof(serverUrl));
3536
ServerEndPoint = new IPEndPoint(IPAddress.Parse(parts[0]), int.Parse(parts[1]));
3637
}

src/NUnitCommon/nunit.agent.core/Drivers/DriverService.cs

+4-2
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,9 @@ public class DriverService : IDriverService
1717
{
1818
static readonly Logger log = InternalTrace.GetLogger("DriverService");
1919

20-
readonly IList<IDriverFactory> _factories = new List<IDriverFactory>();
20+
private static readonly char[] CommaSeparator = [','];
21+
22+
readonly List<IDriverFactory> _factories = new List<IDriverFactory>();
2123

2224
public DriverService()
2325
{
@@ -63,7 +65,7 @@ public IFrameworkDriver GetDriver(AppDomain domain, TestPackage package, string
6365
// any true Portable assembly would have a Profile as part of its name.
6466
var platform = targetFramework == ".NETPortable,Version=v5.0"
6567
? ".NETStandard"
66-
: targetFramework.Split(new char[] { ',' })[0];
68+
: targetFramework.Split(CommaSeparator)[0];
6769

6870
if (platform == "Silverlight" || platform == ".NETPortable" || platform == ".NETStandard" || platform == ".NETCompactFramework")
6971
if (skipNonTestAssemblies)

src/NUnitCommon/nunit.agent.core/Drivers/NUnit2DriverFactory.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ public bool IsSupportedTestFramework(AssemblyName reference)
4545
public IFrameworkDriver GetDriver(AppDomain domain, string id, AssemblyName reference)
4646
{
4747
if (!IsSupportedTestFramework(reference))
48-
throw new ArgumentException("Invalid framework", "reference");
48+
throw new ArgumentException("Invalid framework", nameof(reference));
4949

5050
if (!_resolverInstalled)
5151
{

src/NUnitCommon/nunit.agent.core/Drivers/NUnit3DriverFactory.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ public bool IsSupportedTestFramework(AssemblyName reference)
3131
public IFrameworkDriver GetDriver(AppDomain domain, string id, AssemblyName reference)
3232
{
3333
Guard.ArgumentNotNullOrEmpty(id, nameof(id));
34-
Guard.ArgumentValid(IsSupportedTestFramework(reference), "Invalid framework", "reference");
34+
Guard.ArgumentValid(IsSupportedTestFramework(reference), "Invalid framework", nameof(reference));
3535

3636
log.Info("Using NUnitFrameworkDriver");
3737
return new NUnitFrameworkDriver(domain, id, reference);

src/NUnitCommon/nunit.agent.core/Drivers/NUnitFrameworkApi2009.cs

+2-3
Original file line numberDiff line numberDiff line change
@@ -48,15 +48,14 @@ public NUnitFrameworkApi2009(AppDomain testDomain, string driverId, AssemblyName
4848

4949
public string Load(string testAssemblyPath, IDictionary<string, object> settings)
5050
{
51-
Guard.ArgumentValid(File.Exists(testAssemblyPath), "Framework driver called with a file name that doesn't exist.", "testAssemblyPath");
51+
Guard.ArgumentValid(File.Exists(testAssemblyPath), "Framework driver called with a file name that doesn't exist.", nameof(testAssemblyPath));
5252

5353
log.Info($"Loading {testAssemblyPath} - see separate log file");
5454

5555
_testAssemblyPath = testAssemblyPath;
5656

5757
// Normally, the caller should check for an invalid requested runtime, but we make sure here
58-
var requestedRuntime = settings.ContainsKey(EnginePackageSettings.RequestedRuntimeFramework)
59-
? settings[EnginePackageSettings.RequestedRuntimeFramework] : null;
58+
settings.TryGetValue(EnginePackageSettings.RequestedRuntimeFramework, out object? requestedRuntime);
6059

6160
var idPrefix = _driverId + "-";
6261

src/NUnitCommon/nunit.agent.core/Drivers/NUnitFrameworkDriver.cs

+3-1
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ public class NUnitFrameworkDriver : IFrameworkDriver
1717
static readonly Version MINIMUM_NUNIT_VERSION = new(3, 2, 0);
1818
static readonly Logger log = InternalTrace.GetLogger(nameof(NUnitFrameworkDriver));
1919

20+
#if NETFRAMEWORK
2021
readonly NUnitFrameworkApi _api;
2122

22-
#if NETFRAMEWORK
2323
/// <summary>
2424
/// Construct an NUnitFrameworkDriver
2525
/// </summary>
@@ -82,6 +82,8 @@ internal NUnitFrameworkDriver(AppDomain testDomain, string api, string id, Assem
8282
: new NUnitFrameworkApi2009(testDomain, ID, nunitRef);
8383
}
8484
#else
85+
readonly NUnitFrameworkApi2018 _api;
86+
8587
/// <summary>
8688
/// Construct an NUnitFrameworkDriver
8789
/// </summary>

src/NUnitCommon/nunit.agent.core/NUnitAgent.cs

+4
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,11 @@ public class NUnitAgent<TAgent>
1919
{
2020
static Process? AgencyProcess;
2121
static RemoteTestAgent? Agent;
22+
#if NET6_0_OR_GREATER
23+
static readonly int _pid = Environment.ProcessId;
24+
#else
2225
static readonly int _pid = Process.GetCurrentProcess().Id;
26+
#endif
2327
static readonly Logger log = InternalTrace.GetLogger(typeof(TestAgent));
2428

2529
/// <summary>

src/NUnitCommon/nunit.agent.core/RunTestsCallbackHandler.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ private void ReportProgress(string state)
4141
_listener.OnTestEvent(state);
4242
}
4343

44-
private bool IsFinalResult(string eventArgument)
44+
private static bool IsFinalResult(string eventArgument)
4545
{
4646
// TODO: If we add a prefix to the final result in the next framework
4747
// release, then we can immediately recognize the final result but we

src/NUnitCommon/nunit.agent.core/Runners/DomainManager.cs

+2-2
Original file line numberDiff line numberDiff line change
@@ -59,7 +59,7 @@ public AppDomain CreateDomain( TestPackage package )
5959
}
6060

6161
// Made separate and internal for testing
62-
AppDomainSetup CreateAppDomainSetup(TestPackage package)
62+
static AppDomainSetup CreateAppDomainSetup(TestPackage package)
6363
{
6464
AppDomainSetup setup = new AppDomainSetup();
6565

@@ -99,7 +99,7 @@ AppDomainSetup CreateAppDomainSetup(TestPackage package)
9999
return setup;
100100
}
101101

102-
public void Unload(AppDomain domain)
102+
public static void Unload(AppDomain domain)
103103
{
104104
new DomainUnloader(domain).Unload();
105105
}

src/NUnitCommon/nunit.agent.core/Runners/TestDomainRunner.cs

+1-1
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ public override void Unload()
3030
{
3131
if (this.TestDomain != null)
3232
{
33-
_domainManager.Unload(this.TestDomain);
33+
DomainManager.Unload(this.TestDomain);
3434
this.TestDomain = null;
3535
}
3636
}

src/NUnitCommon/nunit.agent.core/TestAssemblyResolver.cs

+3-3
Original file line numberDiff line numberDiff line change
@@ -91,7 +91,7 @@ public void Dispose()
9191

9292
private Assembly? OnResolving(AssemblyLoadContext loadContext, AssemblyName assemblyName)
9393
{
94-
if (loadContext == null) throw new ArgumentNullException("context");
94+
Guard.ArgumentNotNull(loadContext, nameof(loadContext));
9595

9696
Assembly? loadedAssembly;
9797
foreach (var strategy in ResolutionStrategies)
@@ -152,7 +152,7 @@ bool FileMatchesAssembly(string fileName) =>
152152
public class RuntimeLibrariesStrategy : ResolutionStrategy
153153
{
154154
private DependencyContext? _dependencyContext;
155-
private readonly ICompilationAssemblyResolver _assemblyResolver;
155+
private readonly CompositeCompilationAssemblyResolver _assemblyResolver;
156156

157157
public RuntimeLibrariesStrategy(AssemblyLoadContext loadContext, string testAssemblyPath)
158158
{
@@ -304,7 +304,7 @@ private static bool TryGetVersionFromString(string text, out Version newVersion)
304304
int len = 0;
305305
foreach (char c in text)
306306
{
307-
if (VERSION_CHARS.IndexOf(c) >= 0)
307+
if (VERSION_CHARS.Contains(c))
308308
len++;
309309
else
310310
break;

src/NUnitCommon/nunit.common.tests/FileSystemAccess/DirectoryFinderTests.cs

+5-5
Original file line numberDiff line numberDiff line change
@@ -441,15 +441,15 @@ public void GetDirectories_StartDirectoryIsNull()
441441
{
442442
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
443443

444-
Assert.That(() => finder.GetDirectories((IDirectory)null!, "notused"), Throws.ArgumentNullException.With.Message.Contains(" startDirectory "));
444+
Assert.That(() => finder.GetDirectories((IDirectory)null!, "notused"), Throws.ArgumentNullException.With.Message.Contains("startDirectory"));
445445
}
446446

447447
[Test]
448448
public void GetDirectories_PatternIsNull()
449449
{
450450
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
451451

452-
Assert.That(() => finder.GetDirectories(Substitute.For<IDirectory>(), null!), Throws.ArgumentNullException.With.Message.Contains(" pattern "));
452+
Assert.That(() => finder.GetDirectories(Substitute.For<IDirectory>(), null!), Throws.ArgumentNullException.With.Message.Contains("pattern"));
453453
}
454454

455455
[Test]
@@ -594,23 +594,23 @@ public void GetFiles_StartDirectoryIsNull()
594594
{
595595
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
596596

597-
Assert.That(() => finder.GetFiles((IDirectory)null!, "notused"), Throws.ArgumentNullException.With.Message.Contains(" startDirectory "));
597+
Assert.That(() => finder.GetFiles((IDirectory)null!, "notused"), Throws.ArgumentNullException.With.Message.Contains("startDirectory"));
598598
}
599599

600600
[Test]
601601
public void GetFiles_PatternIsNull()
602602
{
603603
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
604604

605-
Assert.That(() => finder.GetDirectories(Substitute.For<IDirectory>(), null!), Throws.ArgumentNullException.With.Message.Contains(" pattern "));
605+
Assert.That(() => finder.GetDirectories(Substitute.For<IDirectory>(), null!), Throws.ArgumentNullException.With.Message.Contains("pattern"));
606606
}
607607

608608
[Test]
609609
public void GetFiles_PatternIsEmpty()
610610
{
611611
var finder = new DirectoryFinder(Substitute.For<IFileSystem>());
612612

613-
Assert.That(() => finder.GetFiles(Substitute.For<IDirectory>(), string.Empty), Throws.ArgumentException.With.Message.Contains(" pattern "));
613+
Assert.That(() => finder.GetFiles(Substitute.For<IDirectory>(), string.Empty), Throws.ArgumentException.With.Message.Contains("pattern"));
614614
}
615615

616616
private static string CreateAbsolutePath(IEnumerable<string> parts)

src/NUnitCommon/nunit.common.tests/FileSystemAccess/FileSystemTests.cs

+4-4
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,7 @@ public void GetDirectory_DirectoryDoesNotExist()
3838
[Test]
3939
public void GetFile()
4040
{
41-
var path = this.GetTestFileLocation();
41+
var path = GetTestFileLocation();
4242
var parent = SIO.Path.GetDirectoryName(path);
4343
var fileSystem = new FileSystem();
4444

@@ -66,7 +66,7 @@ public void GetFile_DirectoryDoesNotExist()
6666
[Test]
6767
public void Exists_FileExists()
6868
{
69-
var path = this.GetTestFileLocation();
69+
var path = GetTestFileLocation();
7070
var file = new File(path);
7171
var fileSystem = new FileSystem();
7272

@@ -78,7 +78,7 @@ public void Exists_FileExists()
7878
[Test]
7979
public void Exists_FileDoesNotExist()
8080
{
81-
var path = this.GetTestFileLocation();
81+
var path = GetTestFileLocation();
8282
while (SIO.File.Exists(path))
8383
{
8484
path += "x";
@@ -137,7 +137,7 @@ public void Exists_DirectoryIsNull()
137137
Assert.That(() => fileSystem.Exists((IDirectory)null!), Throws.ArgumentNullException);
138138
}
139139

140-
private string GetTestFileLocation()
140+
private static string GetTestFileLocation()
141141
{
142142
return Assembly.GetAssembly(typeof(FileTests))!.Location;
143143
}

0 commit comments

Comments
 (0)