Skip to content

Commit

Permalink
Warning cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
OsirisTerje committed Apr 9, 2024
1 parent 88638cb commit 6aec955
Show file tree
Hide file tree
Showing 21 changed files with 108 additions and 159 deletions.
1 change: 1 addition & 0 deletions src/Directory.Build.props
Expand Up @@ -6,6 +6,7 @@
<AssemblyOriginatorKeyFile>..\NUnitAdapter.snk</AssemblyOriginatorKeyFile>
<CodeAnalysisRuleSet>..\..\Osiris.Extended.ruleset</CodeAnalysisRuleSet>
<TreatWarningsAsErrors Condition="'$(Configuration)' == 'Release'">true</TreatWarningsAsErrors>
<SuppressTfmSupportBuildWarnings>true</SuppressTfmSupportBuildWarnings>
</PropertyGroup>

<ItemGroup>
Expand Down
4 changes: 2 additions & 2 deletions src/NUnit.TestAdapter.Tests.Acceptance/AcceptanceTests.cs
Expand Up @@ -172,7 +172,7 @@ private static void ClearCachedTestNupkgs(string packageCachePath)
Utils.DeleteDirectoryRobust(Path.Combine(packageCachePath, NuGetPackageId));
}

private static readonly Dictionary<string, List<IsolatedWorkspace>> WorkspacesByTestId = new();
private static readonly Dictionary<string, List<IsolatedWorkspace>> WorkspacesByTestId = [];

