Skip to content

Commit

Permalink
Code analysis with static analysers based on microsoft rules (#2831)
Browse files Browse the repository at this point in the history
Code refactoring.
  • Loading branch information
HeroMaxPower authored Mar 29, 2021
1 parent 620f420 commit 633235e
Show file tree
Hide file tree
Showing 54 changed files with 115 additions and 109 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -371,7 +371,6 @@ protected override void Dispose(bool disposing)

// Delete all the temp event log directories
this.RemoveTempEventLogDirs(this.eventLogDirectories);
GC.SuppressFinalize(this);
}

#endregion
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,12 +24,12 @@ public static partial class ManagedNameHelper
/// A <see cref="MethodBase" /> instance to get fully qualified managed type and method name.
/// </param>
/// <param name="managedTypeName">
/// When this method returns, contains the fully qualified managed type name of the <paramref name="method"/>.
/// When this method returns, contains the fully qualified managed type name of the <paramref name="method"/>.
/// This parameter is passed uninitialized; any value originally supplied in result will be overwritten.
/// The format is defined in <see href="https://github.com/microsoft/vstest-docs/blob/master/RFCs/0017-Managed-TestCase-Properties.md#managedtype-property">the RFC</see>.
/// </param>
/// <param name="managedMethodName">
/// When this method returns, contains the fully qualified managed method name of the <paramref name="method"/>.
/// When this method returns, contains the fully qualified managed method name of the <paramref name="method"/>.
/// This parameter is passed uninitialized; any value originally supplied in result will be overwritten.
/// The format is defined in <see href="https://github.com/microsoft/vstest-docs/blob/master/RFCs/0017-Managed-TestCase-Properties.md#managedmethod-property">the RFC</see>.
/// </param>
Expand All @@ -43,7 +43,7 @@ public static partial class ManagedNameHelper
/// Required functionality on <paramref name="method"/> is missing on the current platform.
/// </exception>
/// <remarks>
/// More information about <paramref name="managedTypeName"/> and <paramref name="managedMethodName"/> can be found in
/// More information about <paramref name="managedTypeName"/> and <paramref name="managedMethodName"/> can be found in
/// <see href="https://github.com/microsoft/vstest-docs/blob/master/RFCs/0017-Managed-TestCase-Properties.md">the RFC</see>.
/// </remarks>
public static void GetManagedName(MethodBase method, out string managedTypeName, out string managedMethodName)
Expand All @@ -65,7 +65,7 @@ public static void GetManagedName(MethodBase method, out string managedTypeName,
// sure we are working with the open form of the generic type.
semanticType = semanticType.GetGenericTypeDefinition();

// The method might have some of its parameters specified by the original closed type
// The method might have some of its parameters specified by the original closed type
// declaration. Here we use the method handle (basically metadata token) to create
// a new method reference using the open form of the reflected type. The intent is
// to strip all generic type parameters.
Expand Down Expand Up @@ -114,7 +114,7 @@ public static void GetManagedName(MethodBase method, out string managedTypeName,
}

/// <summary>
/// Gets the <see cref="MethodBase"/> object with the specified <paramref name="managedTypeName"/>
/// Gets the <see cref="MethodBase"/> object with the specified <paramref name="managedTypeName"/>
/// and <paramref name="managedMethodName"/> in the <paramref name="assembly"/> instance.
/// </summary>
/// <param name="assembly">
Expand All @@ -132,11 +132,11 @@ public static void GetManagedName(MethodBase method, out string managedTypeName,
/// A <see cref="MethodBase" /> object that represents specified parameters, throws if null.
/// </returns>
/// <exception cref="InvalidManagedNameException">
/// Values specified with <paramref name="managedTypeName"/> and <paramref name="managedMethodName"/>
/// Values specified with <paramref name="managedTypeName"/> and <paramref name="managedMethodName"/>
/// does not correspond to a method in the <paramref name="assembly"/> instance, or malformed.
/// </exception>
/// <remarks>
/// More information about <paramref name="managedTypeName"/> and <paramref name="managedMethodName"/> can be found in
/// More information about <paramref name="managedTypeName"/> and <paramref name="managedMethodName"/> can be found in
/// <see href="https://github.com/microsoft/vstest-docs/blob/master/RFCs/0017-Managed-TestCase-Properties.md">the RFC</see>.
/// </remarks>
public static MethodBase GetMethod(Assembly assembly, string managedTypeName, string managedMethodName)
Expand Down Expand Up @@ -335,7 +335,7 @@ private static void AppendMethodString(StringBuilder methodBuilder, string name,

private static void NormalizeAndAppendString(StringBuilder b, string name)
{
b.Append("'");
b.Append('\'');
for (int i = 0; i < name.Length; i++)
{
char c = name[i];
Expand All @@ -348,15 +348,15 @@ private static void NormalizeAndAppendString(StringBuilder b, string name)
// b.Append('0', 4 - encoded.Length);
// b.Append(encoded);

b.Append("\\");
b.Append('\\');
b.Append(c);
continue;
}
}

b.Append(c);
}
b.Append("'");
b.Append('\'');
}

private static int AppendNestedTypeName(StringBuilder b, Type type)
Expand Down Expand Up @@ -439,7 +439,7 @@ private static bool NeedsEscaping(char c, int pos)
}

