From 84db69b18789f9ff0fded223998b1f601dd34899 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Tue, 22 Mar 2022 20:50:18 +0100 Subject: [PATCH 1/2] Enable nullable on extension and utilities tests --- .../CommandLineArgumentsHelperTests.cs | 2 - .../Helpers/DotnetHostHelperTest.cs | 55 ++- .../Helpers/EnvironmentHelperTests.cs | 2 - .../Helpers/FileHelperTests.cs | 2 - .../Output/OutputExtensionsTests.cs | 2 - .../Tracing/EqtTraceTests.cs | 25 +- .../Utilities/JobQueueTests.cs | 6 +- .../Utilities/TimeSpanParserTests.cs | 2 - .../BlameCollectorTests.cs | 35 +- .../BlameLoggerTests.cs | 8 +- .../InactivityTimerTests.cs | 2 - .../ProcDumpArgsBuilderTests.cs | 2 - .../ProcessDumpUtilityTests.cs | 2 - .../XmlReaderWriterTests.cs | 2 - .../HtmlLoggerTests.cs | 26 +- .../TrxLoggerTests.cs | 75 ++-- .../Utility/ConverterTests.cs | 6 +- .../Utility/TrxFileHelperTests.cs | 2 - .../XmlPersistenceTests.cs | 2 - .../PerfInstrumentation/Constants.cs | 2 - .../PerfInstrumentation/PerfAnalyzer.cs | 6 +- .../PerformanceTestBase.cs | 2 - .../PerfInstrumentation/TestPlatformTask.cs | 2 - .../AssemblyUtility.cs | 2 - .../FileAssert.cs | 2 - .../IntegrationTestBase.cs | 35 +- .../IntegrationTestEnvironment.cs | 52 +-- .../TestPluginCacheHelper.cs | 8 +- .../TestableTestPluginCache.cs | 5 +- .../ClientUtilitiesTests.cs | 6 +- ...CodeCoverageDataAttachmentsHandlerTests.cs | 8 +- .../CodeCoverageRunSettingsProcessorTests.cs | 28 +- .../CommandLineUtilitiesTest.cs | 4 +- .../InferRunSettingsHelperTests.cs | 394 +++++++++--------- .../MSTestSettingsUtilitiesTests.cs | 6 +- .../StringUtilitiesTests.cs | 2 - .../XmlUtilitiesTests.cs | 4 +- 37 files changed, 360 insertions(+), 466 deletions(-) diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs index 24b23bd32a..240d4d8c03 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.CoreUtilities.UnitTests.Helpers; [TestClass] diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/DotnetHostHelperTest.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/DotnetHostHelperTest.cs index bf5894f611..2507049221 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/DotnetHostHelperTest.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/DotnetHostHelperTest.cs @@ -15,12 +15,10 @@ using Moq; -#nullable disable - namespace Microsoft.TestPlatform.CoreUtilities.UnitTests.Helpers; [TestClass] -public class DotnetHostHelperTest : IDisposable +public sealed class DotnetHostHelperTest : IDisposable { private readonly Mock _fileHelper = new(); private readonly Mock _processHelper = new(); @@ -71,13 +69,11 @@ public void GetDotnetPathByArchitecture_SameArchitecture() // Arrange string dotnetRootX64 = _muxerHelper.RenameMuxerAndReturnPath(platformSystem, PlatformArchitecture.X64); string dotnetRootArm64 = _muxerHelper.RenameMuxerAndReturnPath(platformSystem, PlatformArchitecture.ARM64); - string dotnetRootX86 = null; - if (platformSystem == PlatformOperatingSystem.Windows) - { - dotnetRootX86 = _muxerHelper.RenameMuxerAndReturnPath(platformSystem, PlatformArchitecture.X86); - } + string? dotnetRootX86 = platformSystem == PlatformOperatingSystem.Windows + ? _muxerHelper.RenameMuxerAndReturnPath(platformSystem, PlatformArchitecture.X86) + : null; string dotnetRoot = _muxerHelper.RenameMuxerAndReturnPath(platformSystem, targetArchitecture); - Dictionary envVars = new() + Dictionary envVars = new() { { "DOTNET_ROOT_X64", dotnetRootX64 }, { "DOTNET_ROOT_ARM64", dotnetRootArm64 }, @@ -87,13 +83,13 @@ public void GetDotnetPathByArchitecture_SameArchitecture() _environmentHelper.SetupGet(x => x.Architecture).Returns(platformArchitecture); _environmentHelper.SetupGet(x => x.OperatingSystem).Returns(platformSystem); - _environmentVariableHelper.Setup(x => x.GetEnvironmentVariable(envVar)).Returns(Path.GetDirectoryName(envVars[envVar])); + _environmentVariableHelper.Setup(x => x.GetEnvironmentVariable(envVar)).Returns(Path.GetDirectoryName(envVars[envVar])!); _environmentVariableHelper.Setup(x => x.GetEnvironmentVariable("ProgramFiles")).Returns("notfound"); _fileHelper.Setup(x => x.DirectoryExists(Path.GetDirectoryName(envVars[envVar]))).Returns(true); _fileHelper.Setup(x => x.Exists(envVars[envVar])).Returns(true); if (found) { - _fileHelper.Setup(x => x.GetStream(envVars[envVar], FileMode.Open, FileAccess.Read)).Returns(File.OpenRead(envVars[envVar])); + _fileHelper.Setup(x => x.GetStream(envVars[envVar], FileMode.Open, FileAccess.Read)).Returns(File.OpenRead(envVars[envVar]!)); } // Act & Assert @@ -122,8 +118,8 @@ public void GetDotnetPathByArchitecture_EnvVars_DirectoryNotExists_TryNext(strin _environmentHelper.SetupGet(x => x.Architecture).Returns(platformArchitecture); _environmentHelper.SetupGet(x => x.OperatingSystem).Returns(PlatformOperatingSystem.Windows); - _environmentVariableHelper.Setup(x => x.GetEnvironmentVariable(notExists)).Returns(Path.GetDirectoryName(envVars[notExists])); - _environmentVariableHelper.Setup(x => x.GetEnvironmentVariable(nextEnv)).Returns(Path.GetDirectoryName(envVars[nextEnv])); + _environmentVariableHelper.Setup(x => x.GetEnvironmentVariable(notExists)).Returns(Path.GetDirectoryName(envVars[notExists])!); + _environmentVariableHelper.Setup(x => x.GetEnvironmentVariable(nextEnv)).Returns(Path.GetDirectoryName(envVars[nextEnv])!); _fileHelper.Setup(x => x.DirectoryExists(Path.GetDirectoryName(envVars[nextEnv]))).Returns(true); _fileHelper.Setup(x => x.Exists(envVars[nextEnv])).Returns(true); _fileHelper.Setup(x => x.GetStream(envVars[nextEnv], FileMode.Open, FileAccess.Read)).Returns(File.OpenRead(envVars[nextEnv])); @@ -146,7 +142,7 @@ public void GetDotnetPathByArchitecture_GlobalInstallation_Windows(PlatformArchi Mock nativeArchSubKey = new(); installedVersionKey.Setup(x => x.OpenSubKey(It.IsAny())).Returns(architectureSubKey.Object); architectureSubKey.Setup(x => x.OpenSubKey(It.IsAny())).Returns(nativeArchSubKey.Object); - nativeArchSubKey.Setup(x => x.GetValue(It.IsAny())).Returns(Path.GetDirectoryName(dotnetMuxer)); + nativeArchSubKey.Setup(x => x.GetValue(It.IsAny())).Returns(Path.GetDirectoryName(dotnetMuxer)!); _windowsRegistrytHelper.Setup(x => x.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)).Returns(installedVersionKey.Object); _fileHelper.Setup(x => x.Exists(dotnetMuxer)).Returns(true); _fileHelper.Setup(x => x.GetStream(dotnetMuxer, FileMode.Open, FileAccess.Read)).Returns(File.OpenRead(dotnetMuxer)); @@ -168,13 +164,17 @@ public void GetDotnetPathByArchitecture_GlobalInstallation_NullSubkeys(bool null Mock installedVersionKey = new(); Mock architectureSubKey = new(); Mock nativeArchSubKey = new(); - installedVersionKey.Setup(x => x.OpenSubKey(It.IsAny())).Returns(nullArchitecture ? null : architectureSubKey.Object); - architectureSubKey.Setup(x => x.OpenSubKey(It.IsAny())).Returns(nullNative ? null : nativeArchSubKey.Object); - nativeArchSubKey.Setup(x => x.GetValue(It.IsAny())).Returns(nullInstallLocation ? null : ""); - _windowsRegistrytHelper.Setup(x => x.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)).Returns(nullInstalledVersion ? null : installedVersionKey.Object); + installedVersionKey.Setup(x => x.OpenSubKey(It.IsAny())) + .Returns(nullArchitecture ? null! : architectureSubKey.Object); + architectureSubKey.Setup(x => x.OpenSubKey(It.IsAny())) + .Returns(nullNative ? null! : nativeArchSubKey.Object); + nativeArchSubKey.Setup(x => x.GetValue(It.IsAny())) + .Returns(nullInstallLocation ? null! : ""); + _windowsRegistrytHelper.Setup(x => x.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) + .Returns(nullInstalledVersion ? null! : installedVersionKey.Object); _environmentVariableHelper.Setup(x => x.GetEnvironmentVariable("ProgramFiles")).Returns("notfound"); - //Act & Assert + // Act & Assert var dotnetHostHelper = new DotnetHostHelper(_fileHelper.Object, _environmentHelper.Object, _windowsRegistrytHelper.Object, _environmentVariableHelper.Object, _processHelper.Object); Assert.IsFalse(dotnetHostHelper.TryGetDotnetPathByArchitecture(PlatformArchitecture.X64, out string muxerPath)); } @@ -198,7 +198,7 @@ public void GetDotnetPathByArchitecture_GlobalInstallation_Unix(PlatformArchitec _environmentHelper.SetupGet(x => x.OperatingSystem).Returns(os); _fileHelper.Setup(x => x.Exists(installLocation)).Returns(true); _fileHelper.Setup(x => x.Exists(dotnetMuxer)).Returns(true); - _fileHelper.Setup(x => x.GetStream(installLocation, FileMode.Open, FileAccess.Read)).Returns(new MemoryStream(Encoding.UTF8.GetBytes(Path.GetDirectoryName(dotnetMuxer)))); + _fileHelper.Setup(x => x.GetStream(installLocation, FileMode.Open, FileAccess.Read)).Returns(new MemoryStream(Encoding.UTF8.GetBytes(Path.GetDirectoryName(dotnetMuxer)!))); if (found) { _fileHelper.Setup(x => x.GetStream(dotnetMuxer, FileMode.Open, FileAccess.Read)).Returns(File.OpenRead(dotnetMuxer)); @@ -226,7 +226,7 @@ public void GetDotnetPathByArchitecture_DefaultInstallation_Win(PlatformArchitec if (found) { _fileHelper.Setup(x => x.Exists(dotnetMuxer)).Returns(true); - _fileHelper.Setup(x => x.GetStream(dotnetMuxer, FileMode.Open, FileAccess.Read)).Returns(new MemoryStream(Encoding.UTF8.GetBytes(Path.GetDirectoryName(dotnetMuxer)))); + _fileHelper.Setup(x => x.GetStream(dotnetMuxer, FileMode.Open, FileAccess.Read)).Returns(new MemoryStream(Encoding.UTF8.GetBytes(Path.GetDirectoryName(dotnetMuxer)!))); _fileHelper.Setup(x => x.GetStream(dotnetMuxer, FileMode.Open, FileAccess.Read)).Returns(File.OpenRead(dotnetMuxer)); } @@ -254,7 +254,7 @@ public void GetDotnetPathByArchitecture_DefaultInstallation_Unix(PlatformArchite _environmentHelper.Setup(x => x.Architecture).Returns(platformArchitecture); string expectedMuxerPath = Path.Combine(expectedFolder, "dotnet"); _fileHelper.Setup(x => x.Exists(expectedMuxerPath)).Returns(true); - _fileHelper.Setup(x => x.GetStream(expectedMuxerPath, FileMode.Open, FileAccess.Read)).Returns(new MemoryStream(Encoding.UTF8.GetBytes(Path.GetDirectoryName(dotnetMuxer)))); + _fileHelper.Setup(x => x.GetStream(expectedMuxerPath, FileMode.Open, FileAccess.Read)).Returns(new MemoryStream(Encoding.UTF8.GetBytes(Path.GetDirectoryName(dotnetMuxer)!))); if (found) { _fileHelper.Setup(x => x.GetStream(expectedMuxerPath, FileMode.Open, FileAccess.Read)).Returns(File.OpenRead(dotnetMuxer)); @@ -268,8 +268,7 @@ public void GetDotnetPathByArchitecture_DefaultInstallation_Unix(PlatformArchite public void Dispose() => _muxerHelper.Dispose(); - - class MockMuxerHelper : IDisposable + private class MockMuxerHelper : IDisposable { private static readonly string DotnetMuxerWinX86 = "TestAssets/dotnetWinX86.exe"; private static readonly string DotnetMuxerWinX64 = "TestAssets/dotnetWinX64.exe"; @@ -296,7 +295,7 @@ public string RenameMuxerAndReturnPath(PlatformOperatingSystem platform, Platfor case PlatformOperatingSystem.Windows: { muxerPath = Path.Combine(tmpDirectory, Guid.NewGuid().ToString("N"), subfolder, "dotnet.exe"); - Directory.CreateDirectory(Path.GetDirectoryName(muxerPath)); + Directory.CreateDirectory(Path.GetDirectoryName(muxerPath)!); if (architecture == PlatformArchitecture.ARM64) { File.Copy(DotnetMuxerWinArm64, muxerPath); @@ -318,7 +317,7 @@ public string RenameMuxerAndReturnPath(PlatformOperatingSystem platform, Platfor case PlatformOperatingSystem.OSX: { muxerPath = Path.Combine(tmpDirectory, Guid.NewGuid().ToString("N"), subfolder, "dotnet"); - Directory.CreateDirectory(Path.GetDirectoryName(muxerPath)); + Directory.CreateDirectory(Path.GetDirectoryName(muxerPath)!); if (architecture == PlatformArchitecture.ARM64) { File.Copy(DotnetMuxerMacArm64, muxerPath); @@ -335,7 +334,7 @@ public string RenameMuxerAndReturnPath(PlatformOperatingSystem platform, Platfor case PlatformOperatingSystem.Unix: { muxerPath = Path.Combine(tmpDirectory, Guid.NewGuid().ToString("N"), subfolder, "dotnet"); - Directory.CreateDirectory(Path.GetDirectoryName(muxerPath)); + Directory.CreateDirectory(Path.GetDirectoryName(muxerPath)!); File.WriteAllText(muxerPath, "not supported"); break; } @@ -351,7 +350,7 @@ public void Dispose() { foreach (var muxer in _muxers) { - Directory.Delete(Path.GetDirectoryName(muxer), true); + Directory.Delete(Path.GetDirectoryName(muxer)!, true); } } } diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/EnvironmentHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/EnvironmentHelperTests.cs index 15a961881f..c45d45f38f 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/EnvironmentHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/EnvironmentHelperTests.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.CoreUtilities.UnitTests.Helpers; [TestClass] diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/FileHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/FileHelperTests.cs index 345ae11358..5a80646144 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/FileHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/FileHelperTests.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.CoreUtilities.UnitTests.Helpers; [TestClass] diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Output/OutputExtensionsTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Output/OutputExtensionsTests.cs index 32371ea757..59a8006b64 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Output/OutputExtensionsTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Output/OutputExtensionsTests.cs @@ -8,8 +8,6 @@ using Moq; -#nullable disable - namespace Microsoft.TestPlatform.CoreUtilities.UnitTests.Output; [TestClass] diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs index 7bc580528b..f9e38311d2 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Tracing/EqtTraceTests.cs @@ -1,35 +1,23 @@ // 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; #if NETFRAMEWORK using System.Diagnostics; #endif -using System; using System.IO; using Microsoft.VisualStudio.TestPlatform.ObjectModel; -/* Unmerged change from project 'Microsoft.TestPlatform.CoreUtilities.UnitTests (net451)' -Before: -using Microsoft.VisualStudio.TestPlatform.ObjectModel; -using System; -After: -using Microsoft.VisualStudio.TestPlatform.ObjectModel; - -using System; -*/ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace TestPlatform.CoreUtilities.UnitTests; [TestClass] public class EqtTraceTests { - private static string s_dirPath; - private static string s_logFile; + private static string? s_dirPath; + private static string? s_logFile; [ClassInitialize] public static void Init(TestContext _) @@ -177,12 +165,12 @@ public void TraceShouldNotWriteIfDoNotInitializationIsSetToTrue() Assert.IsFalse(ReadLogFile().Contains("Dummy Info Message: TraceShouldNotWriteIfDoNotInitializationIsSetToTrue"), "Did not expect Dummy Info message"); } - private string ReadLogFile() + private static string ReadLogFile() { - string log = null; + string? log = null; try { - using var fs = new FileStream(s_logFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); + using var fs = new FileStream(s_logFile!, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using var sr = new StreamReader(fs); log = sr.ReadToEnd(); } @@ -191,6 +179,7 @@ private string ReadLogFile() Console.WriteLine(ex.Message); } + Assert.IsNotNull(log); return log; } } diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs index 326b9d9505..ff61c71c50 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace TestPlatform.CoreUtilities.UnitTests; [TestClass] @@ -18,7 +16,7 @@ public class JobQueueTests [TestMethod] public void ConstructorThrowsWhenNullProcessHandlerIsProvided() { - JobQueue jobQueue = null; + JobQueue? jobQueue = null; Assert.ThrowsException(() => jobQueue = new JobQueue(null, "dp", int.MaxValue, int.MaxValue, false, (message) => { })); if (jobQueue != null) @@ -30,7 +28,7 @@ public void ConstructorThrowsWhenNullProcessHandlerIsProvided() [TestMethod] public void ThrowsWhenNullEmptyOrWhiteSpaceDisplayNameIsProvided() { - JobQueue jobQueue = null; + JobQueue? jobQueue = null; Assert.ThrowsException(() => jobQueue = new JobQueue(GetEmptyProcessHandler(), null, int.MaxValue, int.MaxValue, false, (message) => { })); Assert.ThrowsException(() => jobQueue = new JobQueue(GetEmptyProcessHandler(), "", int.MaxValue, int.MaxValue, false, (message) => { })); Assert.ThrowsException(() => jobQueue = new JobQueue(GetEmptyProcessHandler(), " ", int.MaxValue, int.MaxValue, false, (message) => { })); diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/TimeSpanParserTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/TimeSpanParserTests.cs index 1448fe6365..7b145b99d6 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/TimeSpanParserTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/TimeSpanParserTests.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities; using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace TestPlatform.CoreUtilities.UnitTests; [TestClass] diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs index 8b72831c36..de1fd28468 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs @@ -16,8 +16,6 @@ using Moq; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests; /// @@ -37,7 +35,7 @@ public class BlameCollectorTests private readonly Mock _mockProcessDumpUtility; private readonly Mock _mockInactivityTimer; private readonly Mock _mockFileHelper; - private readonly XmlElement _configurationElement; + private readonly XmlElement? _configurationElement; private readonly string _filepath; /// @@ -509,10 +507,10 @@ public void TriggerTestHostLaunchedHandlerShouldStartProcDumpUtilityForFullDumpI var dumpConfig = GetDumpConfigurationElement(); var dumpTypeAttribute = dumpConfig.OwnerDocument.CreateAttribute("DuMpType"); dumpTypeAttribute.Value = "FuLl"; - dumpConfig[BlameDataCollector.Constants.DumpModeKey].Attributes.Append(dumpTypeAttribute); + dumpConfig[Constants.DumpModeKey]!.Attributes.Append(dumpTypeAttribute); var dumpOnExitAttribute = dumpConfig.OwnerDocument.CreateAttribute("CollEctAlways"); dumpOnExitAttribute.Value = "FaLSe"; - dumpConfig[BlameDataCollector.Constants.DumpModeKey].Attributes.Append(dumpOnExitAttribute); + dumpConfig[Constants.DumpModeKey]!.Attributes.Append(dumpOnExitAttribute); // Initializing Blame Data Collector _blameDataCollector.Initialize( @@ -538,7 +536,7 @@ public void TriggerTestHostLaunchedHandlerShouldLogWarningForWrongCollectDumpKey var dumpConfig = GetDumpConfigurationElement(); var dumpTypeAttribute = dumpConfig.OwnerDocument.CreateAttribute("Xyz"); dumpTypeAttribute.Value = "FuLl"; - dumpConfig[BlameDataCollector.Constants.DumpModeKey].Attributes.Append(dumpTypeAttribute); + dumpConfig[Constants.DumpModeKey]!.Attributes.Append(dumpTypeAttribute); // Initializing Blame Data Collector _blameDataCollector.Initialize( @@ -564,7 +562,7 @@ public void TriggerTestHostLaunchedHandlerShouldLogWarningForWrongDumpType() var dumpConfig = GetDumpConfigurationElement(); var dumpTypeAttribute = dumpConfig.OwnerDocument.CreateAttribute("DumpType"); dumpTypeAttribute.Value = "random"; - dumpConfig[BlameDataCollector.Constants.DumpModeKey].Attributes.Append(dumpTypeAttribute); + dumpConfig[Constants.DumpModeKey]!.Attributes.Append(dumpTypeAttribute); // Initializing Blame Data Collector _blameDataCollector.Initialize( @@ -578,7 +576,7 @@ public void TriggerTestHostLaunchedHandlerShouldLogWarningForWrongDumpType() _mockDataColectionEvents.Raise(x => x.TestHostLaunched += null, new TestHostLaunchedEventArgs(_dataCollectionContext, 1234)); // Verify - _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, "DumpType", BlameDataCollector.Constants.FullConfigurationValue, BlameDataCollector.Constants.MiniConfigurationValue))), Times.Once); + _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, "DumpType", Constants.FullConfigurationValue, Constants.MiniConfigurationValue))), Times.Once); } /// @@ -590,7 +588,7 @@ public void TriggerTestHostLaunchedHandlerShouldLogWarningForNonBooleanCollectAl var dumpConfig = GetDumpConfigurationElement(); var dumpTypeAttribute = dumpConfig.OwnerDocument.CreateAttribute("DumpType"); dumpTypeAttribute.Value = "random"; - dumpConfig[BlameDataCollector.Constants.DumpModeKey].Attributes.Append(dumpTypeAttribute); + dumpConfig[Constants.DumpModeKey]!.Attributes.Append(dumpTypeAttribute); // Initializing Blame Data Collector _blameDataCollector.Initialize( @@ -604,7 +602,7 @@ public void TriggerTestHostLaunchedHandlerShouldLogWarningForNonBooleanCollectAl _mockDataColectionEvents.Raise(x => x.TestHostLaunched += null, new TestHostLaunchedEventArgs(_dataCollectionContext, 1234)); // Verify - _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, "DumpType", BlameDataCollector.Constants.FullConfigurationValue, BlameDataCollector.Constants.MiniConfigurationValue))), Times.Once); + _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, "DumpType", Constants.FullConfigurationValue, Constants.MiniConfigurationValue))), Times.Once); } /// @@ -688,7 +686,7 @@ public void CleanUp() File.Delete(_filepath); } - private XmlElement GetDumpConfigurationElement( + private static XmlElement GetDumpConfigurationElement( bool isFullDump = false, bool collectDumpOnExit = false, bool colectDumpOnHang = false, @@ -696,36 +694,36 @@ public void CleanUp() { var xmldoc = new XmlDocument(); var outernode = xmldoc.CreateElement("Configuration"); - var node = xmldoc.CreateElement(BlameDataCollector.Constants.DumpModeKey); + var node = xmldoc.CreateElement(Constants.DumpModeKey); outernode.AppendChild(node); node.InnerText = "Text"; if (isFullDump) { - var fulldumpAttribute = xmldoc.CreateAttribute(BlameDataCollector.Constants.DumpTypeKey); + var fulldumpAttribute = xmldoc.CreateAttribute(Constants.DumpTypeKey); fulldumpAttribute.Value = "full"; node.Attributes.Append(fulldumpAttribute); } if (collectDumpOnExit) { - var collectDumpOnExitAttribute = xmldoc.CreateAttribute(BlameDataCollector.Constants.CollectDumpAlwaysKey); + var collectDumpOnExitAttribute = xmldoc.CreateAttribute(Constants.CollectDumpAlwaysKey); collectDumpOnExitAttribute.Value = "true"; node.Attributes.Append(collectDumpOnExitAttribute); } if (colectDumpOnHang) { - var hangDumpNode = xmldoc.CreateElement(BlameDataCollector.Constants.CollectDumpOnTestSessionHang); + var hangDumpNode = xmldoc.CreateElement(Constants.CollectDumpOnTestSessionHang); outernode.AppendChild(hangDumpNode); - var inactivityTimeAttribute = xmldoc.CreateAttribute(BlameDataCollector.Constants.TestTimeout); + var inactivityTimeAttribute = xmldoc.CreateAttribute(Constants.TestTimeout); inactivityTimeAttribute.Value = $"{inactivityTimeInMilliseconds}"; hangDumpNode.Attributes.Append(inactivityTimeAttribute); if (isFullDump) { - var fulldumpAttribute = xmldoc.CreateAttribute(BlameDataCollector.Constants.DumpTypeKey); + var fulldumpAttribute = xmldoc.CreateAttribute(Constants.DumpTypeKey); fulldumpAttribute.Value = "full"; hangDumpNode.Attributes.Append(fulldumpAttribute); } @@ -754,7 +752,8 @@ internal class TestableBlameCollector : BlameCollector /// /// MockFileHelper instance. /// - internal TestableBlameCollector(IBlameReaderWriter blameReaderWriter, IProcessDumpUtility processDumpUtility, IInactivityTimer inactivityTimer, IFileHelper mockFileHelper) + internal TestableBlameCollector(IBlameReaderWriter blameReaderWriter, IProcessDumpUtility processDumpUtility, IInactivityTimer? inactivityTimer, + IFileHelper mockFileHelper) : base(blameReaderWriter, processDumpUtility, inactivityTimer, mockFileHelper) { } diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameLoggerTests.cs index f6cdf687ce..11a1ee402f 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameLoggerTests.cs @@ -12,8 +12,6 @@ using Moq; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests; /// @@ -73,7 +71,7 @@ public void TestRunCompleteHandlerShouldNotReadFileIfTestRunNotAborted() // Initialize Blame Logger var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - _blameLogger.Initialize(loggerEvents, (string)null); + _blameLogger.Initialize(loggerEvents, null); // Setup and Raise event _mockBlameReaderWriter.Setup(x => x.ReadTestSequence(It.IsAny())); @@ -96,7 +94,7 @@ public void TestRunCompleteHandlerShouldReturnIfUriAttachmentIsNull() // Initialize Blame Logger var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - _blameLogger.Initialize(loggerEvents, (string)null); + _blameLogger.Initialize(loggerEvents, null); // Setup and Raise event loggerEvents.CompleteTestRun(null, false, true, null, new Collection(attachmentSetList), new Collection(), new TimeSpan(1, 0, 0, 0)); @@ -127,7 +125,7 @@ private void InitializeAndVerify(int count) // Initialize Blame Logger var loggerEvents = new InternalTestLoggerEvents(TestSessionMessageLogger.Instance); loggerEvents.EnableEvents(); - _blameLogger.Initialize(loggerEvents, (string)null); + _blameLogger.Initialize(loggerEvents, null); var testCaseList = new List { diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/InactivityTimerTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/InactivityTimerTests.cs index f8d353b12f..2014f39a7d 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/InactivityTimerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/InactivityTimerTests.cs @@ -6,8 +6,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests; [TestClass] diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcDumpArgsBuilderTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcDumpArgsBuilderTests.cs index 9efe2db0c4..8c7c9af632 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcDumpArgsBuilderTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcDumpArgsBuilderTests.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests; [TestClass] diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs index ddc3abeafe..9a8058cd3b 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/ProcessDumpUtilityTests.cs @@ -9,8 +9,6 @@ using Moq; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests; /// diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/XmlReaderWriterTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/XmlReaderWriterTests.cs index 4dd782d5e0..818a1a9667 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/XmlReaderWriterTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/XmlReaderWriterTests.cs @@ -13,8 +13,6 @@ using Moq; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests; /// diff --git a/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs index 39aa3d61b0..b0d575a510 100644 --- a/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests/HtmlLoggerTests.cs @@ -20,31 +20,29 @@ using HtmlLoggerConstants = Microsoft.VisualStudio.TestPlatform.Extensions.HtmlLogger.Constants; using ObjectModel = Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.HtmlLogger.UnitTests; [TestClass] public class HtmlLoggerTests { - private Mock _events; - private VisualStudio.TestPlatform.Extensions.HtmlLogger.HtmlLogger _htmlLogger; - private Dictionary _parameters; private static readonly string DefaultTestRunDirectory = Path.GetTempPath(); private static readonly string DefaultLogFileNameParameterValue = "logfilevalue.html"; - private Mock _mockFileHelper; - private Mock _mockXmlSerializer; - private Mock _mockHtmlTransformer; - [TestInitialize] - public void TestInitialize() + private Mock _events; + private readonly VisualStudio.TestPlatform.Extensions.HtmlLogger.HtmlLogger _htmlLogger; + private readonly Dictionary _parameters; + private readonly Mock _mockFileHelper; + private readonly Mock _mockXmlSerializer; + private readonly Mock _mockHtmlTransformer; + + public HtmlLoggerTests() { _events = new Mock(); _mockFileHelper = new Mock(); _mockHtmlTransformer = new Mock(); _mockXmlSerializer = new Mock(); _htmlLogger = new VisualStudio.TestPlatform.Extensions.HtmlLogger.HtmlLogger(_mockFileHelper.Object, _mockHtmlTransformer.Object, _mockXmlSerializer.Object); - _parameters = new Dictionary(2) + _parameters = new Dictionary(2) { [DefaultLoggerParameterNames.TestRunDirectory] = DefaultTestRunDirectory, [HtmlLoggerConstants.LogFileNameKey] = DefaultLogFileNameParameterValue @@ -123,7 +121,7 @@ public void TestMessageHandlerShouldNotInitializelistForInformationErrorAndWarni [TestMethod] public void TestCompleteHandlerShouldThrowExceptionIfParametersAreNull() { - Dictionary parameters = null; + Dictionary? parameters = null; var events = new Mock(); Assert.ThrowsException(() => _htmlLogger.Initialize(events.Object, parameters)); } @@ -400,7 +398,7 @@ public void TestCompleteHandlerShouldKeepTackOfSummary() [TestMethod] public void TestCompleteHandlerShouldCreateCustumHtmlFileNamewithLogFileNameKey() { - var parameters = new Dictionary + var parameters = new Dictionary { [HtmlLoggerConstants.LogFileNameKey] = null, [DefaultLoggerParameterNames.TestRunDirectory] = "dsa" @@ -459,7 +457,7 @@ public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixIfTarg [TestMethod] public void TestCompleteHandlerShouldCreateCustumHtmlFileNameWithLogPrefixNull() { - var parameters = new Dictionary + var parameters = new Dictionary { [HtmlLoggerConstants.LogFilePrefixKey] = null, [DefaultLoggerParameterNames.TestRunDirectory] = "dsa", diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs index ea5b379494..b67098e244 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs @@ -24,29 +24,28 @@ using TrxLoggerObjectModel = Microsoft.TestPlatform.Extensions.TrxLogger.ObjectModel; using TrxLoggerResources = Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger.Resources.TrxResource; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests; [TestClass] public class TrxLoggerTests { - private Mock _events; - private TestableTrxLogger _testableTrxLogger; - private Dictionary _parameters; + private const string DefaultLogFilePrefixParameterValue = "log_prefix"; + private const int MultipleLoggerInstanceCount = 2; + private static readonly string DefaultTestRunDirectory = Path.GetTempPath(); private static readonly string DefaultLogFileNameParameterValue = "logfilevalue.trx"; - private const string DefaultLogFilePrefixParameterValue = "log_prefix"; - private const int MultipleLoggerInstanceCount = 2; + private readonly Mock _events; + private readonly Dictionary _parameters; + + private TestableTrxLogger _testableTrxLogger; - [TestInitialize] - public void Initialize() + public TrxLoggerTests() { _events = new Mock(); _testableTrxLogger = new TestableTrxLogger(); - _parameters = new Dictionary(2) + _parameters = new Dictionary(2) { [DefaultLoggerParameterNames.TestRunDirectory] = DefaultTestRunDirectory, [TrxLoggerConstants.LogFileNameKey] = DefaultLogFileNameParameterValue @@ -57,7 +56,7 @@ public void Initialize() [TestCleanup] public void Cleanup() { - if (!string.IsNullOrEmpty(_testableTrxLogger?.TrxFile) && File.Exists(_testableTrxLogger.TrxFile)) + if (!string.IsNullOrEmpty(_testableTrxLogger?.TrxFile) && File.Exists(_testableTrxLogger!.TrxFile)) { File.Delete(_testableTrxLogger.TrxFile); } @@ -620,7 +619,7 @@ public void TheDefaultTrxFileNameShouldNotHaveWhiteSpace() MakeTestRunComplete(); - bool trxFileNameContainsWhiteSpace = Path.GetFileName(_testableTrxLogger.TrxFile).Contains(' '); + bool trxFileNameContainsWhiteSpace = Path.GetFileName(_testableTrxLogger.TrxFile)!.Contains(' '); Assert.IsFalse(trxFileNameContainsWhiteSpace, $"\"{_testableTrxLogger.TrxFile}\": Trx file name should not have white spaces"); } @@ -685,9 +684,9 @@ public void TrxPrefixFileNameShouldIterate() Assert.AreEqual(MultipleLoggerInstanceCount, files.Length, "All logger instances should get different file names!"); } - private string[] TestMultipleTrxLoggers() + private string?[] TestMultipleTrxLoggers() { - var files = new string[2]; + var files = new string?[2]; try { @@ -793,7 +792,7 @@ public void CrlfCharactersShouldGetRetainedInTrx() Assert.IsTrue(File.Exists(_testableTrxLogger.TrxFile), string.Format("TRX file: {0}, should have got created.", _testableTrxLogger.TrxFile)); - string actualMessage = GetElementValueFromTrx(_testableTrxLogger.TrxFile, "StdOut"); + string? actualMessage = GetElementValueFromTrx(_testableTrxLogger.TrxFile!, "StdOut"); Assert.IsNotNull(actualMessage); Assert.IsTrue(string.Equals(message, actualMessage), string.Format("StdOut messages do not match. Expected:{0}, Actual:{1}", message, actualMessage)); @@ -803,20 +802,20 @@ public void CrlfCharactersShouldGetRetainedInTrx() public void TestRunInformationShouldContainUtcDateTime() { MakeTestRunComplete(); - ValidateDateTimeInTrx(_testableTrxLogger.TrxFile); + ValidateDateTimeInTrx(_testableTrxLogger.TrxFile!); } - private void ValidateDateTimeInTrx(string trxFileName) + private static void ValidateDateTimeInTrx(string trxFileName) { using FileStream file = File.OpenRead(trxFileName); using XmlReader reader = XmlReader.Create(file); XDocument document = XDocument.Load(reader); - var timesNode = document.Descendants(document.Root.GetDefaultNamespace() + "Times").FirstOrDefault(); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("creation").FirstOrDefault().Value)); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("start").FirstOrDefault().Value)); - var resultNode = document.Descendants(document.Root.GetDefaultNamespace() + "UnitTestResult").FirstOrDefault(); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("endTime").FirstOrDefault().Value)); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("startTime").FirstOrDefault().Value)); + var timesNode = document.Descendants(document.Root!.GetDefaultNamespace() + "Times").First(); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("creation").First().Value)); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("start").First().Value)); + var resultNode = document.Descendants(document.Root.GetDefaultNamespace() + "UnitTestResult").First(); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("endTime").First().Value)); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("startTime").First().Value)); } [TestMethod] @@ -830,7 +829,7 @@ public void CustomTrxFileNameShouldBeConstructedFromRelativeLogFilePrefixParamet MakeTestRunComplete(); - string actualFileNameWithoutTimestamp = _testableTrxLogger.TrxFile.Substring(0, _testableTrxLogger.TrxFile.LastIndexOf('_')); + string actualFileNameWithoutTimestamp = _testableTrxLogger.TrxFile!.Substring(0, _testableTrxLogger.TrxFile.LastIndexOf('_')); Assert.AreNotEqual(Path.Combine(DefaultTestRunDirectory, "results.trx"), _testableTrxLogger.TrxFile, "Expected framework name to appear in file name"); Assert.AreNotEqual(Path.Combine(DefaultTestRunDirectory, "results_net451.trx"), _testableTrxLogger.TrxFile, "Expected time stamp to appear in file name"); @@ -848,7 +847,7 @@ public void CustomTrxFileNameShouldBeConstructedFromAbsoluteLogFilePrefixParamet MakeTestRunComplete(); - string actualFileNameWithoutTimestamp = _testableTrxLogger.TrxFile.Substring(0, _testableTrxLogger.TrxFile.LastIndexOf('_')); + string actualFileNameWithoutTimestamp = _testableTrxLogger.TrxFile!.Substring(0, _testableTrxLogger.TrxFile.LastIndexOf('_')); Assert.AreEqual(trxPrefix + "_net451", actualFileNameWithoutTimestamp); @@ -883,7 +882,7 @@ private void ValidateTestIdAndNameInTrx(bool isMstestAdapter) var testRunCompleteEventArgs = CreateTestRunCompleteEventArgs(); _testableTrxLogger.TestRunCompleteHandler(new object(), testRunCompleteEventArgs); - ValidateResultAttributesInTrx(_testableTrxLogger.TrxFile, testCase.Id, testCase.DisplayName, isMstestAdapter); + ValidateResultAttributesInTrx(_testableTrxLogger.TrxFile!, testCase.Id, testCase.DisplayName, isMstestAdapter); } private void ValidateResultAttributesInTrx(string trxFileName, Guid testId, string testName, bool isMstestAdapter) @@ -891,25 +890,25 @@ private void ValidateResultAttributesInTrx(string trxFileName, Guid testId, stri using FileStream file = File.OpenRead(trxFileName); using XmlReader reader = XmlReader.Create(file); XDocument document = XDocument.Load(reader); - var resultNode = document.Descendants(document.Root.GetDefaultNamespace() + "UnitTestResult").FirstOrDefault(); + var resultNode = document.Descendants(document.Root!.GetDefaultNamespace() + "UnitTestResult").First(); if (isMstestAdapter) { - Assert.AreNotEqual(resultNode.Attributes("testId").FirstOrDefault().Value, testId.ToString()); - Assert.AreNotEqual(resultNode.Attributes("testName").FirstOrDefault().Value, testName); + Assert.AreNotEqual(resultNode.Attributes("testId").First().Value, testId.ToString()); + Assert.AreNotEqual(resultNode.Attributes("testName").First().Value, testName); } else { - Assert.AreEqual(resultNode.Attributes("testId").FirstOrDefault().Value, testId.ToString()); - Assert.AreEqual(resultNode.Attributes("testName").FirstOrDefault().Value, testName); + Assert.AreEqual(resultNode.Attributes("testId").First().Value, testId.ToString()); + Assert.AreEqual(resultNode.Attributes("testName").First().Value, testName); } } - private void ValidateTimeWithinUtcLimits(DateTimeOffset dateTime) + private static void ValidateTimeWithinUtcLimits(DateTimeOffset dateTime) { Assert.IsTrue(dateTime.UtcDateTime.Subtract(DateTime.UtcNow) < new TimeSpan(0, 0, 0, 60)); } - private string GetElementValueFromTrx(string trxFileName, string fieldName) + private static string? GetElementValueFromTrx(string trxFileName, string fieldName) { using (FileStream file = File.OpenRead(trxFileName)) using (XmlReader reader = XmlReader.Create(file)) @@ -938,7 +937,7 @@ private static TestRunCompleteEventArgs CreateTestRunCompleteEventArgs() return testRunCompleteEventArgs; } - private static Mock CreatePassTestResultEventArgsMock(string testCaseName = "Pass1", List testResultMessages = null) + private static Mock CreatePassTestResultEventArgsMock(string testCaseName = "Pass1", List? testResultMessages = null) { TestCase passTestCase = CreateTestCase(testCaseName); var passResult = new VisualStudio.TestPlatform.ObjectModel.TestResult(passTestCase); @@ -968,10 +967,12 @@ private void MakeTestRunComplete(TestableTrxLogger testableTrxLogger) internal class TestableTrxLogger : VisualStudio.TestPlatform.Extensions.TrxLogger.TrxLogger { - public TestableTrxLogger() : base() { } - public TestableTrxLogger(IFileHelper fileHelper, TrxFileHelper trxFileHelper) : base(fileHelper, trxFileHelper) { } + public TestableTrxLogger() + : base() { } + public TestableTrxLogger(IFileHelper fileHelper, TrxFileHelper trxFileHelper) + : base(fileHelper, trxFileHelper) { } - public string TrxFile; + public string? TrxFile; internal override void PopulateTrxFile(string trxFileName, XmlElement rootElement) { TrxFile = trxFileName; diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs index 5983da8bc6..f9bc122e6c 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/ConverterTests.cs @@ -21,8 +21,6 @@ using TrxLoggerOutcome = Microsoft.TestPlatform.Extensions.TrxLogger.ObjectModel.TestOutcome; using UriDataAttachment = Microsoft.VisualStudio.TestPlatform.ObjectModel.UriDataAttachment; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests.Utility; [TestClass] @@ -199,7 +197,7 @@ public void ToTestElementShouldNotFailWhenClassNameIsTheSameAsFullyQualifiedName expectedClassName = expectedTestName = fullyQualifiedName = source = testName = "test1"; TestCase testCase = new(fullyQualifiedName, new Uri("some://uri"), source); - var unitTestElement = _converter.ToTestElement(testCase.Id, Guid.Empty, Guid.Empty, testName, TrxLoggerConstants.UnitTestType, testCase) as UnitTestElement; + var unitTestElement = (UnitTestElement)_converter.ToTestElement(testCase.Id, Guid.Empty, Guid.Empty, testName, TrxLoggerConstants.UnitTestType, testCase); Assert.AreEqual(expectedClassName, unitTestElement.TestMethod.ClassName); Assert.AreEqual(expectedTestName, unitTestElement.TestMethod.Name); @@ -209,7 +207,7 @@ private void ValidateTestMethodProperties(string testName, string fullyQualified { TestCase testCase = CreateTestCase(fullyQualifiedName); - var unitTestElement = _converter.ToTestElement(testCase.Id, Guid.Empty, Guid.Empty, testName, TrxLoggerConstants.UnitTestType, testCase) as UnitTestElement; + var unitTestElement = (UnitTestElement)_converter.ToTestElement(testCase.Id, Guid.Empty, Guid.Empty, testName, TrxLoggerConstants.UnitTestType, testCase); Assert.AreEqual(expectedClassName, unitTestElement.TestMethod.ClassName); Assert.AreEqual(expectedTestName, unitTestElement.TestMethod.Name); diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/TrxFileHelperTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/TrxFileHelperTests.cs index 8836252d72..19371aef67 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/TrxFileHelperTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/Utility/TrxFileHelperTests.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests.Utility; [TestClass] diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/XmlPersistenceTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/XmlPersistenceTests.cs index 4e1009d88a..bc410dedae 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/XmlPersistenceTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/XmlPersistenceTests.cs @@ -4,8 +4,6 @@ using Microsoft.TestPlatform.Extensions.TrxLogger.XML; using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests; [TestClass] diff --git a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/Constants.cs b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/Constants.cs index b9ec22d2af..3d29668003 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/Constants.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/Constants.cs @@ -1,8 +1,6 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#nullable disable - namespace Microsoft.TestPlatform.PerformanceTests.PerfInstrumentation; /// diff --git a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerfAnalyzer.cs b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerfAnalyzer.cs index 390b7e1bd3..101795ddb9 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerfAnalyzer.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerfAnalyzer.cs @@ -11,8 +11,6 @@ using Microsoft.Diagnostics.Tracing.Parsers; using Microsoft.Diagnostics.Tracing.Session; -#nullable disable - namespace Microsoft.TestPlatform.PerformanceTests.PerfInstrumentation; /// @@ -192,9 +190,9 @@ public long GetAdapterExecutedTests(string executorUri) } - private string GetEventKey(string taskName) + private string? GetEventKey(string taskName) { - string key = null; + string? key = null; key = _testPlatformTaskMap.Keys.FirstOrDefault(k => k.Split('_')[2].Equals(taskName)); diff --git a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerformanceTestBase.cs b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerformanceTestBase.cs index af637743ac..2a6d85927c 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerformanceTestBase.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerformanceTestBase.cs @@ -6,8 +6,6 @@ using Microsoft.TestPlatform.TestUtilities; -#nullable disable - namespace Microsoft.TestPlatform.PerformanceTests.PerfInstrumentation; /// diff --git a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/TestPlatformTask.cs b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/TestPlatformTask.cs index 25d0ce439a..a16db5cfab 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/TestPlatformTask.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/TestPlatformTask.cs @@ -3,8 +3,6 @@ using System.Collections.Generic; -#nullable disable - namespace Microsoft.TestPlatform.PerformanceTests.PerfInstrumentation; /// diff --git a/test/Microsoft.TestPlatform.TestUtilities/AssemblyUtility.cs b/test/Microsoft.TestPlatform.TestUtilities/AssemblyUtility.cs index a3c67178a7..866927c808 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/AssemblyUtility.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/AssemblyUtility.cs @@ -6,8 +6,6 @@ using System.Runtime.Loader; #endif -#nullable disable - namespace Microsoft.TestPlatform.TestUtilities; /// diff --git a/test/Microsoft.TestPlatform.TestUtilities/FileAssert.cs b/test/Microsoft.TestPlatform.TestUtilities/FileAssert.cs index 3a281ab3dc..622f6d2886 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/FileAssert.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/FileAssert.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace TestPlatform.TestUtilities; public static class FileAssert diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs index c0e317d0f6..de93b4a8fe 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs @@ -20,8 +20,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.TestUtilities; /// @@ -77,7 +75,7 @@ public IntegrationTestBase() public TempDirectory TempDirectory { get; } - public TestContext TestContext { get; set; } + public TestContext? TestContext { get; set; } public string BuildConfiguration { get; } @@ -88,7 +86,7 @@ public void TempDirectoryCleanup() { // In CI always delete the results, because we have limited disk space there. // - // Locally delete the directory only when the test succeeded, so we can look + // Locally delete the directory only when the test succeeded, so we can look // at results and logs of failed tests. if (IsCI || TestContext.CurrentTestOutcome == UnitTestOutcome.Passed) { @@ -106,18 +104,18 @@ public void TempDirectoryCleanup() /// /// Command line arguments string. public static string PrepareArguments(string[] testAssemblies, string testAdapterPath, string runSettings, - string framework, string inIsolation = "", string resultsDirectory = null) + string framework, string inIsolation = "", string? resultsDirectory = null) { var arguments = ""; foreach (var path in testAssemblies) { - // The incoming testAssembly path is either a single dll path in quotes or without quotes. - // Or multiple assembly paths in a single string each double quoted and joined by space. + // The incoming testAssembly path is either a single dll path in quotes or without quotes. + // Or multiple assembly paths in a single string each double quoted and joined by space. // We trim, and add quotes here to get either: // C:\1.dll -> "C:\1.dll" // "C:\1.dll" -> "C:\1.dll" // "C:\1.dll" "C:\2.dll" -> "C:\1.dll" "C:\2.dll" - // + // // For unquoted multi path string C:\1.dll C:\2.dll, we will get "C:\1.dll C:\2.dll" // which is wrong and will fail later, but it's the test's fault for doing it wrong // rather than providing an array of strings that this overload takes. @@ -175,7 +173,7 @@ public void TempDirectoryCleanup() /// /// Command line arguments string. public static string PrepareArguments(string testAssembly, string testAdapterPath, string runSettings, - string framework, string inIsolation = "", string resultsDirectory = null) + string framework, string inIsolation = "", string? resultsDirectory = null) => PrepareArguments(new string[] { testAssembly }, testAdapterPath, runSettings, framework, inIsolation, resultsDirectory); @@ -183,7 +181,7 @@ public void TempDirectoryCleanup() /// Invokes vstest.console with specified arguments. /// /// Arguments provided to vstest.console.exe - public void InvokeVsTest(string arguments, Dictionary environmentVariables = null) + public void InvokeVsTest(string arguments, Dictionary? environmentVariables = null) { var debugEnvironmentVariables = AddDebugEnvironmentVariables(environmentVariables); ExecuteVsTestConsole(arguments, out _standardTestOutput, out _standardTestError, out _runnerExitCode, debugEnvironmentVariables); @@ -224,7 +222,7 @@ public void InvokeDotnetTest(string arguments, Dictionary enviro string testAdapterPath, string framework, string runSettings = "", - Dictionary environmentVariables = null) + Dictionary? environmentVariables = null) { var arguments = PrepareArguments(testAssembly, testAdapterPath, runSettings, framework, _testEnvironment.InIsolationValue, resultsDirectory: TempDirectory.Path); InvokeVsTest(arguments, environmentVariables); @@ -266,9 +264,10 @@ public void InvokeDotnetTest(string arguments, Dictionary enviro /// A test assembly. /// Path to test adapters. /// Run settings for execution. - public void InvokeVsTestForDiscovery(string testAssembly, string testAdapterPath, string runSettings = "", string targetFramework = "", Dictionary environmentVariables = null) + public void InvokeVsTestForDiscovery(string testAssembly, string testAdapterPath, string runSettings = "", string targetFramework = "", + Dictionary? environmentVariables = null) { - var arguments = PrepareArguments(testAssembly, testAdapterPath, runSettings, targetFramework, _testEnvironment.InIsolationValue, resultsDirectory: TempDirectory.Path); + var arguments = PrepareArguments(testAssembly, testAdapterPath, runSettings, targetFramework, _testEnvironment.InIsolationValue!, resultsDirectory: TempDirectory.Path); arguments = string.Concat(arguments, " /listtests"); InvokeVsTest(arguments, environmentVariables); } @@ -564,7 +563,7 @@ protected string GetProjectFullPath(string projectName) protected string GetProjectAssetFullPath(string projectName, string assetName) { var projectPath = _testEnvironment.GetTestProject(projectName); - return Path.Combine(Path.GetDirectoryName(projectPath), assetName); + return Path.Combine(Path.GetDirectoryName(projectPath)!, assetName); } protected string GetTestAdapterPath(UnitTestFramework testFramework = UnitTestFramework.MSTest) @@ -740,7 +739,7 @@ private static string GetTestMethodName(string testFullName) return testMethodName; } - protected void ExecuteVsTestConsole(string args, out string stdOut, out string stdError, out int exitCode, Dictionary environmentVariables = null) + protected void ExecuteVsTestConsole(string args, out string stdOut, out string stdError, out int exitCode, Dictionary? environmentVariables = null) { if (IsNetCoreRunner()) { @@ -775,7 +774,8 @@ private void ExecutePatchedDotnet(string command, string args, out string stdOut ExecuteApplication(patchedDotnetPath, string.Join(" ", command, args), out stdOut, out stdError, out exitCode, environmentVariables); } - protected static void ExecuteApplication(string path, string args, out string stdOut, out string stdError, out int exitCode, Dictionary environmentVariables = null, string workingDirectory = null) + protected static void ExecuteApplication(string path, string args, out string stdOut, out string stdError, out int exitCode, + Dictionary? environmentVariables = null, string? workingDirectory = null) { if (string.IsNullOrWhiteSpace(path)) { @@ -932,7 +932,8 @@ protected static string GetDiagArg(string rootDir) protected static int CountTestHostLogs(string diagLogsDir) => Directory.GetFiles(diagLogsDir, "*.host.*").Length; - protected static void AssertExpectedNumberOfHostProcesses(int expectedNumOfProcessCreated, string diagLogsDir, IEnumerable testHostProcessNames, string arguments = null, string runnerPath = null) + protected static void AssertExpectedNumberOfHostProcesses(int expectedNumOfProcessCreated, string diagLogsDir, IEnumerable testHostProcessNames, + string? arguments = null, string? runnerPath = null) { var processCreatedCount = CountTestHostLogs(diagLogsDir); Assert.AreEqual( diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs index 01c3069ee1..be39dacd48 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs @@ -8,8 +8,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.TestUtilities; /// @@ -23,9 +21,9 @@ public class IntegrationTestEnvironment Environment.GetEnvironmentVariable("TP_ROOT_DIR") ?? Path.GetFullPath(@"..\..\..\..\..".Replace('\\', Path.DirectorySeparatorChar)); - private static Dictionary s_dependencyVersions; + private static Dictionary? s_dependencyVersions; - private string _targetRuntime; + private string? _targetRuntime; public IntegrationTestEnvironment() { @@ -74,11 +72,7 @@ public static string BuildConfiguration /// /// Gets the nuget packages directory for enlistment. /// - public string PackageDirectory - { - get; - private set; - } + public string PackageDirectory { get; private set; } /// /// Gets the publish directory for vstest.console package. @@ -95,7 +89,7 @@ public string PublishDirectory "artifacts", BuildConfiguration, RunnerFramework, - TargetRuntime); + TargetRuntime!); return !Directory.Exists(publishDirectory) ? throw new InvalidOperationException($"Path '{publishDirectory}' does not exist, did you build the solution via build.cmd?") @@ -112,17 +106,13 @@ public string PublishDirectory /// Gets the target framework. /// Supported values = net451, netcoreapp1.0. /// - public string TargetFramework - { - get; - set; - } + public string? TargetFramework { get; set; } /// /// Gets the target runtime. /// Supported values = win7-x64. /// - public string TargetRuntime + public string? TargetRuntime { get { @@ -150,46 +140,28 @@ public string TargetRuntime /// Gets the inIsolation. /// Supported values = /InIsolation. /// - public string InIsolationValue - { - get; set; - } + public string? InIsolationValue { get; set; } /// /// Gets the root directory for test assets. /// - public string TestAssetsPath - { - get; - } + public string TestAssetsPath { get; } /// /// Gets the tools directory for dependent tools /// - public string ToolsDirectory - { - get; - private set; - } + public string ToolsDirectory { get; private set; } /// /// Gets the test artifacts directory. /// - public string TestArtifactsDirectory - { - get; - private set; - } + public string TestArtifactsDirectory { get; private set; } /// /// Gets the application type. /// Supported values = net451, netcoreapp1.0. /// - public string RunnerFramework - { - get; - set; - } + public string RunnerFramework { get; set; } // A known AzureDevOps env variable meaning we are running in CI. public static bool IsCI { get; } = Environment.GetEnvironmentVariable("TF_BUILD") == "True"; @@ -211,7 +183,7 @@ public string RunnerFramework /// public string GetTestAsset(string assetName) { - return GetTestAsset(assetName, TargetFramework); + return GetTestAsset(assetName, TargetFramework!); } /// diff --git a/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs b/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs index 7c96f33f23..642157428d 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/TestPluginCacheHelper.cs @@ -11,8 +11,6 @@ using Moq; -#nullable disable - namespace Microsoft.TestPlatform.TestUtilities; public static class TestPluginCacheHelper @@ -38,17 +36,17 @@ public static TestableTestPluginCache SetupMockAdditionalPathExtensions(string[] return testPluginCache; } - public static void SetupMockExtensions(Type callingTest, Mock mockFileHelper = null) + public static void SetupMockExtensions(Type callingTest, Mock? mockFileHelper = null) { SetupMockExtensions(callingTest, () => { }, mockFileHelper); } - public static void SetupMockExtensions(Type callingTest, Action callback, Mock mockFileHelper = null) + public static void SetupMockExtensions(Type callingTest, Action callback, Mock? mockFileHelper = null) { SetupMockExtensions(new[] { callingTest.GetTypeInfo().Assembly.Location }, callback, mockFileHelper); } - public static void SetupMockExtensions(string[] extensions, Action callback, Mock mockFileHelper = null) + public static void SetupMockExtensions(string[] extensions, Action callback, Mock? mockFileHelper = null) { // Setup mocks. if (mockFileHelper == null) diff --git a/test/Microsoft.TestPlatform.TestUtilities/TestableTestPluginCache.cs b/test/Microsoft.TestPlatform.TestUtilities/TestableTestPluginCache.cs index b9700d4fa4..e8855920d4 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/TestableTestPluginCache.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/TestableTestPluginCache.cs @@ -7,13 +7,12 @@ using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework; using Microsoft.VisualStudio.TestPlatform.Common.SettingsProvider; -#nullable disable - namespace Microsoft.TestPlatform.TestUtilities; public class TestableTestPluginCache : TestPluginCache { - public Action Action; + public Action? Action; + public TestableTestPluginCache(List extensionsPath) { TestDiscoveryExtensionManager.Destroy(); diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/ClientUtilitiesTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/ClientUtilitiesTests.cs index 1b6faa1b38..b84ef4de57 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/ClientUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/ClientUtilitiesTests.cs @@ -10,8 +10,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Utilities.Tests; [TestClass] @@ -66,7 +64,7 @@ public void FixRelativePathsInRunSettingsShouldModifyRelativeTestSettingsFilePat var finalSettingsXml = doc.OuterXml; var expectedPath = Path.GetFullPath(Path.Combine( - Path.GetDirectoryName(currentAssemblyLocation), "..\\remote.testsettings")); + Path.GetDirectoryName(currentAssemblyLocation)!, "..\\remote.testsettings")); var expectedSettingsXml = string.Concat( "", expectedPath, @@ -135,7 +133,7 @@ public void FixRelativePathsInRunSettingsShouldModifyRelativeResultsDirectory() var finalSettingsXml = doc.OuterXml; var expectedPath = Path.GetFullPath(Path.Combine( - Path.GetDirectoryName(currentAssemblyLocation), "..\\results")); + Path.GetDirectoryName(currentAssemblyLocation)!, "..\\results")); var expectedSettingsXml = string.Concat( "", expectedPath, diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs index 2ceaa2c5fa..05c860a3dc 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageDataAttachmentsHandlerTests.cs @@ -19,21 +19,19 @@ using Moq; -#nullable disable - namespace Microsoft.TestPlatform.Utilities.UnitTests; [TestClass] public class CodeCoverageDataAttachmentsHandlerTests { private readonly Mock> _mockProgressReporter; - private readonly XmlElement _configurationElement; + private readonly XmlElement? _configurationElement; private readonly CodeCoverageDataAttachmentsHandler _coverageDataAttachmentsHandler; private readonly string _filePrefix; - public TestContext TestContext { get; set; } + public TestContext? TestContext { get; set; } - internal string TestFilesDirectory => Path.Combine(TestContext.DeploymentDirectory, "TestFiles"); + internal string TestFilesDirectory => Path.Combine(TestContext!.DeploymentDirectory, "TestFiles"); public CodeCoverageDataAttachmentsHandlerTests() { diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageRunSettingsProcessorTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageRunSettingsProcessorTests.cs index 622cbf17d0..1659359a67 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageRunSettingsProcessorTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CodeCoverageRunSettingsProcessorTests.cs @@ -11,37 +11,30 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Utilities.UnitTests; [TestClass] public class CodeCoverageRunSettingsProcessorTests { - #region Members private readonly XmlElement _defaultSettings; - private readonly CodeCoverageRunSettingsProcessor _processor; - #endregion - #region Constructors public CodeCoverageRunSettingsProcessorTests() { _defaultSettings = GetDefaultConfiguration(); _processor = new CodeCoverageRunSettingsProcessor(_defaultSettings); } - #endregion #region Test Methods [TestMethod] public void ProcessingShouldReturnNullForNullOrEmptySettings() { - Assert.IsNull(_processor.Process((string)null)); + Assert.IsNull(_processor.Process((string?)null)); Assert.IsNull(_processor.Process("")); - Assert.IsNull(_processor.Process((XmlNode)null)); + Assert.IsNull(_processor.Process((XmlNode?)null)); - Assert.IsNull(_processor.Process((XmlDocument)null)); + Assert.IsNull(_processor.Process((XmlDocument?)null)); } [TestMethod] @@ -209,7 +202,7 @@ public void MixedTestShouldCorrectlyAddMissingTags() var processedNode = _processor.Process(settings); Assert.IsNotNull(processedNode); - var codeCoverageNodes = ExtractNodes(processedNode, expectedResultDocument.DocumentElement, "./CodeCoverage"); + var codeCoverageNodes = ExtractNodes(processedNode, expectedResultDocument.DocumentElement!, "./CodeCoverage"); CompareResults(codeCoverageNodes.Item1, codeCoverageNodes.Item2, "./ModulePaths/Exclude"); CompareResults(codeCoverageNodes.Item1, codeCoverageNodes.Item2, "./Functions/Exclude"); @@ -219,7 +212,7 @@ public void MixedTestShouldCorrectlyAddMissingTags() #endregion #region Helpers - private XmlNode ExtractNode(XmlNode node, string path) + private static XmlNode? ExtractNode(XmlNode node, string path) { try { @@ -232,20 +225,19 @@ private XmlNode ExtractNode(XmlNode node, string path) return null; } - private XmlElement GetDefaultConfiguration() + private static XmlElement GetDefaultConfiguration() { var document = new XmlDocument(); Assembly assembly = typeof(CodeCoverageRunSettingsProcessorTests).GetTypeInfo().Assembly; - using (Stream stream = assembly.GetManifestResourceStream( - "Microsoft.TestPlatform.Utilities.UnitTests.DefaultCodeCoverageConfig.xml")) + using (Stream stream = assembly.GetManifestResourceStream("Microsoft.TestPlatform.Utilities.UnitTests.DefaultCodeCoverageConfig.xml")!) { document.Load(stream); } - return document.DocumentElement; + return document.DocumentElement!; } - private Tuple ExtractNodes(XmlNode currentSettingsRoot, XmlNode defaultSettingsRoot, string path) + private static Tuple ExtractNodes(XmlNode currentSettingsRoot, XmlNode defaultSettingsRoot, string path) { var currentNode = ExtractNode(currentSettingsRoot, path); var defaultNode = ExtractNode(defaultSettingsRoot, path); @@ -255,7 +247,7 @@ private XmlElement GetDefaultConfiguration() return new Tuple(currentNode, defaultNode); } - private void CompareResults(XmlNode currentSettingsRoot, XmlNode defaultSettingsRoot, string path) + private static void CompareResults(XmlNode currentSettingsRoot, XmlNode defaultSettingsRoot, string path) { var nodes = ExtractNodes(currentSettingsRoot, defaultSettingsRoot, path); diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs index 099c5ece6d..eca85d9705 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/CommandLineUtilitiesTest.cs @@ -5,14 +5,12 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Utilities.Tests; [TestClass] public class CommandLineUtilitiesTest { - private void VerifyCommandLineSplitter(string commandLine, string[] expected) + private static void VerifyCommandLineSplitter(string commandLine, string[] expected) { CommandLineUtilities.SplitCommandLineIntoArguments(commandLine, out var actual); diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs index 842530b4e0..5e9bb4f9f3 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs @@ -16,8 +16,6 @@ using OMResources = Microsoft.VisualStudio.TestPlatform.ObjectModel.Resources.CommonResources; -#nullable disable - namespace Microsoft.TestPlatform.Utilities.UnitTests; [TestClass] @@ -260,19 +258,19 @@ public void MakeRunsettingsCompatibleShouldDeleteNewlyAddedRunConfigurationNode( public void MakeRunsettingsCompatibleShouldNotDeleteOldRunConfigurationNode() { var settings = @" - - False - False - x86 - net46 - dummypath - dummypath - dummypath - 2 - False - False - - "; + + False + False + x86 + net46 + dummypath + dummypath + dummypath + 2 + False + False + + "; var result = InferRunSettingsHelper.MakeRunsettingsCompatible(settings); @@ -290,15 +288,15 @@ public void MakeRunsettingsCompatibleShouldNotDeleteOldRunConfigurationNode() public void UpdateTargetDeviceValueFromOldMsTestSettings() { var settings = @" - - 2 - False - False - - - 169.254.193.190 - - "; + + 2 + False + False + + + 169.254.193.190 + + "; var xmlDocument = GetXmlDocument(settings); @@ -453,11 +451,11 @@ public void FilterCompatibleSourcesShouldRetrunWarningMessageIfNoConflict() public void IsTestSettingsEnabledShouldReturnTrueIfRunsettingsHasTestSettings() { string runsettingsString = @" - - C:\temp.testsettings - true - - "; + + C:\temp.testsettings + true + + "; Assert.IsTrue(InferRunSettingsHelper.IsTestSettingsEnabled(runsettingsString)); } @@ -466,10 +464,10 @@ public void IsTestSettingsEnabledShouldReturnTrueIfRunsettingsHasTestSettings() public void IsTestSettingsEnabledShouldReturnFalseIfRunsettingsDoesnotHaveTestSettings() { string runsettingsString = @" - - true - - "; + + true + + "; Assert.IsFalse(InferRunSettingsHelper.IsTestSettingsEnabled(runsettingsString)); } @@ -478,7 +476,7 @@ public void IsTestSettingsEnabledShouldReturnFalseIfRunsettingsDoesnotHaveTestSe public void TryGetLegacySettingsForRunSettingsWithoutLegacySettingsShouldReturnFalse() { string runSettingsXml = @" - "; + "; Assert.IsFalse(InferRunSettingsHelper.TryGetLegacySettingElements(runSettingsXml, out _)); } @@ -486,10 +484,10 @@ public void TryGetLegacySettingsForRunSettingsWithoutLegacySettingsShouldReturnF public void TryGetLegacySettingsForRunSettingsWithInvalidLegacySettingsShouldReturnFalse() { string runSettingsXml = @" - - - - "; + + + + "; Assert.IsFalse(InferRunSettingsHelper.TryGetLegacySettingElements(runSettingsXml, out _)); } @@ -497,9 +495,9 @@ public void TryGetLegacySettingsForRunSettingsWithInvalidLegacySettingsShouldRet public void TryGetLegacySettingsForRunSettingsWithEmptyLegacySettingsShouldReturnTrueAndEmptyListForLegacySettingElements() { string runSettingsXml = @" - - - "; + + + "; Assert.IsTrue(InferRunSettingsHelper.TryGetLegacySettingElements(runSettingsXml, out Dictionary legacySettings)); Assert.AreEqual(0, legacySettings.Count); @@ -509,22 +507,22 @@ public void TryGetLegacySettingsForRunSettingsWithEmptyLegacySettingsShouldRetur public void TryGetLegacySettingsForRunSettingsWithValidLegacySettingsShouldReturnTrueAndListForLegacySettingElements() { string runSettingsXml = @" - - - - - - - - - - - - - - - - "; + + + + + + + + + + + + + + + + "; var expectedElements = "Deployment, Scripts, Execution, AssemblyResolution, Timeouts, Hosts"; var expectedDeploymentAttributes = "enabled, deploySatelliteAssemblies"; @@ -541,13 +539,13 @@ public void TryGetLegacySettingsForRunSettingsWithValidLegacySettingsShouldRetur public void GetEnvironmentVariablesWithValidValuesInRunSettingsShouldReturnValidDictionary() { string runSettingsXml = @" - - - C:\temp - C:\temp2 - - - "; + + + C:\temp + C:\temp2 + + + "; var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettingsXml); @@ -560,13 +558,13 @@ public void GetEnvironmentVariablesWithValidValuesInRunSettingsShouldReturnValid public void GetEnvironmentVariablesWithDuplicateEnvValuesInRunSettingsShouldReturnValidDictionary() { string runSettingsXml = @" - - - C:\temp - C:\temp2 - - - "; + + + C:\temp + C:\temp2 + + + "; var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettingsXml); @@ -578,11 +576,11 @@ public void GetEnvironmentVariablesWithDuplicateEnvValuesInRunSettingsShouldRetu public void GetEnvironmentVariablesWithEmptyVariablesInRunSettingsShouldReturnEmptyDictionary() { string runSettingsXml = @" - - - - - "; + + + + + "; var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettingsXml); Assert.AreEqual(0, envVars.Count); @@ -592,12 +590,12 @@ public void GetEnvironmentVariablesWithEmptyVariablesInRunSettingsShouldReturnEm public void GetEnvironmentVariablesWithInvalidValuesInRunSettingsShouldReturnNull() { string runSettingsXml = @" - - - - - - "; + + + + + + "; var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettingsXml); Assert.IsNull(envVars); @@ -607,9 +605,9 @@ public void GetEnvironmentVariablesWithInvalidValuesInRunSettingsShouldReturnNul public void GetEnvironmentVariablesWithoutEnvVarNodeInRunSettingsShouldReturnNull() { string runSettingsXml = @" - - - "; + + + "; var envVars = InferRunSettingsHelper.GetEnvironmentVariables(runSettingsXml); Assert.IsNull(envVars); @@ -622,30 +620,30 @@ public void RunSettingsWithCodeCoverageAndInlineTestSettingsXml() { // Setup var runSettingsWithCodeCoverageAndInlineTestSettingsXml = @" - - - Framework45 - C:\TestProject1\TestResults - C:\TestProject1\ - X86 - - - C:\TestProject1\TestSettings1.testsettings - true - true - - - - - - DevBox 2018-01-07 20_42_30.coverage - - - - - - - "; + + + Framework45 + C:\TestProject1\TestResults + C:\TestProject1\ + X86 + + + C:\TestProject1\TestSettings1.testsettings + true + true + + + + + + DevBox 2018-01-07 20_42_30.coverage + + + + + + + "; // Act and validate Assert.IsFalse(InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings( @@ -658,27 +656,27 @@ public void RunSettingsWithCodeCoverageAndInlineTestSettingsXml() public void RunSettingsWithFakesAndCodeCoverageAndInlineTestSettingsXml() { var runSettingsWithFakesAndCodeCoverageAndInlineTestSettingsXml = @" - - - Framework45 - C:\TestProject1\TestResults - C:\TestProject1\ - X86 - - - C:\TestProject1\TestSettings1.testsettings - true - true - - - - - - - - - - "; + + + Framework45 + C:\TestProject1\TestResults + C:\TestProject1\ + X86 + + + C:\TestProject1\TestSettings1.testsettings + true + true + + + + + + + + + + "; // Act and validate Assert.IsFalse(InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings( @@ -691,24 +689,24 @@ public void RunSettingsWithFakesAndCodeCoverageAndInlineTestSettingsXml() public void RunSettingsWithEnabledAndDisabledCollectorAndNoEmbeddedTestSettingsXml() { var runSettingsWithEnabledAndDisabledCollectorAndInlineTestSettingsXml = @" - - - Framework45 - C:\TestProject1\TestResults - C:\TestProject1\ - X86 - - - - - - - - - - - - "; + + + Framework45 + C:\TestProject1\TestResults + C:\TestProject1\ + X86 + + + + + + + + + + + + "; // Act and validate Assert.IsFalse(InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings( @@ -721,29 +719,29 @@ public void RunSettingsWithEnabledAndDisabledCollectorAndNoEmbeddedTestSettingsX public void RunSettingsWithEnabledAndDisabledCollectorAndInlineTestSettingsXml() { var runSettingsWithEnabledAndDisabledCollectorAndInlineTestSettingsXml = @" - - - Framework45 - C:\TestProject1\TestResults - C:\TestProject1\ - X86 - - - C:\TestProject1\TestSettings1.testsettings - true - true - - - - - - - - - - - - "; + + + Framework45 + C:\TestProject1\TestResults + C:\TestProject1\ + X86 + + + C:\TestProject1\TestSettings1.testsettings + true + true + + + + + + + + + + + + "; // Act and validate Assert.IsTrue(InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings( @@ -756,29 +754,29 @@ public void RunSettingsWithEnabledAndDisabledCollectorAndInlineTestSettingsXml() public void RunSettingsWithDisabledCollectionSettingsAndInlineTestSettingsXml() { var runSettingsWithDisabledCollectionSettingsAndInlineTestSettingsXml = @" - - - Framework45 - C:\TestProject1\TestResults - C:\TestProject1\ - X86 - - - C:\TestProject1\TestSettings1.testsettings - true - true - - - - - - - - - - - - "; + + + Framework45 + C:\TestProject1\TestResults + C:\TestProject1\ + X86 + + + C:\TestProject1\TestSettings1.testsettings + true + true + + + + + + + + + + + + "; // Act and validate Assert.IsFalse(InferRunSettingsHelper.AreRunSettingsCollectorsIncompatibleWithTestSettings( @@ -796,7 +794,7 @@ private string GetSourceIncompatibleMessage(string source) return string.Format(CultureInfo.CurrentCulture, OMResources.SourceIncompatible, source, _sourceFrameworks[source].Name, _sourceArchitectures[source]); } - private XmlDocument GetXmlDocument(string settingsXml) + private static XmlDocument GetXmlDocument(string settingsXml) { var doc = new XmlDocument(); doc.LoadXml(settingsXml); @@ -804,12 +802,12 @@ private XmlDocument GetXmlDocument(string settingsXml) return doc; } - private string GetValueOf(XmlDocument xmlDocument, string xpath) + private static string GetValueOf(XmlDocument xmlDocument, string xpath) { - return xmlDocument.SelectSingleNode(xpath).InnerText; + return xmlDocument.SelectSingleNode(xpath)!.InnerText; } - private string ConvertOutOfProcToInProcDataCollectionSettings(string settings) + private static string ConvertOutOfProcToInProcDataCollectionSettings(string settings) { return settings.Replace("DataCollectionRunSettings", "InProcDataCollectionRunSettings") .Replace("", "") diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/MSTestSettingsUtilitiesTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/MSTestSettingsUtilitiesTests.cs index 764e43eaf2..7b5e257b1d 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/MSTestSettingsUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/MSTestSettingsUtilitiesTests.cs @@ -9,8 +9,6 @@ using MSTest.TestFramework.AssertExtensions; -#nullable disable - namespace Microsoft.TestPlatform.Utilities.Tests; [TestClass] @@ -80,7 +78,7 @@ public void ImportShouldEmbedTestSettingsInformation() "C:\\temp\\r.testsettings", xmlDocument); - var finalSettingsXml = finalxPath.CreateNavigator().OuterXml; + var finalSettingsXml = finalxPath.CreateNavigator()!.OuterXml; var expectedSettingsXml = string.Join(Environment.NewLine, "", @@ -105,7 +103,7 @@ public void ImportShouldEmbedTestSettingsAndDefaultRunConfigurationInformation() "C:\\temp\\r.testsettings", xmlDocument); - var finalSettingsXml = finalxPath.CreateNavigator().OuterXml; + var finalSettingsXml = finalxPath.CreateNavigator()!.OuterXml; var expectedSettingsXml = string.Join(Environment.NewLine, "", diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/StringUtilitiesTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/StringUtilitiesTests.cs index 01499a68bc..85bb55149b 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/StringUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/StringUtilitiesTests.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Utilities.UnitTests; [TestClass] diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/XmlUtilitiesTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/XmlUtilitiesTests.cs index bfb0454d30..b3b3e385ad 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/XmlUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/XmlUtilitiesTests.cs @@ -10,8 +10,6 @@ using Microsoft.VisualStudio.TestTools.UnitTesting; -#nullable disable - namespace Microsoft.TestPlatform.Utilities.UnitTests; [TestClass] @@ -195,7 +193,7 @@ public void RemoveChildNodeShouldRemoveXmlIfExist() var settingsXml = @"abc"; var xmlDocument = GetXmlDocument(settingsXml); var navigator = xmlDocument.CreateNavigator(); - navigator.MoveToChild("RunSettings", string.Empty); + navigator!.MoveToChild("RunSettings", string.Empty); XmlUtilities.RemoveChildNode(navigator, @"/RunSettings/RC", "RC"); Assert.AreEqual(@"", xmlDocument.OuterXml); From dbf9d2954ff497a9875e8e4a026377202a173a13 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Wed, 30 Mar 2022 14:52:02 +0200 Subject: [PATCH 2/2] Fix new issues --- StringUtils.cs | 17 ++++++++ .../AcceptanceTestBase.cs | 2 +- .../BannedSymbols.txt | 4 +- .../IntegrationTestBase.cs | 42 +++++++++---------- .../IntegrationTestEnvironment.cs | 12 +++--- ...icrosoft.TestPlatform.TestUtilities.csproj | 4 ++ 6 files changed, 50 insertions(+), 31 deletions(-) create mode 100644 StringUtils.cs diff --git a/StringUtils.cs b/StringUtils.cs new file mode 100644 index 0000000000..edc97e2c3d --- /dev/null +++ b/StringUtils.cs @@ -0,0 +1,17 @@ +// 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; + +namespace Microsoft.TestPlatform; + +internal static class StringUtils +{ + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrEmpty([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrEmpty(value); + + [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] + public static bool IsNullOrWhiteSpace([NotNullWhen(returnValue: false)] this string? value) + => string.IsNullOrWhiteSpace(value); +} diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/AcceptanceTestBase.cs b/test/Microsoft.TestPlatform.AcceptanceTests/AcceptanceTestBase.cs index 934b7de8e6..244ecbc7a6 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/AcceptanceTestBase.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/AcceptanceTestBase.cs @@ -61,7 +61,7 @@ public class AcceptanceTestBase : IntegrationTestBase public const string LATEST_TO_LEGACY = "Latest;LatestPreview;LatestStable;RecentStable;MostDownloaded;PreviousStable;LegacyStable"; public const string LATESTPREVIEW_TO_LEGACY = "LatestPreview;LatestStable;RecentStable;MostDownloaded;PreviousStable;LegacyStable"; public const string LATEST = "Latest"; - public const string LATESTSTABLE= "LatestStable"; + public const string LATESTSTABLE = "LatestStable"; internal const string MSTEST = "MSTest"; public static string And(string left, string right) diff --git a/test/Microsoft.TestPlatform.TestUtilities/BannedSymbols.txt b/test/Microsoft.TestPlatform.TestUtilities/BannedSymbols.txt index c8eaef56e1..87ce187c16 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/BannedSymbols.txt +++ b/test/Microsoft.TestPlatform.TestUtilities/BannedSymbols.txt @@ -1,3 +1,5 @@ M:System.IO.Path.GetTempPath(); Use 'IntegrationTestBase.GetTempPath()' instead M:System.Environment.SetEnvironmentVariable(System.String,System.String); Use one of the overload accepting a dictionary of environment variables instead -M:System.Environment.SetEnvironmentVariable(System.String,System.String,System.EnvironmentVariableTarget); Use one of the overload accepting a dictionary of environment variables instead \ No newline at end of file +M:System.Environment.SetEnvironmentVariable(System.String,System.String,System.EnvironmentVariableTarget); Use one of the overload accepting a dictionary of environment variables instead +M:System.String.IsNullOrEmpty(System.String); Use 'StringUtils.IsNullOrEmpty' instead +M:System.String.IsNullOrWhiteSpace(System.String); Use 'StringUtils.IsNullOrWhiteSpace' instead diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs index de93b4a8fe..2530d9f2e9 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs @@ -88,7 +88,7 @@ public void TempDirectoryCleanup() // // Locally delete the directory only when the test succeeded, so we can look // at results and logs of failed tests. - if (IsCI || TestContext.CurrentTestOutcome == UnitTestOutcome.Passed) + if (IsCI || TestContext?.CurrentTestOutcome == UnitTestOutcome.Passed) { TempDirectory.Dispose(); } @@ -104,7 +104,7 @@ public void TempDirectoryCleanup() /// /// Command line arguments string. public static string PrepareArguments(string[] testAssemblies, string testAdapterPath, string runSettings, - string framework, string inIsolation = "", string? resultsDirectory = null) + string framework, string? inIsolation = "", string? resultsDirectory = null) { var arguments = ""; foreach (var path in testAssemblies) @@ -124,19 +124,19 @@ public void TempDirectoryCleanup() arguments = arguments.Trim(); - if (!string.IsNullOrWhiteSpace(testAdapterPath)) + if (!testAdapterPath.IsNullOrWhiteSpace()) { // Append adapter path arguments = string.Concat(arguments, " /testadapterpath:", testAdapterPath.AddDoubleQuote()); } - if (!string.IsNullOrWhiteSpace(runSettings)) + if (!runSettings.IsNullOrWhiteSpace()) { // Append run settings arguments = string.Concat(arguments, " /settings:", runSettings.AddDoubleQuote()); } - if (!string.IsNullOrWhiteSpace(framework)) + if (!framework.IsNullOrWhiteSpace()) { // Append run settings arguments = string.Concat(arguments, " /framework:", framework.AddDoubleQuote()); @@ -144,7 +144,7 @@ public void TempDirectoryCleanup() arguments = string.Concat(arguments, " /logger:", "console;verbosity=normal".AddDoubleQuote()); - if (!string.IsNullOrWhiteSpace(inIsolation)) + if (!inIsolation.IsNullOrWhiteSpace()) { if (inIsolation != "/InIsolation") { @@ -154,7 +154,7 @@ public void TempDirectoryCleanup() arguments = string.Concat(arguments, " ", inIsolation); } - if (!string.IsNullOrWhiteSpace(resultsDirectory)) + if (!resultsDirectory.IsNullOrWhiteSpace()) { // Append results directory arguments = string.Concat(arguments, " /ResultsDirectory:", resultsDirectory.AddDoubleQuote()); @@ -173,7 +173,7 @@ public void TempDirectoryCleanup() /// /// Command line arguments string. public static string PrepareArguments(string testAssembly, string testAdapterPath, string runSettings, - string framework, string inIsolation = "", string? resultsDirectory = null) + string framework, string? inIsolation = "", string? resultsDirectory = null) => PrepareArguments(new string[] { testAssembly }, testAdapterPath, runSettings, framework, inIsolation, resultsDirectory); @@ -192,7 +192,7 @@ public void InvokeVsTest(string arguments, Dictionary? environme /// Invokes our local copy of dotnet that is patched with artifacts from the build with specified arguments. /// /// Arguments provided to vstest.console.exe - public void InvokeDotnetTest(string arguments, Dictionary environmentVariables = null) + public void InvokeDotnetTest(string arguments, Dictionary? environmentVariables = null) { var debugEnvironmentVariables = AddDebugEnvironmentVariables(environmentVariables); @@ -228,7 +228,7 @@ public void InvokeDotnetTest(string arguments, Dictionary enviro InvokeVsTest(arguments, environmentVariables); } - private Dictionary AddDebugEnvironmentVariables(Dictionary environmentVariables) + private Dictionary AddDebugEnvironmentVariables(Dictionary? environmentVariables) { environmentVariables ??= new Dictionary(); @@ -295,7 +295,7 @@ public void ExecuteNotSupportedRunnerFrameworkTests(string runnerFramework, stri public void ValidateSummaryStatus(int passed, int failed, int skipped) { // TODO: Switch on the actual version of vstest console when we have that set on test environment. - if (_testEnvironment.VSTestConsoleInfo != null && _testEnvironment.VSTestConsoleInfo.Path.Contains($"{Path.DirectorySeparatorChar}15.")) + if (_testEnvironment.VSTestConsoleInfo?.Path?.Contains($"{Path.DirectorySeparatorChar}15.") == true) { ValidateSummaryStatusv15(passed, failed, skipped); return; @@ -612,14 +612,9 @@ public virtual string GetConsoleRunnerPath() if (IsDesktopRunner()) { - if (!string.IsNullOrWhiteSpace(_testEnvironment.VSTestConsoleInfo?.Path)) - { - consoleRunnerPath = _testEnvironment.VSTestConsoleInfo.Path; - } - else - { - consoleRunnerPath = Path.Combine(_testEnvironment.PublishDirectory, "vstest.console.exe"); - } + consoleRunnerPath = StringUtils.IsNullOrWhiteSpace(_testEnvironment.VSTestConsoleInfo?.Path) + ? Path.Combine(_testEnvironment.PublishDirectory, "vstest.console.exe") + : _testEnvironment.VSTestConsoleInfo.Path; } else if (IsNetCoreRunner()) { @@ -699,10 +694,10 @@ public IVsTestConsoleWrapper GetVsTestConsoleWrapper(TraceLevel traceLevel = Tra // variables, unless we explicitly say to clean them. https://github.com/microsoft/vstest/pull/3433 // Remove this code later, and just pass the variables you want to add. var debugEnvironmentVariables = AddDebugEnvironmentVariables(new Dictionary()); - Dictionary environmentVariables = new(); + Dictionary environmentVariables = new(); if (debugEnvironmentVariables.Count > 0) { - Environment.GetEnvironmentVariables().OfType().ToList().ForEach(e => environmentVariables.Add(e.Key.ToString(), e.Value.ToString())); + Environment.GetEnvironmentVariables().OfType().ToList().ForEach(e => environmentVariables.Add(e.Key.ToString()!, e.Value?.ToString())); foreach (var pair in debugEnvironmentVariables) { environmentVariables[pair.Key] = pair.Value; @@ -760,7 +755,8 @@ protected void ExecuteVsTestConsole(string args, out string stdOut, out string s /// /// /// - private void ExecutePatchedDotnet(string command, string args, out string stdOut, out string stdError, out int exitCode, Dictionary environmentVariables = null) + private void ExecutePatchedDotnet(string command, string args, out string stdOut, out string stdError, out int exitCode, + Dictionary? environmentVariables = null) { if (environmentVariables is null) { @@ -777,7 +773,7 @@ private void ExecutePatchedDotnet(string command, string args, out string stdOut protected static void ExecuteApplication(string path, string args, out string stdOut, out string stdError, out int exitCode, Dictionary? environmentVariables = null, string? workingDirectory = null) { - if (string.IsNullOrWhiteSpace(path)) + if (path.IsNullOrWhiteSpace()) { throw new ArgumentException("Executable path must not be null or whitespace.", nameof(path)); } diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs index be39dacd48..4bf3e6d7a7 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestEnvironment.cs @@ -28,13 +28,13 @@ public class IntegrationTestEnvironment public IntegrationTestEnvironment() { // If the variables are not set, valid defaults are assumed. - if (string.IsNullOrEmpty(TargetFramework)) + if (TargetFramework.IsNullOrEmpty()) { // Run integration tests for net451 by default. TargetFramework = "net451"; } - if (string.IsNullOrEmpty(TestPlatformRootDirectory)) + if (TestPlatformRootDirectory.IsNullOrEmpty()) { // Running in VS/IDE. Use artifacts directory as root. // Get root directory from test assembly output directory @@ -118,7 +118,7 @@ public string PublishDirectory { if (RunnerFramework == IntegrationTestBase.DesktopRunnerFramework) { - if (string.IsNullOrEmpty(_targetRuntime)) + if (_targetRuntime.IsNullOrEmpty()) { _targetRuntime = "win7-x64"; } @@ -165,8 +165,8 @@ public string PublishDirectory // A known AzureDevOps env variable meaning we are running in CI. public static bool IsCI { get; } = Environment.GetEnvironmentVariable("TF_BUILD") == "True"; - public DebugInfo DebugInfo { get; set; } - public VSTestConsoleInfo VSTestConsoleInfo { get; set; } + public DebugInfo? DebugInfo { get; set; } + public VSTestConsoleInfo? VSTestConsoleInfo { get; set; } public List DllInfos { get; set; } = new(); /// @@ -258,7 +258,7 @@ public string GetNugetPackage(string packageSuffix) props.Read(); // Read thru the PropertyGroup node while (!props.EOF) { - if (props.IsStartElement() && !string.IsNullOrEmpty(props.Name)) + if (props.IsStartElement() && !props.Name.IsNullOrEmpty()) { if (!dependencyProps.ContainsKey(props.Name)) { diff --git a/test/Microsoft.TestPlatform.TestUtilities/Microsoft.TestPlatform.TestUtilities.csproj b/test/Microsoft.TestPlatform.TestUtilities/Microsoft.TestPlatform.TestUtilities.csproj index 527a9a44b3..874507d07d 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/Microsoft.TestPlatform.TestUtilities.csproj +++ b/test/Microsoft.TestPlatform.TestUtilities/Microsoft.TestPlatform.TestUtilities.csproj @@ -16,6 +16,10 @@ + + + +