Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
23 commits
Select commit Hold shift + click to select a range
9f809bf
IDE0016 Null check can be simplified
Apr 4, 2021
a34277f
IDE0018 Variable declaration can be inlined
Apr 4, 2021
c13d7b6
IDE0019 Use pattern matching
Apr 4, 2021
cc75b2d
IDE0054 Use '++' operator
Apr 4, 2021
a89f2f6
IDE0029 Null check can be simplified
Apr 4, 2021
4262d2b
S1155 Use '.Any()' to test whether this 'IEnumerable<string>' is empt…
Apr 4, 2021
3079cce
S3415 Make sure these 2 arguments are in the correct order: expected …
Apr 4, 2021
e742b1d
S2971 Drop 'Where' and move the condition into the 'Count'.
Apr 4, 2021
14b5d6c
IDE0054 Use compound assignment
Apr 4, 2021
9289601
SA1512 Single-line comments must not be followed by blank line
Apr 4, 2021
6195c80
SA1611 The documentation for parameter 'runSettingsXml' is missing
Apr 4, 2021
4cf8b78
IDE0075 Conditional expression can be simplified
Apr 4, 2021
619acfb
IDE0075 Conditional expression can be simplified
Apr 4, 2021
a2c11b1
CA1507 Use nameof in place of string literal.
Apr 5, 2021
8540c30
RCS1077 Optimize LINQ method call.
Apr 5, 2021
f5621da
RCS1090 Add call to 'ConfigureAwait'.
Apr 5, 2021
e19a83d
RCS1235 Optimize 'string.Compare' call.
Apr 5, 2021
fcbc218
RCS1235 Optimize 'Debug.Assert' call.
Apr 5, 2021
a007801
RCS1197 Optimize StringBuilder.Append call.
Apr 5, 2021
e164c36
RCS1247 Fix documentation comment tag.
Apr 5, 2021
2467bd9
RCS1192 Unnecessary usage of verbatim string literal.
Apr 5, 2021
fcc6480
RCS1113 Use 'string.IsNullOrEmpty' method.
Apr 5, 2021
56fa165
Fixed `build.ps1` to accommodate the refactoring.
Haplois Apr 8, 2021
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion scripts/Build.ps1
Original file line number Diff line number Diff line change
Expand Up @@ -312,7 +312,7 @@ function Replace-InFile($File, $RegEx, $ReplaceWith) {
function Sync-PackageVersions {
$versionsRegex = '(?mi)<(TestPlatformVersion.*?)>(.*?)<\/TestPlatformVersion>'
$packageRegex = '(?mi)<package id="Microsoft\.TestPlatform([0-9a-z.]+)?" version="([0-9a-z.-]*)"'
$sourceRegex = '(?mi)(.+[a-z =]+\@\")Microsoft\.TestPlatform\.([0-9.-a-z]+)\";'
$sourceRegex = '(?mi)(.+[a-z =]+\@?\")Microsoft\.TestPlatform\.([0-9.-a-z]+)\";'

if ([String]::IsNullOrWhiteSpace($TestPlatformVersion)) {
$TestPlatformVersion = (([XML](Get-Content $TF_VERSIONS_FILE)).Project.PropertyGroup.TestPlatformVersion).InnerText
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -92,10 +92,8 @@ internal ICollection<UnitTestElement> EnumerateAssembly(string assemblyFileName,

try
{
ICollection<string> warningsFromTypeEnumerator;

typeFullName = type.FullName;
var unitTestCases = this.GetTypeEnumerator(type, assemblyFileName).Enumerate(out warningsFromTypeEnumerator);
var unitTestCases = this.GetTypeEnumerator(type, assemblyFileName).Enumerate(out var warningsFromTypeEnumerator);

if (warningsFromTypeEnumerator != null)
{
Expand Down
17 changes: 5 additions & 12 deletions src/Adapter/MSTest.CoreAdapter/Discovery/UnitTestDiscoverer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,9 +58,7 @@ internal virtual void DiscoverTestsInSource(
ITestCaseDiscoverySink discoverySink,
IDiscoveryContext discoveryContext)
{
ICollection<string> warnings;

var testElements = this.assemblyEnumeratorWrapper.GetTests(source, discoveryContext?.RunSettings, out warnings);
var testElements = this.assemblyEnumeratorWrapper.GetTests(source, discoveryContext?.RunSettings, out var warnings);

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

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

object testNavigationSession;
if (shouldCollectSourceInformation)
{
string testSource = testElement.TestMethod.DeclaringAssemblyName ?? source;

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

int minLineNumber;
string fileName;

PlatformServiceProvider.Instance.FileOperations.GetNavigationData(
testNavigationSession,
className,
methodName,
out minLineNumber,
out fileName);
out var minLineNumber,
out var fileName);

if (!string.IsNullOrEmpty(fileName))
{
Expand Down
12 changes: 5 additions & 7 deletions src/Adapter/MSTest.CoreAdapter/Execution/StackTraceHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -97,13 +97,12 @@ internal static StackTraceInformation GetStackTraceInformation(Exception ex)
bool first = true;
while (stackTraces.Count != 0)
{
result.Append(
string.Format(
result.AppendFormat(
CultureInfo.CurrentCulture,
"{0} {1}{2}",
first ? string.Empty : (Resource.UTA_EndOfInnerExceptionTrace + Environment.NewLine),
stackTraces.Pop(),
Environment.NewLine));
Environment.NewLine);
first = false;
}

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

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

result.Append(
string.Format(
result.AppendFormat(
CultureInfo.CurrentCulture,
"{0}{1}: {2}",
first ? string.Empty : " ---> ",
curException.GetType(),
msg));
msg);
first = false;
}

Expand Down
4 changes: 1 addition & 3 deletions src/Adapter/MSTest.CoreAdapter/Execution/TestAssemblyInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -173,9 +173,7 @@ public void RunAssemblyInitialize(TestContext testContext)
?? this.AssemblyInitializationException;

var outcome = UnitTestOutcome.Failed;
string errorMessage = null;
StackTraceInformation stackTraceInfo = null;
if (!realException.TryGetUnitTestAssertException(out outcome, out errorMessage, out stackTraceInfo))
if (!realException.TryGetUnitTestAssertException(out outcome, out var errorMessage, out var stackTraceInfo))
{
var exception = realException.GetType().ToString();
var message = StackTraceHelper.GetExceptionMessage(realException);
Expand Down
18 changes: 5 additions & 13 deletions src/Adapter/MSTest.CoreAdapter/Execution/TestMethodInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -95,8 +95,7 @@ public TAttributeType[] GetAttributes<TAttributeType>(bool inherit)
{
Attribute[] attributeArray = ReflectHelper.GetCustomAttributes(this.TestMethod, typeof(TAttributeType), inherit);

TAttributeType[] tAttributeArray = attributeArray as TAttributeType[];
if (tAttributeArray != null)
if (attributeArray is TAttributeType[] tAttributeArray)
{
return tAttributeArray;
}
Expand All @@ -106,8 +105,7 @@ public TAttributeType[] GetAttributes<TAttributeType>(bool inherit)
{
foreach (Attribute attribute in attributeArray)
{
TAttributeType tAttribute = attribute as TAttributeType;
if (tAttribute != null)
if (attribute is TAttributeType tAttribute)
{
tAttributeList.Add(tAttribute);
}
Expand Down Expand Up @@ -453,11 +451,9 @@ private Exception HandleMethodException(Exception ex, string className, string m

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

if (realException.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out exceptionStackTraceInfo))
if (realException.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var exceptionStackTraceInfo))
{
return new TestFailedException(outcome.ToUnitTestOutcome(), exceptionMessage, exceptionStackTraceInfo, realException);
}
Expand Down Expand Up @@ -546,11 +542,9 @@ private void RunTestCleanupMethod(object classInstance, TestResult result)
}

Exception realException = ex.GetInnerExceptionOrDefault();
string exceptionMessage = null;
StackTraceInformation realExceptionStackTraceInfo = null;

// special case UnitTestAssertException to trim off part of the stack trace
if (!realException.TryGetUnitTestAssertException(out cleanupOutcome, out exceptionMessage, out realExceptionStackTraceInfo))
if (!realException.TryGetUnitTestAssertException(out cleanupOutcome, out var exceptionMessage, out var realExceptionStackTraceInfo))
{
cleanupOutcome = UTF.UnitTestOutcome.Failed;
exceptionMessage = this.GetTestCleanUpExceptionMessage(testCleanupMethod, realException);
Expand Down Expand Up @@ -632,11 +626,9 @@ private bool RunTestInitializeMethod(object classInstance, TestResult result)
catch (Exception ex)
{
var innerException = ex.GetInnerExceptionOrDefault();
string exceptionMessage = null;
StackTraceInformation exceptionStackTraceInfo = null;
var outcome = TestTools.UnitTesting.UnitTestOutcome.Failed;

if (innerException.TryGetUnitTestAssertException(out outcome, out exceptionMessage, out exceptionStackTraceInfo))
if (innerException.TryGetUnitTestAssertException(out outcome, out var exceptionMessage, out var exceptionStackTraceInfo))
{
result.Outcome = outcome;
result.TestFailureException = new TestFailedException(
Expand Down
8 changes: 4 additions & 4 deletions src/Adapter/MSTest.CoreAdapter/Execution/TypeCache.cs
Original file line number Diff line number Diff line change
Expand Up @@ -100,12 +100,12 @@ public TestMethodInfo GetTestMethodInfo(TestMethod testMethod, ITestContext test
{
if (testMethod == null)
{
throw new ArgumentNullException("testMethod");
throw new ArgumentNullException(nameof(testMethod));
}

if (testContext == null)
{
throw new ArgumentNullException("testContext");
throw new ArgumentNullException(nameof(testContext));
}

// Get the classInfo (This may throw as GetType calls assembly.GetType(..,true);)
Expand Down Expand Up @@ -682,9 +682,9 @@ private MethodInfo GetMethodInfoUsingRuntimeMethods(TestMethod testMethod, TestC
{
// Only find methods that match the given declaring name.
testMethodInfo =
methodsInClass.Where(method => method.Name.Equals(testMethod.Name)
Array.Find(methodsInClass, method => method.Name.Equals(testMethod.Name)
&& method.DeclaringType.FullName.Equals(testMethod.DeclaringClassFullName)
&& method.HasCorrectTestMethodSignature(true)).FirstOrDefault();
&& method.HasCorrectTestMethodSignature(true));
}
else
{
Expand Down
2 changes: 1 addition & 1 deletion src/Adapter/MSTest.CoreAdapter/Execution/UnitTestRunner.cs
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ internal UnitTestResult[] RunSingleTest(TestMethod testMethod, IDictionary<strin
{
if (testMethod == null)
{
throw new ArgumentNullException("testMethod");
throw new ArgumentNullException(nameof(testMethod));
}

try
Expand Down
2 changes: 1 addition & 1 deletion src/Adapter/MSTest.CoreAdapter/MSTestDiscoverer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ internal bool AreValidSources(IEnumerable<string> sources)
source =>
PlatformServiceProvider.Instance.TestSource.ValidSourceExtensions.Any(
extension =>
string.Compare(Path.GetExtension(source), extension, StringComparison.OrdinalIgnoreCase) == 0));
string.Equals(Path.GetExtension(source), extension, StringComparison.OrdinalIgnoreCase)));
}
}
}
2 changes: 1 addition & 1 deletion src/Adapter/MSTest.CoreAdapter/MSTestSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -245,7 +245,7 @@ public static bool IsLegacyScenario(IMessageLogger logger)
/// <summary>
/// Gets the adapter specific settings from the xml.
/// </summary>
/// <param name="runsettingsXml"> The xml with the settings passed from the test platform. </param>
/// <param name="runSettingsXml"> The xml with the settings passed from the test platform. </param>
/// <param name="settingName"> The name of the adapter settings to fetch - Its either MSTest or MSTestV2 </param>
/// <returns> The settings if found. Null otherwise. </returns>
internal static MSTestSettings GetSettings(string runSettingsXml, string settingName)
Expand Down
3 changes: 1 addition & 2 deletions src/Adapter/MSTest.CoreAdapter/RunConfigurationSettings.cs
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,12 @@ private static RunConfigurationSettings ToSettings(XmlReader reader)

while (reader.NodeType == XmlNodeType.Element)
{
bool result;
string elementName = reader.Name.ToUpperInvariant();
switch (elementName)
{
case "COLLECTSOURCEINFORMATION":
{
if (bool.TryParse(reader.ReadInnerXml(), out result))
if (bool.TryParse(reader.ReadInnerXml(), out var result))
{
settings.CollectSourceInformation = result;
PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo(
Expand Down
6 changes: 2 additions & 4 deletions src/Adapter/MSTest.CoreAdapter/TestMethodFilter.cs
Original file line number Diff line number Diff line change
Expand Up @@ -65,8 +65,7 @@ internal ITestCaseFilterExpression GetFilterExpression(IDiscoveryContext context
/// <returns>a TestProperty instance.</returns>
internal TestProperty PropertyProvider(string propertyName)
{
TestProperty testProperty;
this.supportedProperties.TryGetValue(propertyName, out testProperty);
this.supportedProperties.TryGetValue(propertyName, out var testProperty);
Debug.Assert(testProperty != null, "Invalid property queried");
return testProperty;
}
Expand All @@ -81,8 +80,7 @@ internal object PropertyValueProvider(TestCase currentTest, string propertyName)
{
if (currentTest != null && propertyName != null)
{
TestProperty testProperty;
if (this.supportedProperties.TryGetValue(propertyName, out testProperty))
if (this.supportedProperties.TryGetValue(propertyName, out var testProperty))
{
// Test case might not have defined this property. In that case GetPropertyValue()
// would return default value. For filtering, if property is not defined return null.
Expand Down
8 changes: 3 additions & 5 deletions src/Adapter/PlatformServices.Desktop/AssemblyResolver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ public AssemblyResolver(IList<string> directories)
{
if (directories == null || directories.Count == 0)
{
throw new ArgumentNullException("directories");
throw new ArgumentNullException(nameof(directories));
}

this.searchDirectories = new List<string>(directories);
Expand Down Expand Up @@ -395,7 +395,7 @@ private Assembly OnResolveInternal(object senderAppDomain, ResolveEventArgs args
{
if (string.IsNullOrEmpty(args?.Name))
{
Debug.Assert(false, "AssemblyResolver.OnResolve: args.Name is null or empty.");
Debug.Fail("AssemblyResolver.OnResolve: args.Name is null or empty.");
return null;
}

Expand Down Expand Up @@ -424,9 +424,7 @@ private Assembly OnResolveInternal(object senderAppDomain, ResolveEventArgs args
lock (this.syncLock)
{
// Since both normal and reflection only cache are accessed in same block, putting only one lock should be sufficient.
Assembly assembly = null;

if (this.TryLoadFromCache(assemblyNameToLoad, isReflectionOnly, out assembly))
if (this.TryLoadFromCache(assemblyNameToLoad, isReflectionOnly, out var assembly))
{
return assembly;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ public OdbcDataConnection(string invariantProviderName, string connectionString,
// Need open connection to get Connection.Driver.
Debug.Assert(this.IsOpen(), "The connection must be open!");

this.isMSSql = this.Connection != null ? IsMSSql(this.Connection.Driver) : false;
this.isMSSql = this.Connection != null && IsMSSql(this.Connection.Driver);
}

public new OdbcCommandBuilder CommandBuilder
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ public OleDataConnection(string invariantProviderName, string connectionString,
Debug.Assert(this.IsOpen(), "The connection must be open!");

// Fill m_isMSSql.
this.isMSSql = this.Connection != null ? IsMSSql(this.Connection.Provider) : false;
this.isMSSql = this.Connection != null && IsMSSql(this.Connection.Provider);
}

public new OleDbCommandBuilder CommandBuilder
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,7 @@ public virtual TestDataConnection Create(string invariantProviderName, string co

// Most, but not all, connections are actually database based,
// here we look for special cases
TestDataConnectionFactory factory;
if (specializedProviders.TryGetValue(invariantProviderName, out factory))
if (specializedProviders.TryGetValue(invariantProviderName, out var factory))
{
Debug.Assert(factory != null, "factory");
return factory.Create(invariantProviderName, connectionString, dataFolders);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -443,7 +443,7 @@ private int FindIdentifierEnd(string text, int start)
}

// Skip the quote we just found
here = here + 1;
here++;

// If this the end?
if (here == end || text[here] != suffixChar)
Expand All @@ -453,7 +453,7 @@ private int FindIdentifierEnd(string text, int start)
}

// We have a double quote, skip the second one, then keep looking
here = here + 1;
here++;
}

// If we fall off end of loop,
Expand Down Expand Up @@ -601,9 +601,7 @@ public override List<string> GetColumns(string tableName)
WriteDiagnostics("GetColumns for {0}", tableName);
try
{
string targetSchema;
string targetName;
this.SplitTableName(tableName, out targetSchema, out targetName);
this.SplitTableName(tableName, out var targetSchema, out var targetName);

// This lets us specifically query for columns from the appropriate table name
// but assumes all databases have the same restrictions on all the column
Expand Down Expand Up @@ -728,7 +726,7 @@ private static bool IsInArray(string candidate, string[] values)
public bool IsOpen()
#pragma warning restore SA1202 // Elements must be ordered by access
{
return this.connection != null ? this.connection.State == ConnectionState.Open : false;
return this.connection != null && this.connection.State == ConnectionState.Open;
}

/// <summary>
Expand Down
Loading