Skip to content

Commit

Permalink
CA1822: Mark members as static (#3853)
Browse files Browse the repository at this point in the history
  • Loading branch information
Evangelink authored Jul 15, 2022
1 parent 09ef5af commit 1eb80c2
Show file tree
Hide file tree
Showing 73 changed files with 199 additions and 200 deletions.
3 changes: 3 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,9 @@ dotnet_diagnostic.CA1304.severity = warning # not default, increased severity to
# CA1305: Specify IFormatProvider
dotnet_diagnostic.CA1305.severity = warning # not default, increased severity to ensure it is applied

# CA1822: Mark members as static
dotnet_diagnostic.CA1822.severity = warning # not default, increased severity to ensure it is applied

#### C# Coding Conventions ####

# var preferences
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -320,8 +320,8 @@ internal Dictionary<string, TPluginInfo> GetTestExtensions<TPluginInfo, TExtensi
}

// Check if extensions from this assembly have already been discovered.
var extensions = TestExtensions?.GetExtensionsDiscoveredFromAssembly(
TestExtensions.GetTestExtensionCache<TPluginInfo>(),
var extensions = TestExtensions.GetExtensionsDiscoveredFromAssembly(
TestExtensions?.GetTestExtensionCache<TPluginInfo>(),
extensionAssembly);

if (extensions?.Count > 0)
Expand All @@ -347,7 +347,7 @@ internal Dictionary<string, TPluginInfo> GetTestExtensions<TPluginInfo, TExtensi
/// </summary>
/// <param name="extensionAssembly">The extension assembly.</param>
/// <returns>Resolution paths for the assembly.</returns>
internal IList<string> GetResolutionPaths(string extensionAssembly)
internal static IList<string> GetResolutionPaths(string extensionAssembly)
{
var resolutionPaths = new List<string>();

Expand Down Expand Up @@ -463,7 +463,7 @@ private Dictionary<string, TPluginInfo> GetTestExtensions<TPluginInfo, TExtensio
SetupAssemblyResolver(extensionPath);
}

return new TestPluginDiscoverer().GetTestExtensionsInformation<TPluginInfo, TExtension>(extensionPaths);
return TestPluginDiscoverer.GetTestExtensionsInformation<TPluginInfo, TExtension>(extensionPaths);
}

