Skip to content

Commit 8d12bc1

Browse files
Use RegexGenerator in applicable tests (#66179)
1 parent f5ebdf8 commit 8d12bc1

File tree

16 files changed

+78
-90
lines changed

16 files changed

+78
-90
lines changed

src/libraries/System.Configuration.ConfigurationManager/tests/Mono/ConfigurationErrorsExceptionTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public void Constructor1()
4949
// \p{Pi} any kind of opening quote https://www.compart.com/en/unicode/category/Pi
5050
// \p{Pf} any kind of closing quote https://www.compart.com/en/unicode/category/Pf
5151
// \p{Po} any kind of punctuation character that is not a dash, bracket, quote or connector https://www.compart.com/en/unicode/category/Po
52-
Assert.True(Regex.IsMatch(cee.BareMessage, @"[\p{Pi}\p{Po}]" + Regex.Escape(typeof(ConfigurationErrorsException).FullName) + @"[\p{Pf}\p{Po}]"), "#2:" + cee.BareMessage);
52+
Assert.Matches(@"[\p{Pi}\p{Po}]" + Regex.Escape(typeof(ConfigurationErrorsException).FullName) + @"[\p{Pf}\p{Po}]", cee.BareMessage);
5353

5454
Assert.NotNull(cee.Data);
5555
Assert.Equal(0, cee.Data.Count);

src/libraries/System.Diagnostics.StackTrace/tests/StackTraceTests.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -340,7 +340,7 @@ public void ToString_ShowILOffset()
340340
catch (Exception e)
341341
{
342342
Assert.Contains(asmName, e.InnerException.StackTrace);
343-
Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success);
343+
Assert.Matches(p, e.InnerException.StackTrace);
344344
}
345345
}, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose();
346346

@@ -357,7 +357,7 @@ public void ToString_ShowILOffset()
357357
catch (Exception e)
358358
{
359359
Assert.Contains(asmName, e.InnerException.StackTrace);
360-
Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success);
360+
Assert.Matches(p, e.InnerException.StackTrace);
361361
}
362362
}, SourceTestAssemblyPath, AssemblyName, regPattern).Dispose();
363363

@@ -381,7 +381,7 @@ public void ToString_ShowILOffset()
381381
catch (Exception e)
382382
{
383383
Assert.Contains("RefEmit_InMemoryManifestModule", e.InnerException.StackTrace);
384-
Assert.True(Regex.Match(e.InnerException.StackTrace, p).Success);
384+
Assert.Matches(p, e.InnerException.StackTrace);
385385
}
386386
}, regPattern).Dispose();
387387
}

src/libraries/System.Diagnostics.Tracing/tests/BasicEventSourceTest/TestsUserErrors.cs

Lines changed: 20 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ private void Test_BadTypes_Manifest(EventSource source)
5151

5252
string message = _event.PayloadString(0, "message");
5353
// expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. "
54-
Assert.Matches("Unsupported type", message);
54+
Assert.Contains("Unsupported type", message);
5555
}
5656
}
5757
finally
@@ -126,7 +126,7 @@ private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, Eve
126126
Debug.WriteLine(string.Format("Message=\"{0}\"", message));
127127
// expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. "
128128
if (!PlatformDetection.IsNetFramework) // .NET Framework has typo
129-
Assert.Matches("Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent", message);
129+
Assert.Contains("Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent", message);
130130

131131
// Validate the details of the EventWrittenEventArgs object
132132
if (_event is EventListenerListener.EventListenerEvent elEvent)
@@ -158,46 +158,28 @@ public void Test_Bad_WriteRelatedID_ParameterName()
158158
#if true
159159
Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet.");
160160
#else
161-
BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null;
162-
EventListenerListener listener = null;
163-
try
164-
{
165-
Guid oldGuid;
166-
Guid newGuid = Guid.NewGuid();
167-
Guid newGuid2 = Guid.NewGuid();
168-
EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid);
169-
170-
bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter();
161+
Guid oldGuid;
162+
Guid newGuid = Guid.NewGuid();
163+
Guid newGuid2 = Guid.NewGuid();
164+
EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid);
171165

