From 270e9d3db0563648581c93f9e78af1a4be63c687 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Mon, 13 Jun 2022 14:56:44 +0200 Subject: [PATCH 1/2] Enable nullables on CoreUtilities --- .../Constants.cs | 2 - .../Extensions/StringBuilderExtensions.cs | 34 +++---- .../Extensions/StringExtensions.cs | 2 - .../FeatureFlag/FeatureFlag.cs | 4 +- .../Helpers/CommandLineArgumentsHelper.cs | 12 +-- .../Helpers/DotnetHostHelper.cs | 95 +++++++++---------- .../Helpers/EnvironmentHelper.cs | 4 +- .../Helpers/EnvironmentVariableHelper.cs | 2 - .../Helpers/FileHelper.cs | 2 - .../Interfaces/IWindowsRegistryHelper.cs | 10 +- .../Helpers/RunSettingsHelper.cs | 2 - .../Helpers/WindowsRegistryHelper.cs | 10 +- ...icrosoft.TestPlatform.CoreUtilities.csproj | 16 ++++ .../NullableHelpers.cs | 42 ++++++++ .../NullableHelpers.tt | 45 +++++++++ .../Output/ConsoleOutput.cs | 4 +- .../Output/IOutput.cs | 2 - .../Output/OutputExtensions.cs | 14 ++- .../Output/OutputLevel.cs | 2 - .../Tracing/EqtTrace.cs | 50 +++++----- .../Interfaces/ITestPlatformEventSource.cs | 2 - .../Tracing/TestPlatformEventSource.cs | 2 - .../TestPlatformInstrumentationEvents.cs | 2 - .../Utilities/Job.cs | 6 +- .../Utilities/JobQueue.cs | 8 +- .../Utilities/MulticastDelegateUtilities.cs | 57 +++++------ .../Utilities/TimeSpanParser.cs | 2 - .../ValidateArg.cs | 2 - .../Friends.cs | 1 + .../Interfaces/Tracing/IPlatformEqtTrace.cs | 4 +- .../PublicAPI/PublicAPI.Shipped.txt | 6 +- .../PublicAPI/net45/PublicAPI.Shipped.txt | 2 +- .../PublicAPI/net451/PublicAPI.Shipped.txt | 2 +- .../PublicAPI/net6.0/PublicAPI.Shipped.txt | 2 +- .../netcoreapp1.0/PublicAPI.Shipped.txt | 2 +- .../netcoreapp2.1/PublicAPI.Shipped.txt | 2 +- .../netstandard1.0/PublicAPI.Shipped.txt | 2 +- .../netstandard1.3/PublicAPI.Shipped.txt | 2 +- .../netstandard2.0/PublicAPI.Shipped.txt | 2 +- .../PublicAPI/uap10.0/PublicAPI.Shipped.txt | 2 +- .../common/Tracing/PlatformEqtTrace.cs | 4 +- .../netstandard/Tracing/PlatformEqtTrace.cs | 4 +- .../uap10.0/Tracing/PlatformEqtTrace.cs | 8 +- .../Hosting/DefaultTestHostManager.cs | 11 +-- .../Hosting/DotnetTestHostManager.cs | 6 +- src/testhost.x86/DefaultEngineInvoker.cs | 4 +- src/testhost.x86/Program.cs | 7 +- src/vstest.console/Internal/ConsoleLogger.cs | 3 + .../CommandLineArgumentsHelperTests.cs | 6 +- .../Helpers/DotnetHostHelperTest.cs | 16 ++-- .../Utilities/JobQueueTests.cs | 38 ++++---- .../EventHandlers/TestRequestHandlerTests.cs | 2 +- .../EnableDiagArgumentProcessorTests.cs | 4 +- 53 files changed, 317 insertions(+), 260 deletions(-) create mode 100644 src/Microsoft.TestPlatform.CoreUtilities/NullableHelpers.cs create mode 100644 src/Microsoft.TestPlatform.CoreUtilities/NullableHelpers.tt diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Constants.cs b/src/Microsoft.TestPlatform.CoreUtilities/Constants.cs index 8e31371274..83f51aca7f 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Constants.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/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.VisualStudio.TestPlatform.CoreUtilities; /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Extensions/StringBuilderExtensions.cs b/src/Microsoft.TestPlatform.CoreUtilities/Extensions/StringBuilderExtensions.cs index 72c60d395e..47ae3abe32 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Extensions/StringBuilderExtensions.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Extensions/StringBuilderExtensions.cs @@ -4,8 +4,6 @@ using System; using System.Text; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CoreUtilities.Extensions; public static class StringBuilderExtensions @@ -16,26 +14,28 @@ public static class StringBuilderExtensions /// string builder /// data to be appended. /// - public static void AppendSafeWithNewLine(this StringBuilder result, string data) + public static void AppendSafeWithNewLine(this StringBuilder result, string? data) { - if (!string.IsNullOrEmpty(data)) + if (data.IsNullOrEmpty()) { - // Don't append more data if already reached max length. - if (result.Length >= result.MaxCapacity) - { - return; - } + return; + } - // Add newline for readability. - data += Environment.NewLine; + // Don't append more data if already reached max length. + if (result.Length >= result.MaxCapacity) + { + return; + } - // Append sub string of data if appending all the data exceeds max capacity. - if (result.Length + data.Length >= result.MaxCapacity) - { - data = data.Substring(0, result.MaxCapacity - result.Length); - } + // Add newline for readability. + data += Environment.NewLine; - result.Append(data); + // Append sub string of data if appending all the data exceeds max capacity. + if (result.Length + data.Length >= result.MaxCapacity) + { + data = data.Substring(0, result.MaxCapacity - result.Length); } + + result.Append(data); } } diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Extensions/StringExtensions.cs b/src/Microsoft.TestPlatform.CoreUtilities/Extensions/StringExtensions.cs index c34bd55fef..c47ab5918c 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Extensions/StringExtensions.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Extensions/StringExtensions.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.VisualStudio.TestPlatform.CoreUtilities.Extensions; public static class StringExtensions diff --git a/src/Microsoft.TestPlatform.CoreUtilities/FeatureFlag/FeatureFlag.cs b/src/Microsoft.TestPlatform.CoreUtilities/FeatureFlag/FeatureFlag.cs index 26ab30b2c9..d61a4b260e 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/FeatureFlag/FeatureFlag.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/FeatureFlag/FeatureFlag.cs @@ -10,9 +10,9 @@ namespace Microsoft.VisualStudio.TestPlatform.Utilities; /// /// !!!NEVER USE A FLAG TO ENABLE FUNCTIONALITY!!! -/// +/// /// The reasoning is: -/// +/// /// * New version will automatically ship with the feature enabled. There is no action needed to be done just before release. /// * Anyone interested in the new feature will get it automatically by grabbing our preview. /// * Anyone who needs more time before using the new feature can disable it in the released package. diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/CommandLineArgumentsHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/CommandLineArgumentsHelper.cs index c0bb72a7a2..216db267a1 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/CommandLineArgumentsHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/CommandLineArgumentsHelper.cs @@ -4,8 +4,6 @@ using System; using System.Collections.Generic; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers; /// @@ -18,9 +16,9 @@ public class CommandLineArgumentsHelper /// /// Command line arguments. Ex: { "--port", "12312", "--parentprocessid", "2312", "--testsourcepath", "C:\temp\1.dll" } /// Dictionary of arguments keys and values. - public static IDictionary GetArgumentsDictionary(string[] args) + public static IDictionary GetArgumentsDictionary(string[]? args) { - var argsDictionary = new Dictionary(); + var argsDictionary = new Dictionary(); if (args == null) { return argsDictionary; @@ -52,7 +50,7 @@ public static IDictionary GetArgumentsDictionary(string[] args) /// The full name for required argument. Ex: "--port" /// Value of the argument. /// Thrown if value of an argument is not an integer. - public static int GetIntArgFromDict(IDictionary argsDictionary, string fullname) + public static int GetIntArgFromDict(IDictionary argsDictionary, string fullname) { var found = TryGetIntArgFromDict(argsDictionary, fullname, out var value); return found ? value : 0; @@ -65,7 +63,7 @@ public static int GetIntArgFromDict(IDictionary argsDictionary, /// The full name for required argument. Ex: "--port" /// Value of the argument. /// Thrown if value of an argument is not an integer. - public static bool TryGetIntArgFromDict(IDictionary argsDictionary, string fullname, out int value) + public static bool TryGetIntArgFromDict(IDictionary argsDictionary, string fullname, out int value) { var found = argsDictionary.TryGetValue(fullname, out var optionValue); if (!found) @@ -86,7 +84,7 @@ public static bool TryGetIntArgFromDict(IDictionary argsDictiona /// The full name for required argument. Ex: "--port" /// Value of the argument. /// Thrown if value of an argument is not an integer. - public static string GetStringArgFromDict(IDictionary argsDictionary, string fullname) + public static string? GetStringArgFromDict(IDictionary argsDictionary, string fullname) { return argsDictionary.TryGetValue(fullname, out var optionValue) ? optionValue : string.Empty; } diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs index 8c45d307e9..abd4b03361 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs @@ -4,6 +4,7 @@ #if !NETSTANDARD1_0 using System; +using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection.PortableExecutable; @@ -17,8 +18,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; using Microsoft.Win32; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Helpers; public class DotnetHostHelper : IDotnetHostHelper @@ -120,12 +119,12 @@ private bool TryGetExecutablePath(string executableBaseName, out string executab return false; } - public bool TryGetDotnetPathByArchitecture(PlatformArchitecture targetArchitecture, out string muxerPath) + public bool TryGetDotnetPathByArchitecture(PlatformArchitecture targetArchitecture, [NotNullWhen(true)] out string? muxerPath) { // If current process is the same as the target architecture we return the current process filename. if (_processHelper.GetCurrentProcessArchitecture() == targetArchitecture) { - string currentProcessFileName = _processHelper.GetCurrentProcessFileName(); + string currentProcessFileName = _processHelper.GetCurrentProcessFileName()!; if (Path.GetFileName(currentProcessFileName) == _muxerName) { muxerPath = currentProcessFileName; @@ -279,48 +278,40 @@ public bool TryGetDotnetPathByArchitecture(PlatformArchitecture targetArchitectu return true; } - private string GetMuxerFromGlobalRegistrationWin(PlatformArchitecture targetArchitecture) + private string? GetMuxerFromGlobalRegistrationWin(PlatformArchitecture targetArchitecture) { // Installed version are always in 32-bit view of registry // https://github.com/dotnet/designs/blob/main/accepted/2020/install-locations.md#globally-registered-install-location-new // "Note that this registry key is "redirected" that means that 32-bit processes see different copy of the key than 64bit processes. // So it's important that both installers and the host access only the 32-bit view of the registry." - using (IRegistryKey hklm = _windowsRegistryHelper.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32)) + using IRegistryKey? hklm = _windowsRegistryHelper.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32); + if (hklm == null) { - if (hklm != null) - { - using IRegistryKey dotnetInstalledVersion = hklm.OpenSubKey(@"SOFTWARE\dotnet\Setup\InstalledVersions"); - if (dotnetInstalledVersion != null) - { - using IRegistryKey nativeArch = dotnetInstalledVersion.OpenSubKey(targetArchitecture.ToString().ToLowerInvariant()); - string installLocation = nativeArch?.GetValue("InstallLocation")?.ToString(); - - if (installLocation != null) - { - string path = Path.Combine(installLocation.Trim(), _muxerName); - EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Muxer resolved using win registry key 'SOFTWARE\dotnet\Setup\InstalledVersions\{targetArchitecture.ToString().ToLowerInvariant()}\InstallLocation' in '{path}'"); - return path; - } - else - { - EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing registry InstallLocation"); - } - } - else - { - EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing RegistryHive.LocalMachine for RegistryView.Registry32"); - } - } - else - { - EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing SOFTWARE\dotnet\Setup\InstalledVersions subkey"); - } + EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing SOFTWARE\dotnet\Setup\InstalledVersions subkey"); + return null; } - return null; + using IRegistryKey? dotnetInstalledVersion = hklm.OpenSubKey(@"SOFTWARE\dotnet\Setup\InstalledVersions"); + if (dotnetInstalledVersion == null) + { + EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing RegistryHive.LocalMachine for RegistryView.Registry32"); + return null; + } + + using IRegistryKey? nativeArch = dotnetInstalledVersion.OpenSubKey(targetArchitecture.ToString().ToLowerInvariant()); + string? installLocation = nativeArch?.GetValue("InstallLocation")?.ToString(); + if (installLocation == null) + { + EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Missing registry InstallLocation"); + return null; + } + + string path = Path.Combine(installLocation.Trim(), _muxerName); + EqtTrace.Verbose($@"DotnetHostHelper.GetMuxerFromGlobalRegistrationWin: Muxer resolved using win registry key 'SOFTWARE\dotnet\Setup\InstalledVersions\{targetArchitecture.ToString().ToLowerInvariant()}\InstallLocation' in '{path}'"); + return path; } - private string GetMuxerFromGlobalRegistrationOnUnix(PlatformArchitecture targetArchitecture) + private string? GetMuxerFromGlobalRegistrationOnUnix(PlatformArchitecture targetArchitecture) { string baseInstallLocation = "/etc/dotnet/"; @@ -333,22 +324,24 @@ private string GetMuxerFromGlobalRegistrationOnUnix(PlatformArchitecture targetA installLocation = $"{baseInstallLocation}install_location"; } - if (_fileHelper.Exists(installLocation)) + if (!_fileHelper.Exists(installLocation)) { - try - { - using Stream stream = _fileHelper.GetStream(installLocation, FileMode.Open, FileAccess.Read); - using StreamReader streamReader = new(stream); - string content = streamReader.ReadToEnd().Trim(); - EqtTrace.Verbose($"DotnetHostHelper: '{installLocation}' content '{content}'"); - string path = Path.Combine(content, _muxerName); - EqtTrace.Verbose($"DotnetHostHelper: Muxer resolved using '{installLocation}' in '{path}'"); - return path; - } - catch (Exception ex) - { - EqtTrace.Error($"DotnetHostHelper.GetMuxerFromGlobalRegistrationOnUnix: Exception during '{installLocation}' muxer resolution.\n{ex}"); - } + return null; + } + + try + { + using Stream stream = _fileHelper.GetStream(installLocation, FileMode.Open, FileAccess.Read); + using StreamReader streamReader = new(stream); + string content = streamReader.ReadToEnd().Trim(); + EqtTrace.Verbose($"DotnetHostHelper: '{installLocation}' content '{content}'"); + string path = Path.Combine(content, _muxerName); + EqtTrace.Verbose($"DotnetHostHelper: Muxer resolved using '{installLocation}' in '{path}'"); + return path; + } + catch (Exception ex) + { + EqtTrace.Error($"DotnetHostHelper.GetMuxerFromGlobalRegistrationOnUnix: Exception during '{installLocation}' muxer resolution.\n{ex}"); } return null; diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/EnvironmentHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/EnvironmentHelper.cs index 11d0502af9..36579f9e18 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/EnvironmentHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/EnvironmentHelper.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers; public class EnvironmentHelper @@ -28,7 +26,7 @@ public static int GetConnectionTimeout() var envVarValue = Environment.GetEnvironmentVariable(VstestConnectionTimeout); #endif - if (!string.IsNullOrEmpty(envVarValue) && int.TryParse(envVarValue, out int value) && value >= 0) + if (!envVarValue.IsNullOrEmpty() && int.TryParse(envVarValue, out int value) && value >= 0) { EqtTrace.Info("EnvironmentHelper.GetConnectionTimeout: {0} value set to {1}.", VstestConnectionTimeout, value); } diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/EnvironmentVariableHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/EnvironmentVariableHelper.cs index bc249f5318..d7457292ea 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/EnvironmentVariableHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/EnvironmentVariableHelper.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers; internal class EnvironmentVariableHelper : IEnvironmentVariableHelper diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/FileHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/FileHelper.cs index 8cc850ac0a..4c144d9e96 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/FileHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/FileHelper.cs @@ -11,8 +11,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/Interfaces/IWindowsRegistryHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/Interfaces/IWindowsRegistryHelper.cs index fb0fa983cc..08ace47c5d 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/Interfaces/IWindowsRegistryHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/Interfaces/IWindowsRegistryHelper.cs @@ -7,22 +7,20 @@ using Microsoft.Win32; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; internal interface IWindowsRegistryHelper { - IRegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view); + IRegistryKey? OpenBaseKey(RegistryHive hKey, RegistryView view); } internal interface IRegistryKey : IDisposable { - IRegistryKey OpenSubKey(string name); + IRegistryKey? OpenSubKey(string name); - object GetValue(string name); + object? GetValue(string name); - string[] GetSubKeyNames(); + string[]? GetSubKeyNames(); } #endif diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/RunSettingsHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/RunSettingsHelper.cs index 80f9514149..2679c50e68 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/RunSettingsHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/RunSettingsHelper.cs @@ -3,8 +3,6 @@ using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/WindowsRegistryHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/WindowsRegistryHelper.cs index f0fb628926..51a675dea4 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/WindowsRegistryHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/WindowsRegistryHelper.cs @@ -7,13 +7,11 @@ using Microsoft.Win32; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; internal class WindowsRegistryHelper : IWindowsRegistryHelper { - public IRegistryKey OpenBaseKey(RegistryHive hKey, RegistryView view) + public IRegistryKey? OpenBaseKey(RegistryHive hKey, RegistryView view) { var keyRegistry = RegistryKey.OpenBaseKey(hKey, view); return keyRegistry is null ? null : new RegistryKeyWrapper(keyRegistry); @@ -29,18 +27,18 @@ public RegistryKeyWrapper(RegistryKey registryKey) _registryKey = registryKey; } - public object GetValue(string name) + public object? GetValue(string name) { return _registryKey?.GetValue(name)?.ToString(); } - public IRegistryKey OpenSubKey(string name) + public IRegistryKey? OpenSubKey(string name) { var keyRegistry = _registryKey.OpenSubKey(name); return keyRegistry is null ? null : new RegistryKeyWrapper(keyRegistry); } - public string[] GetSubKeyNames() + public string[]? GetSubKeyNames() => _registryKey?.GetSubKeyNames(); public void Dispose() diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Microsoft.TestPlatform.CoreUtilities.csproj b/src/Microsoft.TestPlatform.CoreUtilities/Microsoft.TestPlatform.CoreUtilities.csproj index 631819d485..a47d0f305e 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Microsoft.TestPlatform.CoreUtilities.csproj +++ b/src/Microsoft.TestPlatform.CoreUtilities/Microsoft.TestPlatform.CoreUtilities.csproj @@ -51,6 +51,11 @@ + + True + True + NullableHelpers.tt + True True @@ -78,6 +83,17 @@ + + + + NullableHelpers.cs + TextTemplatingFileGenerator + + + + + + Microsoft.VisualStudio.TestPlatform.CoreUtilities diff --git a/src/Microsoft.TestPlatform.CoreUtilities/NullableHelpers.cs b/src/Microsoft.TestPlatform.CoreUtilities/NullableHelpers.cs new file mode 100644 index 0000000000..38f7ec583f --- /dev/null +++ b/src/Microsoft.TestPlatform.CoreUtilities/NullableHelpers.cs @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// +// This code is auto-generated. Changes to this file will be lost! +// This T4 file is copied in various projects because inclusion as link or through shared project +// doesn't allow to generate the C# file locally. If some modification is required, please update +// all instances. +// + +#nullable enable + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace Microsoft.VisualStudio.TestPlatform.CoreUtilities; + +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); +} + +[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] +internal static class TPDebug +{ + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b) + => Debug.Assert(b); + + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b, string message) + => Debug.Assert(b, message); +} diff --git a/src/Microsoft.TestPlatform.CoreUtilities/NullableHelpers.tt b/src/Microsoft.TestPlatform.CoreUtilities/NullableHelpers.tt new file mode 100644 index 0000000000..7e3d8e7270 --- /dev/null +++ b/src/Microsoft.TestPlatform.CoreUtilities/NullableHelpers.tt @@ -0,0 +1,45 @@ +<#@ template debug="true" hostspecific="true" language="C#" #> +<#@ output extension=".cs" #> +<#@ assembly name="System.Core" #> +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT license. See LICENSE file in the project root for full license information. +// +// This code is auto-generated. Changes to this file will be lost! +// This T4 file is copied in various projects because inclusion as link or through shared project +// doesn't allow to generate the C# file locally. If some modification is required, please update +// all instances. +// + +#nullable enable + +using System.Diagnostics; +using System.Diagnostics.CodeAnalysis; + +namespace <#= System.Runtime.Remoting.Messaging.CallContext.LogicalGetData("NamespaceHint") #>; + +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); +} + +[SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "Replacement API to allow nullable hints for compiler")] +internal static class TPDebug +{ + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b) + => Debug.Assert(b); + + /// + [Conditional("DEBUG")] + public static void Assert([DoesNotReturnIf(false)] bool b, string message) + => Debug.Assert(b, message); +} diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Output/ConsoleOutput.cs b/src/Microsoft.TestPlatform.CoreUtilities/Output/ConsoleOutput.cs index 0d13018807..7734512571 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Output/ConsoleOutput.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Output/ConsoleOutput.cs @@ -6,8 +6,6 @@ using System; using System.IO; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities; /// @@ -16,7 +14,7 @@ namespace Microsoft.VisualStudio.TestPlatform.Utilities; public class ConsoleOutput : IOutput { private static readonly object LockObject = new(); - private static ConsoleOutput s_consoleOutput; + private static ConsoleOutput? s_consoleOutput; private readonly TextWriter _standardOutput; private readonly TextWriter _standardError; diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Output/IOutput.cs b/src/Microsoft.TestPlatform.CoreUtilities/Output/IOutput.cs index 8836ed1e92..9cf43b6046 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Output/IOutput.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Output/IOutput.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.VisualStudio.TestPlatform.Utilities; /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Output/OutputExtensions.cs b/src/Microsoft.TestPlatform.CoreUtilities/Output/OutputExtensions.cs index 00b0a8d912..a73e987495 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Output/OutputExtensions.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Output/OutputExtensions.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Resources; using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities; /// @@ -27,7 +25,7 @@ public static class OutputExtensions /// Bool to decide whether Verbose level should be added as prefix or not in log messages. /// Format string for the error message. /// Arguments to format into the format string. - public static void Error(this IOutput output, bool appendPrefix, string format, params object[] args) + public static void Error(this IOutput output, bool appendPrefix, string format, params object?[]? args) { SetColorForAction(ConsoleColor.Red, () => Output(output, OutputLevel.Error, appendPrefix ? Resources.CommandLineError : DefaultFormat, format, args)); } @@ -39,7 +37,7 @@ public static void Error(this IOutput output, bool appendPrefix, string format, /// Bool to decide whether Verbose level should be added as prefix or not in log messages. /// Format string for the warning message. /// Arguments to format into the format string. - public static void Warning(this IOutput output, bool appendPrefix, string format, params object[] args) + public static void Warning(this IOutput output, bool appendPrefix, string format, params object?[]? args) { SetColorForAction(ConsoleColor.Yellow, () => Output(output, OutputLevel.Warning, appendPrefix ? Resources.CommandLineWarning : DefaultFormat, format, args)); } @@ -51,7 +49,7 @@ public static void Warning(this IOutput output, bool appendPrefix, string format /// Bool to decide whether Verbose level should be added as prefix or not in log messages. /// Format string for the informational message. /// Arguments to format into the format string. - public static void Information(this IOutput output, bool appendPrefix, string format, params object[] args) + public static void Information(this IOutput output, bool appendPrefix, string format, params object?[]? args) { Information(output, appendPrefix, Console.ForegroundColor, format, args); } @@ -64,7 +62,7 @@ public static void Information(this IOutput output, bool appendPrefix, string fo /// Color in which text prints. /// Format string for the informational message. /// Arguments to format into the format string. - public static void Information(this IOutput output, bool appendPrefix, ConsoleColor foregroundColor, string format, params object[] args) + public static void Information(this IOutput output, bool appendPrefix, ConsoleColor foregroundColor, string format, params object?[]? args) { SetColorForAction(foregroundColor, () => Output(output, OutputLevel.Information, appendPrefix ? Resources.CommandLineInformational : DefaultFormat, format, args)); } @@ -89,7 +87,7 @@ public static void Write(this IOutput output, string message, OutputLevel level, /// Format string for the message type. /// Format string for the error message. /// Arguments to format into the format string. - private static void Output(IOutput output, OutputLevel level, string messageTypeFormat, string format, params object[] args) + private static void Output(IOutput output, OutputLevel level, string messageTypeFormat, string format, params object?[]? args) { ValidateArg.NotNull(output, nameof(output)); output.WriteLine(Format(messageTypeFormat, format, args), level); @@ -102,7 +100,7 @@ private static void Output(IOutput output, OutputLevel level, string messageType /// Format string for the error message. /// Arguments to format into the format string. /// Formatted message. - private static string Format(string messageTypeFormat, string format, params object[] args) + private static string Format(string messageTypeFormat, string format, params object?[]? args) { if (format == null || string.IsNullOrEmpty(format.Trim())) { diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Output/OutputLevel.cs b/src/Microsoft.TestPlatform.CoreUtilities/Output/OutputLevel.cs index 648e427e06..08d4a84983 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Output/OutputLevel.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Output/OutputLevel.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.VisualStudio.TestPlatform.Utilities; /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/EqtTrace.cs b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/EqtTrace.cs index cb48a59fc8..1b74ef4720 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/EqtTrace.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/EqtTrace.cs @@ -6,7 +6,7 @@ using System.Globalization; using System.Text; -#nullable disable +using Microsoft.VisualStudio.TestPlatform.CoreUtilities; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -66,7 +66,7 @@ public static PlatformTraceLevel TraceLevel } #endif - public static string LogFile + public static string? LogFile { get { @@ -87,7 +87,7 @@ public static bool DoNotInitailize } } - public static string ErrorOnInitialization + public static string? ErrorOnInitialization { get; set; @@ -147,7 +147,7 @@ public static bool IsWarningEnabled /// /// The . /// - public static bool InitializeVerboseTrace(string customLogFile) + public static bool InitializeVerboseTrace(string? customLogFile) { return InitializeTrace(customLogFile, PlatformTraceLevel.Verbose); } @@ -159,7 +159,7 @@ public static bool InitializeVerboseTrace(string customLogFile) /// Custom log file for trace messages. /// Trace level. /// Trace initialized flag. - public static bool InitializeTrace(string customLogFile, PlatformTraceLevel traceLevel) + public static bool InitializeTrace(string? customLogFile, PlatformTraceLevel traceLevel) { // Remove extra quotes if we get them passed on the parameter, // System.IO.File does not ignore them when checking the file existence. @@ -190,7 +190,7 @@ public static void Fail(string message) /// The formatted error message /// Arguments to the format [Conditional("TRACE")] - public static void Fail(string format, params object[] args) + public static void Fail(string format, params object?[]? args) { string message = string.Format(CultureInfo.InvariantCulture, format, args); @@ -262,7 +262,7 @@ public static void ErrorUnlessAlterTrace(bool condition, PlatformTraceLevel bump /// Format of error message. /// Parameters for the error message. [Conditional("TRACE")] - public static void Error(string format, params object[] args) + public static void Error(string format, params object?[] args) { Debug.Assert(format != null, "format != null"); @@ -280,7 +280,7 @@ public static void Error(string format, params object[] args) /// Message format. /// Trace message format arguments. [Conditional("TRACE")] - public static void ErrorUnless(bool condition, string format, params object[] args) + public static void ErrorUnless(bool condition, string format, params object?[] args) { ErrorIf(!condition, format, args); } @@ -294,7 +294,7 @@ public static void ErrorUnless(bool condition, string format, params object[] ar /// Message format. /// Trace message format arguments. [Conditional("TRACE")] - public static void ErrorUnlessAlterTrace(bool condition, PlatformTraceLevel bumpLevel, string format, params object[] args) + public static void ErrorUnlessAlterTrace(bool condition, PlatformTraceLevel bumpLevel, string format, params object?[] args) { if (condition) { @@ -313,7 +313,7 @@ public static void ErrorUnlessAlterTrace(bool condition, PlatformTraceLevel bump /// Message format. /// Trace message format arguments. [Conditional("TRACE")] - public static void ErrorIf(bool condition, string format, params object[] args) + public static void ErrorIf(bool condition, string format, params object?[] args) { if (condition) { @@ -327,7 +327,7 @@ public static void ErrorIf(bool condition, string format, params object[] args) /// The message to send to Debug.Fail and Error. /// Arguments to string.Format. [Conditional("TRACE")] - public static void ErrorAssert(string format, params object[] args) + public static void ErrorAssert(string format, params object?[] args) { Debug.Assert(format != null, "format != null"); var message = string.Format(CultureInfo.InvariantCulture, format, args); @@ -342,7 +342,7 @@ public static void ErrorAssert(string format, params object[] args) [Conditional("TRACE")] public static void Error(Exception exceptionToTrace) { - Debug.Assert(exceptionToTrace != null, "exceptionToTrace != null"); + TPDebug.Assert(exceptionToTrace != null, "exceptionToTrace != null"); // Write only if tracing for error is enabled. // Done upfront to avoid performance hit. @@ -417,7 +417,7 @@ public static void WarningUnlessAlterTrace(bool condition, PlatformTraceLevel bu /// Format of the trace message. /// Arguments for the trace message format. [Conditional("TRACE")] - public static void Warning(string format, params object[] args) + public static void Warning(string format, params object?[] args) { Debug.Assert(format != null, "format != null"); @@ -435,7 +435,7 @@ public static void Warning(string format, params object[] args) /// Format of the trace message. /// Arguments for the trace message. [Conditional("TRACE")] - public static void WarningIf(bool condition, string format, params object[] args) + public static void WarningIf(bool condition, string format, params object?[] args) { if (condition) { @@ -450,7 +450,7 @@ public static void WarningIf(bool condition, string format, params object[] args /// Format of trace message. /// Arguments for the trace message. [Conditional("TRACE")] - public static void WarningUnless(bool condition, string format, params object[] args) + public static void WarningUnless(bool condition, string format, params object?[] args) { WarningIf(!condition, format, args); } @@ -464,7 +464,7 @@ public static void WarningUnless(bool condition, string format, params object[] /// Format of the trace message. /// Arguments for trace message. [Conditional("TRACE")] - public static void WarningUnlessAlterTrace(bool condition, PlatformTraceLevel bumpLevel, string format, params object[] args) + public static void WarningUnlessAlterTrace(bool condition, PlatformTraceLevel bumpLevel, string format, params object?[] args) { if (condition) { @@ -540,7 +540,7 @@ public static void InfoUnlessAlterTrace(bool condition, PlatformTraceLevel bumpL /// Trace message format. /// Arguments for trace format. [Conditional("TRACE")] - public static void Info(string format, params object[] args) + public static void Info(string format, params object?[] args) { Debug.Assert(format != null, "format != null"); @@ -558,7 +558,7 @@ public static void Info(string format, params object[] args) /// Format of the trace message. /// Arguments for the trace format. [Conditional("TRACE")] - public static void InfoIf(bool condition, string format, params object[] args) + public static void InfoIf(bool condition, string format, params object?[] args) { if (condition) { @@ -573,7 +573,7 @@ public static void InfoIf(bool condition, string format, params object[] args) /// Trace message format. /// Trace message format arguments. [Conditional("TRACE")] - public static void InfoUnless(bool condition, string format, params object[] args) + public static void InfoUnless(bool condition, string format, params object?[] args) { InfoIf(!condition, format, args); } @@ -587,7 +587,7 @@ public static void InfoUnless(bool condition, string format, params object[] arg /// Trace message format. /// Trace message arguments. [Conditional("TRACE")] - public static void InfoUnlessAlterTrace(bool condition, PlatformTraceLevel bumpLevel, string format, params object[] args) + public static void InfoUnlessAlterTrace(bool condition, PlatformTraceLevel bumpLevel, string format, params object?[] args) { if (condition) { @@ -663,7 +663,7 @@ public static void VerboseUnlessAlterTrace(bool condition, PlatformTraceLevel le /// Format of trace message. /// Arguments for trace message. [Conditional("TRACE")] - public static void Verbose(string format, params object[] args) + public static void Verbose(string format, params object?[] args) { Debug.Assert(format != null, "format != null"); @@ -681,7 +681,7 @@ public static void Verbose(string format, params object[] args) /// Message format. /// Arguments for trace message. [Conditional("TRACE")] - public static void VerboseIf(bool condition, string format, params object[] args) + public static void VerboseIf(bool condition, string format, params object?[] args) { if (condition) { @@ -696,7 +696,7 @@ public static void VerboseIf(bool condition, string format, params object[] args /// Format for the trace message. /// Trace message arguments. [Conditional("TRACE")] - public static void VerboseUnless(bool condition, string format, params object[] args) + public static void VerboseUnless(bool condition, string format, params object?[] args) { VerboseIf(!condition, format, args); } @@ -710,7 +710,7 @@ public static void VerboseUnless(bool condition, string format, params object[] /// Format of the trace message. /// Arguments for the trace message format. [Conditional("TRACE")] - public static void VerboseUnlessAlterTrace(bool condition, PlatformTraceLevel level, string format, params object[] args) + public static void VerboseUnlessAlterTrace(bool condition, PlatformTraceLevel level, string format, params object?[] args) { if (condition) { @@ -815,7 +815,7 @@ private static void WriteAtLevel(PlatformTraceLevel level, string message) } } - private static void WriteAtLevel(PlatformTraceLevel level, string format, params object[] args) + private static void WriteAtLevel(PlatformTraceLevel level, string format, params object?[] args) { Debug.Assert(format != null, "format != null"); WriteAtLevel(level, string.Format(CultureInfo.InvariantCulture, format, args)); diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/Interfaces/ITestPlatformEventSource.cs b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/Interfaces/ITestPlatformEventSource.cs index cc78358ba2..3953533dcf 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/Interfaces/ITestPlatformEventSource.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/Interfaces/ITestPlatformEventSource.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.VisualStudio.TestPlatform.CoreUtilities.Tracing.Interfaces; /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/TestPlatformEventSource.cs b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/TestPlatformEventSource.cs index 407043228e..00a1908d8e 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/TestPlatformEventSource.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/TestPlatformEventSource.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Tracing.Interfaces; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.CoreUtilities.Tracing; /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/TestPlatformInstrumentationEvents.cs b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/TestPlatformInstrumentationEvents.cs index 7e88374cee..13073697aa 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Tracing/TestPlatformInstrumentationEvents.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Tracing/TestPlatformInstrumentationEvents.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.VisualStudio.TestPlatform.CoreUtilities.Tracing; /// diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/Job.cs b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/Job.cs index 6b9538ef74..4b69a6cb11 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/Job.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/Job.cs @@ -5,8 +5,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Common.Utilities; /// @@ -55,7 +53,7 @@ public static Job ShutdownJob /// /// Gets the job to be processed. /// - public TPayload Payload { get; private set; } + public TPayload? Payload { get; private set; } /// /// Gets a value indicating whether the background thread should shutdown. @@ -65,7 +63,7 @@ public static Job ShutdownJob /// /// Gets the signal that this job is being processed. /// - public ManualResetEvent WaitManualResetEvent { get; private set; } + public ManualResetEvent? WaitManualResetEvent { get; private set; } /// /// Gets the size of this job instance. This is used to manage the total size of Job Queue. diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs index 2c978306e4..8800ced76b 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs @@ -12,8 +12,6 @@ using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Resources; using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities; /// @@ -25,7 +23,7 @@ public class JobQueue : IDisposable /// /// Handler which processes the individual jobs. /// - private readonly Action _processJob; + private readonly Action _processJob; /// /// Name used when displaying information or reporting errors about this queue. @@ -99,7 +97,7 @@ public class JobQueue : IDisposable /// The max Queue Size. /// The enable Bounds. /// The exception Logger. - public JobQueue(Action processJob, string displayName, int maxQueueLength, int maxQueueSize, bool enableBounds, Action exceptionLogger) + public JobQueue(Action processJob, string displayName, int maxQueueLength, int maxQueueSize, bool enableBounds, Action exceptionLogger) { _processJob = processJob ?? throw new ArgumentNullException(nameof(processJob)); @@ -347,7 +345,7 @@ private void BackgroundJobProcessor(string threadName) /// Executes the process job handler and logs any exceptions which occur. /// /// Job to be executed. - private void SafeProcessJob(T job) + private void SafeProcessJob(T? job) { try { diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/MulticastDelegateUtilities.cs b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/MulticastDelegateUtilities.cs index 13cd5c5b55..b073bd4ae7 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/MulticastDelegateUtilities.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/MulticastDelegateUtilities.cs @@ -7,8 +7,6 @@ using Microsoft.VisualStudio.TestPlatform.ObjectModel; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities; /// @@ -42,39 +40,39 @@ public static void SafeInvoke(this Delegate delegates, object sender, EventArgs public static void SafeInvoke(this Delegate delegates, object sender, object args, string traceDisplayName) { ValidateArg.NotNull(args, nameof(args)); + ValidateArg.NotNullOrWhiteSpace(traceDisplayName, nameof(traceDisplayName)); - if (string.IsNullOrWhiteSpace(traceDisplayName)) + if (delegates == null) { - throw new ArgumentNullException(nameof(traceDisplayName)); + EqtTrace.Verbose("MulticastDelegateUtilities.SafeInvoke: {0}: Invoking callbacks was skipped because there are no subscribers.", traceDisplayName); + return; } - if (delegates != null) + var invocationList = delegates.GetInvocationList(); + var i = 0; + foreach (Delegate handler in invocationList) { - var invocationList = delegates.GetInvocationList(); - var i = 0; - foreach (Delegate handler in invocationList) - { - var stopwatch = Stopwatch.StartNew(); + var stopwatch = Stopwatch.StartNew(); - try + try + { + handler.DynamicInvoke(sender, args); + if (EqtTrace.IsVerboseEnabled) { - handler.DynamicInvoke(sender, args); - if (EqtTrace.IsVerboseEnabled) - { - EqtTrace.Verbose("MulticastDelegateUtilities.SafeInvoke: {0}: Invoking callback {1}/{2} for {3}.{4}, took {5} ms.", - traceDisplayName, - ++i, - invocationList.Length, - handler.GetTargetName(), - handler.GetMethodName(), - stopwatch.ElapsedMilliseconds); - } + EqtTrace.Verbose("MulticastDelegateUtilities.SafeInvoke: {0}: Invoking callback {1}/{2} for {3}.{4}, took {5} ms.", + traceDisplayName, + ++i, + invocationList.Length, + handler.GetTargetName(), + handler.GetMethodName(), + stopwatch.ElapsedMilliseconds); } - catch (TargetInvocationException exception) + } + catch (TargetInvocationException exception) + { + if (EqtTrace.IsErrorEnabled) { - if (EqtTrace.IsErrorEnabled) - { - EqtTrace.Error( + EqtTrace.Error( "MulticastDelegateUtilities.SafeInvoke: {0}: Invoking callback {1}/{2} for {3}.{4}, failed after {5} ms with: {6}.", ++i, invocationList.Length, @@ -83,17 +81,12 @@ public static void SafeInvoke(this Delegate delegates, object sender, object arg traceDisplayName, stopwatch.ElapsedMilliseconds, exception); - } } } } - else - { - EqtTrace.Verbose("MulticastDelegateUtilities.SafeInvoke: {0}: Invoking callbacks was skipped because there are no subscribers.", traceDisplayName); - } } - internal static string GetMethodName(this Delegate @delegate) + internal static string? GetMethodName(this Delegate @delegate) { #if NETSTANDARD2_0 return @delegate.Method.Name; diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/TimeSpanParser.cs b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/TimeSpanParser.cs index 48eb7acd4b..714b2826da 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/TimeSpanParser.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/TimeSpanParser.cs @@ -4,8 +4,6 @@ using System; using System.Text.RegularExpressions; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.Utilities; public static class TimeSpanParser diff --git a/src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs b/src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs index bf67a55c32..0b559e3225 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/ValidateArg.cs @@ -9,8 +9,6 @@ using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Resources; -#nullable disable - namespace Microsoft.VisualStudio.TestPlatform.ObjectModel; /// diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/Friends.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/Friends.cs index 4a9dd358c6..ded0266d5d 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/Friends.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/Friends.cs @@ -5,4 +5,5 @@ #region Product Assemblies [assembly: InternalsVisibleTo("Microsoft.TestPlatform.TestHostRuntimeProvider, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] +[assembly: InternalsVisibleTo("Microsoft.TestPlatform.CoreUtilities, PublicKey=002400000480000094000000060200000024000052534131000400000100010007d1fa57c4aed9f0a32e84aa0faefd0de9e8fd6aec8f87fb03766c834c99921eb23be79ad9d5dcc1dd9ad236132102900b723cf980957fc4e177108fc607774f29e8320e92ea05ece4e821c0a5efe8f1645c4c0c93c1ab99285d622caa652c1dfad63d745d6f2de5f17e5eaf0fc4963d261c8a12436518206dc093344d5ad293")] #endregion diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Tracing/IPlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Tracing/IPlatformEqtTrace.cs index ea01d92123..7969c3b50f 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Tracing/IPlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/Interfaces/Tracing/IPlatformEqtTrace.cs @@ -35,7 +35,7 @@ bool DoNotInitialize /// /// The . /// - bool InitializeVerboseTrace(string customLogFile); + bool InitializeVerboseTrace(string? customLogFile); /// /// Initializes the tracing with custom log file and trace level. @@ -44,7 +44,7 @@ bool DoNotInitialize /// Custom log file for trace messages. /// Trace level. /// Trace initialized flag. - bool InitializeTrace(string customLogFile, PlatformTraceLevel traceLevel); + bool InitializeTrace(string? customLogFile, PlatformTraceLevel traceLevel); /// /// Gets a value indicating if tracing is enabled for a trace level. diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/PublicAPI.Shipped.txt index 958dfb06d7..b7b0acdf31 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/PublicAPI.Shipped.txt @@ -4,8 +4,8 @@ Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.DoNotInitializ Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.DoNotInitialize.set -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.GetLogFile() -> string? Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.GetTraceLevel() -> Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel -Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool -Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.InitializeVerboseTrace(string! customLogFile) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.InitializeVerboseTrace(string? customLogFile) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.SetTraceLevel(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel value) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.ShouldTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void @@ -14,7 +14,7 @@ Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.DoNotInitialize Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.DoNotInitialize.set -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.GetLogFile() -> string? Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.GetTraceLevel() -> Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeVerboseTrace(string! customLogFile) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeVerboseTrace(string? customLogFile) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.PlatformEqtTrace() -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetTraceLevel(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel value) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.ShouldTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net45/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net45/PublicAPI.Shipped.txt index aa55e083b1..0fcd69c201 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net45/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net45/PublicAPI.Shipped.txt @@ -1,7 +1,7 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.SetupListener(System.Diagnostics.TraceListener? listener) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.SetupRemoteEqtTraceListeners(System.AppDomain? childDomain) -> void -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetupListener(System.Diagnostics.TraceListener? listener) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetupRemoteEqtTraceListeners(System.AppDomain? childDomain) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net451/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net451/PublicAPI.Shipped.txt index aa55e083b1..0fcd69c201 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net451/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net451/PublicAPI.Shipped.txt @@ -1,7 +1,7 @@ #nullable enable Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.SetupListener(System.Diagnostics.TraceListener? listener) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.IPlatformEqtTrace.SetupRemoteEqtTraceListeners(System.AppDomain? childDomain) -> void -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetupListener(System.Diagnostics.TraceListener? listener) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.SetupRemoteEqtTraceListeners(System.AppDomain? childDomain) -> void diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net6.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net6.0/PublicAPI.Shipped.txt index df690acd14..eca93b34d1 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net6.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/net6.0/PublicAPI.Shipped.txt @@ -1,5 +1,5 @@ #nullable enable -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp1.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp1.0/PublicAPI.Shipped.txt index df690acd14..eca93b34d1 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp1.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp1.0/PublicAPI.Shipped.txt @@ -1,5 +1,5 @@ #nullable enable -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp2.1/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp2.1/PublicAPI.Shipped.txt index df690acd14..eca93b34d1 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp2.1/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netcoreapp2.1/PublicAPI.Shipped.txt @@ -1,5 +1,5 @@ #nullable enable -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.0/PublicAPI.Shipped.txt index 418bb85194..354151a095 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.0/PublicAPI.Shipped.txt @@ -1,5 +1,5 @@ #nullable enable -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel, string! message) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState platformApartmentState, bool waitForCompletion) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.GetProcessById(int processId) -> object! diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.3/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.3/PublicAPI.Shipped.txt index 418bb85194..354151a095 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.3/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard1.3/PublicAPI.Shipped.txt @@ -1,5 +1,5 @@ #nullable enable -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel, string! message) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState platformApartmentState, bool waitForCompletion) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.GetProcessById(int processId) -> object! diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt index df690acd14..eca93b34d1 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/netstandard2.0/PublicAPI.Shipped.txt @@ -1,5 +1,5 @@ #nullable enable -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel platformTraceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.MapPlatformTraceToTrace(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> System.Diagnostics.TraceLevel Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void Microsoft.VisualStudio.TestPlatform.ObjectModel.RollingFileTraceListener diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/uap10.0/PublicAPI.Shipped.txt b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/uap10.0/PublicAPI.Shipped.txt index 7b161321f0..9a6c07b4ee 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/uap10.0/PublicAPI.Shipped.txt +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/PublicAPI/uap10.0/PublicAPI.Shipped.txt @@ -1,5 +1,5 @@ #nullable enable -Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string! customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool +Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.InitializeTrace(string? customLogFile, Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel traceLevel) -> bool Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformEqtTrace.WriteLine(Microsoft.VisualStudio.TestPlatform.ObjectModel.PlatformTraceLevel level, string! message) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformThread.Run(System.Action? action, Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.PlatformApartmentState apartmentState, bool waitForCompletion) -> void Microsoft.VisualStudio.TestPlatform.PlatformAbstractions.ProcessHelper.GetProcessById(int processId) -> object! diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/PlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/PlatformEqtTrace.cs index 54627fa02e..5997cd5a6f 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/PlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/common/Tracing/PlatformEqtTrace.cs @@ -163,13 +163,13 @@ private static TraceSource Source } /// - public bool InitializeVerboseTrace(string customLogFile) + public bool InitializeVerboseTrace(string? customLogFile) { return InitializeTrace(customLogFile, PlatformTraceLevel.Verbose); } /// - public bool InitializeTrace(string customLogFile, PlatformTraceLevel platformTraceLevel) + public bool InitializeTrace(string? customLogFile, PlatformTraceLevel platformTraceLevel) { s_isInitialized = false; diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/Tracing/PlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/Tracing/PlatformEqtTrace.cs index 20f1cfc645..46fb0e76e6 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/Tracing/PlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/netstandard/Tracing/PlatformEqtTrace.cs @@ -41,7 +41,7 @@ public void WriteLine(PlatformTraceLevel traceLevel, string message) Debug.WriteLine($"[{level}] {message}"); } - public bool InitializeVerboseTrace(string customLogFile) + public bool InitializeVerboseTrace(string? customLogFile) { #if DEBUG // We don't have access to System.Diagnostics.Trace on netstandard1.3 @@ -52,7 +52,7 @@ public bool InitializeVerboseTrace(string customLogFile) #endif } - public bool InitializeTrace(string customLogFile, PlatformTraceLevel traceLevel) + public bool InitializeTrace(string? customLogFile, PlatformTraceLevel traceLevel) { _traceLevel = traceLevel; diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/PlatformEqtTrace.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/PlatformEqtTrace.cs index 4a25a4e33b..94849beceb 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/PlatformEqtTrace.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/PlatformEqtTrace.cs @@ -72,18 +72,20 @@ public void WriteLine(PlatformTraceLevel level, string message) } /// - public bool InitializeVerboseTrace(string customLogFile) + public bool InitializeVerboseTrace(string? customLogFile) { return InitializeTrace(customLogFile, PlatformTraceLevel.Verbose); } /// - public bool InitializeTrace(string customLogFile, PlatformTraceLevel traceLevel) + public bool InitializeTrace(string? customLogFile, PlatformTraceLevel traceLevel) { string logFileName; try { - logFileName = Path.GetFileNameWithoutExtension(customLogFile.TrimStart('"').TrimEnd('"')).Replace(" ", "_"); + logFileName = customLogFile is not null + ? Path.GetFileNameWithoutExtension(customLogFile.TrimStart('"').TrimEnd('"')).Replace(" ", "_") + : Guid.NewGuid().ToString(); } catch { diff --git a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs index e5249eb83b..1f3e69450c 100644 --- a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs +++ b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs @@ -180,7 +180,7 @@ public virtual TestProcessStartInfo GetTestHostProcessStartInfo( { // Not sharing the host which means we need to pass the test assembly path as argument // so that the test host can create an appdomain on startup (Main method) and set appbase - argumentsString += " --testsourcepath " + sources.FirstOrDefault().AddDoubleQuote(); + argumentsString += " --testsourcepath " + sources.FirstOrDefault()?.AddDoubleQuote(); } EqtTrace.Verbose("DefaultTestHostmanager: Full path of {0} is {1}", testHostProcessName, testhostProcessPath); @@ -451,7 +451,7 @@ private Version GetAndLogFileVersion(string path) /// host provider event args private void OnHostLaunched(HostProviderEventArgs e) { - HostLaunched.SafeInvoke(this, e, "HostProviderEvents.OnHostLaunched"); + HostLaunched?.SafeInvoke(this, e, "HostProviderEvents.OnHostLaunched"); } /// @@ -463,7 +463,7 @@ private void OnHostExited(HostProviderEventArgs e) if (!_hostExitedEventRaised) { _hostExitedEventRaised = true; - HostExited.SafeInvoke(this, e, "HostProviderEvents.OnHostExited"); + HostExited?.SafeInvoke(this, e, "HostProviderEvents.OnHostExited"); } } @@ -480,9 +480,8 @@ private bool LaunchHost(TestProcessStartInfo testHostStartInfo, CancellationToke // For every other workflow (e.g.: profiling) we ask the IDE to launch the custom test // host for us. In the profiling case this is needed because then the IDE sets some // additional environmental variables for us to help with probing. - if ((_customTestHostLauncher == null) - || (_customTestHostLauncher.IsDebug - && _customTestHostLauncher is ITestHostLauncher2)) + if (_customTestHostLauncher == null + || (_customTestHostLauncher.IsDebug && _customTestHostLauncher is ITestHostLauncher2)) { EqtTrace.Verbose("DefaultTestHostManager: Starting process '{0}' with command line '{1}'", testHostStartInfo.FileName, testHostStartInfo.Arguments); cancellationToken.ThrowIfCancellationRequested(); diff --git a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs index c0a756e51b..59c0221525 100644 --- a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs +++ b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs @@ -355,7 +355,7 @@ public virtual TestProcessStartInfo GetTestHostProcessStartInfo( // // If they were in the base path (where the test dll is) it would work // fine, because in base folder, dotnet searches directly in that folder, but not in probing paths. - var testHostProbingPath = Path.GetDirectoryName(testHostNextToRunner); + var testHostProbingPath = Path.GetDirectoryName(testHostNextToRunner)!; argsToAdd = " --additionalprobingpath " + testHostProbingPath.AddDoubleQuote(); args += argsToAdd; EqtTrace.Verbose("DotnetTestHostmanager: Adding {0} in args", argsToAdd); @@ -666,7 +666,7 @@ public bool AttachDebuggerToTestHost() /// host provider event args private void OnHostLaunched(HostProviderEventArgs e) { - HostLaunched.SafeInvoke(this, e, "HostProviderEvents.OnHostLaunched"); + HostLaunched?.SafeInvoke(this, e, "HostProviderEvents.OnHostLaunched"); } /// @@ -679,7 +679,7 @@ private void OnHostExited(HostProviderEventArgs e) { _hostExitedEventRaised = true; EqtTrace.Verbose("DotnetTestHostManager.OnHostExited: invoking OnHostExited callback"); - HostExited.SafeInvoke(this, e, "HostProviderEvents.OnHostExited"); + HostExited?.SafeInvoke(this, e, "HostProviderEvents.OnHostExited"); } else { diff --git a/src/testhost.x86/DefaultEngineInvoker.cs b/src/testhost.x86/DefaultEngineInvoker.cs index 1c1e666c0a..fc8a797ee3 100644 --- a/src/testhost.x86/DefaultEngineInvoker.cs +++ b/src/testhost.x86/DefaultEngineInvoker.cs @@ -240,8 +240,8 @@ private static TestHostConnectionInfo GetConnectionInfo(IDictionary argsDictionary) + private static IEngineInvoker GetEngineInvoker(IDictionary argsDictionary) { IEngineInvoker? invoker = null; #if NETFRAMEWORK // If Args contains test source argument, invoker Engine in new appdomain - if (argsDictionary.TryGetValue(TestSourceArgumentString, out var testSourcePath) && !string.IsNullOrWhiteSpace(testSourcePath)) + if (argsDictionary.TryGetValue(TestSourceArgumentString, out var testSourcePath) && !testSourcePath.IsNullOrWhiteSpace()) { // remove the test source arg from dictionary argsDictionary.Remove(TestSourceArgumentString); diff --git a/src/vstest.console/Internal/ConsoleLogger.cs b/src/vstest.console/Internal/ConsoleLogger.cs index 8277acf1cb..0aa1da5214 100644 --- a/src/vstest.console/Internal/ConsoleLogger.cs +++ b/src/vstest.console/Internal/ConsoleLogger.cs @@ -233,6 +233,8 @@ public void Initialize(TestLoggerEvents events, Dictionary param /// private static void PrintTimeSpan(TimeSpan timeSpan) { + TPDebug.Assert(Output is not null, "ConsoleLogger.Output is null"); + if (timeSpan.TotalDays >= 1) { Output.Information(false, string.Format(CultureInfo.CurrentCulture, CommandLineResources.ExecutionTimeFormatString, timeSpan.TotalDays, CommandLineResources.Days)); @@ -430,6 +432,7 @@ private void TestMessageHandler(object sender, TestRunMessageEventArgs e) { ValidateArg.NotNull(sender, nameof(sender)); ValidateArg.NotNull(e, nameof(e)); + TPDebug.Assert(Output is not null, "ConsoleLogger.Output is null"); switch (e.Level) { diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs index 240d4d8c03..dbb9abb8a9 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/CommandLineArgumentsHelperTests.cs @@ -47,7 +47,7 @@ public void GetStringArgFromDictShouldReturnStringValueOrEmpty() var args = new List() { "--port", "12312", "--parentprocessid", "2312", "--testsourcepath", @"C:\temp\1.dll" }; var argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(args.ToArray()); - string data = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, "--port"); + string? data = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, "--port"); Assert.AreEqual("12312", data); } @@ -57,7 +57,7 @@ public void GetStringArgFromDictShouldReturnNullIfValueIsNotPresent() var args = new List() { "--hello", "--world" }; var argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(args.ToArray()); - string data = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, "--hello"); + string? data = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, "--hello"); Assert.IsTrue(argsDictionary.Count == 2); Assert.IsNull(data); @@ -69,7 +69,7 @@ public void GetStringArgFromDictShouldReturnEmptyStringIfKeyIsNotPresent() var args = new List() { "--hello", "--world" }; var argsDictionary = CommandLineArgumentsHelper.GetArgumentsDictionary(args.ToArray()); - string data = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, "--port"); + string? data = CommandLineArgumentsHelper.GetStringArgFromDict(argsDictionary, "--port"); Assert.IsTrue(argsDictionary.Count == 2); Assert.AreEqual(string.Empty, data); diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/DotnetHostHelperTest.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/DotnetHostHelperTest.cs index 2507049221..4a7e074033 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/DotnetHostHelperTest.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/DotnetHostHelperTest.cs @@ -39,7 +39,7 @@ public void GetDotnetPathByArchitecture_SameArchitecture() _processHelper.Setup(x => x.GetCurrentProcessArchitecture()).Returns(PlatformArchitecture.X64); // Act & Assert - Assert.IsTrue(dotnetHostHelper.TryGetDotnetPathByArchitecture(PlatformArchitecture.X64, out string muxerPath)); + Assert.IsTrue(dotnetHostHelper.TryGetDotnetPathByArchitecture(PlatformArchitecture.X64, out string? muxerPath)); Assert.AreEqual(finalMuxerPath, muxerPath); } @@ -94,7 +94,7 @@ public void GetDotnetPathByArchitecture_EnvVars(PlatformArchitecture targetArchi // Act & Assert var dotnetHostHelper = new DotnetHostHelper(_fileHelper.Object, _environmentHelper.Object, _windowsRegistrytHelper.Object, _environmentVariableHelper.Object, _processHelper.Object); - Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string muxerPath)); + Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string? muxerPath)); Assert.AreEqual(found ? envVars[envVar] : null, muxerPath); } @@ -126,7 +126,7 @@ public void GetDotnetPathByArchitecture_EnvVars_DirectoryNotExists_TryNext(strin //Act & Assert var dotnetHostHelper = new DotnetHostHelper(_fileHelper.Object, _environmentHelper.Object, _windowsRegistrytHelper.Object, _environmentVariableHelper.Object, _processHelper.Object); - Assert.IsTrue(dotnetHostHelper.TryGetDotnetPathByArchitecture(targetAchitecture, out string muxerPath)); + Assert.IsTrue(dotnetHostHelper.TryGetDotnetPathByArchitecture(targetAchitecture, out string? muxerPath)); Assert.AreEqual(envVars[nextEnv], muxerPath); } @@ -149,7 +149,7 @@ public void GetDotnetPathByArchitecture_GlobalInstallation_Windows(PlatformArchi //Act & Assert var dotnetHostHelper = new DotnetHostHelper(_fileHelper.Object, _environmentHelper.Object, _windowsRegistrytHelper.Object, _environmentVariableHelper.Object, _processHelper.Object); - Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string muxerPath)); + Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string? muxerPath)); Assert.AreEqual(found ? dotnetMuxer : null, muxerPath); } @@ -176,7 +176,7 @@ public void GetDotnetPathByArchitecture_GlobalInstallation_NullSubkeys(bool null // 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)); + Assert.IsFalse(dotnetHostHelper.TryGetDotnetPathByArchitecture(PlatformArchitecture.X64, out string? muxerPath)); } [DataTestMethod] @@ -206,7 +206,7 @@ public void GetDotnetPathByArchitecture_GlobalInstallation_Unix(PlatformArchitec //Act & Assert var dotnetHostHelper = new DotnetHostHelper(_fileHelper.Object, _environmentHelper.Object, _windowsRegistrytHelper.Object, _environmentVariableHelper.Object, _processHelper.Object); - Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string muxerPath)); + Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string? muxerPath)); Assert.AreEqual(found ? dotnetMuxer : null, muxerPath); } @@ -232,7 +232,7 @@ public void GetDotnetPathByArchitecture_DefaultInstallation_Win(PlatformArchitec //Act & Assert var dotnetHostHelper = new DotnetHostHelper(_fileHelper.Object, _environmentHelper.Object, _windowsRegistrytHelper.Object, _environmentVariableHelper.Object, _processHelper.Object); - Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string muxerPath)); + Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string? muxerPath)); Assert.AreEqual(found ? dotnetMuxer : null, muxerPath); } @@ -262,7 +262,7 @@ public void GetDotnetPathByArchitecture_DefaultInstallation_Unix(PlatformArchite //Act & Assert var dotnetHostHelper = new DotnetHostHelper(_fileHelper.Object, _environmentHelper.Object, _windowsRegistrytHelper.Object, _environmentVariableHelper.Object, _processHelper.Object); - Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string muxerPath)); + Assert.AreEqual(found, dotnetHostHelper.TryGetDotnetPathByArchitecture(targetArchitecture, out string? muxerPath)); Assert.AreEqual(found ? expectedMuxerPath : null, muxerPath); } diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs index ff61c71c50..b986d94fcc 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Utilities/JobQueueTests.cs @@ -17,7 +17,7 @@ public class JobQueueTests public void ConstructorThrowsWhenNullProcessHandlerIsProvided() { JobQueue? jobQueue = null; - Assert.ThrowsException(() => jobQueue = new JobQueue(null, "dp", int.MaxValue, int.MaxValue, false, (message) => { })); + Assert.ThrowsException(() => jobQueue = new JobQueue(null!, "dp", int.MaxValue, int.MaxValue, false, (message) => { })); if (jobQueue != null) { @@ -29,7 +29,7 @@ public void ConstructorThrowsWhenNullProcessHandlerIsProvided() public void ThrowsWhenNullEmptyOrWhiteSpaceDisplayNameIsProvided() { JobQueue? jobQueue = null; - Assert.ThrowsException(() => jobQueue = new JobQueue(GetEmptyProcessHandler(), null, int.MaxValue, int.MaxValue, false, (message) => { })); + 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) => { })); @@ -69,7 +69,7 @@ public void JobsAreProcessedOnABackgroundThread() { // Setup the job process handler to keep track of the jobs. var jobsProcessed = new List(); - Action processHandler = (job) => jobsProcessed.Add(Environment.CurrentManagedThreadId); + Action processHandler = job => jobsProcessed.Add(Environment.CurrentManagedThreadId); // Queue the jobs and verify they are processed on a background thread. using (var queue = new JobQueue(processHandler, "dp", int.MaxValue, int.MaxValue, false, (message) => { })) @@ -128,8 +128,8 @@ public void DisposeDoesNotThrowWhenCalledTwice() public void OncePausedNoFurtherJobsAreProcessedUntilResumeIsCalled() { // Setup the job process handler to keep track of the jobs it is called with. - List processedJobs = new(); - Action processHandler = (job) => processedJobs.Add(job); + List processedJobs = new(); + Action processHandler = job => processedJobs.Add(job); // Queue the jobs after paused and verify they are not processed until resumed. using (var queue = new JobQueue(processHandler, "dp", int.MaxValue, int.MaxValue, false, (message) => { })) @@ -165,7 +165,7 @@ public void FlushMethodWaitsForAllJobsToBeProcessedBeforeReturning() { // Setup the job process handler to keep track of the jobs it has processed. var jobsProcessed = 0; - Action processHandler = (job) => jobsProcessed++; + Action processHandler = job => jobsProcessed++; // Queue several jobs and verify they have been processed when wait returns. using var queue = new JobQueue(processHandler, "dp", int.MaxValue, int.MaxValue, false, (message) => { }); @@ -186,10 +186,10 @@ public void TestBlockAtEnqueueDueToLength() // process handler for the jobs in queue. It blocks on a job till the queue gets full and the handler sets the // event allowHandlerToProceed. - Action processHandler = (job) => + Action processHandler = job => { allowJobProcessingHandlerToProceed.WaitOne(); - if (job.Equals("job11", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(job, "job11", StringComparison.OrdinalIgnoreCase)) { jobProcessed.Set(); } @@ -240,10 +240,10 @@ public void TestBlockAtEnqueueDueToSize() // process handler for the jobs in queue. It blocks on a job till the queue gets full and the handler sets the // event allowHandlerToProceed. - Action processHandler = (job) => + Action processHandler = job => { allowJobProcessingHandlerToProceed.WaitOne(); - if (job.Equals("job11", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(job, "job11", StringComparison.OrdinalIgnoreCase)) { jobProcessed.Set(); } @@ -294,10 +294,10 @@ public void TestBlockingDisabled() // process handler for the jobs in queue. It blocks on a job till the test method sets the // event allowHandlerToProceed. - Action processHandler = (job) => + Action processHandler = job => { allowJobProcessingHandlerToProceed.WaitOne(); - if (job.Equals("job5", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(job, "job5", StringComparison.OrdinalIgnoreCase)) { jobProcessed.Set(); } @@ -342,7 +342,7 @@ public void TestLargeTestResultCanBeLoadedWithBlockingEnabled() var jobProcessed = new AutoResetEvent(false); // process handler for the jobs in queue. - Action processHandler = (job) => jobProcessed.Set(); + Action processHandler = (job) => jobProcessed.Set(); using JobQueueNonBlocking queue = new(processHandler); // run the same thing multiple times to ensure that the queue isn't in a erroneous state after first run. @@ -370,9 +370,9 @@ public void TestDisposeUnblocksBlockedThreads() // process handler for the jobs in queue. It blocks on a job till the test method sets the // event allowHandlerToProceed. - Action processHandler = (job) => + Action processHandler = job => { - if (job.Equals("job1", StringComparison.OrdinalIgnoreCase)) + if (string.Equals(job, "job1", StringComparison.OrdinalIgnoreCase)) job1Running.Set(); allowJobProcessingHandlerToProceed.WaitOne(); @@ -404,7 +404,7 @@ public void TestDisposeUnblocksBlockedThreads() /// internal class JobQueueWrapper : JobQueue { - public JobQueueWrapper(Action processJob, + public JobQueueWrapper(Action processJob, int maxNoOfStringsQueueCanHold, int maxNoOfBytesQueueCanHold, bool isBoundsEnabled, @@ -440,7 +440,7 @@ public bool IsEnqueueBlocked /// internal class JobQueueNonBlocking : JobQueue { - public JobQueueNonBlocking(Action processHandler) + public JobQueueNonBlocking(Action processHandler) : base(processHandler, "foo", 1, 5, true, (message) => { }) { EnteredBlockingMethod = false; @@ -464,9 +464,9 @@ protected override bool WaitForQueueToGetEmpty() /// /// Type of job the handler processes. /// Job processing handler which does nothing. - private static Action GetEmptyProcessHandler() + private static Action GetEmptyProcessHandler() { - Action handler = (job) => + Action handler = (job) => { }; diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs index e1e19d362b..af8338f0bd 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/EventHandlers/TestRequestHandlerTests.cs @@ -51,7 +51,7 @@ public TestRequestHandlerTests() }; _jobQueue = new JobQueue( - action => action(), + action => action?.Invoke(), "TestHostOperationQueue", 500, 25000000, diff --git a/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs index bb03b56a82..29d243bb68 100644 --- a/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs @@ -27,7 +27,7 @@ public class EnableDiagArgumentProcessorTests private readonly Mock _mockFileHelper; private readonly TraceLevel _traceLevel; - private readonly string _traceFileName; + private readonly string? _traceFileName; public EnableDiagArgumentProcessorTests() { @@ -146,7 +146,7 @@ public void EnableDiagArgumentProcessorExecutorShouldInitializeTraceWithCorrectT _diagProcessor.Executor!.Value.Initialize(argument); Assert.AreEqual(TraceLevel.Info, (TraceLevel)EqtTrace.TraceLevel); - Assert.IsTrue(EqtTrace.LogFile.Contains("abc.txt")); + Assert.IsTrue(EqtTrace.LogFile?.Contains("abc.txt")); } [TestMethod] From b010059ee07b043a69d72ceba8fffc81e6631f7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Amaury=20Lev=C3=A9?= Date: Mon, 13 Jun 2022 18:33:25 +0200 Subject: [PATCH 2/2] Fix missed nullability cases following rebase --- .../Utilities/MulticastDelegateUtilities.cs | 4 ++-- .../Hosting/DotnetTestHostManager.cs | 1 + 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/MulticastDelegateUtilities.cs b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/MulticastDelegateUtilities.cs index b073bd4ae7..070141bbaf 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/MulticastDelegateUtilities.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/MulticastDelegateUtilities.cs @@ -24,7 +24,7 @@ public static class MulticastDelegateUtilities /// Name to use when tracing out errors. // Using [CallerMemberName] for the traceDisplayName is a possibility, but in few places we call through other // methods until we reach here. And it would change the public API. - public static void SafeInvoke(this Delegate delegates, object sender, EventArgs args, string traceDisplayName) + public static void SafeInvoke(this Delegate? delegates, object sender, EventArgs args, string traceDisplayName) { SafeInvoke(delegates, sender, (object)args, traceDisplayName); } @@ -37,7 +37,7 @@ public static void SafeInvoke(this Delegate delegates, object sender, EventArgs /// Sender to use when raising the event. /// Arguments to provide. /// Name to use when tracing out errors. - public static void SafeInvoke(this Delegate delegates, object sender, object args, string traceDisplayName) + public static void SafeInvoke(this Delegate? delegates, object sender, object args, string traceDisplayName) { ValidateArg.NotNull(args, nameof(args)); ValidateArg.NotNullOrWhiteSpace(traceDisplayName, nameof(traceDisplayName)); diff --git a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs index 59c0221525..c44b98ab69 100644 --- a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs +++ b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs @@ -553,6 +553,7 @@ bool SilentlyForceToX64() internal /* for testing purposes */ void ForwardDotnetRootEnvironmentVariable(TestProcessStartInfo startInfo) { + TPDebug.Assert(_targetFramework is not null, "Initialize must have been called before this method."); const string prefix = "VSTEST_WINAPPHOST_"; const string dotnetRoot = "DOTNET_ROOT"; string vstestDotnetRootEnvName = $"{prefix}{dotnetRoot}(x86)";