Skip to content

Commit 4c980dd

Browse files
authored
Code cleanup with analysers. (#807)
Doing some code cleanup with some static analyzers. IDE0016 Null check can be simplified IDE0018 Variable declaration can be inlined
1 parent 348e322 commit 4c980dd

File tree

57 files changed

+185
-302
lines changed

Some content is hidden

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

57 files changed

+185
-302
lines changed

scripts/Build.ps1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -312,7 +312,7 @@ function Replace-InFile($File, $RegEx, $ReplaceWith) {
312312
function Sync-PackageVersions {
313313
$versionsRegex = '(?mi)<(TestPlatformVersion.*?)>(.*?)<\/TestPlatformVersion>'
314314
$packageRegex = '(?mi)<package id="Microsoft\.TestPlatform([0-9a-z.]+)?" version="([0-9a-z.-]*)"'
315-
$sourceRegex = '(?mi)(.+[a-z =]+\@\")Microsoft\.TestPlatform\.([0-9.-a-z]+)\";'
315+
$sourceRegex = '(?mi)(.+[a-z =]+\@?\")Microsoft\.TestPlatform\.([0-9.-a-z]+)\";'
316316

317317
if ([String]::IsNullOrWhiteSpace($TestPlatformVersion)) {
318318
$TestPlatformVersion = (([XML](Get-Content $TF_VERSIONS_FILE)).Project.PropertyGroup.TestPlatformVersion).InnerText

src/Adapter/MSTest.CoreAdapter/Discovery/AssemblyEnumerator.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -92,10 +92,8 @@ internal ICollection<UnitTestElement> EnumerateAssembly(string assemblyFileName,
9292

9393
try
9494
{
95-
ICollection<string> warningsFromTypeEnumerator;
96-
9795
typeFullName = type.FullName;
98-
var unitTestCases = this.GetTypeEnumerator(type, assemblyFileName).Enumerate(out warningsFromTypeEnumerator);
96+
var unitTestCases = this.GetTypeEnumerator(type, assemblyFileName).Enumerate(out var warningsFromTypeEnumerator);
9997

10098
if (warningsFromTypeEnumerator != null)
10199
{

src/Adapter/MSTest.CoreAdapter/Discovery/UnitTestDiscoverer.cs

Lines changed: 5 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -58,9 +58,7 @@ internal virtual void DiscoverTestsInSource(
5858
ITestCaseDiscoverySink discoverySink,
5959
IDiscoveryContext discoveryContext)
6060
{
61-
ICollection<string> warnings;
62-
63-
var testElements = this.assemblyEnumeratorWrapper.GetTests(source, discoveryContext?.RunSettings, out warnings);
61+
var testElements = this.assemblyEnumeratorWrapper.GetTests(source, discoveryContext?.RunSettings, out var warnings);
6462

6563
// log the warnings
6664
foreach (var warning in warnings)
@@ -100,8 +98,7 @@ internal void SendTestCases(string source, IEnumerable<UnitTestElement> testElem
10098
}
10199

102100
// Get filter expression and skip discovery in case filter expression has parsing error.
103-
bool filterHasError = false;
104-
ITestCaseFilterExpression filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, logger, out filterHasError);
101+
ITestCaseFilterExpression filterExpression = this.TestMethodFilter.GetFilterExpression(discoveryContext, logger, out var filterHasError);
105102
if (filterHasError)
106103
{
107104
return;
@@ -117,12 +114,11 @@ internal void SendTestCases(string source, IEnumerable<UnitTestElement> testElem
117114
continue;
118115
}
119116

120-
object testNavigationSession;
121117
if (shouldCollectSourceInformation)
122118
{
123119
string testSource = testElement.TestMethod.DeclaringAssemblyName ?? source;
124120

125-
if (!navigationSessions.TryGetValue(testSource, out testNavigationSession))
121+
if (!navigationSessions.TryGetValue(testSource, out var testNavigationSession))
126122
{
127123
testNavigationSession = PlatformServiceProvider.Instance.FileOperations.CreateNavigationSession(testSource);
128124
navigationSessions.Add(testSource, testNavigationSession);
@@ -144,15 +140,12 @@ internal void SendTestCases(string source, IEnumerable<UnitTestElement> testElem
144140
methodName = "MoveNext";
145141
}
146142

147-
int minLineNumber;
148-
string fileName;
149-
150143
PlatformServiceProvider.Instance.FileOperations.GetNavigationData(
151144
testNavigationSession,
152145
className,
153146
methodName,
154-
out minLineNumber,
155-
out fileName);
147+
out var minLineNumber,
148+
out var fileName);
156149

157150
if (!string.IsNullOrEmpty(fileName))
158151
{

src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs

Lines changed: 5 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -97,13 +97,12 @@ internal static StackTraceInformation GetStackTraceInformation(Exception ex)
9797
bool first = true;
9898
while (stackTraces.Count != 0)
9999
{
100-
result.Append(
101-
string.Format(
100+
result.AppendFormat(
102101
CultureInfo.CurrentCulture,
103102
"{0} {1}{2}",
104103
first ? string.Empty : (Resource.UTA_EndOfInnerExceptionTrace + Environment.NewLine),
105104
stackTraces.Pop(),
106-
Environment.NewLine));
105+
Environment.NewLine);
107106
first = false;
108107
}
109108

@@ -121,7 +120,7 @@ internal static StackTraceInformation GetStackTraceInformation(Exception ex)
121120
/// </returns>
122121
internal static string TrimStackTrace(string stackTrace)
123122
{
124-
Debug.Assert(stackTrace != null && stackTrace.Length > 0, "stack trace should be non-empty.");
123+
Debug.Assert(!string.IsNullOrEmpty(stackTrace), "stack trace should be non-empty.");
125124

126125
StringBuilder result = new StringBuilder(stackTrace.Length);
127126
string[] stackFrames = Regex.Split(stackTrace, Environment.NewLine);
@@ -179,13 +178,12 @@ internal static string GetExceptionMessage(Exception ex)
179178
msg = string.Format(CultureInfo.CurrentCulture, Resource.UTF_FailedToGetExceptionMessage, curException.GetType());
180179
}
181180

182-
result.Append(
183-
string.Format(
181+
result.AppendFormat(
184182
CultureInfo.CurrentCulture,
185183
"{0}{1}: {2}",
186184
first ? string.Empty : " ---> ",
187185
curException.GetType(),
188-
msg));
186+
msg);
189187
first = false;
190188
}
191189

src/Adapter/MSTest.CoreAdapter/Execution/TestAssemblyInfo.cs

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -173,9 +173,7 @@ public void RunAssemblyInitialize(TestContext testContext)
173173
?? this.AssemblyInitializationException;
174174

175175
var outcome = UnitTestOutcome.Failed;
176-
string errorMessage = null;
177-
StackTraceInformation stackTraceInfo = null;
178-
if (!realException.TryGetUnitTestAssertException(out outcome, out errorMessage, out stackTraceInfo))
176+
if (!realException.TryGetUnitTestAssertException(out outcome, out var errorMessage, out var stackTraceInfo))
179177
{
180178
var exception = realException.GetType().ToString();
181179
var message = StackTraceHelper.GetExceptionMessage(realException);

src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs

Lines changed: 5 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -95,8 +95,7 @@ public TAttributeType[] GetAttributes<TAttributeType>(bool inherit)
9595
{
9696
Attribute[] attributeArray = ReflectHelper.GetCustomAttributes(this.TestMethod, typeof(TAttributeType), inherit);
9797

98-
TAttributeType[] tAttributeArray = attributeArray as TAttributeType[];
99-
if (tAttributeArray != null)
98+
if (attributeArray is TAttributeType[] tAttributeArray)
10099
{
101100
return tAttributeArray;
102101
}
@@ -106,8 +105,7 @@ public TAttributeType[] GetAttributes<TAttributeType>(bool inherit)
106105
{
107106
foreach (Attribute attribute in attributeArray)
108107
{
109-
TAttributeType tAttribute = attribute as TAttributeType;
110-
if (tAttribute != null)
108+
if (attribute is TAttributeType tAttribute)
111109
{
112110
tAttributeList.Add(tAttribute);
113111
}
@@ -453,11 +451,9 @@ private Exception HandleMethodException(Exception ex, string className, string m
453451

454452
// Get the real exception thrown by the test method
455453
Exception realException = this.GetRealException(ex);
456-
string exceptionMessage = null;
457-
StackTraceInformation exceptionStackTraceInfo = null;
458454
var outcome = TestTools.UnitTesting.UnitTestOutcome.Failed;
459455

460-
if (realException.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out exceptionStackTraceInfo))
456+
if (realException.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var exceptionStackTraceInfo))
461457
{
462458
return new TestFailedException(outcome.ToUnitTestOutcome(), exceptionMessage, exceptionStackTraceInfo, realException);
463459
}
@@ -546,11 +542,9 @@ private void RunTestCleanupMethod(object classInstance, TestResult result)
546542
}
547543

548544
Exception realException = ex.GetInnerExceptionOrDefault();
549-
string exceptionMessage = null;
550-
StackTraceInformation realExceptionStackTraceInfo = null;
551545

552546
// special case UnitTestAssertException to trim off part of the stack trace
553-
if (!realException.TryGetUnitTestAssertException(out cleanupOutcome, out exceptionMessage, out realExceptionStackTraceInfo))
547+
if (!realException.TryGetUnitTestAssertException(out cleanupOutcome, out var exceptionMessage, out var realExceptionStackTraceInfo))
554548
{
555549
cleanupOutcome = UTF.UnitTestOutcome.Failed;
556550
exceptionMessage = this.GetTestCleanUpExceptionMessage(testCleanupMethod, realException);
@@ -632,11 +626,9 @@ private bool RunTestInitializeMethod(object classInstance, TestResult result)
632626
catch (Exception ex)
633627
{
634628
var innerException = ex.GetInnerExceptionOrDefault();
635-
string exceptionMessage = null;
636-
StackTraceInformation exceptionStackTraceInfo = null;
637629
var outcome = TestTools.UnitTesting.UnitTestOutcome.Failed;
638630

639-
if (innerException.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out exceptionStackTraceInfo))
631+
if (innerException.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var exceptionStackTraceInfo))
640632
{
641633
result.Outcome = outcome;
642634
result.TestFailureException = new TestFailedException(

src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -100,12 +100,12 @@ public TestMethodInfo GetTestMethodInfo(TestMethod testMethod, ITestContext test
100100
{
101101
if (testMethod == null)
102102
{
103-
throw new ArgumentNullException("testMethod");
103+
throw new ArgumentNullException(nameof(testMethod));
104104
}
105105

106106
if (testContext == null)
107107
{
108-
throw new ArgumentNullException("testContext");
108+
throw new ArgumentNullException(nameof(testContext));
109109
}
110110

111111
// Get the classInfo (This may throw as GetType calls assembly.GetType(..,true);)
@@ -682,9 +682,9 @@ private MethodInfo GetMethodInfoUsingRuntimeMethods(TestMethod testMethod, TestC
682682
{
683683
// Only find methods that match the given declaring name.
684684
testMethodInfo =
685-
methodsInClass.Where(method => method.Name.Equals(testMethod.Name)
685+
Array.Find(methodsInClass, method => method.Name.Equals(testMethod.Name)
686686
&& method.DeclaringType.FullName.Equals(testMethod.DeclaringClassFullName)
687-
&& method.HasCorrectTestMethodSignature(true)).FirstOrDefault();
687+
&& method.HasCorrectTestMethodSignature(true));
688688
}
689689
else
690690
{

src/Adapter/MSTest.CoreAdapter/Execution/UnitTestRunner.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,7 +68,7 @@ internal UnitTestResult[] RunSingleTest(TestMethod testMethod, IDictionary<strin
6868
{
6969
if (testMethod == null)
7070
{
71-
throw new ArgumentNullException("testMethod");
71+
throw new ArgumentNullException(nameof(testMethod));
7272
}
7373

7474
try

src/Adapter/MSTest.CoreAdapter/MSTestDiscoverer.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -80,7 +80,7 @@ internal bool AreValidSources(IEnumerable<string> sources)
8080
source =>
8181
PlatformServiceProvider.Instance.TestSource.ValidSourceExtensions.Any(
8282
extension =>
83-
string.Compare(Path.GetExtension(source), extension, StringComparison.OrdinalIgnoreCase) == 0));
83+
string.Equals(Path.GetExtension(source), extension, StringComparison.OrdinalIgnoreCase)));
8484
}
8585
}
8686
}

src/Adapter/MSTest.CoreAdapter/MSTestSettings.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ public static bool IsLegacyScenario(IMessageLogger logger)
245245
/// <summary>
246246
/// Gets the adapter specific settings from the xml.
247247
/// </summary>
248-
/// <param name="runsettingsXml"> The xml with the settings passed from the test platform. </param>
248+
/// <param name="runSettingsXml"> The xml with the settings passed from the test platform. </param>
249249
/// <param name="settingName"> The name of the adapter settings to fetch - Its either MSTest or MSTestV2 </param>
250250
/// <returns> The settings if found. Null otherwise. </returns>
251251
internal static MSTestSettings GetSettings(string runSettingsXml, string settingName)

0 commit comments

Comments
 (0)