diff --git a/.editorconfig b/.editorconfig index fe3ccea29e..6a4b177981 100644 --- a/.editorconfig +++ b/.editorconfig @@ -216,6 +216,12 @@ dotnet_diagnostic.RS0041.severity = none # not default, decreased severity becau # CA1824: Mark assemblies with NeutralResourcesLanguageAttribute dotnet_diagnostic.CA1824.severity = warning # not default, increased severity to ensure it is applied +# CA1304: Specify CultureInfo +dotnet_diagnostic.CA1304.severity = warning # not default, increased severity to ensure it is applied + +# CA1305: Specify IFormatProvider +dotnet_diagnostic.CA1305.severity = warning # not default, increased severity to ensure it is applied + #### C# Coding Conventions #### # var preferences diff --git a/playground/TestPlatform.Playground/Program.cs b/playground/TestPlatform.Playground/Program.cs index 9c17968abd..0732a347c8 100644 --- a/playground/TestPlatform.Playground/Program.cs +++ b/playground/TestPlatform.Playground/Program.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -169,7 +170,7 @@ public void HandleDiscoveryComplete(DiscoveryCompleteEventArgs discoveryComplete public void HandleLogMessage(TestMessageLevel level, string? message) { - Console.WriteLine($"[DISCOVERY.{level.ToString().ToUpper()}] {message}"); + Console.WriteLine($"[DISCOVERY.{level.ToString().ToUpper(CultureInfo.InvariantCulture)}] {message}"); } public void HandleRawMessage(string rawMessage) @@ -197,7 +198,7 @@ public TestRunHandler() public void HandleLogMessage(TestMessageLevel level, string? message) { - Console.WriteLine($"[{level.ToString().ToUpper()}]: {message}"); + Console.WriteLine($"[{level.ToString().ToUpper(CultureInfo.InvariantCulture)}]: {message}"); } public void HandleRawMessage(string rawMessage) diff --git a/src/AttachVS/AttachVs.cs b/src/AttachVS/AttachVs.cs index a24c96bef7..1d712c0d5f 100644 --- a/src/AttachVS/AttachVs.cs +++ b/src/AttachVS/AttachVs.cs @@ -4,6 +4,7 @@ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; @@ -132,17 +133,17 @@ private static bool AttachVs(Process vs, int pid) { try { - dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null); - lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null); - var lpn = (System.Collections.IEnumerator)lps.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, lps, null); + dbg = dte.GetType().InvokeMember("Debugger", BindingFlags.GetProperty, null, dte, null, CultureInfo.InvariantCulture); + lps = dbg.GetType().InvokeMember("LocalProcesses", BindingFlags.GetProperty, null, dbg, null, CultureInfo.InvariantCulture); + var lpn = (System.Collections.IEnumerator)lps.GetType().InvokeMember("GetEnumerator", BindingFlags.InvokeMethod, null, lps, null, CultureInfo.InvariantCulture); while (lpn.MoveNext()) { - var pn = Convert.ToInt32(lpn.Current.GetType().InvokeMember("ProcessID", BindingFlags.GetProperty, null, lpn.Current, null)); + var pn = Convert.ToInt32(lpn.Current.GetType().InvokeMember("ProcessID", BindingFlags.GetProperty, null, lpn.Current, null, CultureInfo.InvariantCulture), CultureInfo.InvariantCulture); if (pn == pid) { - lpn.Current.GetType().InvokeMember("Attach", BindingFlags.InvokeMethod, null, lpn.Current, null); + lpn.Current.GetType().InvokeMember("Attach", BindingFlags.InvokeMethod, null, lpn.Current, null, CultureInfo.InvariantCulture); return true; } } diff --git a/src/DataCollectors/DumpMinitool.x86/Program.cs b/src/DataCollectors/DumpMinitool.x86/Program.cs index 8b3c891006..81373b6b99 100644 --- a/src/DataCollectors/DumpMinitool.x86/Program.cs +++ b/src/DataCollectors/DumpMinitool.x86/Program.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics; +using System.Globalization; using System.Threading; using Microsoft.TestPlatform.Extensions.BlameDataCollector; @@ -22,7 +23,7 @@ static int Main(string[] args) } var outputFile = args[1]; - var processId = int.Parse(args[3]); + var processId = int.Parse(args[3], CultureInfo.InvariantCulture); var dumpType = (MiniDumpTypeOption)Enum.Parse(typeof(MiniDumpTypeOption), args[5]); Console.WriteLine($"Output file: '{outputFile}'"); diff --git a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogContainer.cs b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogContainer.cs index 737cb666b0..28894e918c 100644 --- a/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogContainer.cs +++ b/src/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector/EventLogContainer.cs @@ -151,7 +151,7 @@ public void OnEventLogEntryWritten(object? source, EntryWrittenEventArgs? e) _dataCollectionLogger.LogWarning( _dataCollectionContext, string.Format( - CultureInfo.InvariantCulture, + CultureInfo.CurrentCulture, Resource.EventsLostWarning, EventLog.Log)); @@ -203,7 +203,7 @@ public void OnEventLogEntryWritten(object? source, EntryWrittenEventArgs? e) _dataCollectionLogger.LogError( _dataCollectionContext, string.Format( - CultureInfo.InvariantCulture, + CultureInfo.CurrentCulture, Resource.EventsLostError, EventLog.Log, exception), exception); diff --git a/src/Microsoft.TestPlatform.AdapterUtilities/Helpers/ReflectionHelpers.cs b/src/Microsoft.TestPlatform.AdapterUtilities/Helpers/ReflectionHelpers.cs index 9f4370a343..c4cd5c4fb1 100644 --- a/src/Microsoft.TestPlatform.AdapterUtilities/Helpers/ReflectionHelpers.cs +++ b/src/Microsoft.TestPlatform.AdapterUtilities/Helpers/ReflectionHelpers.cs @@ -16,7 +16,7 @@ private static void AssertSupport(T obj, string methodName, string className) { if (obj == null) { - throw new NotImplementedException(string.Format(Resources.Resources.MethodNotImplementedOnPlatform, className, methodName)); + throw new NotImplementedException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.MethodNotImplementedOnPlatform, className, methodName)); } } diff --git a/src/Microsoft.TestPlatform.Build/Tasks/VSTestTask.cs b/src/Microsoft.TestPlatform.Build/Tasks/VSTestTask.cs index bdc2d1d128..b468fecfef 100644 --- a/src/Microsoft.TestPlatform.Build/Tasks/VSTestTask.cs +++ b/src/Microsoft.TestPlatform.Build/Tasks/VSTestTask.cs @@ -86,7 +86,7 @@ public override bool Execute() Console.WriteLine("Waiting for debugger attach..."); var currentProcess = Process.GetCurrentProcess(); - Console.WriteLine(string.Format("Process Id: {0}, Name: {1}", currentProcess.Id, currentProcess.ProcessName)); + Console.WriteLine($"Process Id: {currentProcess.Id}, Name: {currentProcess.ProcessName}"); while (!Debugger.IsAttached) { diff --git a/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs b/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs index 60bffdb837..fd52dbb9f2 100644 --- a/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs +++ b/src/Microsoft.TestPlatform.Client/DesignMode/DesignModeClient.cs @@ -120,7 +120,7 @@ public void ConnectToClientAndProcessRequests(int port, ITestRequestManager test Dispose(); throw new TimeoutException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage, CoreUtilities.Constants.VstestConsoleProcessName, "translation layer", diff --git a/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs b/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs index 002654eb28..5be9c1768d 100644 --- a/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs +++ b/src/Microsoft.TestPlatform.Client/Execution/TestRunRequest.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; +using System.Globalization; using System.Linq; using System.Threading; @@ -169,7 +170,7 @@ internal void OnTestSessionTimeout(object? obj) { EqtTrace.Verbose("TestRunRequest.OnTestSessionTimeout: calling cancellation as test run exceeded testSessionTimeout {0} milliseconds", _testSessionTimeout); - string message = string.Format(ClientResources.TestSessionTimeoutMessage, _testSessionTimeout); + string message = string.Format(CultureInfo.CurrentCulture, ClientResources.TestSessionTimeoutMessage, _testSessionTimeout); var testMessagePayload = new TestMessagePayload { MessageLevel = TestMessageLevel.Error, Message = message }; var rawMessage = _dataSerializer.SerializePayload(MessageType.TestMessage, testMessagePayload); diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionAttachmentManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionAttachmentManager.cs index b7ceae4798..c7d177c3d9 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionAttachmentManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionAttachmentManager.cs @@ -206,7 +206,7 @@ private static void Validate(FileTransferInformation fileTransferInfo, string lo { throw new FileNotFoundException( string.Format( - CultureInfo.CurrentCulture, + CultureInfo.InvariantCulture, "Could not find source file '{0}'.", fileTransferInfo.FileName)); } diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs index d221a949bd..1bf71927dc 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionManager.cs @@ -486,7 +486,7 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri if (!IsUriValid(dataCollectorUri) && !TryGetUriFromFriendlyName(dataCollectorSettings.FriendlyName, out dataCollectorUri)) { - LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.UnableToFetchUriString, dataCollectorSettings.FriendlyName)); + LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.Resources.UnableToFetchUriString, dataCollectorSettings.FriendlyName)); } ObjectModel.DataCollection.DataCollector? dataCollector = null; @@ -497,7 +497,7 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri if (dataCollector == null) { - LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.DataCollectorNotFound, dataCollectorSettings.FriendlyName)); + LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.Resources.DataCollectorNotFound, dataCollectorSettings.FriendlyName)); return; } @@ -527,7 +527,7 @@ private void LoadAndInitialize(DataCollectorSettings dataCollectorSettings, stri EqtTrace.Error("DataCollectionManager.LoadAndInitialize: exception while creating data collector {0} : {1}", dataCollectorSettings.FriendlyName, ex); // No data collector info, so send the error with no direct association to the collector. - LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.DataCollectorInitializationError, dataCollectorSettings.FriendlyName, ex)); + LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.Resources.DataCollectorInitializationError, dataCollectorSettings.FriendlyName, ex)); return; } @@ -570,7 +570,7 @@ private List GetDataCollectorsEnabledForRun(DataCollectio if (runEnabledDataCollectors.Any(dcSettings => string.Equals(dcSettings.FriendlyName, settings.FriendlyName, StringComparison.OrdinalIgnoreCase))) { // If Uri or assembly qualified type name is repeated, consider data collector as duplicate and ignore it. - LogWarning(string.Format(CultureInfo.CurrentUICulture, Resources.Resources.IgnoredDuplicateConfiguration, settings.FriendlyName)); + LogWarning(string.Format(CultureInfo.CurrentCulture, Resources.Resources.IgnoredDuplicateConfiguration, settings.FriendlyName)); continue; } @@ -689,7 +689,7 @@ private void AddCollectorEnvironmentVariables( { // Data collector is overriding an already requested variable, possibly an error. var message = string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, Resources.Resources.DataCollectorRequestedDuplicateEnvironmentVariable, collectorFriendlyName, namevaluepair.Key, diff --git a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionTelemetryManager.cs b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionTelemetryManager.cs index 3d30a542ca..66c1facc50 100644 --- a/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionTelemetryManager.cs +++ b/src/Microsoft.TestPlatform.Common/DataCollection/DataCollectionTelemetryManager.cs @@ -91,6 +91,6 @@ private static Guid GetProfilerGuid(string profilerGuid) private static string GetTelemetryKey(string telemetryPrefix, DataCollectorInformation dataCollectorInformation) { - return string.Format("{0}.{1}", telemetryPrefix, dataCollectorInformation.DataCollectorConfig?.TypeUri?.ToString()); + return $"{telemetryPrefix}.{dataCollectorInformation.DataCollectorConfig?.TypeUri}"; } } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExtensionManager.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExtensionManager.cs index 66a1314448..318b3c0ea8 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestExtensionManager.cs @@ -152,7 +152,7 @@ private void PopulateMap() { _logger.SendMessage( TestMessageLevel.Warning, - string.Format(CultureInfo.CurrentUICulture, CommonResources.InvalidExtensionUriFormat, extension.Metadata.ExtensionUri, e)); + string.Format(CultureInfo.CurrentCulture, CommonResources.InvalidExtensionUriFormat, extension.Metadata.ExtensionUri, e)); } } @@ -170,7 +170,7 @@ private void PopulateMap() { _logger.SendMessage( TestMessageLevel.Warning, - string.Format(CultureInfo.CurrentUICulture, CommonResources.DuplicateExtensionUri, extension.Metadata.ExtensionUri)); + string.Format(CultureInfo.CurrentCulture, CommonResources.DuplicateExtensionUri, extension.Metadata.ExtensionUri)); } } } diff --git a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginDiscoverer.cs b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginDiscoverer.cs index 37864fdf52..47f813e8a4 100644 --- a/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginDiscoverer.cs +++ b/src/Microsoft.TestPlatform.Common/ExtensionFramework/TestPluginDiscoverer.cs @@ -125,7 +125,7 @@ private void GetTestExtensionsFromFiles( catch (FileLoadException e) { EqtTrace.Warning("TestPluginDiscoverer-FileLoadException: Failed to load extensions from file '{0}'. Skipping test extension scan for this file. Error: {1}", file, e); - string fileLoadErrorMessage = string.Format(CultureInfo.CurrentUICulture, CommonResources.FailedToLoadAdapaterFile, file); + string fileLoadErrorMessage = string.Format(CultureInfo.CurrentCulture, CommonResources.FailedToLoadAdapaterFile, file); TestSessionMessageLogger.Instance.SendMessage(TestMessageLevel.Warning, fileLoadErrorMessage); UnloadableFiles.Add(file); } diff --git a/src/Microsoft.TestPlatform.Common/SettingsProvider/SettingsProviderExtensionManager.cs b/src/Microsoft.TestPlatform.Common/SettingsProvider/SettingsProviderExtensionManager.cs index 93d8d0f12e..4b0d58fab1 100644 --- a/src/Microsoft.TestPlatform.Common/SettingsProvider/SettingsProviderExtensionManager.cs +++ b/src/Microsoft.TestPlatform.Common/SettingsProvider/SettingsProviderExtensionManager.cs @@ -72,7 +72,7 @@ protected SettingsProviderExtensionManager( _logger.SendMessage( TestMessageLevel.Error, string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommonResources.DuplicateSettingsName, settingsName)); } diff --git a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs index b2fb297f9e..aa691c27d8 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/RunSettingsProviderExtensions.cs @@ -164,7 +164,7 @@ public static void UpdateRunSettingsNodeInnerXml(this IRunSettingsProvider runSe internal static XmlNode? GetXmlNode(XmlDocument xmlDocument, string key) { var xPath = key.Replace('.', '/'); - var node = xmlDocument.SelectSingleNode(string.Format("//RunSettings/{0}", xPath)); + var node = xmlDocument.SelectSingleNode($"//RunSettings/{xPath}"); return node; } diff --git a/src/Microsoft.TestPlatform.Common/Utilities/SimpleJSON.cs b/src/Microsoft.TestPlatform.Common/Utilities/SimpleJSON.cs index b1786a3bc1..b252c70ea4 100644 --- a/src/Microsoft.TestPlatform.Common/Utilities/SimpleJSON.cs +++ b/src/Microsoft.TestPlatform.Common/Utilities/SimpleJSON.cs @@ -328,7 +328,7 @@ public virtual long AsLong } set { - Value = value.ToString(); + Value = value.ToString(CultureInfo.InvariantCulture); } } @@ -340,7 +340,7 @@ public virtual ulong AsULong } set { - Value = value.ToString(); + Value = value.ToString(CultureInfo.InvariantCulture); } } @@ -403,7 +403,7 @@ public static implicit operator int(JSONNode d) public static implicit operator JSONNode(long n) { - return LongAsString ? new JSONString(n.ToString()) : new JSONNumber(n); + return LongAsString ? new JSONString(n.ToString(CultureInfo.InvariantCulture)) : new JSONNumber(n); } public static implicit operator long(JSONNode d) { @@ -412,7 +412,7 @@ public static implicit operator long(JSONNode d) public static implicit operator JSONNode(ulong n) { - return LongAsString ? new JSONString(n.ToString()) : new JSONNumber(n); + return LongAsString ? new JSONString(n.ToString(CultureInfo.InvariantCulture)) : new JSONNumber(n); } public static implicit operator ulong(JSONNode d) { @@ -505,7 +505,7 @@ internal static string Escape(string aText) if (c < ' ' || (ForceASCII && c > 127)) { ushort val = c; - sb.Append("\\u").Append(val.ToString("X4")); + sb.Append("\\u").Append(val.ToString("X4", CultureInfo.InvariantCulture)); } else sb.Append(c); @@ -523,7 +523,11 @@ private static JSONNode ParseElement(string token, bool quoted) return token; if (token.Length <= 5) { - string tmp = token.ToLower(); + string tmp = token.ToLower( +#if !NETSTANDARD1_3 + CultureInfo.InvariantCulture +#endif + ); if (tmp is "false" or "true") return tmp == "true"; if (tmp == "null") @@ -674,7 +678,8 @@ public static JSONNode Parse(string aJSON) string s = aJSON.Substring(i + 1, 4); token.Append((char)int.Parse( s, - System.Globalization.NumberStyles.AllowHexSpecifier)); + System.Globalization.NumberStyles.AllowHexSpecifier, + CultureInfo.InvariantCulture)); i += 4; break; } @@ -1124,7 +1129,7 @@ public override bool Equals(object obj) if (base.Equals(obj)) return true; JSONNumber s2 = obj as JSONNumber; - return s2 != null ? _data == s2._data : IsNumeric(obj) && Convert.ToDouble(obj) == _data; + return s2 != null ? _data == s2._data : IsNumeric(obj) && Convert.ToDouble(obj, CultureInfo.InvariantCulture) == _data; } public override int GetHashCode() { @@ -1342,7 +1347,7 @@ public override long AsLong set { if (LongAsString) - Set(new JSONString(value.ToString())); + Set(new JSONString(value.ToString(CultureInfo.InvariantCulture))); else Set(new JSONNumber(value)); } @@ -1361,7 +1366,7 @@ public override ulong AsULong set { if (LongAsString) - Set(new JSONString(value.ToString())); + Set(new JSONString(value.ToString(CultureInfo.InvariantCulture))); else Set(new JSONNumber(value)); } diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs index fd3d7861e8..27e0c543a8 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/DataCollectionRequestHandler.cs @@ -358,7 +358,7 @@ private void HandleBeforeTestRunStart(Message message) _dataCollectionTestCaseEventHandler.Close(); throw new TestPlatformException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage, CoreUtilitiesConstants.DatacollectorProcessName, CoreUtilitiesConstants.TesthostProcessName, diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs index dfab1947d5..49906b0008 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestCaseConverter.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -84,7 +85,7 @@ public override bool CanConvert(Type objectType) case "TestCase.CodeFilePath": testCase.CodeFilePath = propertyData; break; case "TestCase.LineNumber": - testCase.LineNumber = int.Parse(propertyData!); break; + testCase.LineNumber = int.Parse(propertyData!, CultureInfo.CurrentCulture); break; default: // No need to register member properties as they get registered as part of TestCaseProperties class. testProperty = TestProperty.Register(testProperty.Id, testProperty.Label, testProperty.GetValueType(), testProperty.Attributes, typeof(TestObject)); diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestResultConverter.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestResultConverter.cs index 3ec65e3500..1ea61521aa 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestResultConverter.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/Serialization/TestResultConverter.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -94,11 +95,11 @@ public override object ReadJson(JsonReader reader, Type objectType, object? exis case "TestResult.Outcome": testResult.Outcome = (TestOutcome)Enum.Parse(typeof(TestOutcome), propertyData!); break; case "TestResult.Duration": - testResult.Duration = TimeSpan.Parse(propertyData!); break; + testResult.Duration = TimeSpan.Parse(propertyData!, CultureInfo.CurrentCulture); break; case "TestResult.StartTime": - testResult.StartTime = DateTimeOffset.Parse(propertyData!); break; + testResult.StartTime = DateTimeOffset.Parse(propertyData!, CultureInfo.CurrentCulture); break; case "TestResult.EndTime": - testResult.EndTime = DateTimeOffset.Parse(propertyData!); break; + testResult.EndTime = DateTimeOffset.Parse(propertyData!, CultureInfo.CurrentCulture); break; case "TestResult.ErrorMessage": testResult.ErrorMessage = propertyData; break; case "TestResult.ErrorStackTrace": diff --git a/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs b/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs index acf538675e..f4a2d0c25a 100644 --- a/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs +++ b/src/Microsoft.TestPlatform.CommunicationUtilities/TestRequestSender.cs @@ -208,12 +208,12 @@ public void CheckVersionWithTestHost() } else if (message.MessageType == MessageType.ProtocolError) { - throw new TestPlatformException(string.Format(CultureInfo.CurrentUICulture, CommonResources.VersionCheckFailed)); + throw new TestPlatformException(CommonResources.VersionCheckFailed); } else { throw new TestPlatformException(string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommonResources.UnexpectedMessage, MessageType.VersionCheck, message.MessageType)); @@ -237,7 +237,7 @@ public void CheckVersionWithTestHost() var timeout = EnvironmentHelper.GetConnectionTimeout(); if (!protocolNegotiated.WaitOne(timeout * 1000)) { - throw new TestPlatformException(string.Format(CultureInfo.CurrentUICulture, CommonResources.VersionCheckTimedout, timeout, EnvironmentHelper.VstestConnectionTimeout)); + throw new TestPlatformException(string.Format(CultureInfo.CurrentCulture, CommonResources.VersionCheckTimedout, timeout, EnvironmentHelper.VstestConnectionTimeout)); } } finally @@ -341,10 +341,7 @@ public void StartTestRun(TestRunCriteriaWithSources runCriteria, IInternalTestRu { if (!convertedRuntimeProvider.AttachDebuggerToTestHost()) { - EqtTrace.Warning( - string.Format( - CultureInfo.CurrentUICulture, - CommonResources.AttachDebuggerToDefaultTestHostFailure)); + EqtTrace.Warning(CommonResources.AttachDebuggerToDefaultTestHostFailure); } } @@ -384,10 +381,7 @@ public void StartTestRun(TestRunCriteriaWithTests runCriteria, IInternalTestRunE { if (!convertedRuntimeProvider.AttachDebuggerToTestHost()) { - EqtTrace.Warning( - string.Format( - CultureInfo.CurrentUICulture, - CommonResources.AttachDebuggerToDefaultTestHostFailure)); + EqtTrace.Warning(CommonResources.AttachDebuggerToDefaultTestHostFailure); } } @@ -629,7 +623,7 @@ private void OnTestRunAbort(IInternalTestRunEventsHandler testRunEventsHandler, var reason = GetAbortErrorMessage(exception, getClientError); EqtTrace.Error("TestRequestSender: Aborting test run because {0}", reason); - LogErrorMessage(string.Format(CommonResources.AbortedTestRun, reason)); + LogErrorMessage(string.Format(CultureInfo.CurrentCulture, CommonResources.AbortedTestRun, reason)); // notify test run abort to vstest console wrapper. var completeArgs = new TestRunCompleteEventArgs(null, false, true, exception, null, null, TimeSpan.Zero); @@ -656,7 +650,7 @@ private void OnDiscoveryAbort(ITestDiscoveryEventsHandler2 eventHandler, Excepti if (GetAbortErrorMessage(exception, getClientError) is string reason) { EqtTrace.Error("TestRequestSender.OnDiscoveryAbort: Aborting test discovery because {0}.", reason); - LogErrorMessage(string.Format(CommonResources.AbortedTestDiscoveryWithReason, reason)); + LogErrorMessage(string.Format(CultureInfo.CurrentCulture, CommonResources.AbortedTestDiscoveryWithReason, reason)); } else { diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs index 79bfdd578d..47a89ff833 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Helpers/DotnetHostHelper.cs @@ -5,6 +5,7 @@ using System; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.IO; using System.Reflection.PortableExecutable; @@ -75,7 +76,7 @@ public string GetDotnetPath() { if (!TryGetExecutablePath("dotnet", out var dotnetPath)) { - string errorMessage = string.Format(Resources.NoDotnetExeFound, "dotnet"); + string errorMessage = string.Format(CultureInfo.CurrentCulture, Resources.NoDotnetExeFound, "dotnet"); EqtTrace.Error(errorMessage); throw new FileNotFoundException(errorMessage); @@ -88,7 +89,7 @@ public string GetMonoPath() { if (!TryGetExecutablePath(MONOEXENAME, out var monoPath)) { - string errorMessage = string.Format(Resources.NoDotnetExeFound, MONOEXENAME); + string errorMessage = string.Format(CultureInfo.CurrentCulture, Resources.NoDotnetExeFound, MONOEXENAME); EqtTrace.Error(errorMessage); throw new FileNotFoundException(errorMessage); diff --git a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs index eba17dc8e6..4661b79243 100644 --- a/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs +++ b/src/Microsoft.TestPlatform.CoreUtilities/Utilities/JobQueue.cs @@ -206,7 +206,7 @@ public void Dispose() if (!_queueProcessing.WaitOne(0)) { throw new InvalidOperationException( - string.Format(CultureInfo.CurrentUICulture, Resources.QueuePausedDisposeError, _displayName)); + string.Format(CultureInfo.CurrentCulture, Resources.QueuePausedDisposeError, _displayName)); } _isDisposed = true; @@ -274,7 +274,7 @@ private void CheckDisposed() if (_isDisposed) { throw new ObjectDisposedException( - string.Format(CultureInfo.CurrentUICulture, Resources.QueueAlreadyDisposed, _displayName)); + string.Format(CultureInfo.CurrentCulture, Resources.QueueAlreadyDisposed, _displayName)); } } @@ -353,12 +353,7 @@ private void SafeProcessJob(T? job) } catch (Exception e) { - _exceptionLogger( - string.Format( - CultureInfo.CurrentUICulture, - Resources.ExceptionFromJobProcessor, - _displayName, - e)); + _exceptionLogger(string.Format(CultureInfo.CurrentCulture, Resources.ExceptionFromJobProcessor, _displayName, e)); } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomain.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomain.cs index 3ac0618b76..28ef57dbd8 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomain.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomain.cs @@ -5,6 +5,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.IO.Pipes; using System.Linq; @@ -124,7 +125,7 @@ private void PipeReaderTask() .SendMessage((TestMessageLevel)Enum.Parse(typeof(TestMessageLevel), prefix.Substring(prefix.LastIndexOf('.') + 1), false), message); break; case AppDomainPipeMessagePrefix.Report: - _progressReporter?.Report(int.Parse(message)); + _progressReporter?.Report(int.Parse(message, CultureInfo.CurrentCulture)); break; default: EqtTrace.Error($"DataCollectorAttachmentProcessorAppDomain:PipeReaderTask: Unknown message: {message}"); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/DiscoveryDataAggregator.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/DiscoveryDataAggregator.cs index efa87b2e94..a54062a44f 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/DiscoveryDataAggregator.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/DiscoveryDataAggregator.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Threading; @@ -141,11 +142,11 @@ public void AggregateMetrics(IDictionary? metrics) || metric.Key.Contains(TelemetryDataConstants.TotalTestsByAdapter) || metric.Key.Contains(TelemetryDataConstants.TimeTakenToLoadAdaptersInSec)) { - var newValue = Convert.ToDouble(metric.Value); + var newValue = Convert.ToDouble(metric.Value, CultureInfo.InvariantCulture); if (_metricsAggregator.TryGetValue(metric.Key, out object? oldValue)) { - double oldDoubleValue = Convert.ToDouble(oldValue); + double oldDoubleValue = Convert.ToDouble(oldValue, CultureInfo.InvariantCulture); _metricsAggregator[metric.Key] = newValue + oldDoubleValue; } else diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunDataAggregator.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunDataAggregator.cs index 1661ebee74..2073336a47 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunDataAggregator.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/Parallel/ParallelRunDataAggregator.cs @@ -5,6 +5,7 @@ using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.Linq; using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; @@ -194,11 +195,11 @@ public void AggregateRunDataMetrics(IDictionary? metrics) { if (metric.Key.Contains(TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter) || metric.Key.Contains(TelemetryDataConstants.TimeTakenByAllAdaptersInSec) || (metric.Key.Contains(TelemetryDataConstants.TotalTestsRun) || metric.Key.Contains(TelemetryDataConstants.TotalTestsRanByAdapter))) { - var newValue = Convert.ToDouble(metric.Value); + var newValue = Convert.ToDouble(metric.Value, CultureInfo.InvariantCulture); if (_metricsAggregator.TryGetValue(metric.Key, out var oldValue)) { - var oldDoubleValue = Convert.ToDouble(oldValue); + var oldDoubleValue = Convert.ToDouble(oldValue, CultureInfo.InvariantCulture); _metricsAggregator[metric.Key] = newValue + oldDoubleValue; } else diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyDiscoveryManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyDiscoveryManager.cs index cd7efafb71..516517d778 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyDiscoveryManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyDiscoveryManager.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using Microsoft.VisualStudio.TestPlatform.Common; @@ -323,7 +324,7 @@ private void InitializeExtensions(IEnumerable sources) var nonExistingExtensions = extensions.Where(extension => !_fileHelper.Exists(extension)); if (nonExistingExtensions.Any()) { - LogMessage(TestMessageLevel.Warning, string.Format(Resources.Resources.NonExistingExtensions, string.Join(",", nonExistingExtensions))); + LogMessage(TestMessageLevel.Warning, string.Format(CultureInfo.CurrentCulture, Resources.Resources.NonExistingExtensions, string.Join(",", nonExistingExtensions))); } var sourceList = sources.ToList(); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManager.cs index 1a4f1ae31d..bfeb38a0eb 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyExecutionManager.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.Linq; using System.Threading; @@ -449,7 +450,7 @@ private void InitializeExtensions(IEnumerable sources) var nonExistingExtensions = extensions.Where(extension => !_fileHelper.Exists(extension)); if (nonExistingExtensions.Any()) { - LogMessage(TestMessageLevel.Warning, string.Format(Resources.Resources.NonExistingExtensions, string.Join(",", nonExistingExtensions))); + LogMessage(TestMessageLevel.Warning, string.Format(CultureInfo.CurrentCulture, Resources.Resources.NonExistingExtensions, string.Join(",", nonExistingExtensions))); } var sourceList = sources.ToList(); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManager.cs index 97e9820f6c..057cb79619 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/ProxyOperationManager.cs @@ -229,10 +229,7 @@ public virtual bool SetupChannel(IEnumerable sources, string? runSetting EqtTrace.Error("ProxyOperationManager: Failed to launch testhost :{0}", ex); CancellationTokenSource.Token.ThrowTestPlatformExceptionIfCancellationRequested(); - throw new TestPlatformException(string.Format( - CultureInfo.CurrentUICulture, - CrossPlatEngineResources.FailedToLaunchTestHost, - ex.ToString())); + throw new TestPlatformException(string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.FailedToLaunchTestHost, ex.ToString())); } // Warn the user that execution will wait for debugger attach. @@ -251,6 +248,7 @@ public virtual bool SetupChannel(IEnumerable sources, string? runSetting ConsoleOutput.Instance.WriteLine( string.Format( + CultureInfo.InvariantCulture, "Process Id: {0}, Name: {1}", _testHostProcessId, _processHelper.GetProcessName(_testHostProcessId)), @@ -412,8 +410,9 @@ public virtual TestProcessStartInfo UpdateTestProcessStartInfo(TestProcessStartI : Path.ChangeExtension( logFile, string.Format( + CultureInfo.InvariantCulture, "host.{0}_{1}{2}", - DateTime.Now.ToString("yy-MM-dd_HH-mm-ss_fffff"), + DateTime.Now.ToString("yy-MM-dd_HH-mm-ss_fffff", CultureInfo.InvariantCulture), new PlatformEnvironment().GetCurrentManagedThreadId(), Path.GetExtension(logFile))).AddDoubleQuote(); } @@ -465,7 +464,7 @@ private void ThrowOnTestHostExited(bool testHostExited) { // We might consider passing standard output here in case standard error is not // available because some errors don't end up in the standard error output. - throw new TestPlatformException(string.Format(CrossPlatEngineResources.TestHostExitedWithError, _testHostProcessStdError)); + throw new TestPlatformException(string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.TestHostExitedWithError, _testHostProcessStdError)); } } @@ -478,6 +477,7 @@ private void ThrowExceptionOnConnectionFailure(int connTimeout) if (_testHostLaunched) { errorMsg = string.Format( + CultureInfo.CurrentCulture, CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage, CoreUtilitiesConstants.VstestConsoleProcessName, CoreUtilitiesConstants.TesthostProcessName, @@ -489,9 +489,9 @@ private void ThrowExceptionOnConnectionFailure(int connTimeout) if (!StringUtils.IsNullOrWhiteSpace(_testHostProcessStdError)) { // Testhost failed with error. - errorMsg = string.Format(CrossPlatEngineResources.TestHostExitedWithError, _testHostProcessStdError); + errorMsg = string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.TestHostExitedWithError, _testHostProcessStdError); } - throw new TestPlatformException(string.Format(CultureInfo.CurrentUICulture, errorMsg)); + throw new TestPlatformException(errorMsg); } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs index a9295aa32d..7a5db4544d 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Client/TestLoggerManager.cs @@ -183,10 +183,7 @@ public void Initialize(string? runSettings) : logger.FriendlyName; throw new InvalidLoggerException( - string.Format( - CultureInfo.CurrentUICulture, - CommonResources.LoggerNotFound, - value)); + string.Format(CultureInfo.CurrentCulture, CommonResources.LoggerNotFound, value)); } } @@ -413,7 +410,7 @@ internal bool TryGetUriFromFriendlyName(string? friendlyName, out Uri? loggerUri throw new InvalidLoggerException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommonResources.LoggerUriInvalid, extension.Metadata.ExtensionUri)); } @@ -617,7 +614,7 @@ private bool InitializeLogger(object? logger, string? extensionUri, Dictionary? environmen EqtTrace.Verbose("DotnetDataCollectionLauncher: Full path of dotnet.exe is {0}", currentProcessFileName); var cliArgs = string.Join(" ", commandLineArguments); - var argumentsString = string.Format("{0} \"{1}\" {2} ", args, dataCollectorAssemblyPath, cliArgs); - + var argumentsString = string.Format(CultureInfo.InvariantCulture, "{0} \"{1}\" {2} ", args, dataCollectorAssemblyPath, cliArgs); var dataCollectorProcess = _processHelper.LaunchProcess(currentProcessFileName, argumentsString, Directory.GetCurrentDirectory(), environmentVariables, ErrorReceivedCallback, ExitCallBack, null); DataCollectorProcessId = _processHelper.GetProcessId(dataCollectorProcess); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs index f0c671b15e..c689ebf21f 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/DataCollection/ProxyDataCollectionManager.cs @@ -250,7 +250,7 @@ public void Initialize() EqtTrace.Error("ProxyDataCollectionManager.Initialize: failed to connect to datacollector process, processId: {0} port: {1}", _dataCollectionProcessId, _dataCollectionPort); throw new TestPlatformException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage, CoreUtilitiesConstants.VstestConsoleProcessName, CoreUtilitiesConstants.DatacollectorProcessName, @@ -271,7 +271,7 @@ private int GetConnectionTimeout(int processId) { ConsoleOutput.Instance.WriteLine(CrossPlatEngineResources.DataCollectorDebuggerWarning, OutputLevel.Warning); ConsoleOutput.Instance.WriteLine( - string.Format("Process Id: {0}, Name: {1}", processId, _processHelper.GetProcessName(processId)), + string.Format(CultureInfo.InvariantCulture, "Process Id: {0}, Name: {1}", processId, _processHelper.GetProcessName(processId)), OutputLevel.Information); // Increase connection timeout when debugging is enabled. @@ -307,10 +307,10 @@ private IList GetCommandLineArguments(int portNumber) var commandlineArguments = new List { PortOption, - portNumber.ToString(), + portNumber.ToString(CultureInfo.CurrentCulture), ParentProcessIdOption, - _processHelper.GetCurrentProcessId().ToString() + _processHelper.GetCurrentProcessId().ToString(CultureInfo.CurrentCulture) }; if (!StringUtils.IsNullOrEmpty(EqtTrace.LogFile)) @@ -319,7 +319,7 @@ private IList GetCommandLineArguments(int portNumber) commandlineArguments.Add(GetTimestampedLogFile(EqtTrace.LogFile)); commandlineArguments.Add(TraceLevelOption); - commandlineArguments.Add(((int)EqtTrace.TraceLevel).ToString()); + commandlineArguments.Add(((int)EqtTrace.TraceLevel).ToString(CultureInfo.CurrentCulture)); } return commandlineArguments; @@ -330,8 +330,9 @@ private static string GetTimestampedLogFile(string logFile) return Path.ChangeExtension( logFile, string.Format( + CultureInfo.InvariantCulture, "datacollector.{0}_{1}{2}", - DateTime.Now.ToString("yy-MM-dd_HH-mm-ss_fffff"), + DateTime.Now.ToString("yy-MM-dd_HH-mm-ss_fffff", CultureInfo.CurrentCulture), new PlatformEnvironment().GetCurrentManagedThreadId(), Path.GetExtension(logFile))).AddDoubleQuote(); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscovererEnumerator.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscovererEnumerator.cs index add9534264..92a85f57ca 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscovererEnumerator.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Discovery/DiscovererEnumerator.cs @@ -232,8 +232,8 @@ private void DiscoverTestsFromSingleDiscoverer( // Record Total Tests Discovered By each Discoverer. var totalTestsDiscoveredByCurrentDiscoverer = _discoveryResultCache.TotalDiscoveredTests - currentTotalTests; _requestData.MetricsCollection.Add( - string.Format("{0}.{1}", TelemetryDataConstants.TotalTestsByAdapter, - discoverer.Metadata.DefaultExecutorUri), totalTestsDiscoveredByCurrentDiscoverer); + $"{TelemetryDataConstants.TotalTestsByAdapter}.{discoverer.Metadata.DefaultExecutorUri}", + totalTestsDiscoveredByCurrentDiscoverer); totalAdaptersUsed++; @@ -249,14 +249,14 @@ private void DiscoverTestsFromSingleDiscoverer( // Collecting Data Point for Time Taken to Discover Tests by each Adapter _requestData.MetricsCollection.Add( - string.Format("{0}.{1}", TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter, - discoverer.Metadata.DefaultExecutorUri), totalAdapterRunTime.TotalSeconds); + $"{TelemetryDataConstants.TimeTakenToDiscoverTestsByAnAdapter}.{discoverer.Metadata.DefaultExecutorUri}", + totalAdapterRunTime.TotalSeconds); totalTimeTakenByAdapters += totalAdapterRunTime.TotalSeconds; } catch (Exception e) { var message = string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CrossPlatEngineResources.ExceptionFromLoadTests, discovererType.Name, e.Message); @@ -277,10 +277,7 @@ private static bool TryToLoadDiscoverer(LazyExtension sources, s logger.SendMessage( TestMessageLevel.Warning, - string.Format(CrossPlatEngineResources.NoTestsAvailableForGivenTestCaseFilter, testCaseFilterToShow, sourcesString)); + string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.NoTestsAvailableForGivenTestCaseFilter, testCaseFilterToShow, sourcesString)); } else { logger.SendMessage( TestMessageLevel.Warning, - string.Format( - CultureInfo.CurrentUICulture, - CrossPlatEngineResources.TestRunFailed_NoDiscovererFound_NoTestsAreAvailableInTheSources, - sourcesString)); + string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.TestRunFailed_NoDiscovererFound_NoTestsAreAvailableInTheSources, sourcesString)); } } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs index eabc5032ce..55a3251627 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/EventHandlers/TestRequestHandler.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.Threading; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.EventHandlers; @@ -348,7 +349,7 @@ public void OnMessageReceived(object? sender, MessageReceivedEventArgs messageRe // Can only do this after InitializeCommunication because TestHost cannot "Send Log" unless communications are initialized if (!StringUtils.IsNullOrEmpty(EqtTrace.LogFile)) { - SendLog(TestMessageLevel.Informational, string.Format(CrossPlatResources.TesthostDiagLogOutputFile, EqtTrace.LogFile)); + SendLog(TestMessageLevel.Informational, string.Format(CultureInfo.CurrentCulture, CrossPlatResources.TesthostDiagLogOutputFile, EqtTrace.LogFile)); } else if (!StringUtils.IsNullOrEmpty(EqtTrace.ErrorOnInitialization)) { diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs index 3ddea6a197..5d21e64282 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/BaseRunTests.cs @@ -382,7 +382,7 @@ private bool RunTestInternalWithExecutors(IEnumerable> execut TestRunEventsHandler?.HandleLogMessage( TestMessageLevel.Warning, string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CrossPlatEngineResources.NoMatchingExecutor, executorUriExtensionTuple.Item1.AbsoluteUri, runtimeVersion)); @@ -418,11 +418,7 @@ private bool RunTestInternalWithExecutors(IEnumerable> execut #endif if (!FrameworkHandle.AttachDebuggerToProcess(pid)) { - EqtTrace.Warning( - string.Format( - CultureInfo.CurrentUICulture, - CrossPlatEngineResources.AttachDebuggerToDefaultTestHostFailure, - pid)); + EqtTrace.Warning(string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.AttachDebuggerToDefaultTestHostFailure, pid)); } } } @@ -479,7 +475,7 @@ private bool RunTestInternalWithExecutors(IEnumerable> execut // Collecting Total Tests Ran by each Adapter var totalTestRun = TestRunCache.TotalExecutedTests - totalTests; - _requestData.MetricsCollection.Add(string.Format("{0}.{1}", TelemetryDataConstants.TotalTestsRanByAdapter, executorUri), totalTestRun); + _requestData.MetricsCollection.Add($"{TelemetryDataConstants.TotalTestsRanByAdapter}.{executorUri}", totalTestRun); // Only enable this for MSTestV1 telemetry for now, this might become more generic later. if (MsTestV1TelemetryHelper.IsMsTestV1Adapter(executorUri)) @@ -488,7 +484,7 @@ private bool RunTestInternalWithExecutors(IEnumerable> execut { var value = TestRunCache.AdapterTelemetry[adapterMetrics]; - _requestData.MetricsCollection.Add(string.Format("{0}.{1}", TelemetryDataConstants.TotalTestsRunByMSTestv1, adapterMetrics), value); + _requestData.MetricsCollection.Add($"{TelemetryDataConstants.TotalTestsRunByMSTestv1}.{adapterMetrics}", value); } } @@ -507,7 +503,7 @@ private bool RunTestInternalWithExecutors(IEnumerable> execut executor.Metadata.ExtensionUri); // Collecting Time Taken by each executor Uri - _requestData.MetricsCollection.Add(string.Format("{0}.{1}", TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter, executorUri), totalTimeTaken.TotalSeconds); + _requestData.MetricsCollection.Add($"{TelemetryDataConstants.TimeTakenToRunTestsByAnAdapter}.{executorUri}", totalTimeTaken.TotalSeconds); totalTimeTakenByAdapters += totalTimeTaken.TotalSeconds; } catch (Exception e) @@ -682,7 +678,7 @@ private bool TryToRunInStaThread(Action action, bool waitForCompletion) EqtTrace.Warning("BaseRunTests.TryToRunInSTAThread: Failed to run in STA thread: {0}", ex); TestRunEventsHandler.HandleLogMessage( TestMessageLevel.Warning, - string.Format(CultureInfo.CurrentUICulture, CrossPlatEngineResources.ExecutionThreadApartmentStateNotSupportedForFramework, _runConfiguration.TargetFramework!.ToString())); + string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.ExecutionThreadApartmentStateNotSupportedForFramework, _runConfiguration.TargetFramework!.ToString())); } return success; diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs index 844c15b150..36c157c4c1 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/Execution/RunTestsWithSources.cs @@ -81,14 +81,14 @@ private void LogWarningOnNoTestsExecuted() var testCaseFilterToShow = TestCaseFilterDeterminer.ShortenTestCaseFilterIfRequired(TestExecutionContext.TestCaseFilter); TestRunEventsHandler?.HandleLogMessage( TestMessageLevel.Warning, - string.Format(CrossPlatEngineResources.NoTestsAvailableForGivenTestCaseFilter, testCaseFilterToShow, sourcesString)); + string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.NoTestsAvailableForGivenTestCaseFilter, testCaseFilterToShow, sourcesString)); } else { TestRunEventsHandler?.HandleLogMessage( TestMessageLevel.Warning, string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CrossPlatEngineResources.TestRunFailed_NoDiscovererFound_NoTestsAreAvailableInTheSources, sourcesString)); } @@ -174,7 +174,7 @@ private Dictionary, IEnumerable> GetExecutorVsSources if (executorUri == null) { string errorMessage = string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CrossPlatEngineResources.IgnoringExecutorAsNoDefaultExecutorUriAttribute, discoverer.Value); logger.SendMessage(TestMessageLevel.Warning, errorMessage); @@ -190,7 +190,7 @@ private Dictionary, IEnumerable> GetExecutorVsSources else { string errorMessage = string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CrossPlatEngineResources.DuplicateAdaptersFound, executorUri, discoverer.Value); diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/TestEngine.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/TestEngine.cs index 9712415193..709d50e431 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/TestEngine.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/TestEngine.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Linq; using System.Text; @@ -640,7 +639,7 @@ private static void ThrowExceptionIfTestHostManagerIsNull(ITestRuntimeProvider? if (testHostManager == null) { EqtTrace.Error($"{nameof(TestEngine)}.{nameof(ThrowExceptionIfTestHostManagerIsNull)}: No suitable testHostProvider found for runsettings: {settingsXml}"); - throw new TestPlatformException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.NoTestHostProviderFound)); + throw new TestPlatformException(Resources.Resources.NoTestHostProviderFound); } } @@ -656,7 +655,7 @@ private static void WarnAboutNotFoundRuntimeProvidersOrThrowWhenNoneAreFound(Lis if (missingRuntimeProviders.Any()) { var stringBuilder = new StringBuilder(); - stringBuilder.AppendLine(string.Format(CultureInfo.CurrentCulture, Resources.Resources.NoSuitableRuntimeProviderFound)); + stringBuilder.AppendLine(Resources.Resources.NoTestHostProviderFound); foreach (var missingRuntimeProvider in missingRuntimeProviders) { var text = $"{nameof(TestEngine)}.{nameof(WarnAboutNotFoundRuntimeProvidersOrThrowWhenNoneAreFound)}: No suitable testHostProvider found for sources {string.Join(", ", missingRuntimeProvider.SourceDetails.Select(s => s.Source))} and runsettings: {missingRuntimeProvider.RunSettings}"; @@ -674,7 +673,11 @@ private static void WarnAboutNotFoundRuntimeProvidersOrThrowWhenNoneAreFound(Lis { stringBuilder.Append(Resources.Resources.SkippingSource).Append(' '); } - stringBuilder.AppendLine($"{detail.Source} ({detail.Framework}, {detail.Architecture})"); + stringBuilder.AppendLine( +#if NET6_0_OR_GREATER + System.Globalization.CultureInfo.InvariantCulture, +#endif + $"{detail.Source} ({detail.Framework}, {detail.Architecture})"); }); } diff --git a/src/Microsoft.TestPlatform.CrossPlatEngine/TestSession/ProxyTestSessionManager.cs b/src/Microsoft.TestPlatform.CrossPlatEngine/TestSession/ProxyTestSessionManager.cs index 522f4fab5e..a05b950f97 100644 --- a/src/Microsoft.TestPlatform.CrossPlatEngine/TestSession/ProxyTestSessionManager.cs +++ b/src/Microsoft.TestPlatform.CrossPlatEngine/TestSession/ProxyTestSessionManager.cs @@ -239,10 +239,7 @@ public virtual ProxyOperationManager DequeueProxy(string source, string? runSett if (!_proxyMap.ContainsKey(source) || !_proxyContainerList[_proxyMap[source]].IsAvailable) { - throw new InvalidOperationException( - string.Format( - CultureInfo.CurrentUICulture, - CrossPlatResources.NoAvailableProxyForDeque)); + throw new InvalidOperationException(CrossPlatResources.NoAvailableProxyForDeque); } // We must ensure the current run settings match the run settings from when the @@ -251,10 +248,7 @@ public virtual ProxyOperationManager DequeueProxy(string source, string? runSett if (!CheckRunSettingsAreCompatible(runSettings)) { EqtTrace.Verbose($"ProxyTestSessionManager.DequeueProxy: A proxy exists, but the runsettings do not match. Skipping it. Incoming settings: {runSettings}, Settings on proxy: {_testSessionCriteria.RunSettings}"); - throw new InvalidOperationException( - string.Format( - CultureInfo.CurrentUICulture, - CrossPlatResources.NoProxyMatchesDescription)); + throw new InvalidOperationException(CrossPlatResources.NoProxyMatchesDescription); } // Get the actual proxy. @@ -283,7 +277,7 @@ public virtual bool EnqueueProxy(int proxyId) { throw new ArgumentException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CrossPlatResources.NoSuchProxyId, proxyId)); } @@ -294,7 +288,7 @@ public virtual bool EnqueueProxy(int proxyId) { throw new InvalidOperationException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CrossPlatResources.ProxyIsAlreadyAvailable, proxyId)); } diff --git a/src/Microsoft.TestPlatform.Execution.Shared/DebuggerBreakpoint.cs b/src/Microsoft.TestPlatform.Execution.Shared/DebuggerBreakpoint.cs index 6806d3745e..4f4d7a2eeb 100644 --- a/src/Microsoft.TestPlatform.Execution.Shared/DebuggerBreakpoint.cs +++ b/src/Microsoft.TestPlatform.Execution.Shared/DebuggerBreakpoint.cs @@ -146,7 +146,7 @@ internal static void WaitForDebugger(string environmentVariable) var currentProcess = Process.GetCurrentProcess(); ConsoleOutput.Instance.WriteLine( - string.Format("Process Id: {0}, Name: {1}", currentProcess.Id, currentProcess.ProcessName), + $"Process Id: {currentProcess.Id}, Name: {currentProcess.ProcessName}", OutputLevel.Information); while (!Debugger.IsAttached) diff --git a/src/Microsoft.TestPlatform.Execution.Shared/UILanguageOverride.cs b/src/Microsoft.TestPlatform.Execution.Shared/UILanguageOverride.cs index 6fee3235f6..a700017e5f 100644 --- a/src/Microsoft.TestPlatform.Execution.Shared/UILanguageOverride.cs +++ b/src/Microsoft.TestPlatform.Execution.Shared/UILanguageOverride.cs @@ -80,7 +80,7 @@ private static void FlowOverrideToChildProcesses(CultureInfo language, IEnvironm // Do not override any environment variables that are already set as we do not want to clobber a more granular setting with our global setting. SetIfNotAlreadySet(DOTNET_CLI_UI_LANGUAGE, language.Name, environmentVariableHelper); #if !NETCOREAPP1_0 && !NETSTANDARD1_3 - SetIfNotAlreadySet(VSLANG, language.LCID.ToString(), environmentVariableHelper); // for tools following VS guidelines to just work in CLI + SetIfNotAlreadySet(VSLANG, language.LCID.ToString(CultureInfo.CurrentCulture), environmentVariableHelper); // for tools following VS guidelines to just work in CLI #endif SetIfNotAlreadySet(PreferredUILang, language.Name, environmentVariableHelper); // for C#/VB targets that pass $(PreferredUILang) to compiler } diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs index 9bb9509ab7..a31eabcd05 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/BlameCollector.cs @@ -201,16 +201,16 @@ private void CollectDumpAndAbortTesthost() if (_inactivityTimespan.TotalSeconds <= 90) { - value = ((int)_inactivityTimespan.TotalSeconds).ToString(); + value = ((int)_inactivityTimespan.TotalSeconds).ToString(CultureInfo.InvariantCulture); unit = Resources.Resources.Seconds; } else { - value = Math.Round(_inactivityTimespan.TotalMinutes, 2).ToString(); + value = Math.Round(_inactivityTimespan.TotalMinutes, 2).ToString(CultureInfo.InvariantCulture); unit = Resources.Resources.Minutes; } - var message = string.Format(CultureInfo.CurrentUICulture, Resources.Resources.InactivityTimeout, value, unit); + var message = string.Format(CultureInfo.CurrentCulture, Resources.Resources.InactivityTimeout, value, unit); EqtTrace.Warning(message); _logger.LogWarning(_context.SessionDataCollectionContext, message); @@ -340,7 +340,7 @@ private void ValidateAndAddCrashProcessDumpParameters(XmlElement collectDumpNode default: - _logger.LogWarning(_context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterKeyIncorrect, blameAttribute.Name)); + _logger.LogWarning(_context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentCulture, Resources.Resources.BlameParameterKeyIncorrect, blameAttribute.Name)); break; } } @@ -348,7 +348,7 @@ private void ValidateAndAddCrashProcessDumpParameters(XmlElement collectDumpNode internal static string FormatBlameParameterValueIncorrectMessage(XmlAttribute attribute, params string[] validValues) { - return string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, attribute.Name, attribute.Value, string.Join(", ", validValues)); + return string.Format(CultureInfo.CurrentCulture, Resources.Resources.BlameParameterValueIncorrect, attribute.Name, attribute.Value, string.Join(", ", validValues)); } private void ValidateAndAddHangProcessDumpParameters(XmlElement collectDumpNode) @@ -366,7 +366,7 @@ private void ValidateAndAddHangProcessDumpParameters(XmlElement collectDumpNode) } else { - _logger.LogWarning(_context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.UnexpectedValueForInactivityTimespanValue, attribute.Value)); + _logger.LogWarning(_context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentCulture, Resources.Resources.UnexpectedValueForInactivityTimespanValue, attribute.Value)); } break; @@ -403,7 +403,7 @@ private void ValidateAndAddHangProcessDumpParameters(XmlElement collectDumpNode) default: - _logger.LogWarning(_context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterKeyIncorrect, blameAttribute.Name)); + _logger.LogWarning(_context.SessionDataCollectionContext, string.Format(CultureInfo.CurrentCulture, Resources.Resources.BlameParameterKeyIncorrect, blameAttribute.Name)); break; } } @@ -561,12 +561,12 @@ private void TestHostLaunchedHandler(object sender, TestHostLaunchedEventArgs ar catch (TestPlatformException e) { EqtTrace.Warning("BlameCollector.TestHostLaunchedHandler: Could not start process dump. {0}", e); - _logger.LogWarning(args.Context, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.ProcDumpCouldNotStart, e.Message)); + _logger.LogWarning(args.Context, string.Format(CultureInfo.CurrentCulture, Resources.Resources.ProcDumpCouldNotStart, e.Message)); } catch (Exception e) { EqtTrace.Warning("BlameCollector.TestHostLaunchedHandler: Could not start process dump. {0}", e); - _logger.LogWarning(args.Context, string.Format(CultureInfo.CurrentUICulture, Resources.Resources.ProcDumpCouldNotStart, e.ToString())); + _logger.LogWarning(args.Context, string.Format(CultureInfo.CurrentCulture, Resources.Resources.ProcDumpCouldNotStart, e.ToString())); } } diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcDumpDumper.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcDumpDumper.cs index 8fd338b744..5c35bd9042 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcDumpDumper.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcDumpDumper.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; @@ -85,7 +86,7 @@ public void AttachToTargetProcess(int processId, string outputDirectory, DumpTyp if (!TryGetProcDumpExecutable(processId, out var procDumpPath)) { - var procdumpNotFound = string.Format(Resources.Resources.ProcDumpNotFound, procDumpPath); + var procdumpNotFound = string.Format(CultureInfo.CurrentCulture, Resources.Resources.ProcDumpNotFound, procDumpPath); logWarning(procdumpNotFound); EqtTrace.Warning($"ProcDumpDumper.AttachToTargetProcess: {procdumpNotFound}"); return; diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcessCodeMethods.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcessCodeMethods.cs index b7956e80d9..54d83c5f1c 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcessCodeMethods.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/ProcessCodeMethods.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; @@ -153,7 +154,7 @@ internal static int GetParentPidLinux(Process process) var stat = File.ReadAllText(path); var parts = stat.Split(' '); - return parts.Length < 5 ? InvalidProcessId : int.Parse(parts[3]); + return parts.Length < 5 ? InvalidProcessId : int.Parse(parts[3], CultureInfo.CurrentCulture); } catch (Exception ex) { diff --git a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/WindowsHangDumper.cs b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/WindowsHangDumper.cs index 881382c367..67097bd268 100644 --- a/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/WindowsHangDumper.cs +++ b/src/Microsoft.TestPlatform.Extensions.BlameDataCollector/WindowsHangDumper.cs @@ -59,7 +59,7 @@ public void Dump(int processId, string outputDirectory, DumpTypeOption type) else { EqtTrace.Verbose($"NetClientHangDumper.Dump: Dumping {process.Id} - {process.ProcessName}."); - var message = string.Format(CultureInfo.CurrentUICulture, Resources.Resources.Dumping, process.Id, process.ProcessName); + var message = string.Format(CultureInfo.CurrentCulture, Resources.Resources.Dumping, process.Id, process.ProcessName); _logWarning(message); } diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestResult.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestResult.cs index f0132c3ad8..9a22b3c87b 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestResult.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestResult.cs @@ -6,7 +6,6 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using Microsoft.TestPlatform.Extensions.TrxLogger.Utility; using Microsoft.TestPlatform.Extensions.TrxLogger.XML; @@ -381,7 +380,7 @@ public string TestResultsDirectory if (_testRun == null) { Debug.Fail("'m_testRun' is null"); - throw new InvalidOperationException(string.Format(CultureInfo.CurrentCulture, TrxLoggerResources.Common_MissingRunInResult)); + throw new InvalidOperationException(TrxLoggerResources.Common_MissingRunInResult); } return _testRun.GetResultFilesDirectory(this); diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestRun.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestRun.cs index b714b2a5b3..228f5f2d1f 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestRun.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/ObjectModel/TestRun.cs @@ -176,13 +176,13 @@ internal string GetResultsDirectory() if (RunConfiguration == null) { Debug.Fail("'RunConfiguration' is null"); - throw new Exception(string.Format(CultureInfo.CurrentCulture, TrxLoggerResources.Common_MissingRunConfigInRun)); + throw new Exception(TrxLoggerResources.Common_MissingRunConfigInRun); } if (string.IsNullOrEmpty(RunConfiguration.RunDeploymentRootDirectory)) { Debug.Fail("'RunConfiguration.RunDeploymentRootDirectory' is null or empty"); - throw new Exception(string.Format(CultureInfo.CurrentCulture, TrxLoggerResources.Common_MissingRunDeploymentRootInRunConfig)); + throw new Exception(TrxLoggerResources.Common_MissingRunDeploymentRootInRunConfig); } return RunConfiguration.RunDeploymentInDirectory; diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs index 8666c2c6be..4087274f8f 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/TrxLogger.cs @@ -140,8 +140,7 @@ public void Initialize(TestLoggerEvents events, Dictionary para if (isLogFilePrefixParameterExists && isLogFileNameParameterExists) { - var trxParameterErrorMsg = string.Format(CultureInfo.CurrentCulture, - TrxLoggerResources.PrefixAndNameProvidedError); + var trxParameterErrorMsg = TrxLoggerResources.PrefixAndNameProvidedError; EqtTrace.Error(trxParameterErrorMsg); throw new ArgumentException(trxParameterErrorMsg); diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs index be7574f9ef..7358535016 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/Converter.cs @@ -69,7 +69,7 @@ public ITestElement ToTestElement( } var workItems = GetCustomPropertyValueFromTestCase(rockSteadyTestCase, "WorkItemIds") - .Select(workItem => int.Parse(workItem)); + .Select(workItem => int.Parse(workItem, CultureInfo.CurrentCulture)); foreach (int workItem in workItems) { testElement.WorkItems.Add(workItem); diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/EqtAssert.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/EqtAssert.cs index ed1eb968ca..d12662bf64 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/EqtAssert.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/EqtAssert.cs @@ -4,7 +4,6 @@ using System; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; -using System.Globalization; using Microsoft.VisualStudio.TestPlatform.Extensions.TrxLogger; @@ -46,7 +45,7 @@ public static void IsTrue(bool expression, string comment) public static void ParameterNotNull([ValidatedNotNull] object? parameter, [ValidatedNotNull] string parameterName) { AssertParameterNameNotNullOrEmpty(parameterName); - TPDebug.Assert(parameter != null, string.Format(CultureInfo.InvariantCulture, "'{0}' is null", parameterName)); + TPDebug.Assert(parameter != null, $"'{nameof(parameterName)}' is null"); if (parameter == null) { throw new ArgumentNullException(parameterName); @@ -61,10 +60,10 @@ public static void ParameterNotNull([ValidatedNotNull] object? parameter, [Valid public static void StringNotNullOrEmpty([ValidatedNotNull] string? parameter, [ValidatedNotNull] string parameterName) { AssertParameterNameNotNullOrEmpty(parameterName); - TPDebug.Assert(!parameter.IsNullOrEmpty(), string.Format(CultureInfo.InvariantCulture, "'{0}' is null or empty", parameterName)); + TPDebug.Assert(!parameter.IsNullOrEmpty(), $"'{nameof(parameterName)}' is null or empty"); if (parameter.IsNullOrEmpty()) { - throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, TrxLoggerResources.Common_CannotBeNullOrEmpty)); + throw new ArgumentException(TrxLoggerResources.Common_CannotBeNullOrEmpty); } } diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/TrxFileHelper.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/TrxFileHelper.cs index 7bf8928a9e..3ab7811f08 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/TrxFileHelper.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/Utility/TrxFileHelper.cs @@ -86,7 +86,7 @@ public string ReplaceInvalidFileNameChars(string fileName) string replaced = result.ToString().TrimEnd(); if (replaced.Length == 0) { - Debug.Fail(string.Format(CultureInfo.InvariantCulture, "After replacing invalid chars in file '{0}' there's nothing left...", fileName)); + Debug.Fail($"After replacing invalid chars in file '{fileName}' there's nothing left..."); throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, TrxLoggerResources.Common_NothingLeftAfterReplaciingBadCharsInName, fileName)); } diff --git a/src/Microsoft.TestPlatform.Extensions.TrxLogger/XML/XmlPersistence.cs b/src/Microsoft.TestPlatform.Extensions.TrxLogger/XML/XmlPersistence.cs index 0b4382463b..b45e196300 100644 --- a/src/Microsoft.TestPlatform.Extensions.TrxLogger/XML/XmlPersistence.cs +++ b/src/Microsoft.TestPlatform.Extensions.TrxLogger/XML/XmlPersistence.cs @@ -689,7 +689,7 @@ private static void SaveSimpleData(object? value, XmlNode nodeToSaveAt, object? private static string ReplaceInvalidCharacterWithUniCodeEscapeSequence(Match match) { char x = match.Value[0]; - return string.Format(@"\u{0:x4}", (ushort)x); + return $@"\u{(ushort)x:x4}"; } private XmlNode? EnsureLocationExists(XmlElement xml, string location, string? nameSpaceUri) diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs index c907d958af..583f2882c8 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/Common/RequestId.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.Runtime.Serialization; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.DataCollection; @@ -132,7 +133,7 @@ public int CompareTo(object? obj) RequestId? other = obj as RequestId; return other == null - ? throw new ArgumentException(string.Format(Resources.Resources.Common_ObjectMustBeOfType, new object[] { typeof(RequestId).Name }), nameof(obj)) + ? throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Common_ObjectMustBeOfType, new object[] { typeof(RequestId).Name }), nameof(obj)) : Id.CompareTo(other.Id); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs index 880622684d..9f691969a4 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/DataCollector/TransferInformation/FileTransferInformation.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.IO; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; @@ -59,7 +60,7 @@ public FileTransferInformation(DataCollectionContext context, string path, bool // Make sure the file exists. if (!_fileHelper.Exists(path)) { - throw new FileNotFoundException(string.Format(Resources.Resources.Common_FileNotExist, new object[] { path }), path); + throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.Common_FileNotExist, new object[] { path }), path); } // Make sure the path we have is a full path (not relative). diff --git a/src/Microsoft.TestPlatform.ObjectModel/Framework.cs b/src/Microsoft.TestPlatform.ObjectModel/Framework.cs index 711511fb70..80a4e7f8f0 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Framework.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Framework.cs @@ -5,6 +5,10 @@ #if !NETSTANDARD1_0 +#if !NETCOREAPP1_0 && !NETSTANDARD1_0 && !NETSTANDARD1_3 && !WINDOWS_UWP +using System.Globalization; +#endif + using NuGet.Frameworks; using static NuGet.Frameworks.FrameworkConstants; @@ -74,7 +78,13 @@ private Framework() { // IDE always sends framework in form of ENUM, which always throws exception // This throws up in first chance exception, refer Bug https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems/edit/591142 - switch (frameworkString.Trim().ToLower()) + var formattedFrameworkString = frameworkString.Trim() + .ToLower( +#if !NETCOREAPP1_0 && !NETSTANDARD1_0 && !NETSTANDARD1_3 && !WINDOWS_UWP + CultureInfo.InvariantCulture +#endif + ); + switch (formattedFrameworkString) { case "framework35": name = CommonFrameworks.Net35.DotNetFrameworkName; diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/FullSymbolReader.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/FullSymbolReader.cs index 1d551bc62e..165d408413 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/FullSymbolReader.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/FullSymbolReader.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Runtime.InteropServices; @@ -138,7 +139,7 @@ private bool OpenSession(string filename, string? searchPath) int hResult = _source.LoadDataForExe(filename, searchPath, IntPtr.Zero); if (HResult.Failed(hResult)) { - throw new COMException(string.Format(Resources.Resources.FailedToCreateDiaSession, hResult)); + throw new COMException(string.Format(CultureInfo.CurrentCulture, Resources.Resources.FailedToCreateDiaSession, hResult)); } // Open the session and return it diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/NativeMethods.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/NativeMethods.cs index 8835fce075..3b59e05659 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/NativeMethods.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/NativeMethods.cs @@ -563,7 +563,7 @@ internal static class DiaSourceObject if (modHandle == IntPtr.Zero) { - throw new COMException(string.Format(Resources.Resources.FailedToLoadMsDia)); + throw new COMException(Resources.Resources.FailedToLoadMsDia); } var diaSourceClassGuid = new Guid("{E6756135-1E65-4D17-8576-610761398C3C}"); diff --git a/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs b/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs index 41b2689916..61fd07983a 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Navigation/PortableSymbolReader.cs @@ -127,11 +127,7 @@ private void PopulateCacheForTypeAndMethodSymbols(string binaryPath) } else { - EqtTrace.Error( - string.Format( - "Unable to find source information for method: {0} type: {1}", - methodInfo.Name, - type.FullName)); + EqtTrace.Error($"Unable to find source information for method: {methodInfo.Name} type: {type.FullName}"); } } diff --git a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/RunConfiguration.cs b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/RunConfiguration.cs index 72c2210597..05d28b5e48 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/RunSettings/RunConfiguration.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/RunSettings/RunConfiguration.cs @@ -459,15 +459,15 @@ public override XmlElement ToXml() } XmlElement maxCpuCount = doc.CreateElement("MaxCpuCount"); - maxCpuCount.InnerXml = MaxCpuCount.ToString(); + maxCpuCount.InnerXml = MaxCpuCount.ToString(CultureInfo.CurrentCulture); root.AppendChild(maxCpuCount); XmlElement batchSize = doc.CreateElement("BatchSize"); - batchSize.InnerXml = BatchSize.ToString(); + batchSize.InnerXml = BatchSize.ToString(CultureInfo.CurrentCulture); root.AppendChild(batchSize); XmlElement testSessionTimeout = doc.CreateElement("TestSessionTimeout"); - testSessionTimeout.InnerXml = TestSessionTimeout.ToString(); + testSessionTimeout.InnerXml = TestSessionTimeout.ToString(CultureInfo.CurrentCulture); root.AppendChild(testSessionTimeout); XmlElement designMode = doc.CreateElement("DesignMode"); diff --git a/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs b/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs index 8f363e4d8a..35838f1b31 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/TestResult.cs @@ -119,7 +119,7 @@ public override string ToString() // Add the outcome of the test and the name of the test. result.AppendFormat( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, Resources.Resources.BasicTestResultFormat, TestCase.DisplayName, TestOutcomeHelper.GetOutcomeString(Outcome)); @@ -129,14 +129,14 @@ public override string ToString() { // Add Error message. result.AppendLine(); - result.AppendFormat(CultureInfo.CurrentUICulture, Resources.Resources.TestFailureMessageFormat, ErrorMessage); + result.AppendFormat(CultureInfo.CurrentCulture, Resources.Resources.TestFailureMessageFormat, ErrorMessage); // Add stack trace if we have one. if (!StringUtils.IsNullOrWhiteSpace(ErrorStackTrace)) { result.AppendLine(); result.AppendFormat( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, Resources.Resources.TestFailureStackTraceFormat, ErrorStackTrace); } @@ -151,7 +151,7 @@ public override string ToString() if (!StringUtils.IsNullOrEmpty(message?.Category) && !StringUtils.IsNullOrEmpty(message.Text)) { testMessages.AppendFormat( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, Resources.Resources.TestResultMessageFormat, message.Category, message.Text); @@ -160,7 +160,7 @@ public override string ToString() result.AppendLine(); result.AppendFormat( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, Resources.Resources.TestResultTextMessagesFormat, testMessages.ToString()); } diff --git a/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlReaderUtilities.cs b/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlReaderUtilities.cs index 69f1866829..833143fe88 100644 --- a/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlReaderUtilities.cs +++ b/src/Microsoft.TestPlatform.ObjectModel/Utilities/XmlReaderUtilities.cs @@ -1,7 +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. -using System.Globalization; using System.Xml; namespace Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; @@ -55,10 +54,7 @@ public static void ReadToRootNode(XmlReader reader) // Verify that it is a "RunSettings" node. if (reader.Name != RunSettingsRootNodeName) { - throw new SettingsException( - string.Format( - CultureInfo.CurrentCulture, - Resources.Resources.InvalidRunSettingsRootNode)); + throw new SettingsException(Resources.Resources.InvalidRunSettingsRootNode); } } diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/common/System/ProcessHelper.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/common/System/ProcessHelper.cs index 79c69169a7..2efe82b7db 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/common/System/ProcessHelper.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/common/System/ProcessHelper.cs @@ -1,11 +1,14 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. -#if NETFRAMEWORK || NETCOREAPP || NETSTANDARD2_0 +#if NETFRAMEWORK || NETCOREAPP || NETSTANDARD2_0 using System; using System.Collections.Generic; using System.Diagnostics; +#if !NETCOREAPP1_0 +using System.Globalization; +#endif using System.IO; using System.Reflection; using System.Threading; @@ -229,10 +232,18 @@ public string GetNativeDllDirectory() { var osArchitecture = new PlatformEnvironment().Architecture; return osArchitecture is PlatformArchitecture.ARM or PlatformArchitecture.ARM64 - ? Path.Combine(GetCurrentProcessLocation(), GetCurrentProcessArchitecture().ToString().ToLower(), Arm) - : Path.Combine(GetCurrentProcessLocation(), GetCurrentProcessArchitecture().ToString().ToLower()); + ? Path.Combine(GetCurrentProcessLocation(), GetFormattedCurrentProcessArchitecture(), Arm) + : Path.Combine(GetCurrentProcessLocation(), GetFormattedCurrentProcessArchitecture()); } + private string GetFormattedCurrentProcessArchitecture() + => GetCurrentProcessArchitecture().ToString() + .ToLower( +#if !NETCOREAPP1_0 + CultureInfo.InvariantCulture +#endif + ); + /// public void WaitForProcessExit(object? process) { diff --git a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/FileEventListener.cs b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/FileEventListener.cs index 4ac201a38c..a2a74cc1cc 100644 --- a/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/FileEventListener.cs +++ b/src/Microsoft.TestPlatform.PlatformAbstractions/uap10.0/Tracing/FileEventListener.cs @@ -7,6 +7,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.Tracing; +using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; @@ -57,7 +58,7 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData) var lines = new List(); - var newFormatedLine = string.Format(_format, DateTime.Now, eventData.Level, eventData.EventId, eventData.Payload[0]); + var newFormatedLine = string.Format(CultureInfo.CurrentCulture, _format, DateTime.Now, eventData.Level, eventData.EventId, eventData.Payload[0]); Debug.WriteLine(newFormatedLine); diff --git a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs index c6a008be58..de807d83f1 100644 --- a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs +++ b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DefaultTestHostManager.cs @@ -429,7 +429,7 @@ private IEnumerable FilterExtensionsBasedOnVersion(IEnumerable e // Log warning if conflicting version extensions are found if (conflictingExtensions.Any()) { - var extensionsString = string.Join("\n", conflictingExtensions.Select(kv => string.Format(" {0} : {1}", kv.Key, kv.Value))); + var extensionsString = string.Join("\n", conflictingExtensions.Select(kv => $" {kv.Key} : {kv.Value}")); string message = string.Format(CultureInfo.CurrentCulture, Resources.MultipleFileVersions, extensionsString); _messageLogger.SendMessage(TestMessageLevel.Warning, message); } diff --git a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs index 128648cef1..d1e3665b2b 100644 --- a/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs +++ b/src/Microsoft.TestPlatform.TestHostProvider/Hosting/DotnetTestHostManager.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -433,7 +434,7 @@ public virtual TestProcessStartInfo GetTestHostProcessStartInfo( PlatformArchitecture finalTargetArchitecture = forceToX64 ? PlatformArchitecture.X64 : targetArchitecture; if (!_dotnetHostHelper.TryGetDotnetPathByArchitecture(finalTargetArchitecture, out string? muxerPath)) { - string message = string.Format(Resources.NoDotnetMuxerFoundForArchitecture, $"dotnet{(_platformEnvironment.OperatingSystem == PlatformOperatingSystem.Windows ? ".exe" : string.Empty)}", finalTargetArchitecture.ToString()); + string message = string.Format(CultureInfo.CurrentCulture, Resources.NoDotnetMuxerFoundForArchitecture, $"dotnet{(_platformEnvironment.OperatingSystem == PlatformOperatingSystem.Windows ? ".exe" : string.Empty)}", finalTargetArchitecture.ToString()); EqtTrace.Error(message); throw new TestPlatformException(message); } diff --git a/src/Microsoft.TestPlatform.Utilities/CommandLineUtilities.cs b/src/Microsoft.TestPlatform.Utilities/CommandLineUtilities.cs index ea96e8069d..b7c7fc0b66 100644 --- a/src/Microsoft.TestPlatform.Utilities/CommandLineUtilities.cs +++ b/src/Microsoft.TestPlatform.Utilities/CommandLineUtilities.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.Text; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -91,7 +90,7 @@ public static bool SplitCommandLineIntoArguments(string args, out string[] argum if (inQuotes) { EqtTrace.Verbose("Executor.Execute: Exiting with exit code of {0}", 1); - EqtTrace.Error(string.Format(CultureInfo.InvariantCulture, "Error: Unbalanced '\"' in command line argument file")); + EqtTrace.Error("Error: Unbalanced '\"' in command line argument file"); hadError = true; } else if (currentArg.Length > 0) diff --git a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleProcessManager.cs b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleProcessManager.cs index 2ffd6b599d..c06f0ed90f 100644 --- a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleProcessManager.cs +++ b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleProcessManager.cs @@ -106,7 +106,7 @@ public void StartProcess(ConsoleParameters consoleParameters) // extra double quotes before testing whether the file exists. if (!File.Exists(consoleRunnerPath.Trim('"'))) { - throw new FileNotFoundException(string.Format(InternalResources.CannotFindConsoleRunner, consoleRunnerPath), consoleRunnerPath); + throw new FileNotFoundException(string.Format(CultureInfo.CurrentCulture, InternalResources.CannotFindConsoleRunner, consoleRunnerPath), consoleRunnerPath); } var arguments = string.Join(" ", BuildArguments(consoleParameters)); @@ -147,7 +147,7 @@ public void StartProcess(ConsoleParameters consoleParameters) } catch (Win32Exception ex) { - throw new Exception(string.Format(InternalResources.ProcessStartWin32Failure, consoleRunnerPath, arguments), ex); + throw new Exception(string.Format(CultureInfo.CurrentCulture, InternalResources.ProcessStartWin32Failure, consoleRunnerPath, arguments), ex); } lock (_syncObject) diff --git a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleWrapper.cs b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleWrapper.cs index 7f9aff9aef..7d02ce54a8 100644 --- a/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleWrapper.cs +++ b/src/Microsoft.TestPlatform.VsTestConsole.TranslationLayer/VsTestConsoleWrapper.cs @@ -1042,7 +1042,7 @@ private bool WaitForConnection() var processName = _processHelper.GetCurrentProcessFileName(); throw new TransationLayerException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage, processName, CoreUtilitiesConstants.VstestConsoleProcessName, diff --git a/src/SettingsMigrator/Migrator.cs b/src/SettingsMigrator/Migrator.cs index 4911b71f00..8a93acd976 100644 --- a/src/SettingsMigrator/Migrator.cs +++ b/src/SettingsMigrator/Migrator.cs @@ -67,7 +67,7 @@ public void Migrate(string oldFilePath, string newFilePath) { if (!Path.IsPathRooted(oldFilePath)) { - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ValidUsage)); + Console.WriteLine(CommandLineResources.ValidUsage); } if (string.Equals(Path.GetExtension(oldFilePath), TestSettingsExtension, StringComparison.OrdinalIgnoreCase)) @@ -80,7 +80,7 @@ public void Migrate(string oldFilePath, string newFilePath) } else { - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ValidUsage)); + Console.WriteLine(CommandLineResources.ValidUsage); } } @@ -124,7 +124,7 @@ private void MigrateRunSettings(string oldRunSettingsPath, string newRunSettings } else { - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.NoEmbeddedSettings)); + Console.WriteLine(CommandLineResources.NoEmbeddedSettings); } } @@ -224,7 +224,7 @@ private TestSettingsNodes ReadTestSettingsNodes(string testSettingsPath) if (testSettingsNodes.Timeout != null && (testSettingsNodes.Timeout.Attributes[AgentNotRespondingTimeoutAttribute] != null || testSettingsNodes.Timeout.Attributes[DeploymentTimeoutAttribute] != null || testSettingsNodes.Timeout.Attributes[ScriptTimeoutAttribute] != null)) { - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.UnsupportedAttributes)); + Console.WriteLine(CommandLineResources.UnsupportedAttributes); } } @@ -289,7 +289,7 @@ private void AddLegacyNodes(TestSettingsNodes testSettingsNodes, string? testTim var legacyNode = newXmlDoc.DocumentElement.SelectSingleNode(@"/RunSettings/LegacySettings"); if (legacyNode != null) { - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.IgnoringLegacySettings)); + Console.WriteLine(CommandLineResources.IgnoringLegacySettings); legacyNode.ParentNode.RemoveChild(legacyNode); } diff --git a/src/SettingsMigrator/PathResolver.cs b/src/SettingsMigrator/PathResolver.cs index 4e627611dd..d89d5d066e 100644 --- a/src/SettingsMigrator/PathResolver.cs +++ b/src/SettingsMigrator/PathResolver.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.IO; namespace Microsoft.VisualStudio.TestPlatform.SettingsMigrator; @@ -29,7 +30,7 @@ public class PathResolver if (args.Length == 1) { var oldFilePath = args[0]; - var newFileName = string.Concat(Path.GetFileNameWithoutExtension(oldFilePath), "_", DateTime.Now.ToString("MM-dd-yyyy_hh-mm-ss"), RunSettingsExtension); + var newFileName = string.Concat(Path.GetFileNameWithoutExtension(oldFilePath), "_", DateTime.Now.ToString("MM-dd-yyyy_hh-mm-ss", CultureInfo.CurrentCulture), RunSettingsExtension); newFilePath = Path.Combine(Path.GetDirectoryName(oldFilePath), newFileName); } else if (args.Length == 2) diff --git a/src/SettingsMigrator/Program.cs b/src/SettingsMigrator/Program.cs index 0a65b64b43..5b84b735bc 100644 --- a/src/SettingsMigrator/Program.cs +++ b/src/SettingsMigrator/Program.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Globalization; using SettingsMigrator; @@ -33,7 +32,7 @@ public static int Main(string[] args) } else { - Console.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.ValidUsage)); + Console.WriteLine(CommandLineResources.ValidUsage); return 1; } diff --git a/src/datacollector/DataCollectorMain.cs b/src/datacollector/DataCollectorMain.cs index a6bfda9156..5653fd4565 100644 --- a/src/datacollector/DataCollectorMain.cs +++ b/src/datacollector/DataCollectorMain.cs @@ -128,7 +128,7 @@ public void Run(string[]? args) }); // Get server port and initialize communication. - int port = argsDictionary.TryGetValue(PortArgument, out var portValue) ? int.Parse(portValue) : 0; + int port = argsDictionary.TryGetValue(PortArgument, out var portValue) ? int.Parse(portValue, CultureInfo.CurrentCulture) : 0; if (port <= 0) { @@ -140,7 +140,7 @@ public void Run(string[]? args) // Can only do this after InitializeCommunication because datacollector cannot "Send Log" unless communications are initialized if (!string.IsNullOrEmpty(EqtTrace.LogFile)) { - (_requestHandler as DataCollectionRequestHandler)?.SendDataCollectionMessage(new DataCollectionMessageEventArgs(TestMessageLevel.Informational, string.Format("Logging DataCollector Diagnostics in file: {0}", EqtTrace.LogFile))); + (_requestHandler as DataCollectionRequestHandler)?.SendDataCollectionMessage(new DataCollectionMessageEventArgs(TestMessageLevel.Informational, $"Logging DataCollector Diagnostics in file: {EqtTrace.LogFile}")); } // Start processing async in a different task @@ -168,7 +168,7 @@ private void StartProcessing() throw new TestPlatformException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage, CoreUtilitiesConstants.DatacollectorProcessName, CoreUtilitiesConstants.VstestConsoleProcessName, diff --git a/src/testhost.x86/DefaultEngineInvoker.cs b/src/testhost.x86/DefaultEngineInvoker.cs index 92d4f6e862..14746cee92 100644 --- a/src/testhost.x86/DefaultEngineInvoker.cs +++ b/src/testhost.x86/DefaultEngineInvoker.cs @@ -194,7 +194,7 @@ private void ConnectToDatacollector(int dcPort) dcPort); throw new TestPlatformException( string.Format( - CultureInfo.CurrentUICulture, + CultureInfo.CurrentCulture, CommunicationUtilitiesResources.ConnectionTimeoutErrorMessage, CoreUtilitiesConstants.TesthostProcessName, CoreUtilitiesConstants.DatacollectorProcessName, diff --git a/src/vstest.console/CommandLine/CommandLineOptions.cs b/src/vstest.console/CommandLine/CommandLineOptions.cs index 6e93b1c115..609c012990 100644 --- a/src/vstest.console/CommandLine/CommandLineOptions.cs +++ b/src/vstest.console/CommandLine/CommandLineOptions.cs @@ -284,7 +284,7 @@ public void AddSource(string source) catch (TestSourceException ex) when (source.StartsWith("-") || source.StartsWith("/")) { throw new TestSourceException( - string.Format(CultureInfo.CurrentUICulture, CommandLineResources.InvalidArgument, source), ex); + string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, source), ex); } // Add the matching files to source list _sources = _sources.Union(matchingFiles).ToList(); diff --git a/src/vstest.console/CommandLine/Executor.cs b/src/vstest.console/CommandLine/Executor.cs index 4a4ed73a19..ffb5ab6891 100644 --- a/src/vstest.console/CommandLine/Executor.cs +++ b/src/vstest.console/CommandLine/Executor.cs @@ -419,7 +419,7 @@ private void PrintSplashScreen(bool isDiag) } string assemblyVersionAndArchitecture = $"{assemblyVersion} ({_processHelper.GetCurrentProcessArchitecture().ToString().ToLowerInvariant()})"; - string commandLineBanner = string.Format(CultureInfo.CurrentUICulture, CommandLineResources.MicrosoftCommandLineTitle, assemblyVersionAndArchitecture); + string commandLineBanner = string.Format(CultureInfo.CurrentCulture, CommandLineResources.MicrosoftCommandLineTitle, assemblyVersionAndArchitecture); Output.WriteLine(commandLineBanner, OutputLevel.Information); Output.WriteLine(CommandLineResources.CopyrightCommandLineTitle, OutputLevel.Information); PrintWarningIfRunningEmulatedOnArm64(); @@ -465,7 +465,7 @@ private int FlattenArguments(IEnumerable arguments, out string[] flatten } else { - Output.WriteLine(string.Format("vstest.console.exe {0}", responseFileArgs), OutputLevel.Information); + Output.WriteLine($"vstest.console.exe {responseFileArgs}", OutputLevel.Information); outputArguments.AddRange(nestedArgs); } } diff --git a/src/vstest.console/Internal/ConsoleLogger.cs b/src/vstest.console/Internal/ConsoleLogger.cs index 58b52de982..93ed032ec6 100644 --- a/src/vstest.console/Internal/ConsoleLogger.cs +++ b/src/vstest.console/Internal/ConsoleLogger.cs @@ -37,6 +37,11 @@ internal class ConsoleLogger : ITestLoggerWithParameters /// private const string TestResultPrefix = " "; + /// + /// Suffix used for formatting the result output + /// + private const string TestResultSuffix = " "; + /// /// Bool to decide whether Verbose level should be added as prefix or not in log messages. /// @@ -301,7 +306,7 @@ private static void DisplayFullInformation(TestResult result) if (!result.ErrorMessage.IsNullOrEmpty()) { addAdditionalNewLine = true; - Output.Information(false, ConsoleColor.Red, string.Format("{0}{1}", TestResultPrefix, CommandLineResources.ErrorMessageBanner)); + Output.Information(false, ConsoleColor.Red, TestResultPrefix + CommandLineResources.ErrorMessageBanner); var errorMessage = string.Format(CultureInfo.CurrentCulture, "{0}{1}{2}", TestResultPrefix, TestMessageFormattingPrefix, result.ErrorMessage); Output.Information(false, ConsoleColor.Red, errorMessage); } @@ -309,7 +314,7 @@ private static void DisplayFullInformation(TestResult result) if (!result.ErrorStackTrace.IsNullOrEmpty()) { addAdditionalNewLine = false; - Output.Information(false, ConsoleColor.Red, string.Format("{0}{1}", TestResultPrefix, CommandLineResources.StacktraceBanner)); + Output.Information(false, ConsoleColor.Red, TestResultPrefix + CommandLineResources.StacktraceBanner); var stackTrace = string.Format(CultureInfo.CurrentCulture, "{0}{1}", TestResultPrefix, result.ErrorStackTrace); Output.Information(false, ConsoleColor.Red, stackTrace); } @@ -322,7 +327,7 @@ private static void DisplayFullInformation(TestResult result) if (!stdOutMessages.IsNullOrEmpty()) { - Output.Information(false, string.Format("{0}{1}", TestResultPrefix, CommandLineResources.StdOutMessagesBanner)); + Output.Information(false, TestResultPrefix + CommandLineResources.StdOutMessagesBanner); Output.Information(false, stdOutMessages); } } @@ -335,7 +340,7 @@ private static void DisplayFullInformation(TestResult result) if (!stdErrMessages.IsNullOrEmpty()) { - Output.Information(false, ConsoleColor.Red, string.Format("{0}{1}", TestResultPrefix, CommandLineResources.StdErrMessagesBanner)); + Output.Information(false, ConsoleColor.Red, TestResultPrefix + CommandLineResources.StdErrMessagesBanner); Output.Information(false, ConsoleColor.Red, stdErrMessages); } } @@ -348,7 +353,7 @@ private static void DisplayFullInformation(TestResult result) if (!dbgTrcMessages.IsNullOrEmpty()) { - Output.Information(false, string.Format("{0}{1}", TestResultPrefix, CommandLineResources.DbgTrcMessagesBanner)); + Output.Information(false, TestResultPrefix + CommandLineResources.DbgTrcMessagesBanner); Output.Information(false, dbgTrcMessages); } } @@ -361,7 +366,7 @@ private static void DisplayFullInformation(TestResult result) if (!addnlInfoMessages.IsNullOrEmpty()) { - Output.Information(false, string.Format("{0}{1}", TestResultPrefix, CommandLineResources.AddnlInfoMessagesBanner)); + Output.Information(false, TestResultPrefix + CommandLineResources.AddnlInfoMessagesBanner); Output.Information(false, addnlInfoMessages); } } @@ -510,7 +515,7 @@ private void TestResultHandler(object sender, TestResultEventArgs e) string? formattedDuration = GetFormattedDurationString(e.Result.Duration); if (!formattedDuration.IsNullOrEmpty()) { - testDisplayName = string.Format("{0} [{1}]", testDisplayName, formattedDuration); + testDisplayName = $"{testDisplayName} [{formattedDuration}]"; } var executionId = GetExecutionId(e.Result); @@ -544,7 +549,7 @@ private void TestResultHandler(object sender, TestResultEventArgs e) // Pause the progress indicator before displaying test result information _progressIndicator?.Pause(); - Output.Write(string.Format("{0}{1} ", TestResultPrefix, CommandLineResources.SkippedTestIndicator), OutputLevel.Information, ConsoleColor.Yellow); + Output.Write(GetFormattedTestIndicator(CommandLineResources.SkippedTestIndicator), OutputLevel.Information, ConsoleColor.Yellow); Output.WriteLine(testDisplayName, OutputLevel.Information); if (VerbosityLevel == Verbosity.Detailed) { @@ -567,7 +572,7 @@ private void TestResultHandler(object sender, TestResultEventArgs e) // Pause the progress indicator before displaying test result information _progressIndicator?.Pause(); - Output.Write(string.Format("{0}{1} ", TestResultPrefix, CommandLineResources.FailedTestIndicator), OutputLevel.Information, ConsoleColor.Red); + Output.Write(GetFormattedTestIndicator(CommandLineResources.FailedTestIndicator), OutputLevel.Information, ConsoleColor.Red); Output.WriteLine(testDisplayName, OutputLevel.Information); DisplayFullInformation(e.Result); @@ -584,7 +589,7 @@ private void TestResultHandler(object sender, TestResultEventArgs e) // Pause the progress indicator before displaying test result information _progressIndicator?.Pause(); - Output.Write(string.Format("{0}{1} ", TestResultPrefix, CommandLineResources.PassedTestIndicator), OutputLevel.Information, ConsoleColor.Green); + Output.Write(GetFormattedTestIndicator(CommandLineResources.PassedTestIndicator), OutputLevel.Information, ConsoleColor.Green); Output.WriteLine(testDisplayName, OutputLevel.Information); if (VerbosityLevel == Verbosity.Detailed) { @@ -608,7 +613,7 @@ private void TestResultHandler(object sender, TestResultEventArgs e) // Pause the progress indicator before displaying test result information _progressIndicator?.Pause(); - Output.Write(string.Format("{0}{1} ", TestResultPrefix, CommandLineResources.SkippedTestIndicator), OutputLevel.Information, ConsoleColor.Yellow); + Output.Write(GetFormattedTestIndicator(CommandLineResources.SkippedTestIndicator), OutputLevel.Information, ConsoleColor.Yellow); Output.WriteLine(testDisplayName, OutputLevel.Information); if (VerbosityLevel == Verbosity.Detailed) { @@ -621,6 +626,9 @@ private void TestResultHandler(object sender, TestResultEventArgs e) break; } } + + // Local functions + static string GetFormattedTestIndicator(string indicator) => TestResultPrefix + indicator + TestResultSuffix; } private string? GetFormattedDurationString(TimeSpan duration) @@ -749,10 +757,10 @@ private void TestRunCompleteHandler(object sender, TestRunCompleteEventArgs e) TestOutcome.Skipped => (CommandLineResources.SkippedTestIndicator + "!").PadRight(LongestResultIndicator), _ => CommandLineResources.None.PadRight(LongestResultIndicator), }; - var failed = sourceSummary.FailedTests.ToString().PadLeft(5); - var passed = sourceSummary.PassedTests.ToString().PadLeft(5); - var skipped = sourceSummary.SkippedTests.ToString().PadLeft(5); - var total = sourceSummary.TotalTests.ToString().PadLeft(5); + var failed = sourceSummary.FailedTests.ToString(CultureInfo.CurrentCulture).PadLeft(5); + var passed = sourceSummary.PassedTests.ToString(CultureInfo.CurrentCulture).PadLeft(5); + var skipped = sourceSummary.SkippedTests.ToString(CultureInfo.CurrentCulture).PadLeft(5); + var total = sourceSummary.TotalTests.ToString(CultureInfo.CurrentCulture).PadLeft(5); var frameworkString = _targetFramework.IsNullOrEmpty() diff --git a/src/vstest.console/Internal/FilePatternParser.cs b/src/vstest.console/Internal/FilePatternParser.cs index 859dc12ea2..918d7a3805 100644 --- a/src/vstest.console/Internal/FilePatternParser.cs +++ b/src/vstest.console/Internal/FilePatternParser.cs @@ -63,7 +63,7 @@ public List GetMatchingFiles(string filePattern) if (!_fileHelper.Exists(filePattern)) { throw new TestSourceException( - string.Format(CultureInfo.CurrentUICulture, CommandLineResources.TestSourceFileNotFound, filePattern)); + string.Format(CultureInfo.CurrentCulture, CommandLineResources.TestSourceFileNotFound, filePattern)); } matchingFiles.Add(filePattern); diff --git a/src/vstest.console/Processors/CLIRunSettingsArgumentProcessor.cs b/src/vstest.console/Processors/CLIRunSettingsArgumentProcessor.cs index fa4596dfce..7573115407 100644 --- a/src/vstest.console/Processors/CLIRunSettingsArgumentProcessor.cs +++ b/src/vstest.console/Processors/CLIRunSettingsArgumentProcessor.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.Contracts; +using System.Globalization; using System.Xml.XPath; using Microsoft.VisualStudio.TestPlatform.Common; @@ -212,7 +213,7 @@ private bool UpdateTestRunParameterNode(IRunSettingsProvider runSettingsProvider return true; } - var exceptionMessage = string.Format(CommandLineResources.InvalidTestRunParameterArgument, node); + var exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidTestRunParameterArgument, node); throw new CommandLineException(exceptionMessage); } diff --git a/src/vstest.console/Processors/CollectArgumentProcessor.cs b/src/vstest.console/Processors/CollectArgumentProcessor.cs index 167b7dd622..4f501c2aab 100644 --- a/src/vstest.console/Processors/CollectArgumentProcessor.cs +++ b/src/vstest.console/Processors/CollectArgumentProcessor.cs @@ -88,7 +88,7 @@ public void Initialize(string? argument) // 1. Disable all other data collectors. Enable only those data collectors that are explicitly specified by user. // 2. Check if Code Coverage Data Collector is specified in runsettings, if not add it and also set enable to true. - string exceptionMessage = string.Format(CultureInfo.CurrentUICulture, CommandLineResources.DataCollectorFriendlyNameInvalid, argument); + string exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.DataCollectorFriendlyNameInvalid, argument); // if argument is null or doesn't contain any element, don't do anything. if (argument.IsNullOrWhiteSpace()) @@ -107,7 +107,7 @@ public void Initialize(string? argument) if (InferRunSettingsHelper.IsTestSettingsEnabled(_runSettingsManager.ActiveRunSettings?.SettingsXml)) { - throw new SettingsException(string.Format(CommandLineResources.CollectWithTestSettingErrorMessage, argument)); + throw new SettingsException(string.Format(CultureInfo.CurrentCulture, CommandLineResources.CollectWithTestSettingErrorMessage, argument)); } AddDataCollectorToRunSettings(collectArgumentList, _runSettingsManager, _fileHelper, exceptionMessage); } @@ -247,7 +247,7 @@ internal static void AddDataCollectorToRunSettings(string[] arguments, IRunSetti { var collectorName = arguments[0]; var additionalConfigurations = arguments.Skip(1).ToArray(); - EnabledDataCollectors.Add(collectorName.ToLower()); + EnabledDataCollectors.Add(collectorName.ToLower(CultureInfo.CurrentCulture)); var settings = runSettingsManager.ActiveRunSettings?.SettingsXml; if (settings == null) @@ -283,7 +283,7 @@ internal static void AddDataCollectorToRunSettings(string[] arguments, IRunSetti internal static void AddDataCollectorFriendlyName(string friendlyName) { - EnabledDataCollectors.Add(friendlyName.ToLower()); + EnabledDataCollectors.Add(friendlyName.ToLower(CultureInfo.CurrentCulture)); } internal static class CoverletConstants diff --git a/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs b/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs index c474d0f4bd..4795320a5d 100644 --- a/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnableBlameArgumentProcessor.cs @@ -120,10 +120,10 @@ public void Initialize(string? argument) { var enableDump = false; var enableHangDump = false; - var exceptionMessage = string.Format(CultureInfo.CurrentUICulture, CommandLineResources.InvalidBlameArgument, argument); + var exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidBlameArgument, argument); Dictionary? collectDumpParameters = null; - if (!StringUtils.IsNullOrWhiteSpace(argument)) + if (!argument.IsNullOrWhiteSpace()) { // Get blame argument list. var blameArgumentList = ArgumentProcessorUtilities.GetArgumentList(argument, ArgumentProcessorUtilities.SemiColonArgumentSeparator, exceptionMessage); @@ -142,7 +142,7 @@ public void Initialize(string? argument) if (!enableDump && !enableHangDump) { - Output.Warning(false, string.Format(CultureInfo.CurrentUICulture, CommandLineResources.BlameIncorrectOption, argument)); + Output.Warning(false, string.Format(CultureInfo.CurrentCulture, CommandLineResources.BlameIncorrectOption, argument)); } else { @@ -228,7 +228,7 @@ private void InitializeBlame(bool enableCrashDump, bool enableHangDump, Dictiona if (!hangDumpParameters.ContainsKey("TestTimeout")) { - hangDumpParameters.Add("TestTimeout", TimeSpan.FromHours(1).TotalMilliseconds.ToString()); + hangDumpParameters.Add("TestTimeout", TimeSpan.FromHours(1).TotalMilliseconds.ToString(CultureInfo.CurrentCulture)); } if (!hangDumpParameters.ContainsKey("HangDumpType")) diff --git a/src/vstest.console/Processors/EnableDiagArgumentProcessor.cs b/src/vstest.console/Processors/EnableDiagArgumentProcessor.cs index 8e3789db11..41406c05ea 100644 --- a/src/vstest.console/Processors/EnableDiagArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnableDiagArgumentProcessor.cs @@ -112,7 +112,7 @@ public EnableDiagArgumentExecutor(IFileHelper fileHelper, IProcessHelper process /// Argument that was provided with the command. public void Initialize(string? argument) { - string exceptionMessage = string.Format(CultureInfo.CurrentUICulture, CommandLineResources.InvalidDiagArgument, argument); + string exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidDiagArgument, argument); // Throw error if argument is null or empty. if (argument.IsNullOrWhiteSpace()) diff --git a/src/vstest.console/Processors/EnableLoggerArgumentProcessor.cs b/src/vstest.console/Processors/EnableLoggerArgumentProcessor.cs index 89a8ed9b9f..6cdc279818 100644 --- a/src/vstest.console/Processors/EnableLoggerArgumentProcessor.cs +++ b/src/vstest.console/Processors/EnableLoggerArgumentProcessor.cs @@ -108,7 +108,7 @@ public EnableLoggerArgumentExecutor(IRunSettingsProvider runSettingsManager) /// Argument that was provided with the command. public void Initialize(string? argument) { - string exceptionMessage = string.Format(CultureInfo.CurrentUICulture, CommandLineResources.LoggerUriInvalid, argument); + string exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.LoggerUriInvalid, argument); // Throw error in case logger argument null or empty. if (argument.IsNullOrWhiteSpace()) diff --git a/src/vstest.console/Processors/HelpArgumentProcessor.cs b/src/vstest.console/Processors/HelpArgumentProcessor.cs index bead5068cf..9ea6b1c95e 100644 --- a/src/vstest.console/Processors/HelpArgumentProcessor.cs +++ b/src/vstest.console/Processors/HelpArgumentProcessor.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using Microsoft.VisualStudio.TestPlatform.Utilities; @@ -140,9 +139,7 @@ public ArgumentProcessorResult Execute() { try { - result = string.Format( - CultureInfo.CurrentUICulture, - argumentProcessor.Metadata.Value.HelpContentResourceName); + result = argumentProcessor.Metadata.Value.HelpContentResourceName; //ResourceHelper.GetString(argumentProcessor.Metadata.HelpContentResourceName, assembly, CultureInfo.CurrentUICulture); } catch (Exception e) diff --git a/src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs b/src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs index f37bd8f36f..9b925023a2 100644 --- a/src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/ListFullyQualifiedTestsArgumentProcessor.cs @@ -3,7 +3,6 @@ using System; using System.Collections.Generic; -using System.Globalization; using System.IO; using System.Linq; @@ -169,7 +168,7 @@ public ArgumentProcessorResult Execute() if (!_commandLineOptions.Sources.Any()) { - throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.MissingTestSourceFile)); + throw new CommandLineException(CommandLineResources.MissingTestSourceFile); } if (!EqtTrace.LogFile.IsNullOrEmpty()) @@ -294,7 +293,7 @@ private static void ValidateFilter(string? filterString) if (filterWrapper.ParseError != null) { - var fe = new FormatException(string.Format("Invalid Test Case Filter: {0}", filterString)); + var fe = new FormatException($"Invalid Test Case Filter: {filterString}"); EqtTrace.Error("TestCaseFilter.ValidateFilter : Filtering failed with exception : " + fe.Message); throw fe; } diff --git a/src/vstest.console/Processors/ListTestsArgumentProcessor.cs b/src/vstest.console/Processors/ListTestsArgumentProcessor.cs index bce24c3e08..794df8928a 100644 --- a/src/vstest.console/Processors/ListTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/ListTestsArgumentProcessor.cs @@ -166,7 +166,7 @@ public ArgumentProcessorResult Execute() if (!_commandLineOptions.Sources.Any()) { - throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.MissingTestSourceFile)); + throw new CommandLineException(CommandLineResources.MissingTestSourceFile); } Output.WriteLine(CommandLineResources.ListTestsHeaderMessage, OutputLevel.Information); @@ -215,9 +215,8 @@ private void DiscoveryRequest_OnDiscoveredTests(object sender, DiscoveredTestsEv // List out each of the tests. foreach (var test in args.DiscoveredTestCases!) { - _output.WriteLine(string.Format(CultureInfo.CurrentUICulture, - CommandLineResources.AvailableTestsFormat, - test.DisplayName), + _output.WriteLine( + string.Format(CultureInfo.CurrentCulture, CommandLineResources.AvailableTestsFormat, test.DisplayName), OutputLevel.Information); } } diff --git a/src/vstest.console/Processors/ListTestsTargetPathArgumentProcessor.cs b/src/vstest.console/Processors/ListTestsTargetPathArgumentProcessor.cs index 0fbf4b08b1..8c2fd26991 100644 --- a/src/vstest.console/Processors/ListTestsTargetPathArgumentProcessor.cs +++ b/src/vstest.console/Processors/ListTestsTargetPathArgumentProcessor.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Globalization; using Microsoft.VisualStudio.TestPlatform.ObjectModel; @@ -79,7 +78,7 @@ public void Initialize(string? argument) if (argument.IsNullOrWhiteSpace()) { // Not adding this string to resources because this processor is only used internally. - throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, "ListTestsTargetPath is required with ListFullyQualifiedTests!")); + throw new CommandLineException("ListTestsTargetPath is required with ListFullyQualifiedTests!"); } _commandLineOptions.ListTestsTargetPath = argument; diff --git a/src/vstest.console/Processors/PortArgumentProcessor.cs b/src/vstest.console/Processors/PortArgumentProcessor.cs index 3b8114afdf..ccbfce8708 100644 --- a/src/vstest.console/Processors/PortArgumentProcessor.cs +++ b/src/vstest.console/Processors/PortArgumentProcessor.cs @@ -156,7 +156,7 @@ public ArgumentProcessorResult Execute() } catch (TimeoutException ex) { - throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, string.Format(CommandLineResources.DesignModeClientTimeoutError, _commandLineOptions.Port)), ex); + throw new CommandLineException(string.Format(CultureInfo.CurrentCulture, CommandLineResources.DesignModeClientTimeoutError, _commandLineOptions.Port), ex); } return ArgumentProcessorResult.Success; diff --git a/src/vstest.console/Processors/ResultsDirectoryArgumentProcessor.cs b/src/vstest.console/Processors/ResultsDirectoryArgumentProcessor.cs index 89e8bfd6bf..3855941ce0 100644 --- a/src/vstest.console/Processors/ResultsDirectoryArgumentProcessor.cs +++ b/src/vstest.console/Processors/ResultsDirectoryArgumentProcessor.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.IO; using System.Security; @@ -117,7 +118,7 @@ public void Initialize(string? argument) } catch (Exception ex) when (ex is NotSupportedException or SecurityException or ArgumentException or PathTooLongException or IOException) { - throw new CommandLineException(string.Format(CommandLineResources.InvalidResultsDirectoryPathCommand, argument, ex.Message)); + throw new CommandLineException(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidResultsDirectoryPathCommand, argument, ex.Message)); } _commandLineOptions.ResultsDirectory = argument; diff --git a/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs b/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs index 5291bc7dff..be2fffb2cf 100644 --- a/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/RunSpecificTestsArgumentProcessor.cs @@ -185,7 +185,7 @@ public ArgumentProcessorResult Execute() if (!_commandLineOptions.Sources.Any()) { - throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.MissingTestSourceFile)); + throw new CommandLineException(CommandLineResources.MissingTestSourceFile); } _effectiveRunSettings = _runSettingsManager.ActiveRunSettings.SettingsXml; @@ -251,7 +251,7 @@ private void ExecuteSelectedTests() else { // No tests were discovered from the given sources. - warningMessage = string.Format(CultureInfo.CurrentUICulture, CommandLineResources.NoTestsAvailableInSources, string.Join(", ", _commandLineOptions.Sources)); + warningMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.NoTestsAvailableInSources, string.Join(", ", _commandLineOptions.Sources)); if (!_commandLineOptions.TestAdapterPathsSet) { diff --git a/src/vstest.console/Processors/RunTestsArgumentProcessor.cs b/src/vstest.console/Processors/RunTestsArgumentProcessor.cs index 555c6e98de..b09ee265bb 100644 --- a/src/vstest.console/Processors/RunTestsArgumentProcessor.cs +++ b/src/vstest.console/Processors/RunTestsArgumentProcessor.cs @@ -2,7 +2,6 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; -using System.Globalization; using System.Linq; using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper; @@ -139,7 +138,7 @@ public ArgumentProcessorResult Execute() var anySource = _commandLineOptions.Sources.FirstOrDefault(); if (anySource == null) { - throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.MissingTestSourceFile)); + throw new CommandLineException(CommandLineResources.MissingTestSourceFile); } Output.WriteLine(CommandLineResources.StartingExecution, OutputLevel.Information); diff --git a/src/vstest.console/Processors/TestCaseFilterArgumentProcessor.cs b/src/vstest.console/Processors/TestCaseFilterArgumentProcessor.cs index b8dd669543..1969e06d4e 100644 --- a/src/vstest.console/Processors/TestCaseFilterArgumentProcessor.cs +++ b/src/vstest.console/Processors/TestCaseFilterArgumentProcessor.cs @@ -92,7 +92,7 @@ public void Initialize(string? argument) if (!hasDefaultFilter && argument.IsNullOrWhiteSpace()) { - throw new CommandLineException(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.TestCaseFilterValueRequired)); + throw new CommandLineException(string.Format(CultureInfo.CurrentCulture, CommandLineResources.TestCaseFilterValueRequired)); } if (!hasDefaultFilter) diff --git a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs index e62d4f2681..e66f1f6bc5 100644 --- a/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs +++ b/src/vstest.console/TestPlatformHelpers/TestRequestManager.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -301,6 +302,7 @@ public void RunTests( { throw new SettingsException( string.Format( + CultureInfo.CurrentCulture, Resources.Resources.RunsettingsWithDCErrorMessage, runsettings)); } @@ -488,6 +490,7 @@ public void StartTestSession( { throw new SettingsException( string.Format( + CultureInfo.CurrentCulture, Resources.Resources.RunsettingsWithDCErrorMessage, payload.RunSettings)); } @@ -591,10 +594,7 @@ private static void LogTelemetryForLegacySettings(IRequestData requestData, stri { // We are collecting telemetry for the legacy nodes and attributes used in the runsettings. requestData.MetricsCollection.Add( - string.Format( - "{0}.{1}", - TelemetryDataConstants.LegacySettingPrefix, - ciData.Key), + $"{TelemetryDataConstants.LegacySettingPrefix}.{ciData.Key}", ciData.Value); } } diff --git a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs index 2328fd2e84..4afa9a62c4 100644 --- a/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs +++ b/test/DataCollectors/Microsoft.TestPlatform.Extensions.EventLogCollector.UnitTests/EventLogDataCollectorTests.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; +using System.Globalization; using System.Linq; using System.Xml; @@ -367,11 +368,11 @@ public void WriteEventLogsShouldFilterTestsBasedOnTimeAndMaxValue() x => x.WriteAllTextToFile( It.IsAny(), It.Is( - str => str.Contains(filteredEntries[0].InstanceId.ToString()) - && str.Contains(filteredEntries[1].InstanceId.ToString()) - && str.Contains(filteredEntries[2].InstanceId.ToString()) - && str.Contains(filteredEntries[3].InstanceId.ToString()) - && str.Contains(filteredEntries[4].InstanceId.ToString())))); + str => str.Contains(filteredEntries[0].InstanceId.ToString(CultureInfo.CurrentCulture)) + && str.Contains(filteredEntries[1].InstanceId.ToString(CultureInfo.CurrentCulture)) + && str.Contains(filteredEntries[2].InstanceId.ToString(CultureInfo.CurrentCulture)) + && str.Contains(filteredEntries[3].InstanceId.ToString(CultureInfo.CurrentCulture)) + && str.Contains(filteredEntries[4].InstanceId.ToString(CultureInfo.CurrentCulture))))); } [TestMethod] @@ -410,11 +411,11 @@ public void WriteEventLogsShouldFilterTestIfMaxValueExceedsEntries() x => x.WriteAllTextToFile( It.IsAny(), It.Is( - str => str.Contains(filteredEntries[0].InstanceId.ToString()) - && str.Contains(filteredEntries[1].InstanceId.ToString()) - && str.Contains(filteredEntries[2].InstanceId.ToString()) - && str.Contains(filteredEntries[3].InstanceId.ToString()) - && str.Contains(filteredEntries[4].InstanceId.ToString())))); + str => str.Contains(filteredEntries[0].InstanceId.ToString(CultureInfo.CurrentCulture)) + && str.Contains(filteredEntries[1].InstanceId.ToString(CultureInfo.CurrentCulture)) + && str.Contains(filteredEntries[2].InstanceId.ToString(CultureInfo.CurrentCulture)) + && str.Contains(filteredEntries[3].InstanceId.ToString(CultureInfo.CurrentCulture)) + && str.Contains(filteredEntries[4].InstanceId.ToString(CultureInfo.CurrentCulture))))); } } diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/AppDomainTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/AppDomainTests.cs index 0a19709466..140ad1431c 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/AppDomainTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/AppDomainTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; #if !NETFRAMEWORK using System.Runtime.Loader; @@ -93,7 +94,7 @@ private string GetInProcDataCollectionRunsettingsFile(bool disableAppDomain, Tem "; - fileContents = string.Format(fileContents, assemblyName, inprocasm); + fileContents = string.Format(CultureInfo.CurrentCulture, fileContents, assemblyName, inprocasm); File.WriteAllText(runSettings, fileContents); return runSettings; diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/BlameDataCollectorTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/BlameDataCollectorTests.cs index b57824a342..06d07bf62f 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/BlameDataCollectorTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/BlameDataCollectorTests.cs @@ -3,6 +3,9 @@ using System; using System.Collections.Generic; +#if NET +using System.Globalization; +#endif using System.IO; using System.Linq; using System.Text; @@ -310,13 +313,21 @@ private void ValidateDump(int expectedDumpCount = 1) err.AppendLine("Expected all dumps in the list of attachments to exist, and not be empty, but:"); if (nonExistingDumps.Any()) { - err.AppendLine($"{nonExistingDumps.Count} don't exist:") + err.AppendLine( +#if NET + CultureInfo.InvariantCulture, +#endif + $"{nonExistingDumps.Count} don't exist:") .AppendLine(string.Join(Environment.NewLine, nonExistingDumps)); } if (emptyDumps.Any()) { - err.AppendLine($"{emptyDumps.Count} are empty:") + err.AppendLine( +#if NET + CultureInfo.InvariantCulture, +#endif + $"{emptyDumps.Count} are empty:") .AppendLine(string.Join(Environment.NewLine, emptyDumps)); } diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageAcceptanceTestBase.cs b/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageAcceptanceTestBase.cs index 3b2b5368c3..21f578cb77 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageAcceptanceTestBase.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageAcceptanceTestBase.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Xml; @@ -54,7 +55,7 @@ protected static string GetCodeCoverageExePath() protected static XmlNode? GetNode(XmlNode node, string type, string name) { - return node.SelectSingleNode($"//{type}[@name='{name}']") ?? node.SelectSingleNode($"//{type}[@name='{name.ToLower()}']"); + return node.SelectSingleNode($"//{type}[@name='{name}']") ?? node.SelectSingleNode($"//{type}[@name='{name.ToLower(CultureInfo.CurrentCulture)}']"); } protected static XmlDocument GetXmlCoverage(string coverageResult, TempDirectory tempDirectory) @@ -97,8 +98,8 @@ protected static XmlDocument GetXmlCoverage(string coverageResult, TempDirectory protected static void AssertCoverage(XmlNode node, double expectedCoverage) { var coverage = node.Attributes!["block_coverage"] != null - ? double.Parse(node.Attributes!["block_coverage"]!.Value) - : double.Parse(node.Attributes!["line-rate"]!.Value) * 100; + ? double.Parse(node.Attributes!["block_coverage"]!.Value, CultureInfo.InvariantCulture) + : double.Parse(node.Attributes!["line-rate"]!.Value, CultureInfo.InvariantCulture) * 100; Console.WriteLine($"Checking coverage for {node.Name} {node.Attributes!["name"]!.Value}. Expected at least: {expectedCoverage}. Result: {coverage}"); Assert.IsTrue(coverage > expectedCoverage, $"Coverage check failed for {node.Name} {node.Attributes!["name"]!.Value}. Expected at least: {expectedCoverage}. Found: {coverage}"); } diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageTests.cs index 2c15ead6ae..2cebe7e374 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/CodeCoverageTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.IO; using System.Xml; @@ -306,7 +307,7 @@ private static void AssertSkippedMethod(XmlDocument document) var module = GetModuleNode(document.DocumentElement!, "codecoveragetest.dll"); Assert.IsNotNull(module); - var coverage = double.Parse(module.Attributes!["block_coverage"]!.Value); + var coverage = double.Parse(module.Attributes!["block_coverage"]!.Value, CultureInfo.InvariantCulture); Assert.IsTrue(coverage > ExpectedMinimalModuleCoverage); var testSignFunction = GetNode(module, "skipped_function", "TestSign()"); @@ -323,7 +324,7 @@ private static void AssertSkippedMethod(XmlDocument document) private static void ValidateCoverageData(XmlDocument document, string moduleName, bool validateSourceFileNames) { - var module = GetModuleNode(document.DocumentElement!, moduleName.ToLower()); + var module = GetModuleNode(document.DocumentElement!, moduleName.ToLowerInvariant()); if (module == null) { diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/DifferentTestFrameworkSimpleTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/DifferentTestFrameworkSimpleTests.cs index 2a543b508b..3c374ee9e5 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/DifferentTestFrameworkSimpleTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/DifferentTestFrameworkSimpleTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.IO; using Microsoft.TestPlatform.TestUtilities; @@ -192,8 +193,8 @@ private void CppRunAllTests(string platform) { string assemblyRelativePathFormat = @"microsoft.testplatform.testasset.nativecpp\2.0.0\contentFiles\any\any\{0}\Microsoft.TestPlatform.TestAsset.NativeCPP.dll"; var assemblyRelativePath = platform.Equals("x64", StringComparison.OrdinalIgnoreCase) - ? string.Format(assemblyRelativePathFormat, platform) - : string.Format(assemblyRelativePathFormat, ""); + ? string.Format(CultureInfo.CurrentCulture, assemblyRelativePathFormat, platform) + : string.Format(CultureInfo.CurrentCulture, assemblyRelativePathFormat, ""); var assemblyAbsolutePath = Path.Combine(_testEnvironment.PackageDirectory, assemblyRelativePath); var arguments = PrepareArguments(assemblyAbsolutePath, string.Empty, string.Empty, FrameworkArgValue, _testEnvironment.InIsolationValue, resultsDirectory: TempDirectory.Path); diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/DisableAppdomainTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/DisableAppdomainTests.cs index aa66c29ee4..430fcdf16b 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/DisableAppdomainTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/DisableAppdomainTests.cs @@ -24,7 +24,7 @@ public void DisableAppdomainTest(RunnerInfo runnerInfo) var diableAppdomainTest1 = _testEnvironment.GetTestAsset("DisableAppdomainTest1.dll", "net451"); var diableAppdomainTest2 = _testEnvironment.GetTestAsset("DisableAppdomainTest2.dll", "net451"); - RunTests(runnerInfo, string.Format("{0}\" \"{1}", diableAppdomainTest1, diableAppdomainTest2), 2); + RunTests(runnerInfo, $"{diableAppdomainTest1}\" \"{diableAppdomainTest2}", 2); } [TestMethod] @@ -64,7 +64,7 @@ private void RunTests(RunnerInfo runnerInfo, string testAssembly, int passedTest private static string GetRunsettingsFilePath(TempDirectory tempDirectory, Dictionary runConfigurationDictionary) { - var runsettingsPath = Path.Combine(tempDirectory.Path, "test_" + Guid.NewGuid() + ".runsettings"); + var runsettingsPath = Path.Combine(tempDirectory.Path, $"test_{Guid.NewGuid()}.runsettings"); CreateRunSettingsFile(runsettingsPath, runConfigurationDictionary); return runsettingsPath; } diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.Windows.cs b/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.Windows.cs index d6a446b5d4..f3a6b07a6e 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.Windows.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/DotnetArchitectureSwitchTests.Windows.cs @@ -4,6 +4,7 @@ #if !NETFRAMEWORK using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; @@ -62,7 +63,7 @@ public void TestMethod1() } }"); - ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out string stdOut, out _, out int exitCode, environmentVariables, TempDirectory.Path); + ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower(CultureInfo.InvariantCulture)} --diag:log.txt", out string stdOut, out _, out int exitCode, environmentVariables, TempDirectory.Path); Assert.AreEqual(0, exitCode, stdOut); environmentVariables = new Dictionary @@ -71,7 +72,7 @@ public void TestMethod1() ["DOTNET_ROOT"] = Path.GetDirectoryName(dotnetPathTo), ["ExpectedArchitecture"] = architectureTo }; - ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out stdOut, out _, out exitCode, environmentVariables, TempDirectory.Path); + ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower(CultureInfo.InvariantCulture)} --diag:log.txt", out stdOut, out _, out exitCode, environmentVariables, TempDirectory.Path); Assert.AreEqual(0, exitCode, stdOut); environmentVariables = new Dictionary @@ -81,7 +82,7 @@ public void TestMethod1() ["DOTNET_ROOT"] = "WE SHOULD PICK THE ABOVE ONE BEFORE FALLBACK TO DOTNET_ROOT", ["ExpectedArchitecture"] = architectureTo }; - ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower()} --diag:log.txt", out stdOut, out _, out exitCode, environmentVariables, TempDirectory.Path); + ExecuteApplication(dotnetPath, $"test -p:VsTestConsolePath=\"{Path.Combine(dotnetRunnerPath.FullName, Path.GetFileName(vstestConsolePath))}\" --arch {architectureTo.ToLower(CultureInfo.InvariantCulture)} --diag:log.txt", out stdOut, out _, out exitCode, environmentVariables, TempDirectory.Path); Assert.AreEqual(0, exitCode, stdOut); } diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/EventLogCollectorTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/EventLogCollectorTests.cs index 60fcaebcf2..cc0979cd53 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/EventLogCollectorTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/EventLogCollectorTests.cs @@ -108,11 +108,11 @@ private void VaildateDataCollectorOutput(TempDirectory tempDirectory) }; // Since there is no guaranty that test will run in a particular order, we will check file for all available list of ids - Assert.IsTrue(VerifyOrder2(fileContent1, eventIdsDics), string.Format("Event log file content: {0}", fileContent1)); - Assert.IsTrue(VerifyOrder2(fileContent2, eventIdsDics), string.Format("Event log file content: {0}", fileContent2)); - Assert.IsTrue(VerifyOrder2(fileContent3, eventIdsDics), string.Format("Event log file content: {0}", fileContent3)); + Assert.IsTrue(VerifyOrder2(fileContent1, eventIdsDics), $"Event log file content: {fileContent1}"); + Assert.IsTrue(VerifyOrder2(fileContent2, eventIdsDics), $"Event log file content: {fileContent2}"); + Assert.IsTrue(VerifyOrder2(fileContent3, eventIdsDics), $"Event log file content: {fileContent3}"); - Assert.IsTrue(VerifyOrder(fileContent4, new[] { "110", "111", "112", "220", "221", "222", "223", "330", "331", "332" }), string.Format("Event log file content: {0}", fileContent4)); + Assert.IsTrue(VerifyOrder(fileContent4, new[] { "110", "111", "112", "220", "221", "222", "223", "330", "331", "332" }), $"Event log file content: {fileContent4}"); } private static bool VerifyOrder2(string content, Dictionary eventIdsDics) diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/PostProcessingTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/PostProcessingTests.cs index 59101ce9ea..6099139024 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/PostProcessingTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/PostProcessingTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Threading.Tasks; @@ -47,7 +48,7 @@ public void DotnetSDKSimulation_PostProcessing() // Build and run tests like msbuild Parallel.For(0, 5, i => { - string projectFolder = Path.Combine(TempDirectory.Path, i.ToString()); + string projectFolder = Path.Combine(TempDirectory.Path, i.ToString(CultureInfo.InvariantCulture)); ExecuteApplication(GetConsoleRunnerPath(), $"new mstest -o {projectFolder}", out string stdOut, out string stdError, out int exitCode); Assert.AreEqual(exitCode, 0); ExecuteApplication(GetConsoleRunnerPath(), $"build {projectFolder} -c release", out stdOut, out stdError, out exitCode); diff --git a/test/Microsoft.TestPlatform.AcceptanceTests/RunsettingsTests.cs b/test/Microsoft.TestPlatform.AcceptanceTests/RunsettingsTests.cs index cd90ac8cce..412a9f016e 100644 --- a/test/Microsoft.TestPlatform.AcceptanceTests/RunsettingsTests.cs +++ b/test/Microsoft.TestPlatform.AcceptanceTests/RunsettingsTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using Microsoft.TestPlatform.TestUtilities; @@ -341,7 +342,7 @@ public void LegacySettingsWithScripts(RunnerInfo runnerInfo) "; // Scripts have relative paths to temp directory where the runsettings is created. - var runsettingsXml = string.Format(runsettingsFormat, setupScriptName, cleanupScriptName); + var runsettingsXml = string.Format(CultureInfo.CurrentCulture, runsettingsFormat, setupScriptName, cleanupScriptName); var runsettingsPath = GetRunsettingsFilePath(null, TempDirectory); File.WriteAllText(runsettingsPath, runsettingsXml); @@ -382,7 +383,7 @@ public void LegacySettingsWithDeploymentItem(RunnerInfo runnerInfo) "; - var runsettingsXml = string.Format(runsettingsFormat, deploymentItem); + var runsettingsXml = string.Format(CultureInfo.CurrentCulture, runsettingsFormat, deploymentItem); var runsettingsPath = GetRunsettingsFilePath(null, TempDirectory); File.WriteAllText(runsettingsPath, runsettingsXml); @@ -449,7 +450,7 @@ public void LegacySettingsAssemblyResolution(RunnerInfo runnerInfo) "; var testAssemblyDirectory = Path.Combine(_testEnvironment.TestAssetsPath, "LegacySettingsUnitTestProject", "DependencyAssembly"); - var runsettingsXml = string.Format(runsettingsFormat, testAssemblyDirectory); + var runsettingsXml = string.Format(CultureInfo.CurrentCulture, runsettingsFormat, testAssemblyDirectory); var runsettingsPath = GetRunsettingsFilePath(null, TempDirectory); File.WriteAllText(runsettingsPath, runsettingsXml); var arguments = PrepareArguments(testAssemblyPath, string.Empty, runsettingsPath, FrameworkArgValue, runnerInfo.InIsolationValue, resultsDirectory: TempDirectory.Path); diff --git a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/SHA1ImplTests.cs b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/SHA1ImplTests.cs index 58daa5f3fd..7e74543651 100644 --- a/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/SHA1ImplTests.cs +++ b/test/Microsoft.TestPlatform.AdapterUtilities.UnitTests/TestIdProvider/SHA1ImplTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.Linq; using System.Text; @@ -166,5 +167,5 @@ private static void SHA1_TestRepetitionVector(char input, int repetition, string Assert.AreEqual(expected, digest2, $"Test vector '{input}'*{repetition} failed! (padding path)"); } - private static string ToHex(byte[] digest) => string.Concat(digest.Select(i => i.ToString("x2"))); + private static string ToHex(byte[] digest) => string.Concat(digest.Select(i => i.ToString("x2", CultureInfo.CurrentCulture))); } diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs index 75e7afbefb..ee056f0d9d 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/DataCollectionRequestHandlerTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Net; @@ -290,7 +291,7 @@ public void ProcessRequestsShouldSetDefaultTimeoutIfNoEnvVarialbeSet() public void ProcessRequestsShouldSetTimeoutBasedOnEnvVariable() { var timeout = 10; - Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, timeout.ToString()); + Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, timeout.ToString(CultureInfo.InvariantCulture)); var beforeTestRunSTartPayload = new BeforeTestRunStartPayload { SettingsXml = "settingsxml", Sources = new List { "test1.dll" } }; _mockDataSerializer.Setup(x => x.DeserializePayload(It.Is(y => y.MessageType == MessageType.BeforeTestRunStart))) .Returns(beforeTestRunSTartPayload); diff --git a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs index 45e2a7b475..892b49ed8c 100644 --- a/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs +++ b/test/Microsoft.TestPlatform.CommunicationUtilities.UnitTests/TestRequestSenderTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Net; using System.Net.Sockets; @@ -796,7 +797,7 @@ private string SetupFakeCommunicationChannel(string connectionArgs = "123") .Returns(_connectionInfo.Endpoint) .Callback(() => _mockServer.Raise(s => s.Connected += null, _mockServer.Object, _connectedEventArgs)); - return _testRequestSender.InitializeCommunication().ToString(); + return _testRequestSender.InitializeCommunication().ToString(CultureInfo.CurrentCulture); } private void SetupFakeChannelWithVersionNegotiation() diff --git a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/EnvironmentHelperTests.cs b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/EnvironmentHelperTests.cs index c45d45f38f..b5fe8e8b27 100644 --- a/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/EnvironmentHelperTests.cs +++ b/test/Microsoft.TestPlatform.CoreUtilities.UnitTests/Helpers/EnvironmentHelperTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers; @@ -29,7 +30,7 @@ public void GetConnectionTimeoutShouldReturnDefaultValue() public void GetConnectionTimeoutShouldReturnEnvVariableValueIfSet() { var val = 100; - Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, val.ToString()); + Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, val.ToString(CultureInfo.CurrentCulture)); Assert.AreEqual(val, EnvironmentHelper.GetConnectionTimeout()); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs index caeab456e1..eeef74233d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/AttachmentsProcessing/DataCollectorAttachmentProcessorAppDomainTests.cs @@ -6,6 +6,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using System.Linq; using System.Threading; using System.Threading.Tasks; @@ -225,7 +226,7 @@ public async Task> ProcessAttachmentSetsAsync(XmlElem { progressReporter.Report(100); - DateTime expire = DateTime.UtcNow + TimeSpan.FromMilliseconds(int.Parse(timeout)); + DateTime expire = DateTime.UtcNow + TimeSpan.FromMilliseconds(int.Parse(timeout, CultureInfo.CurrentCulture)); while (true) { if (DateTime.UtcNow > expire) diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/DiscoveryDataAggregatorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/DiscoveryDataAggregatorTests.cs index 8120283f11..9b466e9a54 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/DiscoveryDataAggregatorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/DiscoveryDataAggregatorTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Concurrent; using System.Collections.Generic; +using System.Globalization; using System.Linq; using Microsoft.VisualStudio.TestPlatform.Common.Telemetry; @@ -75,7 +76,7 @@ public void AggregateDiscoveryDataMetricsShouldAddTotalTestsDiscovered() var runMetrics = aggregator.GetMetrics(); Assert.IsTrue(runMetrics.TryGetValue(TelemetryDataConstants.TotalTestsDiscovered, out var value)); - Assert.AreEqual(4, Convert.ToInt32(value)); + Assert.AreEqual(4, Convert.ToInt32(value, CultureInfo.CurrentCulture)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs index 381fe0220d..63e6c209e6 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/Parallel/ParallelRunDataAggregatorTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Collections.ObjectModel; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.Common.Telemetry; using Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Client.Parallel; @@ -310,7 +311,7 @@ public void AggregateRunDataMetricsShouldAddTotalTestsRun() var runMetrics = aggregator.GetAggregatedRunDataMetrics(); Assert.IsTrue(runMetrics.TryGetValue(TelemetryDataConstants.TotalTestsRanByAdapter, out var value)); - Assert.AreEqual(4, Convert.ToInt32(value)); + Assert.AreEqual(4, Convert.ToInt32(value, CultureInfo.InvariantCulture)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs index 3774208315..4c96c0eda1 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyExecutionManagerTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Linq; using System.Threading; @@ -308,7 +309,7 @@ public void SetupChannelShouldThrowExceptionIfTestHostExitedBeforeConnectionIsEs _mockRequestSender.Setup(s => s.WaitForRequestHandlerConnection(It.IsAny(), It.IsAny())).Returns(false); _mockTestHostManager.Setup(tmh => tmh.LaunchTestHostAsync(It.IsAny(), It.IsAny())).Returns(Task.FromResult(true)).Callback(() => _mockTestHostManager.Raise(t => t.HostExited += null, new HostProviderEventArgs("I crashed!"))); - Assert.AreEqual(string.Format(CrossPlatEngineResources.Resources.TestHostExitedWithError, "I crashed!"), Assert.ThrowsException(() => _testExecutionManager.SetupChannel(new List { "source.dll" }, runsettings)).Message); + Assert.AreEqual(string.Format(CultureInfo.CurrentCulture, CrossPlatEngineResources.Resources.TestHostExitedWithError, "I crashed!"), Assert.ThrowsException(() => _testExecutionManager.SetupChannel(new List { "source.dll" }, runsettings)).Message); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs index 85303d523b..7f8127035d 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Client/ProxyOperationManagerTests.cs @@ -93,7 +93,7 @@ public void SetupChannelShouldCreateTimestampedLogFileForHost() It.IsAny>(), It.IsAny>(), It.Is( - t => t.LogFile!.Contains("log.host." + DateTime.Now.ToString("yy-MM-dd")) + t => t.LogFile!.Contains("log.host." + DateTime.Now.ToString("yy-MM-dd", CultureInfo.CurrentCulture)) && t.LogFile.Contains("_" + Environment.CurrentManagedThreadId + ".txt")))); #if NETFRAMEWORK EqtTrace.TraceLevel = TraceLevel.Off; @@ -309,7 +309,7 @@ public void SetupChannelShouldThrowIfLaunchTestHostFails() var operationManager = new TestableProxyOperationManager(_mockRequestData.Object, _mockRequestSender.Object, _mockTestHostManager.Object); var message = Assert.ThrowsException(() => operationManager.SetupChannel(Enumerable.Empty(), DefaultRunSettings)).Message; - Assert.AreEqual(message, string.Format(CultureInfo.CurrentUICulture, Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Resources.Resources.InitializationFailed)); + Assert.AreEqual(message, Microsoft.VisualStudio.TestPlatform.CrossPlatEngine.Resources.Resources.InitializationFailed); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DotnetDataCollectionLauncherTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DotnetDataCollectionLauncherTests.cs index 0d1dd747b1..6a1df7d787 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DotnetDataCollectionLauncherTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/DotnetDataCollectionLauncherTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Reflection; @@ -53,7 +54,7 @@ public void LaunchDataCollectorShouldAppendDoubleQuoteForDataCollectorDllPath() List arguments = new(); _dataCollectionLauncher.LaunchDataCollector(null, arguments); - _mockProcessHelper.Verify(x => x.LaunchProcess(It.IsAny(), string.Format("{0} \"{1}\" {2} ", "exec", dataCollectorAssemblyPath, string.Join(" ", arguments)), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>()), Times.Once()); + _mockProcessHelper.Verify(x => x.LaunchProcess(It.IsAny(), string.Format(CultureInfo.InvariantCulture, "{0} \"{1}\" {2} ", "exec", dataCollectorAssemblyPath, string.Join(" ", arguments)), It.IsAny(), It.IsAny>(), It.IsAny>(), It.IsAny>(), It.IsAny>()), Times.Once()); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs index 30d35aae84..d0f1629b56 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/DataCollection/ProxyDataCollectionManagerTests.cs @@ -5,6 +5,7 @@ using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Reflection; @@ -78,7 +79,7 @@ public void InitializeShouldThrowExceptionIfConnectionTimeouts() public void InitializeShouldSetTimeoutBasedOnTimeoutEnvironmentVarible() { var timeout = 10; - Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, timeout.ToString()); + Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, timeout.ToString(CultureInfo.CurrentCulture)); _mockDataCollectionRequestSender.Setup(x => x.WaitForRequestHandlerConnection(timeout * 1000)).Returns(true); _proxyDataCollectionManager.Initialize(); @@ -123,7 +124,7 @@ public void InitializeShouldPassDiagArgumentsIfDiagIsEnabled() x => x.LaunchDataCollector( It.IsAny>(), - It.Is>(list => list.Contains("--diag") && list.Contains("--tracelevel") && list.Contains(expectedTraceLevel.ToString()))), + It.Is>(list => list.Contains("--diag") && list.Contains("--tracelevel") && list.Contains(expectedTraceLevel.ToString(CultureInfo.CurrentCulture)))), Times.Once); } finally diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs index b55f118bde..9978da8ae2 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Discovery/DiscovererEnumeratorTests.cs @@ -4,7 +4,6 @@ using System; using System.Collections.Generic; using System.ComponentModel; -using System.Globalization; using System.Linq; using System.Reflection; using System.Threading; @@ -79,13 +78,9 @@ public void LoadTestsShouldReportWarningOnNoDiscoverers() _discovererEnumerator.LoadTests(extensionSourceMap, _runSettingsMock.Object, null, _messageLoggerMock.Object); - var messageFormat = - "No test is available in {0}. Make sure that test discoverer & executors are registered and platform & framework version settings are appropriate and try again."; - var message = string.Format(messageFormat, string.Join(" ", sources)); + var message = $"No test is available in {string.Join(" ", sources)}. Make sure that test discoverer & executors are registered and platform & framework version settings are appropriate and try again."; - _messageLoggerMock.Verify( - l => - l.SendMessage(TestMessageLevel.Warning, message), Times.Once); + _messageLoggerMock.Verify(l => l.SendMessage(TestMessageLevel.Warning, message), Times.Once); } [TestMethod] @@ -354,11 +349,7 @@ public void LoadTestsShouldCallIntoOtherDiscoverersEvenIfDiscoveryInOneFails() Assert.IsNotNull(DllTestDiscoverer.DiscoverySink); // Check if we log the failure. - var message = string.Format( - CultureInfo.CurrentUICulture, - "An exception occurred while test discoverer '{0}' was loading tests. Exception: {1}", - typeof(NotImplementedTestDiscoverer).Name, - "The method or operation is not implemented."); + var message = $"An exception occurred while test discoverer '{typeof(NotImplementedTestDiscoverer).Name}' was loading tests. Exception: The method or operation is not implemented."; _messageLoggerMock.Verify(l => l.SendMessage(TestMessageLevel.Error, message), Times.Once); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs index 1207f87706..f1da1e0c02 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/BaseRunTestsTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.IO; using System.Linq; using System.Reflection; @@ -347,6 +348,7 @@ public void RunTestsShouldReportAWarningIfExecutorUriIsNotDefinedInExtensionAsse var runtimeVersion = " "; var expectedWarningMessage = string.Format( + CultureInfo.InvariantCulture, expectedWarningMessageFormat, "executor://nonexistent/", runtimeVersion); @@ -395,7 +397,7 @@ public void RunTestsShouldAddExecutorUriToExecutorUriListIfExecutorHasRunTests() _runTestsInstance.RunTests(); - var expectedUris = new string[] { BaseRunTestsExecutorUri.ToLower() }; + var expectedUris = new string[] { BaseRunTestsExecutorUri.ToLower(CultureInfo.InvariantCulture) }; CollectionAssert.AreEqual(expectedUris, _runTestsInstance.GetExecutorUrisThatRanTests.ToArray()); } @@ -416,7 +418,7 @@ public void RunTestsShouldReportWarningIfExecutorThrowsAnException() _runTestsInstance.RunTests(); var messageFormat = "An exception occurred while invoking executor '{0}': {1}"; - var message = string.Format(messageFormat, BaseRunTestsExecutorUri.ToLower(), "Test influenced."); + var message = string.Format(CultureInfo.InvariantCulture, messageFormat, BaseRunTestsExecutorUri.ToLower(CultureInfo.InvariantCulture), "Test influenced."); _mockTestRunEventsHandler.Verify( treh => treh.HandleLogMessage(TestMessageLevel.Error, It.Is(s => s.StartsWith(message))), Times.Once); @@ -459,7 +461,7 @@ public void RunTestsShouldNotFailOtherExecutorsRunIfOneExecutorThrowsAnException _runTestsInstance.RunTests(); - var expectedUris = new string[] { BaseRunTestsExecutorUri.ToLower() }; + var expectedUris = new string[] { BaseRunTestsExecutorUri.ToLower(CultureInfo.InvariantCulture) }; CollectionAssert.AreEqual(expectedUris, _runTestsInstance.GetExecutorUrisThatRanTests.ToArray()); } @@ -485,7 +487,7 @@ public void RunTestsShouldIterateThroughAllExecutors() _runTestsInstance.RunTests(); - var expectedUris = new string[] { BadBaseRunTestsExecutorUri.ToLower(), BaseRunTestsExecutorUri.ToLower() }; + var expectedUris = new string[] { BadBaseRunTestsExecutorUri.ToLower(CultureInfo.InvariantCulture), BaseRunTestsExecutorUri.ToLower(CultureInfo.InvariantCulture) }; CollectionAssert.AreEqual(expectedUris, _runTestsInstance.GetExecutorUrisThatRanTests.ToArray()); } @@ -514,7 +516,7 @@ public void RunTestsShouldRaiseTestRunComplete() Assert.IsNotNull(_receivedattachments); // Executor Uris - var expectedUris = new string[] { BadBaseRunTestsExecutorUri.ToLower(), BaseRunTestsExecutorUri.ToLower() }; + var expectedUris = new string[] { BadBaseRunTestsExecutorUri.ToLower(CultureInfo.InvariantCulture), BaseRunTestsExecutorUri.ToLower(CultureInfo.InvariantCulture) }; CollectionAssert.AreEqual(expectedUris, _receivedExecutorUris!.ToArray()); } diff --git a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs index d8d1ce9be2..4c1c64250f 100644 --- a/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs +++ b/test/Microsoft.TestPlatform.CrossPlatEngine.UnitTests/Execution/RunTestsWithSourcesTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; +using System.Globalization; using System.Linq; using System.Reflection; @@ -97,7 +98,7 @@ public void BeforeRaisingTestRunCompleteShouldWarnIfNoTestsAreRun() var messageFormat = "No test is available in {0}. Make sure that test discoverer & executors are registered and platform & framework version settings are appropriate and try again."; - var message = string.Format(messageFormat, "a aa b ab"); + var message = string.Format(CultureInfo.CurrentCulture, messageFormat, "a aa b ab"); _mockTestRunEventsHandler.Verify(treh => treh.HandleLogMessage(TestMessageLevel.Warning, message), Times.Once); } diff --git a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs index 205d76ea5a..9c702cfec1 100644 --- a/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.BlameDataCollector.UnitTests/BlameCollectorTests.cs @@ -550,7 +550,7 @@ public void TriggerTestHostLaunchedHandlerShouldLogWarningForWrongCollectDumpKey _mockDataColectionEvents.Raise(x => x.TestHostLaunched += null, new TestHostLaunchedEventArgs(_dataCollectionContext, 1234)); // Verify - _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterKeyIncorrect, "Xyz"))), Times.Once); + _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentCulture, Resources.Resources.BlameParameterKeyIncorrect, "Xyz"))), Times.Once); } /// @@ -576,7 +576,7 @@ public void TriggerTestHostLaunchedHandlerShouldLogWarningForWrongDumpType() _mockDataColectionEvents.Raise(x => x.TestHostLaunched += null, new TestHostLaunchedEventArgs(_dataCollectionContext, 1234)); // Verify - var expectedMessage = string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, "DumpType", "random", string.Join(", ", Enum.GetNames(typeof(CrashDumpType)))); + var expectedMessage = string.Format(CultureInfo.CurrentCulture, Resources.Resources.BlameParameterValueIncorrect, "DumpType", "random", string.Join(", ", Enum.GetNames(typeof(CrashDumpType)))); _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == expectedMessage)), Times.Once); } @@ -603,7 +603,7 @@ public void TriggerTestHostLaunchedHandlerShouldLogWarningForNonBooleanCollectAl _mockDataColectionEvents.Raise(x => x.TestHostLaunched += null, new TestHostLaunchedEventArgs(_dataCollectionContext, 1234)); // Verify - var expectedMessage = string.Format(CultureInfo.CurrentUICulture, Resources.Resources.BlameParameterValueIncorrect, "CollectAlways", "random", string.Join(", ", new object[] { Constants.TrueConfigurationValue, Constants.FalseConfigurationValue })); + var expectedMessage = string.Format(CultureInfo.CurrentCulture, Resources.Resources.BlameParameterValueIncorrect, "CollectAlways", "random", string.Join(", ", new object[] { Constants.TrueConfigurationValue, Constants.FalseConfigurationValue })); _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == expectedMessage)), Times.Once); } @@ -653,7 +653,7 @@ public void TriggerTestHostLaunchedHandlerShouldCatchTestPlatFormExceptionsAndRe _mockDataColectionEvents.Raise(x => x.TestHostLaunched += null, new TestHostLaunchedEventArgs(_dataCollectionContext, 1234)); // Verify - _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentUICulture, Resources.Resources.ProcDumpCouldNotStart, tpex.Message))), Times.Once); + _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentCulture, Resources.Resources.ProcDumpCouldNotStart, tpex.Message))), Times.Once); } /// @@ -679,7 +679,7 @@ public void TriggerTestHostLaunchedHandlerShouldCatchAllUnexpectedExceptionsAndR _mockDataColectionEvents.Raise(x => x.TestHostLaunched += null, new TestHostLaunchedEventArgs(_dataCollectionContext, 1234)); // Verify - _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentUICulture, Resources.Resources.ProcDumpCouldNotStart, ex.ToString()))), Times.Once); + _mockLogger.Verify(x => x.LogWarning(It.IsAny(), It.Is(str => str == string.Format(CultureInfo.CurrentCulture, Resources.Resources.ProcDumpCouldNotStart, ex.ToString()))), Times.Once); } [TestCleanup] diff --git a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs index 5dad48094e..cb5ba57490 100644 --- a/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs +++ b/test/Microsoft.TestPlatform.Extensions.TrxLogger.UnitTests/TrxLoggerTests.cs @@ -790,12 +790,12 @@ public void CrlfCharactersShouldGetRetainedInTrx() var testRunCompleteEventArgs = CreateTestRunCompleteEventArgs(); _testableTrxLogger.TestRunCompleteHandler(new object(), testRunCompleteEventArgs); - Assert.IsTrue(File.Exists(_testableTrxLogger.TrxFile), string.Format("TRX file: {0}, should have got created.", _testableTrxLogger.TrxFile)); + Assert.IsTrue(File.Exists(_testableTrxLogger.TrxFile), $"TRX file: {_testableTrxLogger.TrxFile}, should have got created."); string? actualMessage = GetElementValueFromTrx(_testableTrxLogger.TrxFile!, "StdOut"); Assert.IsNotNull(actualMessage); - Assert.IsTrue(string.Equals(message, actualMessage), string.Format("StdOut messages do not match. Expected:{0}, Actual:{1}", message, actualMessage)); + Assert.IsTrue(string.Equals(message, actualMessage), $"StdOut messages do not match. Expected:{message}, Actual:{actualMessage}"); } [TestMethod] @@ -811,11 +811,11 @@ private static void ValidateDateTimeInTrx(string trxFileName) using XmlReader reader = XmlReader.Create(file); XDocument document = XDocument.Load(reader); var timesNode = document.Descendants(document.Root!.GetDefaultNamespace() + "Times").First(); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("creation").First().Value)); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("start").First().Value)); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("creation").First().Value, CultureInfo.CurrentCulture)); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(timesNode.Attributes("start").First().Value, CultureInfo.CurrentCulture)); var resultNode = document.Descendants(document.Root.GetDefaultNamespace() + "UnitTestResult").First(); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("endTime").First().Value)); - ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("startTime").First().Value)); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("endTime").First().Value, CultureInfo.CurrentCulture)); + ValidateTimeWithinUtcLimits(DateTimeOffset.Parse(resultNode.Attributes("startTime").First().Value, CultureInfo.CurrentCulture)); } [TestMethod] diff --git a/test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs b/test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs index 386fdab9eb..302456a319 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.PlatformTests/DiaSessionTests.cs @@ -121,7 +121,7 @@ public void DiaSessionPerfTest() ValidateMinLineNumber(9, diaNavigationData.MinLineNumber); Assert.AreEqual(10, diaNavigationData.MaxLineNumber); var expectedTime = 150; - Assert.IsTrue(watch.Elapsed.Milliseconds < expectedTime, string.Format("DiaSession Perf test Actual time:{0} ms Expected time:{1} ms", watch.Elapsed.Milliseconds, expectedTime)); + Assert.IsTrue(watch.Elapsed.Milliseconds < expectedTime, $"DiaSession Perf test Actual time:{watch.Elapsed.Milliseconds} ms Expected time:{expectedTime} ms"); _testEnvironment.TargetFramework = currentTargetFrameWork; } diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs index e81bf05e38..cc548cd386 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/RunSettings/RunConfigurationTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; @@ -247,6 +248,7 @@ public void RunConfigurationFromXmlThrowsSettingsExceptionIfBatchSizeIsNegativeI public void RunConfigurationShouldReadValueForDesignMode(bool designModeValue) { string settingsXml = string.Format( + CultureInfo.CurrentCulture, @" @@ -289,6 +291,7 @@ public void RunConfigurationToXmlShouldProvideDesignMode() public void RunConfigurationShouldReadValueForCollectSourceInformation(bool val) { string settingsXml = string.Format( + CultureInfo.CurrentCulture, @" diff --git a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs index 4d39ae246d..11e62c213a 100644 --- a/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs +++ b/test/Microsoft.TestPlatform.ObjectModel.UnitTests/Utilities/XmlRunSettingsUtilitiesTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.Linq; using System.Xml; @@ -481,6 +482,7 @@ public void GetLoggerRunSettingsShouldThrowWhenInvalidUri() Assert.IsTrue(exceptionMessage.Contains( string.Format( + CultureInfo.CurrentCulture, Resources.InvalidUriInSettings, "invalidUri", "Logger"))); @@ -712,6 +714,7 @@ public void GetLoggerRunSettingsShouldThrowWhenAttribtuesPresentInLoggerRunSetti } Assert.IsTrue(exceptionMessage.Contains(string.Format( + CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlAttribute, "LoggerRunSettings", "name"))); @@ -775,6 +778,7 @@ public void GetLoggerRunSettingsShouldThrowWhenNodeOtherThanLoggersPresentInLogg } Assert.IsTrue(exceptionMessage.Contains(string.Format( + CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlElement, "LoggerRUNSettings", "LoggersInvalid"))); @@ -807,6 +811,7 @@ public void GetLoggerRunSettingsShouldThrowWhenAttribtuesPresentInLoggersNode() } Assert.IsTrue(exceptionMessage.Contains(string.Format( + CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlAttribute, "Loggers", "nameAttr"))); @@ -874,6 +879,7 @@ public void GetLoggerRunSettingsShouldThrowWhenNodeOtherThanLoggerPresentInLogge } Assert.IsTrue(exceptionMessage.Contains(string.Format( + CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlElement, "Loggers", "LoggerInvalid"))); @@ -906,9 +912,7 @@ public void GetLoggerRunSettingsShouldThrowWhenRequiredAttributesNotPresentInLog exceptionMessage = ex.Message; } - Assert.IsTrue(exceptionMessage.Contains(string.Format( - Resources.MissingLoggerAttributes, - "LogGer"))); + Assert.IsTrue(exceptionMessage.Contains(string.Format(CultureInfo.CurrentCulture, Resources.MissingLoggerAttributes, "LogGer"))); } [TestMethod] @@ -973,6 +977,7 @@ public void GetLoggerRunSettingsShouldThrowWhenNodeOtherThanConfigurationPresent } Assert.AreEqual(string.Format( + CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlElement, "Logger", "ConfiGUrationInvalid"), exceptionMessage); @@ -1010,6 +1015,7 @@ public void GetLoggerRunSettingsShouldThrowOnInvalidAttributeInLoggerNode() } Assert.AreEqual(string.Format( + CultureInfo.CurrentCulture, Resources.InvalidSettingsXmlAttribute, "Logger", "invalidAttr"), exceptionMessage); diff --git a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerfAnalyzer.cs b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerfAnalyzer.cs index 101795ddb9..d15664014c 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerfAnalyzer.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/PerfInstrumentation/PerfAnalyzer.cs @@ -10,6 +10,7 @@ using Microsoft.Diagnostics.Tracing; using Microsoft.Diagnostics.Tracing.Parsers; using Microsoft.Diagnostics.Tracing.Session; +using System.Globalization; namespace Microsoft.TestPlatform.PerformanceTests.PerfInstrumentation; @@ -84,8 +85,8 @@ private void AnalyzeEventsData() { if (data.ProviderName.Equals("TestPlatform") && !data.EventName.Equals("ManifestData")) { - Console.WriteLine("Received Event : {0}", data.ToString()); - var key = data.ProcessID + "_" + data.ThreadID.ToString() + "_" + data.TaskName; + Console.WriteLine("Received Event : {0}", data.ToString(CultureInfo.CurrentCulture)); + var key = $"{data.ProcessID}_{data.ThreadID}_{data.TaskName}"; Events.Add(new TestPlatformEvent(data.EventName, data.TimeStampRelativeMSec)); if (!_testPlatformTaskMap.ContainsKey(key)) diff --git a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/DiscoveryPerfTests.cs b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/DiscoveryPerfTests.cs index e96b41e84d..3e3bc341eb 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/DiscoveryPerfTests.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/DiscoveryPerfTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; +using System.Globalization; using Microsoft.TestPlatform.PerformanceTests.PerfInstrumentation; using Microsoft.VisualStudio.TestPlatform.Common.Telemetry; @@ -39,7 +40,7 @@ public void DiscoverTests(string projectName, double expectedNumberOfTests) using (perfAnalyzer.Start()) { // This tells to PerfyTestAdapter how many tests it should return, this is our overhead baseline. - var perfyTestAdapterEnv = new Dictionary { ["TEST_COUNT"] = expectedNumberOfTests.ToString() }; + var perfyTestAdapterEnv = new Dictionary { ["TEST_COUNT"] = expectedNumberOfTests.ToString(CultureInfo.InvariantCulture) }; var vstestConsoleWrapper = GetVsTestConsoleWrapper(perfyTestAdapterEnv, traceLevel: System.Diagnostics.TraceLevel.Off); var assetPath = GetPerfAssetFullPath(projectName); vstestConsoleWrapper.DiscoverTests(assetPath, GetDefaultRunSettings(), options, discoveryEventHandler2); @@ -82,7 +83,7 @@ public void DiscoverTestsWithDefaultAdaptersSkipped(string projectName, double e using (perfAnalyzer.Start()) { // This tells to PerfyTestAdapter how many tests it should return, this is our overhead baseline. - var perfyTestAdapterEnv = new Dictionary { ["TEST_COUNT"] = expectedNumberOfTests.ToString() }; + var perfyTestAdapterEnv = new Dictionary { ["TEST_COUNT"] = expectedNumberOfTests.ToString(CultureInfo.InvariantCulture) }; var vstestConsoleWrapper = GetVsTestConsoleWrapper(perfyTestAdapterEnv, traceLevel: System.Diagnostics.TraceLevel.Off); vstestConsoleWrapper.DiscoverTests(GetPerfAssetFullPath(projectName), GetDefaultRunSettings(), options, discoveryEventHandler2); vstestConsoleWrapper.EndSession(); diff --git a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/ExecutionPerfTests.cs b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/ExecutionPerfTests.cs index 77886038e2..d9d200e545 100644 --- a/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/ExecutionPerfTests.cs +++ b/test/Microsoft.TestPlatform.PerformanceTests/TranslationLayer/ExecutionPerfTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; +using System.Globalization; using Microsoft.TestPlatform.PerformanceTests.PerfInstrumentation; using Microsoft.VisualStudio.TestPlatform.Common.Telemetry; @@ -40,7 +41,7 @@ public void RunTests(string projectName, double expectedNumberOfTests) using (perfAnalyzer.Start()) { // This tells to PerfyTestAdapter how many tests it should return, this is our overhead baseline. - var perfyTestAdapterEnv = new Dictionary { ["TEST_COUNT"] = expectedNumberOfTests.ToString() }; + var perfyTestAdapterEnv = new Dictionary { ["TEST_COUNT"] = expectedNumberOfTests.ToString(CultureInfo.InvariantCulture) }; var vstestConsoleWrapper = GetVsTestConsoleWrapper(perfyTestAdapterEnv, traceLevel: System.Diagnostics.TraceLevel.Off); vstestConsoleWrapper.RunTests(GetPerfAssetFullPath(projectName), GetDefaultRunSettings(), options, runEventHandler); vstestConsoleWrapper.EndSession(); @@ -81,7 +82,7 @@ public void RunTestsWithDefaultAdaptersSkipped(string projectName, double expect using (perfAnalyzer.Start()) { // This tells to PerfyTestAdapter how many tests it should return, this is our overhead baseline. - var perfyTestAdapterEnv = new Dictionary { ["TEST_COUNT"] = expectedNumberOfTests.ToString() }; + var perfyTestAdapterEnv = new Dictionary { ["TEST_COUNT"] = expectedNumberOfTests.ToString(CultureInfo.InvariantCulture) }; var vstestConsoleWrapper = GetVsTestConsoleWrapper(perfyTestAdapterEnv, traceLevel: System.Diagnostics.TraceLevel.Off); vstestConsoleWrapper.RunTests(GetPerfAssetFullPath(projectName), GetDefaultRunSettings(), options, runEventHandler); vstestConsoleWrapper.EndSession(); diff --git a/test/Microsoft.TestPlatform.SmokeTests/DataCollectorTests.cs b/test/Microsoft.TestPlatform.SmokeTests/DataCollectorTests.cs index 0d324a6304..e80db05f02 100644 --- a/test/Microsoft.TestPlatform.SmokeTests/DataCollectorTests.cs +++ b/test/Microsoft.TestPlatform.SmokeTests/DataCollectorTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Globalization; using System.IO; using Microsoft.TestPlatform.TestUtilities; @@ -54,7 +55,7 @@ private string GetInProcDataCollectionRunsettingsFile() "; - fileContents = string.Format(fileContents, AssemblyUtility.GetAssemblyName(inprocasm), inprocasm); + fileContents = string.Format(CultureInfo.CurrentCulture, fileContents, AssemblyUtility.GetAssemblyName(inprocasm), inprocasm); File.WriteAllText(runSettings, fileContents); return runSettings; diff --git a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs index 2a01779450..2b0765f0cc 100644 --- a/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs +++ b/test/Microsoft.TestPlatform.TestUtilities/IntegrationTestBase.cs @@ -5,6 +5,7 @@ using System.Collections; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.IO; using System.Linq; using System.Text; @@ -307,6 +308,7 @@ public void ValidateSummaryStatus(int passed, int failed, int skipped) { // No test should be found/run var summaryStatus = string.Format( + CultureInfo.CurrentCulture, TestSummaryStatusMessageFormat, @"\d+", @"\d+", @@ -323,20 +325,20 @@ public void ValidateSummaryStatus(int passed, int failed, int skipped) } else { - var summaryStatus = string.Format(TotalTestsMessage, totalTestCount); + var summaryStatus = string.Format(CultureInfo.CurrentCulture, TotalTestsMessage, totalTestCount); if (passed != 0) { - summaryStatus += string.Format(PassedTestsMessage, passed); + summaryStatus += string.Format(CultureInfo.CurrentCulture, PassedTestsMessage, passed); } if (failed != 0) { - summaryStatus += string.Format(FailedTestsMessage, failed); + summaryStatus += string.Format(CultureInfo.CurrentCulture, FailedTestsMessage, failed); } if (skipped != 0) { - summaryStatus += string.Format(SkippedTestsMessage, skipped); + summaryStatus += string.Format(CultureInfo.CurrentCulture, SkippedTestsMessage, skipped); } Assert.IsTrue( @@ -439,7 +441,7 @@ public void ExitCodeEquals(int exitCode) public void ValidatePassedTests(params string[] passedTests) { // Convert the unicode character to its unicode value for assertion - _standardTestOutput = Regex.Replace(_standardTestOutput, @"[^\x00-\x7F]", c => string.Format(@"\u{0:x4}", (int)c.Value[0])); + _standardTestOutput = Regex.Replace(_standardTestOutput, @"[^\x00-\x7F]", c => $@"\u{(int)c.Value[0]:x4}"); foreach (var test in passedTests) { // Check for tick or ? both, in some cases as unicode character for tick is not available @@ -578,19 +580,19 @@ protected string GetTestAdapterPath(UnitTestFramework testFramework = UnitTestFr if (testFramework == UnitTestFramework.MSTest) { - adapterRelativePath = string.Format(_testAdapterRelativePath, IntegrationTestEnvironment.DependencyVersions["MSTestAdapterVersion"]); + adapterRelativePath = string.Format(CultureInfo.InvariantCulture, _testAdapterRelativePath, IntegrationTestEnvironment.DependencyVersions["MSTestAdapterVersion"]); } else if (testFramework == UnitTestFramework.NUnit) { - adapterRelativePath = string.Format(_nUnitTestAdapterRelativePath, IntegrationTestEnvironment.DependencyVersions["NUnit3AdapterVersion"]); + adapterRelativePath = string.Format(CultureInfo.InvariantCulture, _nUnitTestAdapterRelativePath, IntegrationTestEnvironment.DependencyVersions["NUnit3AdapterVersion"]); } else if (testFramework == UnitTestFramework.XUnit) { - adapterRelativePath = string.Format(_xUnitTestAdapterRelativePath, IntegrationTestEnvironment.DependencyVersions["XUnitAdapterVersion"]); + adapterRelativePath = string.Format(CultureInfo.InvariantCulture, _xUnitTestAdapterRelativePath, IntegrationTestEnvironment.DependencyVersions["XUnitAdapterVersion"]); } else if (testFramework == UnitTestFramework.Chutzpah) { - adapterRelativePath = string.Format(_chutzpahTestAdapterRelativePath, IntegrationTestEnvironment.DependencyVersions["ChutzpahAdapterVersion"]); + adapterRelativePath = string.Format(CultureInfo.InvariantCulture, _chutzpahTestAdapterRelativePath, IntegrationTestEnvironment.DependencyVersions["ChutzpahAdapterVersion"]); } return _testEnvironment.GetNugetPackage(adapterRelativePath); diff --git a/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs b/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs index 889e1d4aa7..897c96c87d 100644 --- a/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs +++ b/test/Microsoft.TestPlatform.Utilities.UnitTests/InferRunSettingsHelperTests.cs @@ -43,8 +43,7 @@ public void UpdateRunSettingsShouldThrowIfRunSettingsNodeDoesNotExist() Action action = () => InferRunSettingsHelper.UpdateRunSettingsWithUserProvidedSwitches(xmlDocument, Architecture.X86, Framework.DefaultFramework, "temp"); Assert.That.Throws(action) - .WithMessage(string.Format("An error occurred while loading the settings. Error: {0}.", - "Could not find 'RunSettings' node.")); + .WithMessage("An error occurred while loading the settings. Error: Could not find 'RunSettings' node.."); } [TestMethod] @@ -56,11 +55,7 @@ public void UpdateRunSettingsShouldThrowIfPlatformNodeIsInvalid() Action action = () => InferRunSettingsHelper.UpdateRunSettingsWithUserProvidedSwitches(xmlDocument, Architecture.X86, Framework.DefaultFramework, "temp"); Assert.That.Throws(action) - .WithMessage(string.Format("An error occurred while loading the settings. Error: {0}.", - string.Format("Invalid setting '{0}'. Invalid value '{1}' specified for '{2}'", - "RunConfiguration", - "foo", - "TargetPlatform"))); + .WithMessage("An error occurred while loading the settings. Error: Invalid setting 'RunConfiguration'. Invalid value 'foo' specified for 'TargetPlatform'."); } [TestMethod] @@ -72,11 +67,7 @@ public void UpdateRunSettingsShouldThrowIfFrameworkNodeIsInvalid() Action action = () => InferRunSettingsHelper.UpdateRunSettingsWithUserProvidedSwitches(xmlDocument, Architecture.X86, Framework.DefaultFramework, "temp"); Assert.That.Throws(action) - .WithMessage(string.Format("An error occurred while loading the settings. Error: {0}.", - string.Format("Invalid setting '{0}'. Invalid value '{1}' specified for '{2}'", - "RunConfiguration", - "foo", - "TargetFrameworkVersion"))); + .WithMessage("An error occurred while loading the settings. Error: Invalid setting 'RunConfiguration'. Invalid value 'foo' specified for 'TargetFrameworkVersion'."); } [TestMethod] @@ -211,7 +202,7 @@ public void UpdateRunSettingsShouldReturnBackACompleteRunSettings() InferRunSettingsHelper.UpdateRunSettingsWithUserProvidedSwitches(xmlDocument, Architecture.X64, Framework.DefaultFramework, "temp"); var xml = xmlDocument.OuterXml; - var expectedRunSettings = string.Format("tempX64{0}", Framework.DefaultFramework.Name); + var expectedRunSettings = $"tempX64{Framework.DefaultFramework.Name}"; Assert.AreEqual(expectedRunSettings, xml); } diff --git a/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs b/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs index 9a5d96472d..5be007cd7a 100644 --- a/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs +++ b/test/datacollector.PlatformTests/CommunicationLayerIntegrationTests.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using System.Reflection; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities; @@ -37,8 +38,8 @@ public CommunicationLayerIntegrationTests() _mockRequestData = new Mock(); _mockMetricsCollection = new Mock(); _mockRequestData.Setup(rd => rd.MetricsCollection).Returns(_mockMetricsCollection.Object); - _dataCollectorSettings = string.Format("", typeof(CustomDataCollector).AssemblyQualifiedName, typeof(CustomDataCollector).GetTypeInfo().Assembly.Location); - _runSettings = string.Format(_defaultRunSettings, _dataCollectorSettings); + _dataCollectorSettings = string.Format(CultureInfo.InvariantCulture, "", typeof(CustomDataCollector).AssemblyQualifiedName, typeof(CustomDataCollector).GetTypeInfo().Assembly.Location); + _runSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, _dataCollectorSettings); _testSources = new List() { "testsource1.dll" }; _processHelper = new ProcessHelper(); _dataCollectionLauncher = DataCollectionLauncherFactory.GetDataCollectorLauncher(_processHelper, _runSettings); diff --git a/test/datacollector.UnitTests/DataCollectionManagerTests.cs b/test/datacollector.UnitTests/DataCollectionManagerTests.cs index 19c995e71a..cd4fabb017 100644 --- a/test/datacollector.UnitTests/DataCollectionManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionManagerTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using System.IO; using System.Reflection; using System.Threading; @@ -46,7 +47,7 @@ public DataCollectionManagerTests() _mockDataCollector.As().Setup(x => x.GetTestExecutionEnvironmentVariables()).Returns(_envVarList); _mockCodeCoverageDataCollector = new Mock(); _mockCodeCoverageDataCollector.As().Setup(x => x.GetTestExecutionEnvironmentVariables()).Returns(_codeCoverageEnvVarList); - _dataCollectorSettings = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); + _dataCollectorSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); _mockMessageSink = new Mock(); _mockDataCollectionAttachmentManager = new Mock(); _mockDataCollectionAttachmentManager.SetReturnsDefault(new List()); @@ -64,7 +65,7 @@ public void InitializeDataCollectorsShouldThrowExceptionIfSettingsXmlIsNull() [TestMethod] public void InitializeDataCollectorsShouldReturnEmptyDictionaryIfDataCollectorsAreNotConfigured() { - var runSettings = string.Format(_defaultRunSettings, string.Empty); + var runSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Empty); _dataCollectionManager.InitializeDataCollectors(runSettings); Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); @@ -73,7 +74,7 @@ public void InitializeDataCollectorsShouldReturnEmptyDictionaryIfDataCollectorsA [TestMethod] public void InitializeDataCollectorsShouldLoadDataCollector() { - var dataCollectorSettings = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); + var dataCollectorSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettings); Assert.IsTrue(_dataCollectionManager.RunDataCollectors.ContainsKey(_mockDataCollector.Object.GetType())); @@ -85,7 +86,7 @@ public void InitializeDataCollectorsShouldLoadDataCollector() [TestMethod] public void InitializeShouldNotAddDataCollectorIfItIsDisabled() { - var dataCollectorSettingsDisabled = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, "enabled=\"false\"")); + var dataCollectorSettingsDisabled = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, "enabled=\"false\"")); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsDisabled); Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); @@ -95,7 +96,7 @@ public void InitializeShouldNotAddDataCollectorIfItIsDisabled() [TestMethod] public void InitializeShouldAddDataCollectorIfItIsEnabled() { - var dataCollectorSettingsEnabled = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, "enabled=\"true\"")); + var dataCollectorSettingsEnabled = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, "enabled=\"true\"")); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsEnabled); Assert.IsTrue(_dataCollectionManager.RunDataCollectors.ContainsKey(_mockDataCollector.Object.GetType())); @@ -105,7 +106,7 @@ public void InitializeShouldAddDataCollectorIfItIsEnabled() [TestMethod] public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsNotCorrectAndUriIsCorrect() { - var dataCollectorSettingsWithWrongFriendlyName = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, "anyFriendlyName", _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); + var dataCollectorSettingsWithWrongFriendlyName = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, "anyFriendlyName", _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithWrongFriendlyName); Assert.AreEqual(1, _dataCollectionManager.RunDataCollectors.Count); @@ -115,7 +116,7 @@ public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsNotCo [TestMethod] public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsCorrectAndUriIsNotCorrect() { - var dataCollectorSettingsWithWrongUri = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, _friendlyName, "my://custom/WrongDatacollector", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); + var dataCollectorSettingsWithWrongUri = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, "my://custom/WrongDatacollector", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithWrongUri); Assert.AreEqual(1, _dataCollectionManager.RunDataCollectors.Count); @@ -125,7 +126,7 @@ public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsCorre [TestMethod] public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsNullAndUriIsCorrect() { - var dataCollectorSettingsWithNullFriendlyName = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, string.Empty, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty).Replace("friendlyName=\"\"", string.Empty)); + var dataCollectorSettingsWithNullFriendlyName = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, string.Empty, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty).Replace("friendlyName=\"\"", string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithNullFriendlyName); Assert.AreEqual(1, _dataCollectionManager.RunDataCollectors.Count); @@ -135,21 +136,21 @@ public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsNullA [TestMethod] public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsCorrectAndUriIsEmpty() { - var dataCollectorSettingsWithEmptyUri = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, _friendlyName, string.Empty, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); + var dataCollectorSettingsWithEmptyUri = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, string.Empty, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); Assert.ThrowsException(() => _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithEmptyUri)); } [TestMethod] public void InitializeDataCollectorsShouldLoadDataCollectorIfFriendlyNameIsEmptyAndUriIsCorrect() { - var dataCollectorSettingsWithEmptyFriendlyName = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, _friendlyName, string.Empty, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); + var dataCollectorSettingsWithEmptyFriendlyName = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, string.Empty, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); Assert.ThrowsException(() => _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithEmptyFriendlyName)); } [TestMethod] public void InitializeDataCollectorsShouldNotLoadDataCollectorIfFriendlyNameIsNotCorrectAndUriIsNotCorrect() { - var dataCollectorSettingsWithWrongFriendlyNameAndWrongUri = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, "anyFriendlyName", "datacollector://data", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); + var dataCollectorSettingsWithWrongFriendlyNameAndWrongUri = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, "anyFriendlyName", "datacollector://data", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithWrongFriendlyNameAndWrongUri); Assert.AreEqual(0, _dataCollectionManager.RunDataCollectors.Count); @@ -159,8 +160,8 @@ public void InitializeDataCollectorsShouldNotLoadDataCollectorIfFriendlyNameIsNo [TestMethod] public void InitializeDataCollectorsShouldNotAddSameDataCollectorMoreThanOnce() { - var datacollecterSettings = string.Format(_defaultDataCollectionSettings, "CustomDataCollector", "my://custom/datacollector", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, "enabled =\"true\""); - var runSettings = string.Format(_defaultRunSettings, datacollecterSettings + datacollecterSettings); + var datacollecterSettings = string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, "CustomDataCollector", "my://custom/datacollector", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, "enabled =\"true\""); + var runSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, datacollecterSettings + datacollecterSettings); _dataCollectionManager.InitializeDataCollectors(runSettings); @@ -232,9 +233,9 @@ public void InitializeDataCollectorsShouldReturnOtherThanCodeCoverageEnvironment _codeCoverageEnvVarList.Add(new KeyValuePair("clrie_profiler_vanguard", "path")); _codeCoverageEnvVarList.Add(new KeyValuePair("same_key", "same_value")); - _dataCollectorSettings = string.Format(_defaultRunSettings, - string.Format(_defaultDataCollectionSettings, "Code Coverage", "my://custom/ccdatacollector", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty) + - string.Format(_defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); + _dataCollectorSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, + string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, "Code Coverage", "my://custom/ccdatacollector", _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty) + + string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, _friendlyName, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty)); var result = _dataCollectionManager.InitializeDataCollectors(_dataCollectorSettings); @@ -253,7 +254,7 @@ public void InitializeDataCollectorsShouldReturnOtherThanCodeCoverageEnvironment [TestMethod] public void SessionStartedShouldReturnFalseIfDataCollectionIsNotConfiguredInRunSettings() { - var runSettings = string.Format(_defaultRunSettings, string.Empty); + var runSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Empty); _dataCollectionManager.InitializeDataCollectors(runSettings); var sessionStartEventArgs = new SessionStartEventArgs(); @@ -329,7 +330,7 @@ public void SessionStartedShouldHaveCorrectSessionContext() [TestMethod] public void SessionEndedShouldReturnEmptyCollectionIfDataCollectionIsNotEnabled() { - var runSettings = string.Format(_defaultRunSettings, string.Empty); + var runSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Empty); _dataCollectionManager.InitializeDataCollectors(runSettings); var result = _dataCollectionManager.SessionEnded(); @@ -340,7 +341,7 @@ public void SessionEndedShouldReturnEmptyCollectionIfDataCollectionIsNotEnabled( [TestMethod] public void GetInvokedDataCollectorsShouldReturnDataCollector() { - var dataCollectorSettingsWithNullFriendlyName = string.Format(_defaultRunSettings, string.Format(_defaultDataCollectionSettings, string.Empty, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty).Replace("friendlyName=\"\"", string.Empty)); + var dataCollectorSettingsWithNullFriendlyName = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, string.Format(CultureInfo.InvariantCulture, _defaultDataCollectionSettings, string.Empty, _uri, _mockDataCollector.Object.GetType().AssemblyQualifiedName, typeof(DataCollectionManagerTests).GetTypeInfo().Assembly.Location, string.Empty).Replace("friendlyName=\"\"", string.Empty)); _dataCollectionManager.InitializeDataCollectors(dataCollectorSettingsWithNullFriendlyName); var invokedDataCollector = _dataCollectionManager.GetInvokedDataCollectors(); Assert.AreEqual(1, invokedDataCollector.Count); @@ -456,7 +457,7 @@ public void TestCaseEndedShouldSendEventToDataCollector() public void TestCaseEndedShouldNotSendEventToDataCollectorIfDataColletionIsNotEnbled() { var isEndInvoked = false; - var runSettings = string.Format(_defaultRunSettings, _dataCollectorSettings); + var runSettings = string.Format(CultureInfo.InvariantCulture, _defaultRunSettings, _dataCollectorSettings); SetupMockDataCollector((XmlElement a, DataCollectionEvents b, DataCollectionSink c, DataCollectionLogger d, DataCollectionEnvironmentContext e) => b.TestCaseEnd += (sender, eventArgs) => isEndInvoked = true); var args = new TestCaseEndEventArgs(); diff --git a/test/datacollector.UnitTests/DataCollectionTelemetryManagerTests.cs b/test/datacollector.UnitTests/DataCollectionTelemetryManagerTests.cs index 73e35e6cef..ca480810c8 100644 --- a/test/datacollector.UnitTests/DataCollectionTelemetryManagerTests.cs +++ b/test/datacollector.UnitTests/DataCollectionTelemetryManagerTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.Common.DataCollector; using Microsoft.VisualStudio.TestPlatform.Common.DataCollector.Interfaces; @@ -207,7 +208,7 @@ public void RecordEnvironmentVariableConflict_ShouldCollectClrIeTelemetry_IfCore public void RecordEnvironmentVariableConflict_ShouldCollectTelemetry_IfCorProfilerVariableAndBothValuesSame(string profilerGuid, string profilerName) { // act - _telemetryManager.RecordEnvironmentVariableConflict(_dataCollectorInformation, "COR_PROFILER", profilerGuid, profilerGuid.ToLower()); + _telemetryManager.RecordEnvironmentVariableConflict(_dataCollectorInformation, "COR_PROFILER", profilerGuid, profilerGuid.ToLower(CultureInfo.InvariantCulture)); // assert _mockMetricsCollection.Verify(c => c.Add($"VS.TestPlatform.DataCollector.CorProfiler.{_dataCollectorInformation.DataCollectorConfig.TypeUri}", profilerName), Times.Once); @@ -225,7 +226,7 @@ public void RecordEnvironmentVariableConflict_ShouldCollectTelemetry_IfCorProfil public void RecordEnvironmentVariableConflict_ShouldCollectTelemetry_IfCoreClrProfilerVariableAndBothValuesSame(string profilerGuid, string profilerName) { // act - _telemetryManager.RecordEnvironmentVariableConflict(_dataCollectorInformation, "CORECLR_PROFILER", profilerGuid, profilerGuid.ToUpper()); + _telemetryManager.RecordEnvironmentVariableConflict(_dataCollectorInformation, "CORECLR_PROFILER", profilerGuid, profilerGuid.ToUpper(CultureInfo.InvariantCulture)); // assert _mockMetricsCollection.Verify(c => c.Add($"VS.TestPlatform.DataCollector.CoreClrProfiler.{_dataCollectorInformation.DataCollectorConfig.TypeUri}", profilerName), Times.Once); diff --git a/test/datacollector.UnitTests/DataCollectorMainTests.cs b/test/datacollector.UnitTests/DataCollectorMainTests.cs index 2747051022..d76fd505ad 100644 --- a/test/datacollector.UnitTests/DataCollectorMainTests.cs +++ b/test/datacollector.UnitTests/DataCollectorMainTests.cs @@ -137,7 +137,7 @@ public void RunWhenCliUiLanguageIsSetChangesCultureAndFlowsOverride() Assert.IsTrue(threadCultureWasSet, "DefaultThreadCurrentUICulture was not set"); envVarMock.Verify(x => x.GetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE"), Times.Exactly(2)); envVarMock.Verify(x => x.GetEnvironmentVariable("VSLANG"), Times.Once); - envVarMock.Verify(x => x.SetEnvironmentVariable("VSLANG", culture.LCID.ToString()), Times.Once); + envVarMock.Verify(x => x.SetEnvironmentVariable("VSLANG", culture.LCID.ToString(CultureInfo.InvariantCulture)), Times.Once); envVarMock.Verify(x => x.GetEnvironmentVariable("PreferredUILang"), Times.Once); envVarMock.Verify(x => x.SetEnvironmentVariable("PreferredUILang", culture.Name), Times.Once); } @@ -148,7 +148,7 @@ public void RunWhenVsLangIsSetChangesCultureAndFlowsOverride() // Arrange var culture = new CultureInfo("fr-fr"); var envVarMock = new Mock(); - envVarMock.Setup(x => x.GetEnvironmentVariable("VSLANG")).Returns(culture.LCID.ToString()); + envVarMock.Setup(x => x.GetEnvironmentVariable("VSLANG")).Returns(culture.LCID.ToString(CultureInfo.InvariantCulture)); bool threadCultureWasSet = false; var dataCollectorMain = new DataCollectorMain(_mockProcessHelper.Object, _mockEnvironment.Object, _mockDataCollectionRequestHandler.Object, diff --git a/test/testhost.UnitTests/DefaultEngineInvokerTests.cs b/test/testhost.UnitTests/DefaultEngineInvokerTests.cs index 228e1fb14c..ce72b43937 100644 --- a/test/testhost.UnitTests/DefaultEngineInvokerTests.cs +++ b/test/testhost.UnitTests/DefaultEngineInvokerTests.cs @@ -4,6 +4,7 @@ using System; using System.Collections.Generic; using System.Diagnostics; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.Interfaces; using Microsoft.VisualStudio.TestPlatform.CoreUtilities.Helpers; @@ -25,7 +26,7 @@ public class DefaultEngineInvokerTests { "--port", "21291" }, { "--endpoint", "127.0.0.1:021291" }, { "--role", "client"}, - { "--parentprocessid", ParentProcessId.ToString() }, + { "--parentprocessid", ParentProcessId.ToString(CultureInfo.InvariantCulture) }, { "--diag", "temp.txt"}, { "--tracelevel", "3"}, { "--telemetryoptedin", "false"}, @@ -70,7 +71,7 @@ public void InvokeShouldWaitForDefaultTimeoutIfNoEnvVariableSetDuringDataCollect public void InvokeShouldWaitBasedOnTimeoutEnvVariableDuringDataCollectorConnection() { var timeout = 10; - Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, timeout.ToString()); + Environment.SetEnvironmentVariable(EnvironmentHelper.VstestConnectionTimeout, timeout.ToString(CultureInfo.InvariantCulture)); _engineInvoker.Invoke(ArgsDictionary); _mockDataCollectionTestCaseEventSender.Verify(s => s.WaitForRequestSenderConnection(timeout * 1000)); diff --git a/test/testhost.UnitTests/UnitTestClientTests.cs b/test/testhost.UnitTests/UnitTestClientTests.cs index b493875740..e3c43ac440 100644 --- a/test/testhost.UnitTests/UnitTestClientTests.cs +++ b/test/testhost.UnitTests/UnitTestClientTests.cs @@ -65,7 +65,7 @@ public void RunWhenCliUiLanguageIsSetChangesCultureAndFlowsOverride() Assert.IsTrue(threadCultureWasSet, "DefaultThreadCurrentUICulture was not set"); envVarMock.Verify(x => x.GetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE"), Times.Exactly(2)); envVarMock.Verify(x => x.GetEnvironmentVariable("VSLANG"), Times.Once); - envVarMock.Verify(x => x.SetEnvironmentVariable("VSLANG", culture.LCID.ToString()), Times.Once); + envVarMock.Verify(x => x.SetEnvironmentVariable("VSLANG", culture.LCID.ToString(CultureInfo.InvariantCulture)), Times.Once); envVarMock.Verify(x => x.GetEnvironmentVariable("PreferredUILang"), Times.Once); envVarMock.Verify(x => x.SetEnvironmentVariable("PreferredUILang", culture.Name), Times.Once); } @@ -76,7 +76,7 @@ public void RunWhenVsLangIsSetChangesCultureAndFlowsOverride() // Arrange var culture = new CultureInfo("fr-fr"); var envVarMock = new Mock(); - envVarMock.Setup(x => x.GetEnvironmentVariable("VSLANG")).Returns(culture.LCID.ToString()); + envVarMock.Setup(x => x.GetEnvironmentVariable("VSLANG")).Returns(culture.LCID.ToString(CultureInfo.InvariantCulture)); bool threadCultureWasSet = false; diff --git a/test/vstest.console.PlatformTests/AssemblyMetadataProviderTests.cs b/test/vstest.console.PlatformTests/AssemblyMetadataProviderTests.cs index 8b6eef60fe..6a73dc511e 100644 --- a/test/vstest.console.PlatformTests/AssemblyMetadataProviderTests.cs +++ b/test/vstest.console.PlatformTests/AssemblyMetadataProviderTests.cs @@ -3,6 +3,7 @@ using System; using System.Diagnostics; +using System.Globalization; using System.IO; using Microsoft.TestPlatform.TestUtilities; @@ -99,7 +100,7 @@ public void GetArchitectureForNativeDll(string platform) var arch = _assemblyMetadataProvider.GetArchitecture(assemblyPath); stopWatch.Stop(); - Console.WriteLine("Platform:{0}, {1}", platform, string.Format(PerfAssertMessageFormat, expectedElapsedTime, stopWatch.ElapsedMilliseconds)); + Console.WriteLine("Platform:{0}, {1}", platform, string.Format(CultureInfo.CurrentCulture, PerfAssertMessageFormat, expectedElapsedTime, stopWatch.ElapsedMilliseconds)); Assert.AreEqual(Enum.Parse(typeof(Architecture), platform, ignoreCase: true), arch); // We should not assert on time elapsed, it will vary depending on machine, & their state, commenting below assert @@ -129,7 +130,7 @@ public void GetFrameWorkForDotNetAssembly(string framework) Assert.AreEqual(".NETCoreApp,Version=v2.1", actualFx.FullName); } - Console.WriteLine("Framework:{0}, {1}", framework, string.Format(PerfAssertMessageFormat, expectedElapsedTime, stopWatch.ElapsedMilliseconds)); + Console.WriteLine("Framework:{0}, {1}", framework, string.Format(CultureInfo.CurrentCulture, PerfAssertMessageFormat, expectedElapsedTime, stopWatch.ElapsedMilliseconds)); // We should not assert on time elapsed, it will vary depending on machine, & their state. // Assert.IsTrue(stopWatch.ElapsedMilliseconds < expectedElapsedTime, string.Format(PerfAssertMessageFormat, expectedElapsedTime, stopWatch.ElapsedMilliseconds)); @@ -161,7 +162,7 @@ private void TestDotnetAssemblyArch(string projectName, string framework, Archit var arch = _assemblyMetadataProvider.GetArchitecture(assemblyPath); stopWatch.Stop(); - Console.WriteLine("Framework:{0}, {1}", framework, string.Format(PerfAssertMessageFormat, expectedElapsedTime, stopWatch.ElapsedMilliseconds)); + Console.WriteLine("Framework:{0}, {1}", framework, string.Format(CultureInfo.CurrentCulture, PerfAssertMessageFormat, expectedElapsedTime, stopWatch.ElapsedMilliseconds)); Assert.AreEqual(expectedArch, arch, $"Expected: {expectedArch} Actual: {arch}"); // We should not assert on time elapsed, it will vary depending on machine, & their state. diff --git a/test/vstest.console.UnitTests/ExceptionUtilities.cs b/test/vstest.console.UnitTests/ExceptionUtilities.cs index 2f825a8105..196abb3c4f 100644 --- a/test/vstest.console.UnitTests/ExceptionUtilities.cs +++ b/test/vstest.console.UnitTests/ExceptionUtilities.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -25,7 +26,7 @@ public static void ThrowsException(Action action, string format, params strin { Assert.AreEqual(typeof(T), ex.GetType()); isExceptionThrown = true; - var message = string.Format(format, args); + var message = string.Format(CultureInfo.CurrentCulture, format, args); StringAssert.Contains(ex.Message, message); } diff --git a/test/vstest.console.UnitTests/ExecutorUnitTests.cs b/test/vstest.console.UnitTests/ExecutorUnitTests.cs index 5d5fc9787d..12d253e25d 100644 --- a/test/vstest.console.UnitTests/ExecutorUnitTests.cs +++ b/test/vstest.console.UnitTests/ExecutorUnitTests.cs @@ -112,7 +112,7 @@ public void ExecutorWithInvalidArgsShouldPrintErrorMessage() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); + Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)))); } [TestMethod] @@ -124,7 +124,7 @@ public void ExecutorWithInvalidArgsShouldPrintHowToUseHelpOption() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); + Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)))); } [TestMethod] @@ -136,7 +136,7 @@ public void ExecutorWithInvalidArgsAndValueShouldPrintErrorMessage() Assert.AreEqual(1, exitCode, "Exit code must be One when no arguments are provided."); - Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CommandLineResources.InvalidArgument, badArg)))); + Assert.IsTrue(mockOutput.Messages.Any(message => message.Message!.Contains(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidArgument, badArg)))); } /// diff --git a/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs b/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs index de45b60581..7f6c9aa564 100644 --- a/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs +++ b/test/vstest.console.UnitTests/Internal/ConsoleLoggerTests.cs @@ -615,10 +615,10 @@ public void TestResultHandlerShouldShowFailedTestsAndPassedTestsForQuietVebosity _mockOutput.Verify(o => o.Write(string.Format(CultureInfo.CurrentCulture, CommandLineResources.TestRunSummary, (CommandLineResources.PassedTestIndicator + "!").PadRight(8), - 0.ToString().PadLeft(5), - 1.ToString().PadLeft(5), - 1.ToString().PadLeft(5), 2 - .ToString().PadLeft(5), + 0.ToString(CultureInfo.InvariantCulture).PadLeft(5), + 1.ToString(CultureInfo.InvariantCulture).PadLeft(5), + 1.ToString(CultureInfo.InvariantCulture).PadLeft(5), + 2.ToString(CultureInfo.InvariantCulture).PadLeft(5), "1 m 2 s"), OutputLevel.Information), Times.Once); _mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.TestRunSummaryAssemblyAndFramework, @@ -627,10 +627,10 @@ public void TestResultHandlerShouldShowFailedTestsAndPassedTestsForQuietVebosity _mockOutput.Verify(o => o.Write(string.Format(CultureInfo.CurrentCulture, CommandLineResources.TestRunSummary, (CommandLineResources.FailedTestIndicator + "!").PadRight(8), - 1.ToString().PadLeft(5), - 1.ToString().PadLeft(5), - 1.ToString().PadLeft(5), - 3.ToString().PadLeft(5), + 1.ToString(CultureInfo.InvariantCulture).PadLeft(5), + 1.ToString(CultureInfo.InvariantCulture).PadLeft(5), + 1.ToString(CultureInfo.InvariantCulture).PadLeft(5), + 3.ToString(CultureInfo.InvariantCulture).PadLeft(5), "1 h 2 m"), OutputLevel.Information), Times.Once); _mockOutput.Verify(o => o.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.TestRunSummaryAssemblyAndFramework, diff --git a/test/vstest.console.UnitTests/MainTests.cs b/test/vstest.console.UnitTests/MainTests.cs index a302cbbd44..50a5b9baf6 100644 --- a/test/vstest.console.UnitTests/MainTests.cs +++ b/test/vstest.console.UnitTests/MainTests.cs @@ -30,7 +30,7 @@ public void RunWhenCliUiLanguageIsSetChangesCultureAndFlowsOverride() Assert.IsTrue(threadCultureWasSet, "DefaultThreadCurrentUICulture was not set"); envVarMock.Verify(x => x.GetEnvironmentVariable("DOTNET_CLI_UI_LANGUAGE"), Times.Exactly(2)); envVarMock.Verify(x => x.GetEnvironmentVariable("VSLANG"), Times.Once); - envVarMock.Verify(x => x.SetEnvironmentVariable("VSLANG", culture.LCID.ToString()), Times.Once); + envVarMock.Verify(x => x.SetEnvironmentVariable("VSLANG", culture.LCID.ToString(CultureInfo.InvariantCulture)), Times.Once); envVarMock.Verify(x => x.GetEnvironmentVariable("PreferredUILang"), Times.Once); envVarMock.Verify(x => x.SetEnvironmentVariable("PreferredUILang", culture.Name), Times.Once); } @@ -41,7 +41,7 @@ public void RunWhenVsLangIsSetChangesCultureAndFlowsOverride() // Arrange var culture = new CultureInfo("fr-fr"); var envVarMock = new Mock(); - envVarMock.Setup(x => x.GetEnvironmentVariable("VSLANG")).Returns(culture.LCID.ToString()); + envVarMock.Setup(x => x.GetEnvironmentVariable("VSLANG")).Returns(culture.LCID.ToString(CultureInfo.InvariantCulture)); bool threadCultureWasSet = false; diff --git a/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs index 7302a01adc..38b15f965d 100644 --- a/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/CLIRunSettingsArgumentProcessorTests.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Generic; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.CommandLine; using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors; @@ -154,7 +155,7 @@ public void InitializeShouldIgnoreKeyIfValueIsNotPassed() public void InitializeShouldThrowErrorIfArgumentIsInValid(string arg) { var args = new string[] { arg }; - var str = string.Format(CommandLineResources.MalformedRunSettingsKey); + var str = CommandLineResources.MalformedRunSettingsKey; CommandLineException ex = Assert.ThrowsException(() => _executor.Initialize(args)); @@ -331,7 +332,7 @@ public void InitializeShouldValidateTestRunParameter(string arg, string runSetti public void InitializeShouldThrowErrorIfTestRunParameterNodeIsInValid(string arg) { var args = new string[] { arg }; - var str = string.Format(CommandLineResources.InvalidTestRunParameterArgument, arg); + var str = string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidTestRunParameterArgument, arg); CommandLineException ex = Assert.ThrowsException(() => _executor.Initialize(args)); diff --git a/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs index 3184736b1a..75f270983d 100644 --- a/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/CollectArgumentProcessorTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using System.IO; using Microsoft.VisualStudio.TestPlatform.CommandLine; @@ -133,7 +134,7 @@ public void InitializeShouldThrowExceptionWhenTestSettingsIsEnabled() [TestMethod] public void InitializeShouldCreateEntryForDataCollectorInRunSettingsIfNotAlreadyPresent() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -158,7 +159,7 @@ public void InitializeShouldCreateEntryForDataCollectorInRunSettingsIfNotAlready [TestMethod] public void InitializeShouldEnableDataCollectorIfDisabledInRunSettings() { - var runsettingsString = string.Format(_defaultRunSettings, + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); @@ -183,7 +184,7 @@ public void InitializeShouldEnableDataCollectorIfDisabledInRunSettings() [TestMethod] public void InitializeShouldNotDisableOtherDataCollectorsIfEnabled() { - var runsettingsString = string.Format(_defaultRunSettings, + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); @@ -211,7 +212,7 @@ public void InitializeShouldNotDisableOtherDataCollectorsIfEnabled() [TestMethod] public void InitializeShouldNotEnableOtherDataCollectorsIfDisabled() { - var runsettingsString = string.Format(_defaultRunSettings, + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); @@ -239,7 +240,7 @@ public void InitializeShouldNotEnableOtherDataCollectorsIfDisabled() [TestMethod] public void InitializeShouldEnableMultipleCollectorsWhenCalledMoreThanOnce() { - var runsettingsString = string.Format(_defaultRunSettings, string.Empty); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -264,7 +265,7 @@ public void InitializeShouldEnableMultipleCollectorsWhenCalledMoreThanOnce() [TestMethod] public void InitializeShouldAddOutProcAndInprocCollectorWhenXPlatCodeCoverageIsEnabled() { - var runsettingsString = string.Format(_defaultRunSettings, string.Empty); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -292,7 +293,7 @@ public void InitializeShouldAddOutProcAndInprocCollectorWhenXPlatCodeCoverageIsE [TestMethod] public void UpdageXPlatCodeCoverageCodebaseWithFullPathFromTestAdaptersPaths_Found() { - var runsettingsString = string.Format(_defaultRunSettings, string.Empty); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -324,7 +325,7 @@ public void UpdageXPlatCodeCoverageCodebaseWithFullPathFromTestAdaptersPaths_Fou [TestMethod] public void UpdageXPlatCodeCoverageCodebaseWithFullPathFromTestAdaptersPaths_NotFound() { - var runsettingsString = string.Format(_defaultRunSettings, string.Empty); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -367,7 +368,7 @@ public void InitializeXPlatCodeCoverageShouldNotChangeExistingDataCollectors() " ", " ", ""); - runsettingsString = string.Format(runsettingsString, string.Empty); + runsettingsString = string.Format(CultureInfo.CurrentCulture, runsettingsString, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -407,7 +408,7 @@ public void InitializeXPlatCodeCoverageShouldNotChangeExistingXPlatDataCollector " ", " ", " "); - runsettingsString = string.Format(runsettingsString, string.Empty); + runsettingsString = string.Format(CultureInfo.CurrentCulture, runsettingsString, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -452,7 +453,7 @@ public void InitializeXPlatCodeCoverageShouldNotChangeExistingXPlatInProcDataCol " ", " ", ""); - runsettingsString = string.Format(runsettingsString, string.Empty); + runsettingsString = string.Format(CultureInfo.CurrentCulture, runsettingsString, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -496,7 +497,7 @@ public void InitializeXPlatCodeCoverageShouldAddXPlatOutProcProcDataCollectorSet " ", " ", ""); - runsettingsString = string.Format(runsettingsString, string.Empty); + runsettingsString = string.Format(CultureInfo.CurrentCulture, runsettingsString, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -525,7 +526,7 @@ public void InitializeXPlatCodeCoverageShouldAddXPlatOutProcProcDataCollectorSet public void InitializeXPlatCodeCoverageShouldAddXPlatInProcProcDataCollectoPropertiesIfNotPresent() { var runsettingsString = $"\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n"; - runsettingsString = string.Format(runsettingsString, string.Empty); + runsettingsString = string.Format(CultureInfo.CurrentCulture, runsettingsString, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -557,7 +558,7 @@ public void InitializeXPlatCodeCoverageShouldAddXPlatInProcProcDataCollectoPrope public void InitializeXPlatCodeCoverageShouldAddXPlatInProcProcDataCollectoPropertiesIfNotPresent_NoTestAdaptersPaths() { var runsettingsString = $"\r\n\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n"; - runsettingsString = string.Format(runsettingsString, string.Empty); + runsettingsString = string.Format(CultureInfo.CurrentCulture, runsettingsString, string.Empty); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -591,7 +592,7 @@ public void InitializeXPlatCodeCoverageShouldAddXPlatInProcProcDataCollectoPrope [TestMethod] public void InitializeShouldThrowExceptionWhenInvalidCollectorNameProvided() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -602,7 +603,7 @@ public void InitializeShouldThrowExceptionWhenInvalidCollectorNameProvided() [TestMethod] public void InitializeShouldThrowExceptionWhenInvalidConfigurationsProvided() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -613,7 +614,7 @@ public void InitializeShouldThrowExceptionWhenInvalidConfigurationsProvided() [TestMethod] public void InitializeShouldCreateConfigurationsForNewDataCollectorInRunSettings() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -643,7 +644,7 @@ public void InitializeShouldCreateConfigurationsForNewDataCollectorInRunSettings [TestMethod] public void InitializeShouldCreateConfigurationsForExistingDataCollectorInRunSettings() { - var runsettingsString = string.Format(_defaultRunSettings, + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, "" + " " + " SomeValue" + @@ -677,7 +678,7 @@ public void InitializeShouldCreateConfigurationsForExistingDataCollectorInRunSet [TestMethod] public void InitializeShouldUpdateConfigurationsForExistingDataCollectorInRunSettings() { - var runsettingsString = string.Format(_defaultRunSettings, + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, "" + " " + " SomeValue" + diff --git a/test/vstest.console.UnitTests/Processors/EnableBlameArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableBlameArgumentProcessorTests.cs index 2ce434cfa5..42bbd0996f 100644 --- a/test/vstest.console.UnitTests/Processors/EnableBlameArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableBlameArgumentProcessorTests.cs @@ -79,7 +79,7 @@ public void CapabilitiesShouldReturnAppropriateProperties() [TestMethod] public void InitializeShouldCreateEntryForBlameInRunSettingsIfNotAlreadyPresent() { - _ = string.Format(_defaultRunSettings, ""); + _ = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(_defaultRunSettings); _settingsProvider.SetActiveRunSettings(runsettings); @@ -114,7 +114,7 @@ public void InitializeShouldCreateEntryForBlameInRunSettingsIfNotAlreadyPresent( [TestMethod] public void InitializeShouldOverwriteEntryForBlameInRunSettingsIfAlreadyPresent() { - _ = string.Format(_defaultRunSettings, ""); + _ = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(string.Join(Environment.NewLine, "", @@ -172,7 +172,7 @@ public void InitializeShouldOverwriteEntryForBlameInRunSettingsIfAlreadyPresent( public void InitializeShouldWarnIfIncorrectParameterIsSpecifiedForCollectDumpOption() { var invalidParameter = "CollectDumpXX"; - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(_defaultRunSettings); _settingsProvider.SetActiveRunSettings(runsettings); @@ -183,7 +183,7 @@ public void InitializeShouldWarnIfIncorrectParameterIsSpecifiedForCollectDumpOpt .Returns(PlatformArchitecture.X64); _executor.Initialize(invalidParameter); - _mockOutput.Verify(x => x.WriteLine(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.BlameIncorrectOption, invalidParameter), OutputLevel.Warning)); + _mockOutput.Verify(x => x.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.BlameIncorrectOption, invalidParameter), OutputLevel.Warning)); Assert.IsNotNull(_settingsProvider.ActiveRunSettings); Assert.AreEqual(string.Join(Environment.NewLine, @@ -215,7 +215,7 @@ public void InitializeShouldWarnIfIncorrectParameterIsSpecifiedForCollectDumpOpt public void InitializeShouldThrowIfInvalidParameterFormatIsSpecifiedForCollectDumpOption() { var invalidString = "CollectDump;sdf=sdg;;as;a="; - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(_defaultRunSettings); _settingsProvider.SetActiveRunSettings(runsettings); @@ -226,7 +226,7 @@ public void InitializeShouldThrowIfInvalidParameterFormatIsSpecifiedForCollectDu .Returns(PlatformArchitecture.X64); _executor.Initialize(invalidString); - _mockOutput.Verify(x => x.WriteLine(string.Format(CultureInfo.CurrentUICulture, CommandLineResources.InvalidBlameArgument, invalidString), OutputLevel.Warning)); + _mockOutput.Verify(x => x.WriteLine(string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidBlameArgument, invalidString), OutputLevel.Warning)); Assert.IsNotNull(_settingsProvider.ActiveRunSettings); Assert.AreEqual(string.Join(Environment.NewLine, @@ -256,7 +256,7 @@ public void InitializeShouldThrowIfInvalidParameterFormatIsSpecifiedForCollectDu [TestMethod] public void InitializeShouldCreateEntryForBlameAlongWithCollectDumpEntryIfEnabled() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(_defaultRunSettings); _settingsProvider.SetActiveRunSettings(runsettings); @@ -297,7 +297,7 @@ public void InitializeShouldCreateEntryForBlameAlongWithCollectDumpEntryIfEnable [TestMethod] public void InitializeShouldCreateEntryForBlameAlongWithCollectDumpParametersIfEnabled() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(_defaultRunSettings); _settingsProvider.SetActiveRunSettings(runsettings); @@ -338,7 +338,7 @@ public void InitializeShouldCreateEntryForBlameAlongWithCollectDumpParametersIfE [TestMethod] public void InitializeShouldCreateEntryForBlameAlongWithCollectHangDumpEntryIfEnabled() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(_defaultRunSettings); _settingsProvider.SetActiveRunSettings(runsettings); @@ -380,7 +380,7 @@ public void InitializeShouldCreateEntryForBlameAlongWithCollectHangDumpEntryIfEn [TestMethod] public void InitializeShouldCreateEntryForBlameAlongWithCollectHangDumpParametersIfEnabled() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(_defaultRunSettings); _settingsProvider.SetActiveRunSettings(runsettings); diff --git a/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs index b13df6dfb9..405fee6e19 100644 --- a/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableCodeCoverageArgumentProcessorTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.CommandLine; using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors; @@ -73,7 +74,7 @@ public void CapabilitiesShouldReturnAppropriateProperties() [TestMethod] public void InitializeShouldSetEnableCodeCoverageOfCommandLineOption() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -89,7 +90,7 @@ public void InitializeShouldSetEnableCodeCoverageOfCommandLineOption() [TestMethod] public void InitializeShouldCreateEntryForCodeCoverageInRunSettingsIfNotAlreadyPresent() { - var runsettingsString = string.Format(_defaultRunSettings, ""); + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); _settingsProvider.SetActiveRunSettings(runsettings); @@ -107,7 +108,7 @@ public void InitializeShouldCreateEntryForCodeCoverageInRunSettingsIfNotAlreadyP [TestMethod] public void InitializeShouldEnableCodeCoverageIfDisabledInRunSettings() { - var runsettingsString = string.Format(_defaultRunSettings, + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); @@ -130,7 +131,7 @@ public void InitializeShouldEnableCodeCoverageIfDisabledInRunSettings() public void InitializeShouldNotDisableOtherDataCollectors() { CollectArgumentExecutor.EnabledDataCollectors.Add("mydatacollector1"); - var runsettingsString = string.Format(_defaultRunSettings, + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); @@ -153,7 +154,7 @@ public void InitializeShouldNotDisableOtherDataCollectors() [TestMethod] public void InitializeShouldNotEnableOtherDataCollectors() { - var runsettingsString = string.Format(_defaultRunSettings, + var runsettingsString = string.Format(CultureInfo.CurrentCulture, _defaultRunSettings, ""); var runsettings = new RunSettings(); runsettings.LoadSettingsXml(runsettingsString); diff --git a/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs index 3bafe85f41..52f1bce87b 100644 --- a/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableDiagArgumentProcessorTests.cs @@ -78,7 +78,7 @@ public void EnableDiagArgumentProcessorMetadataShouldProvideAppropriateCapabilit [DataRow("")] public void EnableDiagArgumentProcessorExecutorThrowsIfDiagArgumentIsNullOrEmpty(string argument) { - string exceptionMessage = string.Format(CultureInfo.CurrentUICulture, CommandLineResources.InvalidDiagArgument, argument); + string exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.InvalidDiagArgument, argument); EnableDiagArgumentProcessorExecutorShouldThrowIfInvalidArgument(argument, exceptionMessage); } diff --git a/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs index 7ae16e5630..40ef827514 100644 --- a/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnableLoggersArgumentProcessorTests.cs @@ -68,7 +68,7 @@ public void ExectorInitializeShouldThrowExceptionIfInvalidArgumentIsPassed(strin } catch (Exception e) { - string exceptionMessage = string.Format(CultureInfo.CurrentUICulture, CommandLineResources.LoggerUriInvalid, argument); + string exceptionMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.LoggerUriInvalid, argument); Assert.IsTrue(e.GetType().Equals(typeof(CommandLineException))); Assert.IsTrue(e.Message.Contains(exceptionMessage)); } diff --git a/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs index 97afb9b54f..99468471bd 100644 --- a/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/EnvironmentArgumentProcessorTests.cs @@ -1,6 +1,7 @@ // Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. +using System.Globalization; using System.Linq; using System.Xml.Linq; @@ -151,8 +152,8 @@ public void ShoudWarnWhenAValueIsOverriden() // Arrange _settingsProvider.UpdateRunSettingsNode("RunConfiguration.EnvironmentVariables.VARIABLE", "Initial value"); - var warningMessage = string.Format(CommandLineResources.CommandLineWarning, - string.Format(CommandLineResources.EnvironmentVariableXIsOverriden, "VARIABLE") + var warningMessage = string.Format(CultureInfo.CurrentCulture, CommandLineResources.CommandLineWarning, + string.Format(CultureInfo.CurrentCulture, CommandLineResources.EnvironmentVariableXIsOverriden, "VARIABLE") ); _mockOutput.Setup(mock => mock.WriteLine( diff --git a/test/vstest.console.UnitTests/Processors/ParentProcessIdArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/ParentProcessIdArgumentProcessorTests.cs index 968d570952..7624740e17 100644 --- a/test/vstest.console.UnitTests/Processors/ParentProcessIdArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/ParentProcessIdArgumentProcessorTests.cs @@ -2,6 +2,7 @@ // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors; using Microsoft.VisualStudio.TestTools.UnitTesting; @@ -87,7 +88,7 @@ public void ExecutorInitializeWithValidPortShouldAddParentProcessIdToCommandLine { var executor = new ParentProcessIdArgumentExecutor(CommandLineOptions.Instance); int parentProcessId = 2345; - executor.Initialize(parentProcessId.ToString()); + executor.Initialize(parentProcessId.ToString(CultureInfo.InvariantCulture)); Assert.AreEqual(parentProcessId, CommandLineOptions.Instance.ParentProcessId); } @@ -97,7 +98,7 @@ public void ExecutorExecuteReturnsArgumentProcessorResultSuccess() var executor = new ParentProcessIdArgumentExecutor(CommandLineOptions.Instance); int parentProcessId = 2345; - executor.Initialize(parentProcessId.ToString()); + executor.Initialize(parentProcessId.ToString(CultureInfo.InvariantCulture)); var result = executor.Execute(); Assert.AreEqual(ArgumentProcessorResult.Success, result); diff --git a/test/vstest.console.UnitTests/Processors/PortArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/PortArgumentProcessorTests.cs index 612028845b..d7a4db5a34 100644 --- a/test/vstest.console.UnitTests/Processors/PortArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/PortArgumentProcessorTests.cs @@ -5,6 +5,7 @@ #if !NET5_0_OR_GREATER using System.Diagnostics; #endif +using System.Globalization; using Microsoft.VisualStudio.TestPlatform.Client.DesignMode; using Microsoft.VisualStudio.TestPlatform.Client.RequestHelper; @@ -100,7 +101,7 @@ public void ExecutorInitializeWithValidPortShouldAddPortToCommandLineOptionsAndI int port = 2345; CommandLineOptions.Instance.ParentProcessId = 0; - _executor.Initialize(port.ToString()); + _executor.Initialize(port.ToString(CultureInfo.InvariantCulture)); Assert.AreEqual(port, CommandLineOptions.Instance.Port); Assert.IsNotNull(DesignModeClient.Instance); @@ -112,7 +113,7 @@ public void ExecutorInitializeShouldSetDesignMode() int port = 2345; CommandLineOptions.Instance.ParentProcessId = 0; - _executor.Initialize(port.ToString()); + _executor.Initialize(port.ToString(CultureInfo.InvariantCulture)); Assert.IsTrue(CommandLineOptions.Instance.IsDesignMode); } @@ -131,7 +132,7 @@ public void ExecutorInitializeShouldSetProcessExitCallback() #endif CommandLineOptions.Instance.ParentProcessId = pid; - _executor.Initialize(port.ToString()); + _executor.Initialize(port.ToString(CultureInfo.InvariantCulture)); _mockProcessHelper.Verify(ph => ph.SetExitCallback(pid, It.IsAny>()), Times.Once); } @@ -143,7 +144,7 @@ public void ExecutorExecuteForValidConnectionReturnsArgumentProcessorResultSucce (parentProcessId, ph) => _testDesignModeClient.Object, _mockProcessHelper.Object); int port = 2345; - _executor.Initialize(port.ToString()); + _executor.Initialize(port.ToString(CultureInfo.InvariantCulture)); var result = _executor.Execute(); _testDesignModeClient.Verify(td => @@ -162,7 +163,7 @@ public void ExecutorExecuteForFailedConnectionShouldThrowCommandLineException() It.IsAny())).Callback(() => throw new TimeoutException()); int port = 2345; - _executor.Initialize(port.ToString()); + _executor.Initialize(port.ToString(CultureInfo.InvariantCulture)); Assert.ThrowsException(() => _executor.Execute()); _testDesignModeClient.Verify(td => td.ConnectToClientAndProcessRequests(port, _testRequestManager.Object), Times.Once); @@ -174,7 +175,7 @@ public void ExecutorExecuteSetsParentProcessIdOnDesignModeInitializer() { var parentProcessId = 2346; var parentProcessIdArgumentExecutor = new ParentProcessIdArgumentExecutor(CommandLineOptions.Instance); - parentProcessIdArgumentExecutor.Initialize(parentProcessId.ToString()); + parentProcessIdArgumentExecutor.Initialize(parentProcessId.ToString(CultureInfo.InvariantCulture)); int actualParentProcessId = -1; _executor = new PortArgumentExecutor(CommandLineOptions.Instance, @@ -188,7 +189,7 @@ public void ExecutorExecuteSetsParentProcessIdOnDesignModeInitializer() ); int port = 2345; - _executor.Initialize(port.ToString()); + _executor.Initialize(port.ToString(CultureInfo.InvariantCulture)); var result = _executor.Execute(); _testDesignModeClient.Verify(td => diff --git a/test/vstest.console.UnitTests/Processors/TestAdapterLoadingStrategyArgumentProcessorTests.cs b/test/vstest.console.UnitTests/Processors/TestAdapterLoadingStrategyArgumentProcessorTests.cs index 967c9343c2..f60d0ffb8d 100644 --- a/test/vstest.console.UnitTests/Processors/TestAdapterLoadingStrategyArgumentProcessorTests.cs +++ b/test/vstest.console.UnitTests/Processors/TestAdapterLoadingStrategyArgumentProcessorTests.cs @@ -53,7 +53,7 @@ public void InitializeShouldHonorEnvironmentVariablesInTestAdapterPaths() var runConfiguration = XmlRunSettingsUtilities.GetRunConfigurationNode(RunSettingsManager.Instance.ActiveRunSettings.SettingsXml); var tempPath = Path.GetFullPath(Environment.ExpandEnvironmentVariables("%temp%")); - Assert.AreEqual(string.Format("{0}\\adapters1;{0}\\adapters2", tempPath), runConfiguration.TestAdaptersPaths); + Assert.AreEqual($"{tempPath}\\adapters1;{tempPath}\\adapters2", runConfiguration.TestAdaptersPaths); } [TestMethod] @@ -71,10 +71,7 @@ public void InitializeShouldAddRightAdapterPathInErrorMessage() mockFileHelper.Setup(x => x.DirectoryExists("c:\\users")).Returns(true); var executor = new TestAdapterLoadingStrategyArgumentExecutor(CommandLineOptions.Instance, RunSettingsManager.Instance, mockOutput.Object, mockFileHelper.Object); - var message = string.Format( - @"The path '{0}' specified in the 'TestAdapterPath' is invalid. Error: {1}", - "d:\\users", - "The custom test adapter search path provided was not found, provide a valid path and try again."); + var message = "The path 'd:\\users' specified in the 'TestAdapterPath' is invalid. Error: The custom test adapter search path provided was not found, provide a valid path and try again."; var isExceptionThrown = false; try @@ -105,10 +102,7 @@ public void InitializeShouldThrowIfPathDoesNotExist() var mockOutput = new Mock(); var executor = new TestAdapterLoadingStrategyArgumentExecutor(CommandLineOptions.Instance, RunSettingsManager.Instance, mockOutput.Object, new FileHelper()); - var message = string.Format( - @"The path '{0}' specified in the 'TestAdapterPath' is invalid. Error: {1}", - folder, - "The custom test adapter search path provided was not found, provide a valid path and try again."); + var message = $"The path '{folder}' specified in the 'TestAdapterPath' is invalid. Error: The custom test adapter search path provided was not found, provide a valid path and try again."; var isExceptionThrown = false;