Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Enable and fix performance analyzers #1223

Merged
merged 6 commits into from
Sep 7, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
36 changes: 24 additions & 12 deletions .editorconfig
Original file line number Diff line number Diff line change
Expand Up @@ -150,6 +150,30 @@ dotnet_style_null_propagation = true
# IDE0034: Simplify 'default' expression
dotnet_diagnostic.IDE0034.severity = warning

# IDE0090: Use 'new(...)'
dotnet_diagnostic.IDE0090.severity = warning

# IDE0150: Prefer 'null' check over type check
dotnet_diagnostic.IDE0150.severity = warning

# IDE0028: Simplify collection initialization
dotnet_diagnostic.IDE0028.severity = warning

# IDE0017: Simplify object initialization
dotnet_diagnostic.IDE0017.severity = warning

# CA1829: Use Length/Count property instead of Count() when available
dotnet_diagnostic.CA1829.severity = warning

# CA1840: Use 'Environment.CurrentManagedThreadId'
dotnet_diagnostic.CA1840.severity = warning

# CA1825: Avoid zero-length array allocations
dotnet_diagnostic.CA1825.severity = warning

# CA1854: Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method
dotnet_diagnostic.CA1854.severity = warning

#### Naming styles ####

# Naming rules (define naming rule using dotnet_naming_rule.<rule_name>.<option>)
Expand Down Expand Up @@ -229,15 +253,3 @@ dotnet_naming_style.s_underscore_camel_case.required_prefix = s_
dotnet_naming_style.s_underscore_camel_case.required_suffix =
dotnet_naming_style.s_underscore_camel_case.word_separator =
dotnet_naming_style.s_underscore_camel_case.capitalization = camel_case

# IDE0090: Use 'new(...)'
dotnet_diagnostic.IDE0090.severity = warning

# IDE0150: Prefer 'null' check over type check
dotnet_diagnostic.IDE0150.severity = warning

# IDE0028: Simplify collection initialization
dotnet_diagnostic.IDE0028.severity = warning

# IDE0017: Simplify object initialization
dotnet_diagnostic.IDE0017.severity = warning
11 changes: 10 additions & 1 deletion Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,17 @@
<Import Project="scripts\build\TestFx.props" />
<Import Project="eng\TFMConfiguration.props" />