172-
using (var listener = new EventListenerListener())
173-
{
174-
var events = new List<Event>();
175-
listener.OnEvent = delegate (Event data) { events.Add(data); };
166+
using (var bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter())
167+
using (var listener = new EventListenerListener())
168+
{
169+
var events = new List<Event>();
170+
listener.OnEvent = delegate (Event data) { events.Add(data); };
176171

177-
listener.EventSourceCommand(bes.Name, EventCommand.Enable);
172+
listener.EventSourceCommand(bes.Name, EventCommand.Enable);
178173

179-
bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB");
174+
bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB");
180175

181-
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
182-
Assert.Equal(1, events.Count);
183-
Event _event = events[0];
184-
Assert.Equal("EventSourceMessage", _event.EventName);
185-
string message = _event.PayloadString(0, "message");
186-
// expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId."
187-
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."));
188-
}
189-
}
190-
finally
191-
{
192-
if (bes != null)
193-
{
194-
bes.Dispose();
195-
}
196-
197-
if (listener != null)
198-
{
199-
listener.Dispose();
200-
}
176+
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
177+
Assert.Equal(1, events.Count);
178+
Event _event = events[0];
179+
Assert.Equal("EventSourceMessage", _event.EventName);
180+
string message = _event.PayloadString(0, "message");
181+
// expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId."
182+
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);
201183
}
202184
#endif
203185
}

src/libraries/System.IO.Pipelines/tests/PipeReaderWriterFacts.cs

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
using System.Linq;
77
using System.Runtime.CompilerServices;
88
using System.Text;
9-
using System.Text.RegularExpressions;
109
using System.Threading;
1110
using System.Threading.Tasks;
1211
using Xunit;

src/libraries/System.Linq.Expressions/tests/CompilerTests.cs

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,6 @@
33

44
using System.Runtime.CompilerServices;
55
using System.Text.RegularExpressions;
6-
using System.Threading;
76
using Xunit;
87

98
namespace System.Linq.Expressions.Tests
@@ -385,15 +384,15 @@ internal static void VerifyIL(this LambdaExpression expression, string expected,
385384

386385
private static string Normalize(string s)
387386
{
387+
var normalizeRegex = new Regex(@"lambda_method[0-9]*");
388+
388389
Collections.Generic.IEnumerable<string> lines =
389390
s
390-
.Replace("\r\n", "\n")
391-
.Split(new[] { '\n' })
392-
.Select(line => line.Trim())
393-
.Where(line => line != "" && !line.StartsWith("//"));
391+
.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries)
392+
.Where(line => !line.StartsWith("//"))
393+
.Select(beforeLambdaUniquifierRemoval => normalizeRegex.Replace(beforeLambdaUniquifierRemoval, "lambda_method"));
394394

395-
string beforeLambdaUniquifierRemoval = string.Join("\n", lines);
396-
return Regex.Replace(beforeLambdaUniquifierRemoval, "lambda_method[0-9]*", "lambda_method");
395+
return string.Join("\n", lines);
397396
}
398397

399398
private static void VerifyEmitConstantsToIL<T>(T value)

src/libraries/System.Linq.Expressions/tests/DelegateType/GetDelegateTypeTests.cs

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33

44
using System.Runtime.CompilerServices;
5-
using System.Text.RegularExpressions;
65
using Xunit;
76