protected static IsolatedWorkspace CreateWorkspace()
{
Expand All @@ -184,7 +184,7 @@ protected static IsolatedWorkspace CreateWorkspace()
lock (WorkspacesByTestId)
{
if (!WorkspacesByTestId.TryGetValue(test.ID, out var workspaces))
WorkspacesByTestId.Add(test.ID, workspaces = new List<IsolatedWorkspace>());
WorkspacesByTestId.Add(test.ID, workspaces = []);
workspaces.Add(workspace);
}
return workspace;
Expand Down
Expand Up @@ -24,6 +24,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Update="StyleCop.Analyzers" Version="1.2.0-beta.556" />
</ItemGroup>

</Project>
Expand Up @@ -7,7 +7,7 @@ partial class IsolatedWorkspace
{
private sealed class RunSettings
{
private List<string> Arguments { get; } = new();
private List<string> Arguments { get; } = [];

public string WorkingDirectory { get; }
public string FileName { get; }
Expand Down
Expand Up @@ -6,22 +6,17 @@
namespace NUnit.VisualStudio.TestAdapter.Tests.Acceptance.WorkspaceTools
{
[DebuggerDisplay("{Directory,nq}")]
public sealed partial class IsolatedWorkspace : IDisposable
public sealed partial class IsolatedWorkspace(DirectoryMutex directoryMutex, ToolResolver toolResolver)
: IDisposable
{
private readonly List<string> projectPaths = new();
private readonly ToolResolver toolResolver;
private readonly DirectoryMutex directoryMutex;
private readonly List<string> projectPaths = [];
private readonly ToolResolver toolResolver = toolResolver ?? throw new ArgumentNullException(nameof(toolResolver));
private readonly DirectoryMutex directoryMutex = directoryMutex ?? throw new ArgumentNullException(nameof(toolResolver));

public bool DumpTestExecution { get; set; } = false;

public string Directory => directoryMutex.DirectoryPath;

public IsolatedWorkspace(DirectoryMutex directoryMutex, ToolResolver toolResolver)
{
this.directoryMutex = directoryMutex ?? throw new ArgumentNullException(nameof(toolResolver));
this.toolResolver = toolResolver ?? throw new ArgumentNullException(nameof(toolResolver));
}

public void Dispose() => directoryMutex.Dispose();

public IsolatedWorkspace AddProject(string path, string contents)
Expand Down
Expand Up @@ -3,30 +3,24 @@

namespace NUnit.VisualStudio.TestAdapter.Tests.Acceptance.WorkspaceTools
{
public readonly struct ProcessRunResult
public readonly struct ProcessRunResult(
string fileName,
string arguments,
int exitCode,
string stdOut,
string stdErr)
{
public ProcessRunResult(string fileName, string arguments, int exitCode, string stdOut, string stdErr)
{
FileName = fileName ?? throw new ArgumentNullException(nameof(fileName));
Arguments = arguments;
ExitCode = exitCode;
StdOut = stdOut ?? string.Empty;
StdErr = stdErr ?? string.Empty;
}

public string FileName { get; }
public string Arguments { get; }
public string FileName { get; } = fileName ?? throw new ArgumentNullException(nameof(fileName));
public string Arguments { get; } = arguments;

public string ProcessName => Path.GetFileName(FileName);
public int ExitCode { get; }
public string StdOut { get; }
public string StdErr { get; }

public ProcessRunResult ThrowIfError()
{
if (ExitCode == 0 && string.IsNullOrEmpty(StdErr)) return this;
public int ExitCode { get; } = exitCode;
public string StdOut { get; } = stdOut ?? string.Empty;
public string StdErr { get; } = stdErr ?? string.Empty;

throw new ProcessErrorException(this);
}
public ProcessRunResult ThrowIfError() =>
ExitCode == 0 && string.IsNullOrEmpty(StdErr)
? this
: throw new ProcessErrorException(this);
}
}
Expand Up @@ -8,18 +8,19 @@


<ItemGroup Condition=" '$(TargetFramework)' == 'netcoreapp3.1' ">
<PackageReference Include="NUnit" Version="3.14.0"/>
<PackageReference Include="NUnit" Version="3.14.0" />
</ItemGroup>

<ItemGroup Condition=" '$(TargetFramework)' == 'net462' ">
<PackageReference Include="NUnit" Version="4.1.0"/>
<PackageReference Include="NUnit" Version="4.1.0" />
</ItemGroup>

<ItemGroup>
<PackageReference Update="Microsoft.NETFramework.ReferenceAssemblies" Version="1.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Update="StyleCop.Analyzers" Version="1.2.0-beta.556" />
</ItemGroup>

</Project>
42 changes: 16 additions & 26 deletions src/NUnitTestAdapter/AdapterSettings.cs
Expand Up @@ -52,19 +52,9 @@ public enum DiscoveryMethod
Current
}

public class AdapterSettings : IAdapterSettings
public class AdapterSettings(ITestLogger logger) : IAdapterSettings
{
private const string RANDOM_SEED_FILE = "nunit_random_seed.tmp";
private readonly ITestLogger _logger;

#region Constructor

public AdapterSettings(ITestLogger logger)
{
_logger = logger;
}

#endregion
private const string RandomSeedFile = "nunit_random_seed.tmp";

#region Properties - General

Expand Down Expand Up @@ -235,7 +225,7 @@ public void Load(string settingsXml)

var nunitNode = doc.SelectSingleNode("RunSettings/NUnit");
Verbosity = GetInnerTextAsInt(nunitNode, nameof(Verbosity), 0);
_logger.Verbosity = Verbosity;
logger.Verbosity = Verbosity;

ExtractRunConfiguration(doc);

Expand Down Expand Up @@ -301,7 +291,7 @@ public void Load(string settingsXml)
inProcDataCollectorNode?.SelectSingleNode(
"InProcDataCollector[@uri='InProcDataCollector://Microsoft/LiveUnitTesting/1.0']") != null;

// TestPlatform can opt-in to run tests one at a time so that the InProcDataCollectors can collect the data for each one of them separately.
// TestPlatform can choose to opt in to run tests one at a time so that the InProcDataCollectors can collect the data for each one of them separately.
// In that case, we need to ensure that tests do not run in parallel and the test started/test ended events are sent synchronously.
if (CollectDataForEachTestSeparately || hasLiveUnitTestingDataCollector)
{
Expand All @@ -311,7 +301,7 @@ public void Load(string settingsXml)
{
if (!InProcDataCollectorsAvailable)
{
_logger.Info(
logger.Info(
"CollectDataForEachTestSeparately is set, which is used to make InProcDataCollectors collect data for each test separately. No InProcDataCollectors can be found, thus the tests will run slower unnecessarily.");
}
}
Expand Down Expand Up @@ -438,7 +428,7 @@ private void MapTestCategory(string vsTestCategoryType)
if (ok)
VsTestCategoryType = result;
else
_logger.Warning($"Invalid value ({vsTestCategoryType}) for VsTestCategoryType, should be either NUnit or MsTest");
logger.Warning($"Invalid value ({vsTestCategoryType}) for VsTestCategoryType, should be either NUnit or MsTest");
}

private void MapDisplayName(string displaynameoptions)
Expand All @@ -449,26 +439,26 @@ private void MapDisplayName(string displaynameoptions)
if (ok)
DisplayName = result;
else
_logger.Warning($"Invalid value ({displaynameoptions}) for DisplayNameOptions, should be either Name, Fullname or FullnameSep");
logger.Warning($"Invalid value ({displaynameoptions}) for DisplayNameOptions, should be either Name, Fullname or FullnameSep");
}


public void SaveRandomSeed(string dirname)
{
try
{
var path = Path.Combine(dirname, RANDOM_SEED_FILE);
var path = Path.Combine(dirname, RandomSeedFile);
File.WriteAllText(path, RandomSeed.Value.ToString());
}
catch (Exception ex)
{
_logger.Warning("Failed to save random seed.", ex);
logger.Warning("Failed to save random seed.", ex);
}
}

public void RestoreRandomSeed(string dirname)
{
var fullPath = Path.Combine(dirname, RANDOM_SEED_FILE);
var fullPath = Path.Combine(dirname, RandomSeedFile);
if (!File.Exists(fullPath))
return;
try
Expand All @@ -478,7 +468,7 @@ public void RestoreRandomSeed(string dirname)
}
catch (Exception ex)
{
_logger.Warning("Unable to restore random seed.", ex);
logger.Warning("Unable to restore random seed.", ex);
}
}

Expand All @@ -497,9 +487,9 @@ private void UpdateNumberOfTestWorkers()
}
else if (DisableParallelization && NumberOfTestWorkers > 0)
{
if (_logger.Verbosity > 0)
if (logger.Verbosity > 0)
{
_logger.Warning(
logger.Warning(
$"DisableParallelization:{DisableParallelization} & NumberOfTestWorkers:{NumberOfTestWorkers} are conflicting settings, hence not running in parallel");
}
NumberOfTestWorkers = 0;
Expand Down Expand Up @@ -571,7 +561,7 @@ private void Log<T>(string xpath, T res)
{
if (Verbosity >= 4)
{
_logger.Info($"Setting: {xpath} = {res}");
logger.Info($"Setting: {xpath} = {res}");
}
}

Expand All @@ -584,7 +574,7 @@ public TestOutcome MapWarningOutcome(string outcome)

if (!ok)
{
_logger.Warning(
logger.Warning(
$"Invalid value ({outcome}) for MapWarningTo, should be either Skipped,Failed,Passed or None");
return TestOutcome.Skipped;
}
Expand All @@ -599,7 +589,7 @@ public T MapEnum<T>(string setting, T defaultValue)
bool ok = TryParse.EnumTryParse(setting, out T result);
if (!ok)
{
_logger.Warning(
logger.Warning(
$"Invalid value ({setting}) for {typeof(T)}");
return defaultValue;
}
Expand Down
1 change: 1 addition & 0 deletions src/NUnitTestAdapter/NUnit.TestAdapter.csproj
Expand Up @@ -54,6 +54,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Update="StyleCop.Analyzers" Version="1.2.0-beta.556" />
</ItemGroup>

<Target Name="PreventTestPlatformObjectModelCopyLocal" AfterTargets="ResolveReferences">
Expand Down
13 changes: 9 additions & 4 deletions src/NUnitTestAdapter/NUnit3TestExecutor.cs
Expand Up @@ -127,6 +127,14 @@ public void RunTests(IEnumerable<string> sources, IRunContext runContext, IFrame

filter ??= builder.FilterByWhere(Settings.Where);

RunAssemblies(sources, filter);

TestLog.Info($"NUnit Adapter {AdapterVersion}: Test execution complete");
Unload();
}

private void RunAssemblies(IEnumerable<string> sources, TestFilter filter)
{
foreach (string assemblyName in sources)
{
try
Expand All @@ -143,9 +151,6 @@ public void RunTests(IEnumerable<string> sources, IRunContext runContext, IFrame
TestLog.Warning("Exception thrown executing tests", ex);
}
}

TestLog.Info($"NUnit Adapter {AdapterVersion}: Test execution complete");
Unload();
}

private void SetRunTypeByStrings()
Expand All @@ -161,7 +166,7 @@ private void SetRunTypeByStrings()
}

/// <summary>
/// Called by the VisualStudio IDE when all or selected tests are to be run. Never called from TFS Build, except (at least 2022, probably also 2019) when vstest.console uses /test: then this is being used.
/// Called by the VisualStudio IDE when all or selected tests are to be run. Never called from TFS Build, except (at least 2022, probably also 2019) when 'vstest.console' uses /test: then this is being used.
/// </summary>
/// <param name="tests">The tests to be run.</param>
/// <param name="runContext">The RunContext.</param>
Expand Down

0 comments on commit 6aec955

Please sign in to comment.