diff --git a/src/libraries/System.Configuration.ConfigurationManager/tests/Mono/ConfigurationErrorsExceptionTest.cs b/src/libraries/System.Configuration.ConfigurationManager/tests/Mono/ConfigurationErrorsExceptionTest.cs index 328bc11427da71..147265c36adb74 100644 --- a/src/libraries/System.Configuration.ConfigurationManager/tests/Mono/ConfigurationErrorsExceptionTest.cs +++ b/src/libraries/System.Configuration.ConfigurationManager/tests/Mono/ConfigurationErrorsExceptionTest.cs @@ -49,7 +49,7 @@ public void Constructor1() // \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi // \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf // \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po - Assert.True(Regex.IsMatch(cee.BareMessage, @"[\p{Pi}\p{Po}]" + Regex.Escape(typeof(ConfigurationErrorsException).FullName) + @"[\p{Pf}\p{Po}]"), "#2:" + cee.BareMessage); + Assert.Matches(@"[\p{Pi}\p{Po}]" + Regex.Escape(typeof(ConfigurationErrorsException).FullName) + @"[\p{Pf}\p{Po}]", cee.BareMessage); Assert.NotNull(cee.Data); Assert.Equal(0, cee.Data.Count); diff --git a/src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs b/src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs index 604a34dc8cd2a1..e4f909176df160 100644 --- a/src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs +++ b/src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs @@ -340,7 +340,7 @@ public void ToString_ShowILOffset() catch (Exception e) { Assert.Contains(asmName, e.InnerException.StackTrace); - Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success); + Assert.Matches(p, e.InnerException.StackTrace); } }, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose(); @@ -357,7 +357,7 @@ public void ToString_ShowILOffset() catch (Exception e) { Assert.Contains(asmName, e.InnerException.StackTrace); - Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success); + Assert.Matches(p, e.InnerException.StackTrace); } }, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose(); @@ -381,7 +381,7 @@ public void ToString_ShowILOffset() catch (Exception e) { Assert.Contains("RefEmit_InMemoryManifestModule", e.InnerException.StackTrace); - Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success); + Assert.Matches(p, e.InnerException.StackTrace); } }, regPattern).Dispose(); } diff --git a/src/libraries/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs b/src/libraries/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs index 307365529e077d..0b2f2c2986fbae 100644 --- a/src/libraries/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs +++ b/src/libraries/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs @@ -51,7 +51,7 @@ private void Test_BadTypes_Manifest(EventSource source) string message = _event.PayloadString(0, "message"); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. " - Assert.Matches("Unsupported type", message); + Assert.Contains("Unsupported type", message); } } finally @@ -126,7 +126,7 @@ private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, Eve Debug.WriteLine(string.Format("Message=\"{0}\"", message)); // expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. " if (!PlatformDetection.IsNetFramework) // .NET Framework has typo - Assert.Matches("Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent", message); + Assert.Contains("Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent", message); // Validate the details of the EventWrittenEventArgs object if (_event is EventListenerListener.EventListenerEvent elEvent) @@ -158,46 +158,28 @@ public void Test_Bad_WriteRelatedID_ParameterName() #if true Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet."); #else - BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null; - EventListenerListener listener = null; - try - { - Guid oldGuid; - Guid newGuid = Guid.NewGuid(); - Guid newGuid2 = Guid.NewGuid(); - EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid); - - bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter(); + Guid oldGuid; + Guid newGuid = Guid.NewGuid(); + Guid newGuid2 = Guid.NewGuid(); + EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid); - using (var listener = new EventListenerListener()) - { - var events = new List(); - listener.OnEvent = delegate (Event data) { events.Add(data); }; + using (var bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter()) + using (var listener = new EventListenerListener()) + { + var events = new List(); + listener.OnEvent = delegate (Event data) { events.Add(data); }; - listener.EventSourceCommand(bes.Name, EventCommand.Enable); + listener.EventSourceCommand(bes.Name, EventCommand.Enable); - bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB"); + bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB"); - // Confirm that we get exactly one event from this whole process, that has the error message we expect. - Assert.Equal(1, events.Count); - Event _event = events[0]; - Assert.Equal("EventSourceMessage", _event.EventName); - string message = _event.PayloadString(0, "message"); - // expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId." - Assert.True(Regex.IsMatch(message, "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId.")); - } - } - finally - { - if (bes != null) - { - bes.Dispose(); - } - - if (listener != null) - { - listener.Dispose(); - } + // Confirm that we get exactly one event from this whole process, that has the error message we expect. + Assert.Equal(1, events.Count); + Event _event = events[0]; + Assert.Equal("EventSourceMessage", _event.EventName); + string message = _event.PayloadString(0, "message"); + // expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId." + Assert.Contains("EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId.", message); } #endif } diff --git a/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs b/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs index 331216e30f322c..1a325e466a7abf 100644 --- a/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs +++ b/src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs @@ -6,7 +6,6 @@ using System.Linq; using System.Runtime.CompilerServices; using System.Text; -using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Xunit; diff --git a/src/libraries/System.Linq.Expressions/tests/CompilerTests.cs b/src/libraries/System.Linq.Expressions/tests/CompilerTests.cs index 18cd5b02400b2b..1093a8235fc441 100644 --- a/src/libraries/System.Linq.Expressions/tests/CompilerTests.cs +++ b/src/libraries/System.Linq.Expressions/tests/CompilerTests.cs @@ -3,7 +3,6 @@ using System.Runtime.CompilerServices; using System.Text.RegularExpressions; -using System.Threading; using Xunit; namespace System.Linq.Expressions.Tests @@ -385,15 +384,15 @@ internal static void VerifyIL(this LambdaExpression expression, string expected, private static string Normalize(string s) { + var normalizeRegex = new Regex(@"lambda_method[0-9]*"); + Collections.Generic.IEnumerable lines = s - .Replace("\r\n", "\n") - .Split(new[] { '\n' }) - .Select(line => line.Trim()) - .Where(line => line != "" && !line.StartsWith("//")); + .Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries) + .Where(line => !line.StartsWith("//")) + .Select(beforeLambdaUniquifierRemoval => normalizeRegex.Replace(beforeLambdaUniquifierRemoval, "lambda_method")); - string beforeLambdaUniquifierRemoval = string.Join("\n", lines); - return Regex.Replace(beforeLambdaUniquifierRemoval, "lambda_method[0-9]*", "lambda_method"); + return string.Join("\n", lines); } private static void VerifyEmitConstantsToIL(T value) diff --git a/src/libraries/System.Linq.Expressions/tests/DelegateType/GetDelegateTypeTests.cs b/src/libraries/System.Linq.Expressions/tests/DelegateType/GetDelegateTypeTests.cs index a627772d7e6804..cb9be2d5c5ce1d 100644 --- a/src/libraries/System.Linq.Expressions/tests/DelegateType/GetDelegateTypeTests.cs +++ b/src/libraries/System.Linq.Expressions/tests/DelegateType/GetDelegateTypeTests.cs @@ -2,7 +2,6 @@ // The .NET Foundation licenses this file to you under the MIT license. using System.Runtime.CompilerServices; -using System.Text.RegularExpressions; using Xunit; namespace System.Linq.Expressions.Tests @@ -66,8 +65,8 @@ public void CantBeFunc(Type[] typeArgs) { Type delType = Expression.GetDelegateType(typeArgs); Assert.True(typeof(MulticastDelegate).IsAssignableFrom(delType)); - Assert.DoesNotMatch(new Regex(@"System\.Action"), delType.FullName); - Assert.DoesNotMatch(new Regex(@"System\.Func"), delType.FullName); + Assert.DoesNotContain("System.Action", delType.FullName); + Assert.DoesNotContain("System.Func", delType.FullName); Reflection.MethodInfo method = delType.GetMethod("Invoke"); Assert.Equal(typeArgs.Last(), method.ReturnType); Assert.Equal(typeArgs.Take(typeArgs.Length - 1), method.GetParameters().Select(p => p.ParameterType)); @@ -92,8 +91,8 @@ public void CantBeAction(Type[] typeArgs) { Type delType = Expression.GetDelegateType(delegateArgs); Assert.True(typeof(MulticastDelegate).IsAssignableFrom(delType)); - Assert.DoesNotMatch(new Regex(@"System\.Action"), delType.FullName); - Assert.DoesNotMatch(new Regex(@"System\.Func"), delType.FullName); + Assert.DoesNotContain("System.Action", delType.FullName); + Assert.DoesNotContain("System.Func", delType.FullName); Reflection.MethodInfo method = delType.GetMethod("Invoke"); Assert.Equal(typeof(void), method.ReturnType); Assert.Equal(typeArgs, method.GetParameters().Select(p => p.ParameterType)); diff --git a/src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj b/src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj index 1e407a2091bc08..9c04bf5b2a8fb6 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj +++ b/src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj @@ -6,6 +6,7 @@ false enable + true System\Runtime\Serialization diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs index 4480e5f7cb3d6f..94259b2b79d940 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs @@ -2215,7 +2215,7 @@ internal static bool IsAssemblyFriendOfSerialization(Assembly assembly) string internalsVisibleAttributeAssemblyName = internalsVisibleAttribute.AssemblyName; if (internalsVisibleAttributeAssemblyName.Trim().Equals("System.Runtime.Serialization") || - Regex.IsMatch(internalsVisibleAttributeAssemblyName, Globals.FullSRSInternalsVisiblePattern)) + Globals.FullSRSInternalsVisibleRegex().IsMatch(internalsVisibleAttributeAssemblyName)) { return true; } @@ -2238,7 +2238,8 @@ internal interface IGenericNameProvider [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] string GetNamespaces(); string GetGenericTypeName(); - bool ParametersFromBuiltInNamespaces { + bool ParametersFromBuiltInNamespaces + { [RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)] get; } diff --git a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs index a0c64b678bc0e2..318466eb273598 100644 --- a/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs +++ b/src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs @@ -9,13 +9,14 @@ using System.Diagnostics.CodeAnalysis; using System.IO; using System.Reflection; +using System.Text.RegularExpressions; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; namespace System.Runtime.Serialization { - internal static class Globals + internal static partial class Globals { /// /// Review - changes to const could affect code generation logic; any changes should be reviewed. @@ -831,6 +832,8 @@ internal static bool TypeOfScriptObject_IsAssignableFrom(Type type) public static readonly string NewObjectId = string.Empty; public const string NullObjectId = null; public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$"; + [RegexGenerator(FullSRSInternalsVisiblePattern)] + public static partial Regex FullSRSInternalsVisibleRegex(); public const string Space = " "; public const string XsiPrefix = "i"; public const string XsdPrefix = "x"; diff --git a/src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests_Windows.cs b/src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests_Windows.cs index 9f53541319f9a2..ff3d240114b8fe 100644 --- a/src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests_Windows.cs +++ b/src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests_Windows.cs @@ -328,8 +328,8 @@ public static void GetFullPath_Windows_83Paths() // Make sure the shortened name expands back to the original one // Sometimes shortening or GetFullPath is changing the casing of "temp" on some test machines: normalize both sides - tempFilePath = Regex.Replace(tempFilePath, @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase); - shortName = Regex.Replace(Path.GetFullPath(shortName), @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase); + tempFilePath = tempFilePath.Replace(@"\\temp\\", @"\TEMP\", ignoreCase: true, culture: null); + shortName = Path.GetFullPath(shortName).Replace(@"\\temp\\", @"\TEMP\", ignoreCase: true, culture: null); Assert.Equal(tempFilePath, shortName); // Should work with device paths that aren't well-formed extended syntax diff --git a/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj b/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj index c45a71ac87238e..6cb7fdaf327cde 100644 --- a/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj +++ b/src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj @@ -9,6 +9,7 @@ disable $(Features.Replace('nullablePublicOnly', '') + true $(DefineConstants);FEATURE_GENERIC_MATH diff --git a/src/libraries/System.Runtime/tests/System/ExceptionTests.cs b/src/libraries/System.Runtime/tests/System/ExceptionTests.cs index ffc9c36636e89d..6c51eeec19c881 100644 --- a/src/libraries/System.Runtime/tests/System/ExceptionTests.cs +++ b/src/libraries/System.Runtime/tests/System/ExceptionTests.cs @@ -78,7 +78,7 @@ public static void Exception_TargetSite() Assert.True(caught); } - + static void RethrowException() { try @@ -136,7 +136,7 @@ private static (string, string, int) ThrowAndRethrowSameMethod(out (string, stri } } - [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] + [ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))] // [ActiveIssue(https://github.com/dotnet/runtime/issues/1871)] can't use ActiveIssue for archs [ActiveIssue("https://github.com/mono/mono/issues/15141", TestRuntimes.Mono)] public static void ThrowStatementDoesNotResetExceptionStackLineOtherMethod() @@ -198,7 +198,7 @@ private static void VerifyCallStack( var match = Regex.Match(frame, frameParserRegex); Assert.True(match.Success); Assert.Equal(expectedStackFrame.CallerMemberName, match.Groups["memberName"].Value); - + if (PlatformDetection.IsLineNumbersSupported) { Assert.Equal(expectedStackFrame.SourceFilePath, match.Groups["filePath"].Value); diff --git a/src/libraries/System.Runtime/tests/System/Runtime/ExceptionServices/ExceptionDispatchInfoTests.cs b/src/libraries/System.Runtime/tests/System/Runtime/ExceptionServices/ExceptionDispatchInfoTests.cs index 6029e99c1b836f..38685512a480c1 100644 --- a/src/libraries/System.Runtime/tests/System/Runtime/ExceptionServices/ExceptionDispatchInfoTests.cs +++ b/src/libraries/System.Runtime/tests/System/Runtime/ExceptionServices/ExceptionDispatchInfoTests.cs @@ -24,7 +24,7 @@ public static void StaticThrow_UpdatesStackTraceAppropriately() for (int i = 0; i < 3; i++) { Assert.Same(e, Assert.Throws(() => ExceptionDispatchInfo.Throw(e))); - Assert.Equal(i, Regex.Matches(e.StackTrace, RethrowMessageSubstring).Count); + Assert.Equal(i, Regex.Count(e.StackTrace, RethrowMessageSubstring)); } } diff --git a/src/libraries/System.Runtime/tests/System/Text/Unicode/Utf8Tests.cs b/src/libraries/System.Runtime/tests/System/Text/Unicode/Utf8Tests.cs index d675b3f8431ceb..6db4ba15cba375 100644 --- a/src/libraries/System.Runtime/tests/System/Text/Unicode/Utf8Tests.cs +++ b/src/libraries/System.Runtime/tests/System/Text/Unicode/Utf8Tests.cs @@ -62,7 +62,7 @@ static Utf8Tests() public static byte[] DecodeHex(ReadOnlySpan inputHex) { - Assert.True(Regex.IsMatch(inputHex.ToString(), "^([0-9a-fA-F]{2})*$"), "Input must be an even number of hex characters."); + Assert.Matches(@"^([0-9a-fA-F]{2})*$", inputHex.ToString()); return Convert.FromHexString(inputHex); } diff --git a/src/libraries/System.Runtime/tests/System/TimeZoneInfoTests.cs b/src/libraries/System.Runtime/tests/System/TimeZoneInfoTests.cs index e3e5bdd4564f30..b28ad1d9882bea 100644 --- a/src/libraries/System.Runtime/tests/System/TimeZoneInfoTests.cs +++ b/src/libraries/System.Runtime/tests/System/TimeZoneInfoTests.cs @@ -86,7 +86,7 @@ public static void Names() // Due to ICU size limitations, full daylight/standard names are not included for the browser. // Name abbreviations, if available, are used instead - public static IEnumerable Platform_TimeZoneNamesTestData() + public static IEnumerable Platform_TimeZoneNamesTestData() { if (PlatformDetection.IsBrowser || PlatformDetection.IsiOS || PlatformDetection.IstvOS) return new TheoryData @@ -189,7 +189,7 @@ public static void TestYukonTZ() TimeZoneInfo yukon = TimeZoneInfo.FindSystemTimeZoneById("Yukon Standard Time"); // First, ensure we have the updated data - TimeZoneInfo.AdjustmentRule [] rules = yukon.GetAdjustmentRules(); + TimeZoneInfo.AdjustmentRule[] rules = yukon.GetAdjustmentRules(); if (rules.Length <= 0 || rules[rules.Length - 1].DateStart.Year != 2021 || rules[rules.Length - 1].DateEnd.Year != 9999) { return; @@ -213,7 +213,7 @@ public static void TestYukonTZ() { // Some Windows versions don't carry the complete TZ data. Ignore the tests on such versions. } - } + } [Fact] public static void RussianTimeZone() @@ -2192,7 +2192,7 @@ public static void ConvertTimeFromToUtc_UnixOnly() { // if the time is ambiguous this will not round trip the original value because this ambiguous time can be mapped into // 2 UTC times. usually we return the value with the DST delta added to it. - back = back.AddTicks(- london.GetAdjustmentRules()[0].DaylightDelta.Ticks); + back = back.AddTicks(-london.GetAdjustmentRules()[0].DaylightDelta.Ticks); } Assert.Equal(utc, back); @@ -2224,7 +2224,7 @@ public static void CreateCustomTimeZone_Invalid() VerifyCustomTimeZoneException("", new TimeSpan(0), null, null); // empty string Id VerifyCustomTimeZoneException("mytimezone", new TimeSpan(0, 0, 55), null, null); // offset not minutes VerifyCustomTimeZoneException("mytimezone", new TimeSpan(14, 1, 0), null, null); // offset too big - VerifyCustomTimeZoneException("mytimezone", - new TimeSpan(14, 1, 0), null, null); // offset too small + VerifyCustomTimeZoneException("mytimezone", -new TimeSpan(14, 1, 0), null, null); // offset too small } [Fact] @@ -2325,7 +2325,9 @@ public static IEnumerable SystemTimeZonesTestData() } private const string IanaAbbreviationPattern = @"^(?:[A-Z][A-Za-z]+|[+-]\d{2}|[+-]\d{4})$"; - private static readonly Regex s_IanaAbbreviationRegex = new Regex(IanaAbbreviationPattern); + + [RegexGenerator(IanaAbbreviationPattern)] + private static partial Regex IanaAbbreviationRegex(); // UTC aliases per https://github.com/unicode-org/cldr/blob/master/common/bcp47/timezone.xml // (This list is not likely to change.) @@ -2341,7 +2343,7 @@ public static IEnumerable SystemTimeZonesTestData() }; // On Android GMT, GMT+0, and GMT-0 are values - private static readonly string[] s_GMTAliases = new [] { + private static readonly string[] s_GMTAliases = new[] { "GMT", "GMT0", "GMT+0", @@ -2375,9 +2377,9 @@ public static void TimeZoneDisplayNames_Unix(TimeZoneInfo timeZone) else { // For other time zones, match any valid IANA time zone abbreviation, including numeric forms - Assert.True(s_IanaAbbreviationRegex.IsMatch(timeZone.StandardName), + Assert.True(IanaAbbreviationRegex().IsMatch(timeZone.StandardName), $"Id: \"{timeZone.Id}\", StandardName should have matched the pattern @\"{IanaAbbreviationPattern}\", Actual StandardName: \"{timeZone.StandardName}\""); - Assert.True(s_IanaAbbreviationRegex.IsMatch(timeZone.DaylightName), + Assert.True(IanaAbbreviationRegex().IsMatch(timeZone.DaylightName), $"Id: \"{timeZone.Id}\", DaylightName should have matched the pattern @\"{IanaAbbreviationPattern}\", Actual DaylightName: \"{timeZone.DaylightName}\""); } } @@ -2472,7 +2474,7 @@ public static void GetSystemTimeZones_AllTimeZonesHaveOffsetInValidRange() } } - private static byte [] timeZoneFileContents = new byte[] + private static byte[] timeZoneFileContents = new byte[] { 0x54, 0x5A, 0x69, 0x66, 0x32, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, @@ -2510,14 +2512,14 @@ public static void NJulianRuleTest(string posixRule, int dayNumber, int monthNum fs.WriteByte(0x0A); foreach (char c in posixRule) { - fs.WriteByte((byte) c); + fs.WriteByte((byte)c); } fs.WriteByte(0x0A); } try { - ProcessStartInfo psi = new ProcessStartInfo() { UseShellExecute = false }; + ProcessStartInfo psi = new ProcessStartInfo() { UseShellExecute = false }; psi.Environment.Add("TZ", zoneFilePath); RemoteExecutor.Invoke((day, month, succeed) => @@ -2526,7 +2528,7 @@ public static void NJulianRuleTest(string posixRule, int dayNumber, int monthNum int d = int.Parse(day); int m = int.Parse(month); - TimeZoneInfo.AdjustmentRule [] rules = TimeZoneInfo.Local.GetAdjustmentRules(); + TimeZoneInfo.AdjustmentRule[] rules = TimeZoneInfo.Local.GetAdjustmentRules(); if (expectedToSucceed) { @@ -2538,7 +2540,7 @@ public static void NJulianRuleTest(string posixRule, int dayNumber, int monthNum { Assert.Equal(0, rules.Length); } - }, dayNumber.ToString(), monthNumber.ToString(), shouldSucceed.ToString(), new RemoteInvokeOptions { StartInfo = psi}).Dispose(); + }, dayNumber.ToString(), monthNumber.ToString(), shouldSucceed.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose(); } finally { @@ -2551,7 +2553,7 @@ public static void TimeZoneInfo_LocalZoneWithInvariantMode() { string hostTZId = TimeZoneInfo.Local.Id; - ProcessStartInfo psi = new ProcessStartInfo() { UseShellExecute = false }; + ProcessStartInfo psi = new ProcessStartInfo() { UseShellExecute = false }; psi.Environment.Add("DOTNET_SYSTEM_GLOBALIZATION_INVARIANT", PlatformDetection.IsInvariantGlobalization ? "0" : "1"); RemoteExecutor.Invoke((tzId, hostIsRunningInInvariantMode) => @@ -2567,7 +2569,7 @@ public static void TimeZoneInfo_LocalZoneWithInvariantMode() Assert.Equal(tzId, TimeZoneInfo.Local.Id); - }, hostTZId, PlatformDetection.IsInvariantGlobalization.ToString(), new RemoteInvokeOptions { StartInfo = psi}).Dispose(); + }, hostTZId, PlatformDetection.IsInvariantGlobalization.ToString(), new RemoteInvokeOptions { StartInfo = psi }).Dispose(); } [Fact] @@ -2598,16 +2600,17 @@ public static void TimeZoneInfo_DisplayNameStartsWithOffset(TimeZoneInfo tzi) else { Assert.False(string.IsNullOrWhiteSpace(tzi.StandardName)); - Assert.Matches(@"^\(UTC(\+|-)[0-9]{2}:[0-9]{2}\) \S.*", tzi.DisplayName); + Match match = Regex.Match(tzi.DisplayName, @"^\(UTC(?\+|-)(?[0-9]{2}:[0-9]{2})\) \S.*", RegexOptions.ExplicitCapture); + Assert.True(match.Success); // see https://github.com/dotnet/corefx/pull/33204#issuecomment-438782500 if (PlatformDetection.IsNotWindowsNanoServer && !PlatformDetection.IsWindows7) { - string offset = Regex.Match(tzi.DisplayName, @"(-|)[0-9]{2}:[0-9]{2}").Value; + string offset = (match.Groups["sign"].Value == "-" ? "-" : "") + match.Groups["amount"].Value; TimeSpan ts = TimeSpan.Parse(offset); if (PlatformDetection.IsWindows && tzi.BaseUtcOffset != ts && - (tzi.Id.Contains("Morocco") || tzi.Id.Contains("Volgograd"))) + (tzi.Id.Contains("Morocco") || tzi.Id.Contains("Volgograd"))) { // Windows data can report display name with UTC+01:00 offset which is not matching the actual BaseUtcOffset. // We special case this in the test to avoid the test failures like: @@ -2662,8 +2665,8 @@ public static void UsingAlternativeTimeZoneIdsTest(string windowsId, string iana TimeZoneInfo tzi1 = TimeZoneInfo.FindSystemTimeZoneById(ianaId); TimeZoneInfo tzi2 = TimeZoneInfo.FindSystemTimeZoneById(windowsId); - Assert.Equal(tzi1.BaseUtcOffset, tzi2.BaseUtcOffset); - Assert.NotEqual(tzi1.Id, tzi2.Id); + Assert.Equal(tzi1.BaseUtcOffset, tzi2.BaseUtcOffset); + Assert.NotEqual(tzi1.Id, tzi2.Id); } else { @@ -3175,7 +3178,7 @@ private static unsafe int EnumUiLanguagesCallback(char* lpUiLanguageString, IntP try { var handle = GCHandle.FromIntPtr(lParam); - var list = (List) handle.Target; + var list = (List)handle.Target; list!.Add(CultureInfo.GetCultureInfo(cultureName)); return 1; } diff --git a/src/libraries/System.Runtime/tests/System/Uri.CreateStringTests.cs b/src/libraries/System.Runtime/tests/System/Uri.CreateStringTests.cs index 5e475a63d0d611..78a248caa198d0 100644 --- a/src/libraries/System.Runtime/tests/System/Uri.CreateStringTests.cs +++ b/src/libraries/System.Runtime/tests/System/Uri.CreateStringTests.cs @@ -553,14 +553,14 @@ public static IEnumerable Path_Query_Fragment_TestData() yield return new object[] { @"file:///path1\path2/path3\path4", "/path1/path2/path3/path4", "", "" }; yield return new object[] { @"file:///path1\path2/path3%5Cpath4\", "/path1/path2/path3/path4/", "", "" }; yield return new object[] { @"file://localhost/path1\path2/path3\path4\", "/path1/path2/path3/path4/", "", "" }; - yield return new object[] { @"file://localhost/path1%5Cpath2", "/path1/path2", "", ""}; + yield return new object[] { @"file://localhost/path1%5Cpath2", "/path1/path2", "", "" }; } else // Unix paths preserve backslash { yield return new object[] { @"file:///path1\path2/path3\path4", @"/path1%5Cpath2/path3%5Cpath4", "", "" }; - yield return new object[] { @"file:///path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", "", ""}; + yield return new object[] { @"file:///path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", "", "" }; yield return new object[] { @"file://localhost/path1\path2/path3\path4\", @"/path1%5Cpath2/path3%5Cpath4%5C", "", "" }; - yield return new object[] { @"file://localhost/path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", "", ""}; + yield return new object[] { @"file://localhost/path1%5Cpath2\path3", @"/path1%5Cpath2%5Cpath3", "", "" }; } // Implicit file with empty path yield return new object[] { "C:/", "C:/", "", "" };