protected void SetupAssemblyResolver(string? extensionAssembly)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,17 +21,9 @@ namespace Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework;
/// <summary>
/// Discovers test extensions in a directory.
/// </summary>
internal class TestPluginDiscoverer
internal static class TestPluginDiscoverer
{
private static readonly HashSet<string> UnloadableFiles = new();
private readonly MetadataReaderExtensionsHelper _extensionHelper = new();

/// <summary>
/// Initializes a new instance of the <see cref="TestPluginDiscoverer"/> class.
/// </summary>
public TestPluginDiscoverer()
{
}

#if WINDOWS_UAP
private static HashSet<string> platformAssemblies = new HashSet<string>(new string[] {
Expand All @@ -58,7 +50,7 @@ public TestPluginDiscoverer()
/// <returns>
/// A dictionary of assembly qualified name and test plugin information.
/// </returns>
public Dictionary<string, TPluginInfo> GetTestExtensionsInformation<TPluginInfo, TExtension>(IEnumerable<string> extensionPaths) where TPluginInfo : TestPluginInformation
public static Dictionary<string, TPluginInfo> GetTestExtensionsInformation<TPluginInfo, TExtension>(IEnumerable<string> extensionPaths) where TPluginInfo : TestPluginInformation
{
TPDebug.Assert(extensionPaths != null);

Expand Down Expand Up @@ -98,9 +90,10 @@ private static void AddKnownExtensions(ref IEnumerable<string> extensionPaths)
/// <param name="pluginInfos">
/// Test plugins collection to add to.
/// </param>
private void GetTestExtensionsFromFiles<TPluginInfo, TExtension>(
private static void GetTestExtensionsFromFiles<TPluginInfo, TExtension>(
string[] files,
Dictionary<string, TPluginInfo> pluginInfos) where TPluginInfo : TestPluginInformation
Dictionary<string, TPluginInfo> pluginInfos)
where TPluginInfo : TestPluginInformation
{
TPDebug.Assert(files != null, "null files");
TPDebug.Assert(pluginInfos != null, "null pluginInfos");
Expand Down Expand Up @@ -147,7 +140,8 @@ private void GetTestExtensionsFromFiles<TPluginInfo, TExtension>(
/// <typeparam name="TExtension">
/// Type of Extensions.
/// </typeparam>
private void GetTestExtensionsFromAssembly<TPluginInfo, TExtension>(Assembly assembly, Dictionary<string, TPluginInfo> pluginInfos, string filePath) where TPluginInfo : TestPluginInformation
private static void GetTestExtensionsFromAssembly<TPluginInfo, TExtension>(Assembly assembly, Dictionary<string, TPluginInfo> pluginInfos, string filePath)
where TPluginInfo : TestPluginInformation
{
TPDebug.Assert(assembly != null, "null assembly");
TPDebug.Assert(pluginInfos != null, "null pluginInfos");
Expand All @@ -157,7 +151,7 @@ private void GetTestExtensionsFromAssembly<TPluginInfo, TExtension>(Assembly ass

try
{
var discoveredExtensions = _extensionHelper.DiscoverTestExtensionTypesV2Attribute(assembly, filePath);
var discoveredExtensions = MetadataReaderExtensionsHelper.DiscoverTestExtensionTypesV2Attribute(assembly, filePath);
if (discoveredExtensions?.Length > 0)
{
types.AddRange(discoveredExtensions);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -418,7 +418,7 @@ internal void InvalidateCache()
/// <returns>
/// The <see cref="Dictionary"/>. of extensions discovered in assembly
/// </returns>
internal Dictionary<string, TPluginInfo> GetExtensionsDiscoveredFromAssembly<TPluginInfo>(
internal static Dictionary<string, TPluginInfo> GetExtensionsDiscoveredFromAssembly<TPluginInfo>(
Dictionary<string, TPluginInfo>? extensionCollection,
string? extensionAssembly)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -190,7 +190,7 @@ internal void AddSearchDirectories(IEnumerable<string> directories)
/// <returns>
/// The <see cref="bool"/>.
/// </returns>
private bool RequestedAssemblyNameMatchesFound(AssemblyName requestedName, AssemblyName foundName)
private static bool RequestedAssemblyNameMatchesFound(AssemblyName requestedName, AssemblyName foundName)
{
TPDebug.Assert(requestedName != null);
TPDebug.Assert(foundName != null);
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Reflection;

Expand Down Expand Up @@ -39,11 +40,13 @@ public bool TryGetVisualStudioDirectory(out string visualStudioDirectory)
return false;
}

[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Part of the public API")]
public string GetVisualStudioPath(string visualStudioDirectory)
{
return Path.Combine(visualStudioDirectory, DevenvExe);
}

[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Part of the public API")]
public string[] GetVisualStudioCommonLocations(string visualStudioDirectory)
{
return new[]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -38,16 +38,16 @@ public TestExtensionTypesV2Attribute(string extensionType, string extensionIdent
}
}
*/
internal class MetadataReaderExtensionsHelper
internal static class MetadataReaderExtensionsHelper
{
private const string TestExtensionTypesAttributeV2 = "Microsoft.VisualStudio.TestPlatform.TestExtensionTypesV2Attribute";
private static readonly ConcurrentDictionary<string, Type[]> AssemblyCache = new();
private static readonly Type[] EmptyTypeArray = new Type[0];

public Type[] DiscoverTestExtensionTypesV2Attribute(Assembly loadedAssembly, string assemblyFilePath)
public static Type[] DiscoverTestExtensionTypesV2Attribute(Assembly loadedAssembly, string assemblyFilePath)
=> AssemblyCache.GetOrAdd(assemblyFilePath, DiscoverTestExtensionTypesV2AttributeInternal(loadedAssembly, assemblyFilePath));

private Type[] DiscoverTestExtensionTypesV2AttributeInternal(Assembly loadedAssembly, string assemblyFilePath)
private static Type[] DiscoverTestExtensionTypesV2AttributeInternal(Assembly loadedAssembly, string assemblyFilePath)
{
EqtTrace.Verbose($"MetadataReaderExtensionsHelper: Discovering extensions inside assembly '{loadedAssembly.FullName}' file path '{assemblyFilePath}'");

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -292,6 +292,7 @@ private static bool TryGetSubstringUntilDelimiter(string rawMessage, int start,
/// <param name="version">Version of serializer to be used.</param>
/// <typeparam name="T">Target type to deserialize.</typeparam>
/// <returns>An instance of <see cref="T"/>.</returns>
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Part of the public API")]
public T? Deserialize<T>(string json, int version = 1)
{
var payloadSerializer = GetPayloadSerializer(version);
Expand Down Expand Up @@ -355,6 +356,7 @@ public string SerializePayload(string? messageType, object? payload, int version
/// <param name="data">Instance of the object to serialize.</param>
/// <param name="version">Version to be stamped.</param>
/// <returns>JSON string.</returns>
[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Part of the public API")]
public string Serialize<T>(T data, int version = 1)
{
var payloadSerializer = GetPayloadSerializer(version);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -751,7 +751,7 @@ private void SetOperationComplete()
Interlocked.CompareExchange(ref _operationCompleted, 1, 0);
}

private ICommunicationEndPoint SetCommunicationEndPoint(TestHostConnectionInfo testhostConnectionInfo)
private static ICommunicationEndPoint SetCommunicationEndPoint(TestHostConnectionInfo testhostConnectionInfo)
{
// TODO: Use factory to get the communication endpoint. It will abstract out the type of communication endpoint like socket, shared memory or named pipe etc.,
// The connectionInfo here is what is provided to testhost, but we are in runner, and so the role needs
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -427,7 +427,7 @@ internal bool TryGetUriFromFriendlyName(string? friendlyName, out Uri? loggerUri
/// </summary>
/// <param name="runSettings">Test run settings.</param>
/// <returns>Test results directory</returns>
internal string? GetResultsDirectory(string? runSettings)
internal static string? GetResultsDirectory(string? runSettings)
{
string? resultsDirectory = null;
if (runSettings != null)
Expand All @@ -451,7 +451,7 @@ internal bool TryGetUriFromFriendlyName(string? friendlyName, out Uri? loggerUri
/// </summary>
/// <param name="runSettings">Test run settings.</param>
/// <returns>Target framework</returns>
internal Framework? GetTargetFramework(string? runSettings)
internal static Framework? GetTargetFramework(string? runSettings)
{
Framework? targetFramework = null;
if (runSettings != null)
Expand All @@ -475,7 +475,7 @@ internal bool TryGetUriFromFriendlyName(string? friendlyName, out Uri? loggerUri
/// </summary>
/// <param name="runSettings"></param>
/// <returns></returns>
internal bool GetTreatNoTestsAsError(string? runSettings)
internal static bool GetTreatNoTestsAsError(string? runSettings)
{
return RunSettingsUtilities.GetTreatNoTestsAsError(runSettings);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,7 +281,7 @@ private int GetConnectionTimeout(int processId)
return connectionTimeout;
}

private void InvokeDataCollectionServiceAction(Action action, ITestMessageEventHandler? runEventsHandler)
private static void InvokeDataCollectionServiceAction(Action action, ITestMessageEventHandler? runEventsHandler)
{
try
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -119,14 +119,14 @@ public ICollection<AttachmentSet> UpdateAttachmentSets(ICollection<AttachmentSet
return attachmentSets!;
}

private AttachmentSet UpdateAttachmentSet(AttachmentSet attachmentSet, PathConversionDirection updateDirection)
private static AttachmentSet UpdateAttachmentSet(AttachmentSet attachmentSet, PathConversionDirection updateDirection)
{
ValidateArg.NotNull(attachmentSet, nameof(attachmentSet));
attachmentSet.Attachments.ToList().ForEach(a => UpdateAttachment(a, updateDirection));
return attachmentSet;
}

private UriDataAttachment UpdateAttachment(UriDataAttachment attachment, PathConversionDirection _)
private static UriDataAttachment UpdateAttachment(UriDataAttachment attachment, PathConversionDirection _)
{
ValidateArg.NotNull(attachment, nameof(attachment));
// todo: convert uri? https://github.com/microsoft/vstest/issues/3367
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -574,7 +574,7 @@ private bool NotRequiredStaThread()
}
}

private void SetAdapterLoggingSettings()
private static void SetAdapterLoggingSettings()
{
// TODO: enable the below once runsettings is in.
// var sessionMessageLogger = testExecutorFrameworkHandle as TestSessionMessageLogger;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.Linq;
Expand Down Expand Up @@ -48,6 +49,7 @@ public ProcDumpDumper(IProcessHelper processHelper, IFileHelper fileHelper, IEnv
_environment = environment;
}

[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Part of the public API")]
protected Action<object?, string?> OutputReceivedCallback => (process, data) =>
// useful for visibility when debugging this tool
// Console.ForegroundColor = ConsoleColor.Cyan;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@ public ProcessDumpUtility(IProcessHelper processHelper, IFileHelper fileHelper,
_crashDumperFactory = crashDumperFactory;
}

[SuppressMessage("Performance", "CA1822:Mark members as static", Justification = "Part of the public API")]
protected Action<object?, string?> OutputReceivedCallback => (process, data) =>
// Log all standard output message of procdump in diag files.
// Otherwise they end up coming on console in pipleine.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,6 +255,6 @@ public virtual void Save(System.Xml.XmlElement element, XmlTestStoreParameters?

XmlTestStoreParameters testIdParameters = XmlTestStoreParameters.GetParameters();
testIdParameters[TestId.IdLocationKey] = "@id";
h.SaveObject(_id, element, testIdParameters);
XmlPersistence.SaveObject(_id, element, testIdParameters);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -108,7 +108,7 @@ public void Save(System.Xml.XmlElement element, XmlTestStoreParameters? paramete
XmlPersistence helper = new();
helper.SaveSingleFields(element, this, parameters);

helper.SaveObject(_testId, element, null);
XmlPersistence.SaveObject(_testId, element, null);
helper.SaveGuid(element, "@executionId", ExecutionId);
if (ParentExecutionId != Guid.Empty)
helper.SaveGuid(element, "@parentExecutionId", ParentExecutionId);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -457,7 +457,7 @@ internal void AddResultFiles(IEnumerable<string> resultFileList)
TPDebug.Assert(!string.IsNullOrEmpty(resultFile), "'resultFile' is null or empty");
TPDebug.Assert(resultFile.Trim() == resultFile, "'resultFile' has whitespace at the ends");

_resultFiles[_trxFileHelper.MakePathRelative(resultFile, testResultsDirectory)] = null;
_resultFiles[TrxFileHelper.MakePathRelative(resultFile, testResultsDirectory)] = null;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,7 @@ public void Save(XmlElement element, XmlTestStoreParameters? parameters)
helper.SaveSimpleField(
element,
"Deployment/@runDeploymentRoot",
_trxFileHelper.MakePathRelative(_runDeploymentRoot, Path.GetDirectoryName(_runDeploymentRoot)!),
TrxFileHelper.MakePathRelative(_runDeploymentRoot, Path.GetDirectoryName(_runDeploymentRoot)!),
string.Empty);
}
else
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -101,7 +101,7 @@ internal UriDataAttachment Clone(string baseDirectory, bool useAbsoluteUri)
{
Uri uriToUse = useAbsoluteUri
? new Uri(Path.Combine(baseDirectory, Uri.OriginalString), UriKind.Absolute)
: new Uri(_trxFileHelper.MakePathRelative(Uri.OriginalString, baseDirectory), UriKind.Relative);
: new Uri(TrxFileHelper.MakePathRelative(Uri.OriginalString, baseDirectory), UriKind.Relative);
return new UriDataAttachment(Description, uriToUse, _trxFileHelper);
}

Expand Down
14 changes: 7 additions & 7 deletions src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -263,8 +263,8 @@ internal void TestResultHandler(object? sender, TestResultEventArgs e)
if (e.Result.Outcome == ObjectModel.TestOutcome.Skipped)
HandleSkippedTest(e.Result);

var testType = _converter.GetTestType(e.Result);
var executionId = _converter.GetExecutionId(e.Result);
var testType = Converter.GetTestType(e.Result);
var executionId = Converter.GetExecutionId(e.Result);

// Setting parent properties like parent result, parent test element, parent execution id.
var parentExecutionId = _converter.GetParentExecutionId(e.Result);
Expand Down Expand Up @@ -523,7 +523,7 @@ private string SetDefaultTrxFilePath()
TPDebug.Assert(IsInitialized, "Logger is not initialized");
var defaultTrxFileName = LoggerTestRun.RunConfiguration.RunDeploymentRootDirectory + ".trx";

return _trxFileHelper.GetNextIterationFileName(_testResultsDirPath, defaultTrxFileName, false);
return TrxFileHelper.GetNextIterationFileName(_testResultsDirPath, defaultTrxFileName, false);
}

/// <summary>
Expand All @@ -546,7 +546,7 @@ private void CreateTestRun()
LoggerTestRun.Started = TestRunStartTime;

// Save default test settings
string runDeploymentRoot = _trxFileHelper.ReplaceInvalidFileNameChars(LoggerTestRun.Name);
string runDeploymentRoot = TrxFileHelper.ReplaceInvalidFileNameChars(LoggerTestRun.Name);
TestRunConfiguration testrunConfig = new("default", _trxFileHelper);
testrunConfig.RunDeploymentRootDirectory = runDeploymentRoot;
LoggerTestRun.RunConfiguration = testrunConfig;
Expand Down Expand Up @@ -606,7 +606,7 @@ private ITestElement GetOrCreateTestElement(Guid executionId, Guid parentExecuti
}

TestCase testCase = rockSteadyTestResult.TestCase;
Guid testId = _converter.GetTestId(testCase);
Guid testId = Converter.GetTestId(testCase);

// Scenario for inner test case when parent test element is not present.
string? testName = testCase.DisplayName;
Expand All @@ -628,7 +628,7 @@ private ITestElement GetOrCreateTestElement(Guid executionId, Guid parentExecuti
// Create test element
if (testElement == null)
{
testElement = _converter.ToTestElement(testId, executionId, parentExecutionId, testName!, testType, testCase);
testElement = Converter.ToTestElement(testId, executionId, parentExecutionId, testName!, testType, testCase);
_testElements.TryAdd(testId, testElement);
}

Expand Down Expand Up @@ -671,7 +671,7 @@ private ITestResult CreateTestResult(Guid executionId, Guid parentExecutionId, T
{
TPDebug.Assert(IsInitialized, "Logger is not initialized");
// Create test result
TrxLoggerObjectModel.TestOutcome testOutcome = _converter.ToOutcome(rocksteadyTestResult.Outcome);
TrxLoggerObjectModel.TestOutcome testOutcome = Converter.ToOutcome(rocksteadyTestResult.Outcome);
TPDebug.Assert(LoggerTestRun != null, "LoggerTestRun is null");
var testResult = _converter.ToTestResult(testElement.Id.Id, executionId, parentExecutionId, testElement.Name,
_testResultsDirPath, testType, testElement.CategoryId, testOutcome, LoggerTestRun, rocksteadyTestResult);
Expand Down
Loading

0 comments on commit 1eb80c2

Please sign in to comment.