if (c == '_'
|| char.IsLetterOrDigit(c) // Lu, Ll, Lt, Lm, Lo, or Nl
|| char.IsLetterOrDigit(c) // Lu, Ll, Lt, Lm, Lo, or Nl
)
{
return false;
Expand Down
4 changes: 2 additions & 2 deletions src/Microsoft.TestPlatform.Build/ArgumentEscaper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public static string HandleEscapeSequenceInArgForProcessStart(string arg)

if (needsQuotes)
{
sb.Append("\"");
sb.Append('\"');
}

for (int i = 0; i < arg.Length; ++i)
Expand Down Expand Up @@ -70,7 +70,7 @@ public static string HandleEscapeSequenceInArgForProcessStart(string arg)

if (needsQuotes)
{
sb.Append("\"");
sb.Append('\"');
}

return sb.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -267,7 +267,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete
// Raise onDiscoveredTests event if there are some tests in the last chunk.
// (We don't want to send the tests in the discovery complete event so that programming on top of
// RS client is easier i.e. user does not have to listen on discovery complete event.)
if (lastChunk != null && lastChunk.Count() > 0)
if (lastChunk != null && lastChunk.Any())
{
var discoveredTestsEvent = new DiscoveredTestsEventArgs(lastChunk);
this.LoggerManager.HandleDiscoveredTests(discoveredTestsEvent);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public static T CreateTestExtension<T>(Type extensionType)
{
if (extensionType == null)
{
throw new ArgumentNullException("extensionType");
throw new ArgumentNullException(nameof(extensionType));
}

EqtTrace.Info("TestPluginManager.CreateTestExtension: Attempting to load test extension: " + extensionType);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ internal void RaiseTestRunMessage(TestRunMessageEventArgs args)
{
if (args == null)
{
throw new ArgumentNullException("args");
throw new ArgumentNullException(nameof(args));
}

this.CheckDisposed();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -64,7 +64,7 @@ public void SendMessage(TestMessageLevel testMessageLevel, string message)
{
if (string.IsNullOrWhiteSpace(message))
{
throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, "message");
throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, nameof(message));
}

if (this.TreatTestAdapterErrorsAsWarnings
Expand Down
2 changes: 1 addition & 1 deletion src/Microsoft.TestPlatform.Common/RunSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ public ISettingsProvider GetSettings(string settingsName)
{
if (StringUtilities.IsNullOrWhiteSpace(settingsName))
{
throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, "settingsName");
throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, nameof(settingsName));
}

// Try and lookup the settings provider.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -181,7 +181,7 @@ internal LazyExtension<ISettingsProvider, ISettingsProviderCapabilities> GetSett
{
if (string.IsNullOrWhiteSpace(settingsName))
{
throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, "settingsName");
throw new ArgumentException(ObjectModelCommonResources.CannotBeNullOrEmpty, nameof(settingsName));
}

this.SettingsProvidersMap.TryGetValue(settingsName, out LazyExtension<ISettingsProvider, ISettingsProviderCapabilities> settingsProvider);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ public void Dispose()
EqtTrace.Verbose("LengthPrefixCommunicationChannel.Dispose: Dispose reader and writer.");
this.reader.Dispose();
this.writer.Dispose();
GC.SuppressFinalize(this);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ public override object ReadJson(JsonReader reader, Type objectType, object exist
if (objectType != typeof(List<KeyValuePair<TestProperty, object>>))
{
// Support only deserialization of KeyValuePair list
throw new ArgumentException(nameof(objectType));
throw new ArgumentException("the objectType was not a KeyValuePair list", nameof(objectType));
}

var propertyList = new List<KeyValuePair<TestProperty, object>>();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -470,6 +470,7 @@ public void Dispose()
}

this.communicationEndpoint.Stop();
GC.SuppressFinalize(this);
}

private void OnExecutionMessageReceived(object sender, MessageReceivedEventArgs messageReceived, ITestRunEventsHandler testRunEventsHandler)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ public void DeleteEmptyDirectroy(string dirPath)
try
{
if (Directory.Exists(dirPath)
&& Directory.EnumerateFileSystemEntries(dirPath).Count() == 0)
&& !Directory.EnumerateFileSystemEntries(dirPath).Any())
{
Directory.Delete(dirPath, true);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ internal class DataCollectionTestRunEventsHandler : ITestRunEventsHandler2
/// The proxy Data Collection Manager.
/// </param>
public DataCollectionTestRunEventsHandler(ITestRunEventsHandler baseTestRunEventsHandler, IProxyDataCollectionManager proxyDataCollectionManager, CancellationToken cancellationToken)
: this(baseTestRunEventsHandler, proxyDataCollectionManager, cancellationToken, JsonDataSerializer.Instance)
: this(baseTestRunEventsHandler, proxyDataCollectionManager, JsonDataSerializer.Instance, cancellationToken)
{
}

Expand All @@ -56,7 +56,7 @@ public DataCollectionTestRunEventsHandler(ITestRunEventsHandler baseTestRunEvent
/// <param name="dataSerializer">
/// The data Serializer.
/// </param>
public DataCollectionTestRunEventsHandler(ITestRunEventsHandler baseTestRunEventsHandler, IProxyDataCollectionManager proxyDataCollectionManager, CancellationToken cancellationToken, IDataSerializer dataSerializer)
public DataCollectionTestRunEventsHandler(ITestRunEventsHandler baseTestRunEventsHandler, IProxyDataCollectionManager proxyDataCollectionManager, IDataSerializer dataSerializer, CancellationToken cancellationToken)
{
this.proxyDataCollectionManager = proxyDataCollectionManager;
this.testRunEventsHandler = baseTestRunEventsHandler;
Expand Down Expand Up @@ -86,7 +86,7 @@ public void HandleLogMessage(TestMessageLevel level, string message)
/// </param>
public void HandleRawMessage(string rawMessage)
{
// In case of data collection, data collection attachments should be attached to raw message for ExecutionComplete
// In case of data collection, data collection attachments should be attached to raw message for ExecutionComplete
var message = this.dataSerializer.DeserializeMessage(rawMessage);

if (string.Equals(MessageType.ExecutionComplete, message.MessageType))
Expand Down Expand Up @@ -178,20 +178,20 @@ public bool AttachDebuggerToProcess(int pid)
/// </returns>
internal static ICollection<AttachmentSet> GetCombinedAttachmentSets(Collection<AttachmentSet> originalAttachmentSets, ICollection<AttachmentSet> newAttachments)
{
if (null == newAttachments || newAttachments.Count == 0)
if (newAttachments == null || newAttachments.Count == 0)
{
return originalAttachmentSets;
}

if (null == originalAttachmentSets)
if (originalAttachmentSets == null)
{
return new Collection<AttachmentSet>(newAttachments.ToList());
}

foreach (var attachmentSet in newAttachments)
{
var attSet = originalAttachmentSets.FirstOrDefault(item => Uri.Equals(item.Uri, attachmentSet.Uri));
if (null == attSet)
if (attSet == null)
{
originalAttachmentSets.Add(attachmentSet);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -143,7 +143,7 @@ private void LoadTestsFromAnExtension(string extensionAssembly, IEnumerable<stri
try
{
// Collecting Total Number of Adapters Discovered in Machine
this.requestData.MetricsCollection.Add(TelemetryDataConstants.NumberOfAdapterDiscoveredDuringDiscovery, discovererToSourcesMap.Keys.Count());
this.requestData.MetricsCollection.Add(TelemetryDataConstants.NumberOfAdapterDiscoveredDuringDiscovery, discovererToSourcesMap.Keys.Count);

var context = new DiscoveryContext { RunSettings = settings };
context.FilterExpressionWrapper = !string.IsNullOrEmpty(testCaseFilter) ? new FilterExpressionWrapper(testCaseFilter) : null;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -645,7 +645,7 @@ private void RaiseTestRunComplete(
this.requestData.MetricsCollection.Add(TelemetryDataConstants.RunState, canceled ? "Canceled" : (aborted ? "Aborted" : "Completed"));

// Collecting Number of Adapters Used to run tests.
this.requestData.MetricsCollection.Add(TelemetryDataConstants.NumberOfAdapterUsedToRunTests, this.ExecutorUrisThatRanTests.Count());
this.requestData.MetricsCollection.Add(TelemetryDataConstants.NumberOfAdapterUsedToRunTests, this.ExecutorUrisThatRanTests.Count);

if (lastChunkTestResults.Any() && this.IsTestSourceIsPackage())
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,7 @@ private void TestRunCompleteHandler(object sender, TestRunCompleteEventArgs e)

// Gets the faulty test cases if test aborted
var testCaseNames = this.GetFaultyTestCaseNames(e);
if (testCaseNames.Count() == 0)
if (!testCaseNames.Any())
{
return;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ public void ResetTimer(TimeSpan inactivityTimespan)
public void Dispose()
{
this.timer.Dispose();
GC.SuppressFinalize(this);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ public void TestResultHandler(object sender, TestResultEventArgs e)

Results.TryAdd(executionId, testResult);

// Check for parent execution id to store the test results in hierarchical way
// Check for parent execution id to store the test results in hierarchical way
if (parentExecutionId == Guid.Empty)
{
if (e.Result.Outcome == TestOutcome.Failed)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,7 +227,7 @@ public int CompareTo(TestId other)
{
if (other == null)
{
throw new ArgumentNullException("other");
throw new ArgumentNullException(nameof(other));
}

return this.id.CompareTo(other.id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ public TestType(Guid id)
{
if (id == Guid.Empty)
{
throw new ArgumentNullException("id");
throw new ArgumentNullException(nameof(id));
}

this.typeId = id;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ public override void GetObjectData(SerializationInfo info, StreamingContext cont
{
if (info == null)
{
throw new ArgumentNullException("info");
throw new ArgumentNullException(nameof(info));
}

base.GetObjectData(info, context);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -152,7 +152,7 @@ public int CompareTo(object obj)
RequestId other = obj as RequestId;
if (other == null)
{
throw new ArgumentException(string.Format(Resources.Common_ObjectMustBeOfType, new object[] { typeof(RequestId).Name }), "obj");
throw new ArgumentException(string.Format(Resources.Common_ObjectMustBeOfType, new object[] { typeof(RequestId).Name }), nameof(obj));
}

return Id.CompareTo(other.Id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public DefaultExecutorUriAttribute(string executorUri)
{
if (string.IsNullOrWhiteSpace(executorUri))
{
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, "executorUri");
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(executorUri));
}

ExecutorUri = executorUri;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ public ExtensionUriAttribute(string extensionUri)
{
if (string.IsNullOrWhiteSpace(extensionUri))
{
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, "extensionUri");
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(extensionUri));
}

ExtensionUri = extensionUri;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public FileExtensionAttribute(string fileExtension)
{
if (string.IsNullOrWhiteSpace(fileExtension))
{
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, "fileExtension");
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(fileExtension));
}

FileExtension = fileExtension;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public FriendlyNameAttribute(string friendlyName)
{
if (string.IsNullOrWhiteSpace(friendlyName))
{
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, "friendlyName");
throw new ArgumentException(CommonResources.CannotBeNullOrEmpty, nameof(friendlyName));
}

FriendlyName = friendlyName;
Expand Down
Loading

0 comments on commit 633235e

Please sign in to comment.