<!-- Language configuration -->
<PropertyGroup>
<LangVersion>Latest</LangVersion>
<!-- default to allowing all language features -->
<LangVersion>preview</LangVersion>
<!-- enable strict mode for Roslyn compiler -->
<TreatWarningsAsErrors>True</TreatWarningsAsErrors>
<CodeAnalysisTreatWarningsAsErrors>true</CodeAnalysisTreatWarningsAsErrors>
<EnforceCodeStyleInBuild>true</EnforceCodeStyleInBuild>
<EnableNETAnalyzers>true</EnableNETAnalyzers>
<!-- default to max warnlevel -->
<AnalysisLevel>preview</AnalysisLevel>
</PropertyGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -370,10 +370,9 @@ private bool ProcessTestDataSourceTests(UnitTestElement test, MethodInfo methodI
discoveredTest.DisplayName = dataSource.GetDisplayName(methodInfo, d) ?? discoveredTest.DisplayName;

// if we have a duplicate test name don't expand the test, bail out.
if (discoveredTests.ContainsKey(discoveredTest.DisplayName))
if (discoveredTests.TryGetValue(discoveredTest.DisplayName, out var firstTestSeen))
{
var firstSeen = discoveredIndex[discoveredTest.DisplayName];
var warning = string.Format(CultureInfo.CurrentCulture, Resource.CannotExpandIDataSourceAttribute_DuplicateDisplayName, firstSeen, index, discoveredTest.DisplayName);
var warning = string.Format(CultureInfo.CurrentCulture, Resource.CannotExpandIDataSourceAttribute_DuplicateDisplayName, firstTestSeen, index, discoveredTest.DisplayName);
warning = string.Format(CultureInfo.CurrentUICulture, Resource.CannotExpandIDataSourceAttribute, test.TestMethod.ManagedTypeName, test.TestMethod.ManagedMethodName, warning);
PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning($"DynamicDataEnumarator: {warning}");

Expand All @@ -388,7 +387,7 @@ private bool ProcessTestDataSourceTests(UnitTestElement test, MethodInfo methodI
}
catch (SerializationException)
{
var firstSeen = discoveredIndex[discoveredTest.DisplayName];
var firstIndexSeen = discoveredIndex[discoveredTest.DisplayName];
var warning = string.Format(CultureInfo.CurrentCulture, Resource.CannotExpandIDataSourceAttribute_CannotSerialize, index, discoveredTest.DisplayName);
warning = string.Format(CultureInfo.CurrentUICulture, Resource.CannotExpandIDataSourceAttribute, test.TestMethod.ManagedTypeName, test.TestMethod.ManagedMethodName, warning);
PlatformServiceProvider.Instance.AdapterTraceLogger.LogWarning($"DynamicDataEnumarator: {warning}");
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -225,7 +225,7 @@ private void ExecuteTestsInSource(IEnumerable<TestCase> tests, IRunContext runCo
PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo("Created unit-test runner {0}", source);

// Default test set is filtered tests based on user provided filter criteria
ICollection<TestCase> testsToRun = new TestCase[0];
ICollection<TestCase> testsToRun = Array.Empty<TestCase>();
var filterExpression = TestMethodFilter.GetFilterExpression(runContext, frameworkHandle, out var filterHasError);
if (filterHasError)
{
Expand Down
2 changes: 1 addition & 1 deletion src/Adapter/MSTest.TestAdapter/Execution/TestMethodInfo.cs
Original file line number Diff line number Diff line change
Expand Up @@ -770,6 +770,6 @@ void executeAsyncAction()

private static class EmptyHolder<T>
{
internal static readonly T[] Array = new T[0];
internal static readonly T[] Array = System.Array.Empty<T>();
}
}
2 changes: 2 additions & 0 deletions src/Adapter/MSTest.TestAdapter/Helpers/DictionaryHelper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ public static IDictionary<TKey, TValue> ConcatWithOverwrites<TKey, TValue>(
var overwrites = new List<TKey>();
foreach (var k in overwrite.Keys)
{
#pragma warning disable CA1854 // Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method | False-positive
if (destination.ContainsKey(k))
{
PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo("DictionaryHelper.ConcatWithOverwrites: The {0} already contains key {1}. Overwriting it with value from {2}.", sourceFriendlyName, k, overwriteFriendlyName);
Expand All @@ -51,6 +52,7 @@ public static IDictionary<TKey, TValue> ConcatWithOverwrites<TKey, TValue>(
PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo("DictionaryHelper.ConcatWithOverwrites: The {0} does not contain key {1}. Adding it from {2}.", sourceFriendlyName, k, overwriteFriendlyName);
destination.Add(k, overwrite[k]);
}
#pragma warning restore CA1854 // Prefer the 'IDictionary.TryGetValue(TKey, out TValue)' method
}

PlatformServiceProvider.Instance.AdapterTraceLogger.LogInfo("DictionaryHelper.ConcatWithOverwrites: Merging done: Resulting dictionary has keys {0}, overwrites {1}.", string.Join(", ", destination.Keys), string.Join(", ", overwrites));
Expand Down
4 changes: 2 additions & 2 deletions src/Adapter/PlatformServices/Deployment/AssemblyLoadWorker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -59,7 +59,7 @@ public string[] GetFullPathToDependentAssemblies(string assemblyPath, out IList<
EqtTrace.Error(ex);

warnings.Add(ex.Message);
return new string[0]; // Otherwise just return no dependencies.
return Array.Empty<string>(); // Otherwise just return no dependencies.
}

Debug.Assert(assembly != null, "assembly");
Expand Down Expand Up @@ -168,7 +168,7 @@ private void ProcessChildren(Assembly assembly, IList<string> result, ISet<strin
}

// Take care of .netmodule's.
var modules = new Module[0];
var modules = Array.Empty<Module>();
try
{
EqtTrace.Verbose($"AssemblyLoadWorker.GetFullPathToDependentAssemblies: Getting modules of {assembly.FullName}.");
Expand Down
5 changes: 3 additions & 2 deletions src/Adapter/PlatformServices/Services/TestDataSource.cs
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,10 @@ IEnumerable<object> ITestDataSource.GetData(UTF.ITestMethod testMethodInfo, ITes
{
GetConnectionProperties(testMethodInfo.GetAttributes<UTF.DataSourceAttribute>(false)[0], out providerNameInvariant, out connectionString, out tableName, out dataAccessMethod);
}
catch (Exception ex)
catch
{
throw ex;
// REVIEW ME: @Haplois, was there any good reason to mess up stack trace?
throw;
}

try
Expand Down
2 changes: 1 addition & 1 deletion src/TestFramework/MSTest.Core/Assertions/StringAssert.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting;
/// </summary>
public sealed class StringAssert
{
private static readonly object[] Empty = new object[0];
private static readonly object[] Empty = Array.Empty<object>();

private static StringAssert s_that;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public class DataRowAttribute : Attribute, ITestDataSource
/// </summary>
public DataRowAttribute()
{
Data = new object[0];
Data = Array.Empty<object>();
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ private static void ContainsExpectedTestsWithOutcome(IEnumerable<TestResult> out
{
if (matchCount)
{
var expectedCount = expectedTests.Count();
var expectedCount = expectedTests.Length;
AssertOutcomeCount(outcomedTests, expectedOutcome, expectedCount);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ public void DefaultConstructorSetsEmptyArrayPassed()
{
var dataRow = new DataRowAttribute();

CollectionAssert.AreEqual(new object[] { }, dataRow.Data);
CollectionAssert.AreEqual(System.Array.Empty<object>(), dataRow.Data);
}

[TestMethod]
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -310,7 +310,7 @@ public static IEnumerable<object[]> EmptyProperty
{
get
{
return new object[][] { };
return Array.Empty<object[]>();
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -405,13 +405,13 @@ private static Mock<TestableAssembly> CreateMockTestableAssembly()
.Setup(a => a.GetCustomAttributes(
typeof(FrameworkV2::Microsoft.VisualStudio.TestTools.UnitTesting.DiscoverInternalsAttribute),
true))
.Returns(new Attribute[0]);
.Returns(Array.Empty<Attribute>());

mockAssembly
.Setup(a => a.GetCustomAttributes(
typeof(FrameworkV2::Microsoft.VisualStudio.TestTools.UnitTesting.TestDataSourceDiscoveryAttribute),
true))
.Returns(new Attribute[0]);
.Returns(Array.Empty<Attribute>());

return mockAssembly;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ public void GetTestFromMethodShouldSetWorkItemIdsToNullIfNotAny()
SetupTestClassAndTestMethods(isValidTestClass: true, isValidTestMethod: true, isMethodFromSameAssembly: true);
TypeEnumerator typeEnumerator = GetTypeEnumeratorInstance(typeof(DummyTestClass), "DummyAssemblyName");
var methodInfo = typeof(DummyTestClass).GetMethod("MethodWithVoidReturnType");
_mockReflectHelper.Setup(rh => rh.GetCustomAttributes(methodInfo, typeof(UTF.WorkItemAttribute))).Returns(new Attribute[0]);
_mockReflectHelper.Setup(rh => rh.GetCustomAttributes(methodInfo, typeof(UTF.WorkItemAttribute))).Returns(Array.Empty<Attribute>());

var testElement = typeEnumerator.GetTestFromMethod(methodInfo, true, _warnings);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -972,15 +972,15 @@ public void TestMethod1()
{
// Ensures stability.. for the thread to be not used for another test method
System.Threading.Thread.Sleep(2000);
ThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
ThreadIds.Add(Environment.CurrentManagedThreadId);
}

[UTF.TestMethod]
public void TestMethod2()
{
// Ensures stability.. for the thread to be not used for another test method
System.Threading.Thread.Sleep(2000);
ThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
ThreadIds.Add(Environment.CurrentManagedThreadId);
}
}

Expand All @@ -999,15 +999,15 @@ public void TestMethod1()
{
// Ensures stability.. for the thread to be not used for another test method
System.Threading.Thread.Sleep(2000);
ThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
ThreadIds.Add(Environment.CurrentManagedThreadId);
}

[UTF.TestMethod]
public void TestMethod2()
{
// Ensures stability.. for the thread to be not used for another test method
System.Threading.Thread.Sleep(2000);
ThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
ThreadIds.Add(Environment.CurrentManagedThreadId);
}
}

Expand All @@ -1026,7 +1026,7 @@ public void TestMethod1()
{
// Ensures stability.. for the thread to be not used for another test method
Thread.Sleep(2000);
ThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
ThreadIds.Add(Environment.CurrentManagedThreadId);
}
}

Expand Down Expand Up @@ -1058,7 +1058,7 @@ public void TestMethod1()
{
// Ensures stability.. for the thread to be not used for another test method
Thread.Sleep(2000);
ParallelizableTestsThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
ParallelizableTestsThreadIds.Add(Environment.CurrentManagedThreadId);
ThreadApartmentStates.Add(Thread.CurrentThread.GetApartmentState());

LastParallelizableTestRun = DateTime.Now;
Expand All @@ -1069,7 +1069,7 @@ public void TestMethod2()
{
// Ensures stability.. for the thread to be not used for another test method
Thread.Sleep(2000);
ParallelizableTestsThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
ParallelizableTestsThreadIds.Add(Environment.CurrentManagedThreadId);
ThreadApartmentStates.Add(Thread.CurrentThread.GetApartmentState());

LastParallelizableTestRun = DateTime.Now;
Expand All @@ -1084,7 +1084,7 @@ public void TestMethod3()
FirstUnParallelizableTestRun = DateTime.Now;
}

UnParallelizableTestsThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
UnParallelizableTestsThreadIds.Add(Environment.CurrentManagedThreadId);
ThreadApartmentStates.Add(Thread.CurrentThread.GetApartmentState());
}

Expand All @@ -1097,7 +1097,7 @@ public void TestMethod4()
FirstUnParallelizableTestRun = DateTime.Now;
}

UnParallelizableTestsThreadIds.Add(Thread.CurrentThread.ManagedThreadId);
UnParallelizableTestsThreadIds.Add(Environment.CurrentManagedThreadId);
ThreadApartmentStates.Add(Thread.CurrentThread.GetApartmentState());
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1398,7 +1398,7 @@ public void ResolveArgumentsShouldReturnEmptyParamsWithNoneProvided()
_testMethodOptions);

object[] arguments = new object[] { 1 };
object[] expectedArguments = new object[] { 1, new string[] { } };
object[] expectedArguments = new object[] { 1, Array.Empty<string>() };
var resolvedArguments = method.ResolveArguments(arguments);

Assert.AreEqual(2, resolvedArguments.Length);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1183,7 +1183,7 @@ public void GetTestMethodInfoShouldNotAddDuplicateTestPropertiesToTestContext()
public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedTestClasses()
{
var type = typeof(DerivedTestClass);
var methodInfo = type.GetRuntimeMethod("DummyTestMethod", new Type[] { });
var methodInfo = type.GetRuntimeMethod("DummyTestMethod", Array.Empty<Type>());
var testMethod = new TestMethod(methodInfo.Name, type.FullName, "A", isAsync: false);

var testMethodInfo = _typeCache.GetTestMethodInfo(
Expand All @@ -1201,7 +1201,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedTestClasses()
public void GetTestMethodInfoShouldReturnTestMethodInfoForDerivedClassMethodOverloadByDefault()
{
var type = typeof(DerivedTestClass);
var methodInfo = type.GetRuntimeMethod("OverloadedTestMethod", new Type[] { });
var methodInfo = type.GetRuntimeMethod("OverloadedTestMethod", Array.Empty<Type>());
var testMethod = new TestMethod(methodInfo.Name, type.FullName, "A", isAsync: false);

var testMethodInfo = _typeCache.GetTestMethodInfo(
Expand All @@ -1220,7 +1220,7 @@ public void GetTestMethodInfoShouldReturnTestMethodInfoForDeclaringTypeMethodOve
{
var baseType = typeof(BaseTestClass);
var type = typeof(DerivedTestClass);
var methodInfo = baseType.GetRuntimeMethod("OverloadedTestMethod", new Type[] { });
var methodInfo = baseType.GetRuntimeMethod("OverloadedTestMethod", Array.Empty<Type>());
var testMethod = new TestMethod(methodInfo.Name, type.FullName, "A", isAsync: false)
{
DeclaringClassFullName = baseType.FullName
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public void ToTestCaseShouldSetTestCategoryIfPresent()

Assert.IsNull(testCase.GetPropertyValue(Constants.TestCategoryProperty));

_unitTestElement.TestCategory = new string[] { };
_unitTestElement.TestCategory = Array.Empty<string>();
testCase = _unitTestElement.ToTestCase();

Assert.IsNull(testCase.GetPropertyValue(Constants.TestCategoryProperty));
Expand Down Expand Up @@ -195,7 +195,7 @@ public void ToTestCaseShouldSetDeploymentItemPropertyIfPresent()

Assert.IsNull(testCase.GetPropertyValue(Constants.DeploymentItemsProperty));

_unitTestElement.DeploymentItems = new KeyValuePair<string, string>[] { };
_unitTestElement.DeploymentItems = Array.Empty<KeyValuePair<string, string>>();
testCase = _unitTestElement.ToTestCase();

Assert.IsNull(testCase.GetPropertyValue(Constants.DeploymentItemsProperty));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ internal override Attribute[] GetCustomAttributeForAssembly(MemberInfo memberInf
{
var hashcode = MemberTypes.All.GetHashCode() + type.FullName.GetHashCode();

if (_customAttributes.ContainsKey(hashcode))
if (_customAttributes.TryGetValue(hashcode, out Attribute[] value))
{
return _customAttributes[hashcode];
return value;
}
else
{
Expand All @@ -59,9 +59,9 @@ internal override Attribute[] GetCustomAttributes(MemberInfo memberInfo, Type ty
{
var hashcode = memberInfo.MemberType.GetHashCode() + type.FullName.GetHashCode();

if (_customAttributes.ContainsKey(hashcode))
if (_customAttributes.TryGetValue(hashcode, out Attribute[] value))
{
return _customAttributes[hashcode];
return value;
}
else
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,7 @@ public override AssemblyName[] GetReferencedAssemblies()
return GetReferencedAssembliesSetter.Invoke();
}

return new AssemblyName[] { };
return Array.Empty<AssemblyName>();
}

public string Name
Expand Down Expand Up @@ -177,7 +177,7 @@ public override string Location

public override Module[] GetModules(bool getResourceModules)
{
return new Module[] { };
return Array.Empty<Module>();
}
}

Expand Down
Loading