87
namespace System.Linq.Expressions.Tests
@@ -66,8 +65,8 @@ public void CantBeFunc(Type[] typeArgs)
6665
{
6766
Type delType = Expression.GetDelegateType(typeArgs);
6867
Assert.True(typeof(MulticastDelegate).IsAssignableFrom(delType));
69-
Assert.DoesNotMatch(new Regex(@"System\.Action"), delType.FullName);
70-
Assert.DoesNotMatch(new Regex(@"System\.Func"), delType.FullName);
68+
Assert.DoesNotContain("System.Action", delType.FullName);
69+
Assert.DoesNotContain("System.Func", delType.FullName);
7170
Reflection.MethodInfo method = delType.GetMethod("Invoke");
7271
Assert.Equal(typeArgs.Last(), method.ReturnType);
7372
Assert.Equal(typeArgs.Take(typeArgs.Length - 1), method.GetParameters().Select(p => p.ParameterType));
@@ -92,8 +91,8 @@ public void CantBeAction(Type[] typeArgs)
9291
{
9392
Type delType = Expression.GetDelegateType(delegateArgs);
9493
Assert.True(typeof(MulticastDelegate).IsAssignableFrom(delType));
95-
Assert.DoesNotMatch(new Regex(@"System\.Action"), delType.FullName);
96-
Assert.DoesNotMatch(new Regex(@"System\.Func"), delType.FullName);
94+
Assert.DoesNotContain("System.Action", delType.FullName);
95+
Assert.DoesNotContain("System.Func", delType.FullName);
9796
Reflection.MethodInfo method = delType.GetMethod("Invoke");
9897
Assert.Equal(typeof(void), method.ReturnType);
9998
Assert.Equal(typeArgs, method.GetParameters().Select(p => p.ParameterType));

src/libraries/System.Private.DataContractSerialization/src/System.Private.DataContractSerialization.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
<!-- Too much private reflection. Do not bother with trimming -->
77
<ILLinkTrimAssembly>false</ILLinkTrimAssembly>
88
<Nullable>enable</Nullable>
9+
<EnableRegexGenerator>true</EnableRegexGenerator>
910
</PropertyGroup>
1011
<PropertyGroup>
1112
<RuntimeSerializationSources>System\Runtime\Serialization</RuntimeSerializationSources>

src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/DataContract.cs

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2215,7 +2215,7 @@ internal static bool IsAssemblyFriendOfSerialization(Assembly assembly)
22152215
string internalsVisibleAttributeAssemblyName = internalsVisibleAttribute.AssemblyName;
22162216

22172217
if (internalsVisibleAttributeAssemblyName.Trim().Equals("System.Runtime.Serialization") ||
2218-
Regex.IsMatch(internalsVisibleAttributeAssemblyName, Globals.FullSRSInternalsVisiblePattern))
2218+
Globals.FullSRSInternalsVisibleRegex().IsMatch(internalsVisibleAttributeAssemblyName))
22192219
{
22202220
return true;
22212221
}
@@ -2238,7 +2238,8 @@ internal interface IGenericNameProvider
22382238
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
22392239
string GetNamespaces();
22402240
string GetGenericTypeName();
2241-
bool ParametersFromBuiltInNamespaces {
2241+
bool ParametersFromBuiltInNamespaces
2242+
{
22422243
[RequiresUnreferencedCode(DataContract.SerializerTrimmerWarning)]
22432244
get;
22442245
}

src/libraries/System.Private.DataContractSerialization/src/System/Runtime/Serialization/Globals.cs

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -9,13 +9,14 @@
99
using System.Diagnostics.CodeAnalysis;
1010
using System.IO;
1111
using System.Reflection;
12+
using System.Text.RegularExpressions;
1213
using System.Xml;
1314
using System.Xml.Schema;
1415
using System.Xml.Serialization;
1516

1617
namespace System.Runtime.Serialization
1718
{
18-
internal static class Globals
19+
internal static partial class Globals
1920
{
2021
/// <SecurityNote>
2122
/// 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)
831832
public static readonly string NewObjectId = string.Empty;
832833
public const string NullObjectId = null;
833834
public const string FullSRSInternalsVisiblePattern = @"^[\s]*System\.Runtime\.Serialization[\s]*,[\s]*PublicKey[\s]*=[\s]*(?i:00240000048000009400000006020000002400005253413100040000010001008d56c76f9e8649383049f383c44be0ec204181822a6c31cf5eb7ef486944d032188ea1d3920763712ccb12d75fb77e9811149e6148e5d32fbaab37611c1878ddc19e20ef135d0cb2cff2bfec3d115810c3d9069638fe4be215dbf795861920e5ab6f7db2e2ceef136ac23d5dd2bf031700aec232f6c6b1c785b4305c123b37ab)[\s]*$";
835+
[RegexGenerator(FullSRSInternalsVisiblePattern)]
836+
public static partial Regex FullSRSInternalsVisibleRegex();
834837
public const string Space = " ";
835838
public const string XsiPrefix = "i";
836839
public const string XsdPrefix = "x";

src/libraries/System.Runtime.Extensions/tests/System/IO/PathTests_Windows.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -328,8 +328,8 @@ public static void GetFullPath_Windows_83Paths()
328328

329329
// Make sure the shortened name expands back to the original one
330330
// Sometimes shortening or GetFullPath is changing the casing of "temp" on some test machines: normalize both sides
331-
tempFilePath = Regex.Replace(tempFilePath, @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase);
332-
shortName = Regex.Replace(Path.GetFullPath(shortName), @"\\temp\\", @"\TEMP\", RegexOptions.IgnoreCase);
331+
tempFilePath = tempFilePath.Replace(@"\\temp\\", @"\TEMP\", ignoreCase: true, culture: null);
332+
shortName = Path.GetFullPath(shortName).Replace(@"\\temp\\", @"\TEMP\", ignoreCase: true, culture: null);
333333
Assert.Equal(tempFilePath, shortName);
334334

335335
// Should work with device paths that aren't well-formed extended syntax

src/libraries/System.Runtime/tests/System.Runtime.Tests.csproj

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99
<Nullable>disable</Nullable>
1010
<!-- Disable nullability public only feature for NullabilityInfoContextTests -->
1111
<Features>$(Features.Replace('nullablePublicOnly', '')</Features>
12+
<EnableRegexGenerator>true</EnableRegexGenerator>
1213
</PropertyGroup>
1314
<PropertyGroup>
1415
<DefineConstants Condition="'$(FeatureGenericMath)' == 'true'">$(DefineConstants);FEATURE_GENERIC_MATH</DefineConstants>

src/libraries/System.Runtime/tests/System/ExceptionTests.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ public static void Exception_TargetSite()
7878

7979
Assert.True(caught);
8080
}
81-
81+
8282
static void RethrowException()
8383
{
8484
try
@@ -136,7 +136,7 @@ private static (string, string, int) ThrowAndRethrowSameMethod(out (string, stri
136136
}
137137
}
138138

139-
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))]
139+
[ConditionalFact(typeof(PlatformDetection), nameof(PlatformDetection.IsNotArm64Process))]
140140
// [ActiveIssue(https://github.com/dotnet/runtime/issues/1871)] can't use ActiveIssue for archs
141141
[ActiveIssue("https://github.com/mono/mono/issues/15141", TestRuntimes.Mono)]
142142
public static void ThrowStatementDoesNotResetExceptionStackLineOtherMethod()
@@ -198,7 +198,7 @@ private static void VerifyCallStack(
198198
var match = Regex.Match(frame, frameParserRegex);
199199
Assert.True(match.Success);
200200
Assert.Equal(expectedStackFrame.CallerMemberName, match.Groups["memberName"].Value);
201-
201+
202202
if (PlatformDetection.IsLineNumbersSupported)
203203
{
204204
Assert.Equal(expectedStackFrame.SourceFilePath, match.Groups["filePath"].Value);

src/libraries/System.Runtime/tests/System/Runtime/ExceptionServices/ExceptionDispatchInfoTests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ public static void StaticThrow_UpdatesStackTraceAppropriately()
2424
for (int i = 0; i < 3; i++)
2525
{
2626
Assert.Same(e, Assert.Throws<FormatException>(() => ExceptionDispatchInfo.Throw(e)));
27-
Assert.Equal(i, Regex.Matches(e.StackTrace, RethrowMessageSubstring).Count);
27+
Assert.Equal(i, Regex.Count(e.StackTrace, RethrowMessageSubstring));
2828
}
2929
}
3030

src/libraries/System.Runtime/tests/System/Text/Unicode/Utf8Tests.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ static Utf8Tests()
6262

6363
public static byte[] DecodeHex(ReadOnlySpan<char> inputHex)
6464
{
65-
Assert.True(Regex.IsMatch(inputHex.ToString(), "^([0-9a-fA-F]{2})*$"), "Input must be an even number of hex characters.");
65+
Assert.Matches(@"^([0-9a-fA-F]{2})*$", inputHex.ToString());
6666

6767
return Convert.FromHexString(inputHex);
6868
}

0 commit comments

Comments
 (0)