Skip to content

Commit 50b5130

Browse files
authored
Skip regex for wildcard-only and literal tree node filter segments (#12330)
1 parent 6721315 commit 50b5130

4 files changed

Lines changed: 248 additions & 7 deletions

File tree

‎src/Platform/Microsoft.Testing.Platform/InternalAPI/InternalAPI.Unshipped.txt‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,8 @@ Microsoft.Testing.Platform.Helpers.SystemFileStream.SystemFileStream(System.IO.F
7979
*REMOVED*Microsoft.Testing.Platform.Extensions.Messages.TestRequestExecutionTimeInfo.TestRequestExecutionTimeInfo(Microsoft.Testing.Platform.Extensions.Messages.TimingInfo timingInfo) -> void
8080
*REMOVED*Microsoft.Testing.Platform.Extensions.Messages.TestRequestExecutionTimeInfo.TimingInfo.get -> Microsoft.Testing.Platform.Extensions.Messages.TimingInfo
8181
*REMOVED*Microsoft.Testing.Platform.Requests.TestHostTestFrameworkInvoker.DataTypesProduced.get -> System.Type![]!
82+
*REMOVED*Microsoft.Testing.Platform.Requests.ValueExpression.Regex.get -> System.Text.RegularExpressions.Regex!
83+
Microsoft.Testing.Platform.Requests.ValueExpression.IsMatch(string! input) -> bool
8284
*REMOVED*override Microsoft.Testing.Platform.Extensions.Messages.TestRequestExecutionTimeInfo.ToString() -> string!
8385
Microsoft.Testing.Platform.OutputDevice.Terminal.TerminalTestReporter.AssemblyRunNotSelected(string! assembly, string? targetFramework, string? architecture) -> void
8486
Microsoft.Testing.Platform.TestHostControllers.ITestHostControllerRunCompletionHandler

‎src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/TreeNodeFilter.Matching.cs‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ private static bool MatchFilterPattern(
8787
switch (filterExpression)
8888
{
8989
case ValueExpression vExpr:
90-
return vExpr.Regex.IsMatch(testNodeFragment);
90+
return vExpr.IsMatch(testNodeFragment);
9191
case OperatorExpression { Op: FilterOperator.Or, SubExpressions: var subexprs }:
9292
for (int i = 0; i < subexprs.Count; i++)
9393
{
@@ -169,8 +169,8 @@ private static bool MatchProperties(
169169

170170
private static bool IsMatchingProperty(IProperty prop, ValueExpression propExpr, ValueExpression valueExpr)
171171
=> prop is TestMetadataProperty testMetadataProperty &&
172-
propExpr.Regex.IsMatch(testMetadataProperty.Key) &&
173-
valueExpr.Regex.IsMatch(testMetadataProperty.Value);
172+
propExpr.IsMatch(testMetadataProperty.Key) &&
173+
valueExpr.IsMatch(testMetadataProperty.Value);
174174

175175
private static bool HasPropertyFilterExpression(FilterExpression expression)
176176
{

‎src/Platform/Microsoft.Testing.Platform/Requests/TreeNodeFilter/ValueExpression.cs‎

Lines changed: 137 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,143 @@
44
namespace Microsoft.Testing.Platform.Requests;
55

66
// An expression representing a single value.
7-
[DebuggerDisplay("{Regex}")]
8-
internal sealed class ValueExpression(string value) : FilterExpression
7+
[DebuggerDisplay("{Value}")]
8+
internal sealed class ValueExpression : FilterExpression
99
{
10-
public string Value { get; } = value;
10+
private readonly CultureInfo _culture;
11+
private readonly bool _matchesAnyValue;
12+
private readonly string? _asciiLiteral;
13+
private Regex? _regex;
1114

12-
public Regex Regex { get; } = new Regex($"^{value}$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
15+
public ValueExpression(string value)
16+
{
17+
Value = value;
18+
19+
// The regex captures the current culture for case-insensitive matching when it's created.
20+
// It's created lazily, so capture the culture here to keep matching independent of the calling thread.
21+
_culture = CultureInfo.CurrentCulture;
22+
23+
// Most filter segments are either a lone wildcard or a plain name. Both can be matched without
24+
// a regex, which avoids the cost of constructing and compiling one for every run that uses a filter.
25+
_matchesAnyValue = IsOnlyWildcards(value);
26+
if (!_matchesAnyValue && !ContainsWildcard(value) && !HasTurkishCasing(_culture))
27+
{
28+
string literal = Regex.Unescape(value);
29+
if (IsAscii(literal))
30+
{
31+
_asciiLiteral = literal;
32+
}
33+
}
34+
}
35+
36+
// The value, as a regex pattern: every character is escaped, except wildcards which are '.*'.
37+
public string Value { get; }
38+
39+
public bool IsMatch(string input)
40+
{
41+
// '.' doesn't match '\n' and '$' matches before a final '\n', so leave those inputs to the regex.
42+
if (input.IndexOf('\n') < 0)
43+
{
44+
if (_matchesAnyValue)
45+
{
46+
return true;
47+
}
48+
49+
#if NETCOREAPP
50+
if (_asciiLiteral is not null)
51+
#else
52+
// On .NET Framework, the regex also uses the current culture when matching.
53+
if (_asciiLiteral is not null && !HasTurkishCasing(CultureInfo.CurrentCulture))
54+
#endif
55+
{
56+
if (input.Length != _asciiLiteral.Length)
57+
{
58+
return false;
59+
}
60+
61+
// Outside of ASCII, the regex has case equivalences that an ordinal comparison doesn't (e.g. 'K' and the Kelvin sign).
62+
if (IsAscii(input))
63+
{
64+
return string.Equals(input, _asciiLiteral, StringComparison.OrdinalIgnoreCase);
65+
}
66+
}
67+
}
68+
69+
return GetRegex().IsMatch(input);
70+
}
71+
72+
private Regex GetRegex()
73+
{
74+
if (_regex is not null)
75+
{
76+
return _regex;
77+
}
78+
79+
CultureInfo currentCulture = CultureInfo.CurrentCulture;
80+
CultureInfo.CurrentCulture = _culture;
81+
try
82+
{
83+
Regex regex = new($"^{Value}$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
84+
return Interlocked.CompareExchange(ref _regex, regex, null) ?? regex;
85+
}
86+
finally
87+
{
88+
CultureInfo.CurrentCulture = currentCulture;
89+
}
90+
}
91+
92+
private static bool IsOnlyWildcards(string value)
93+
{
94+
if (value.Length == 0 || value.Length % 2 != 0)
95+
{
96+
return false;
97+
}
98+
99+
for (int i = 0; i < value.Length; i += 2)
100+
{
101+
if (value[i] != '.' || value[i + 1] != '*')
102+
{
103+
return false;
104+
}
105+
}
106+
107+
return true;
108+
}
109+
110+
private static bool ContainsWildcard(string value)
111+
{
112+
for (int i = 0; i < value.Length; i++)
113+
{
114+
if (value[i] == '\\')
115+
{
116+
// Skip the escaped character.
117+
i++;
118+
}
119+
else if (value[i] == '.')
120+
{
121+
// A literal '.' is always escaped, so this is the start of a '.*' wildcard.
122+
return true;
123+
}
124+
}
125+
126+
return false;
127+
}
128+
129+
// In these cultures 'i' and 'I' aren't case-insensitively equal, so an ordinal comparison would differ from the regex.
130+
private static bool HasTurkishCasing(CultureInfo culture)
131+
=> culture.Name.StartsWith("tr", StringComparison.OrdinalIgnoreCase)
132+
|| culture.Name.StartsWith("az", StringComparison.OrdinalIgnoreCase);
133+
134+
private static bool IsAscii(string value)
135+
{
136+
foreach (char c in value)
137+
{
138+
if (c > 0x7F)
139+
{
140+
return false;
141+
}
142+
}
143+
144+
return true;
145+
}
13146
}

‎test/UnitTests/Microsoft.Testing.Platform.UnitTests/Requests/TreeNodeFilterTests.cs‎

Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -48,6 +48,112 @@ public void MatchWildcard_MatchesSubstrings()
4848
Assert.IsFalse(filter.MatchesFilter("/ProjectB.FunctionalTests", new PropertyBag()));
4949
}
5050

51+
[TestMethod]
52+
public void LiteralSegment_IsCaseInsensitive()
53+
{
54+
TreeNodeFilter filter = new("/MyAssembly/*/MyClass");
55+
Assert.IsTrue(filter.MatchesFilter("/MyAssembly/MyNamespace/MyClass", new PropertyBag()));
56+
Assert.IsTrue(filter.MatchesFilter("/MYASSEMBLY/MyNamespace/myclass", new PropertyBag()));
57+
Assert.IsFalse(filter.MatchesFilter("/MyAssembly/MyNamespace/MyClass2", new PropertyBag()));
58+
Assert.IsFalse(filter.MatchesFilter("/MyAssembly/MyNamespace/MyKlass", new PropertyBag()));
59+
}
60+
61+
[TestMethod]
62+
public void LiteralSegment_WithEscapedCharacters_MatchesExactly()
63+
{
64+
TreeNodeFilter filter = new("/My.Assembly/Method\\(1, 2\\)");
65+
Assert.IsTrue(filter.MatchesFilter("/My.Assembly/Method(1, 2)", new PropertyBag()));
66+
Assert.IsTrue(filter.MatchesFilter("/my.assembly/method(1, 2)", new PropertyBag()));
67+
Assert.IsFalse(filter.MatchesFilter("/MyXAssembly/Method(1, 2)", new PropertyBag()));
68+
Assert.IsFalse(filter.MatchesFilter("/My.Assembly/Method(1, 3)", new PropertyBag()));
69+
}
70+
71+
[TestMethod]
72+
public void LiteralSegment_NonAsciiCaseEquivalence_MatchesLikeRegex()
73+
{
74+
// The Kelvin sign (U+212A) is case-insensitively equal to 'K' and 'k' in a regex, but not in an ordinal comparison.
75+
TreeNodeFilter filter = new("/Kelvin");
76+
Assert.IsTrue(filter.MatchesFilter("/\u212Aelvin", new PropertyBag()));
77+
Assert.IsFalse(filter.MatchesFilter("/\u212Belvin", new PropertyBag()));
78+
79+
TreeNodeFilter nonAsciiFilter = new("/\u00C9t\u00E9");
80+
Assert.IsTrue(nonAsciiFilter.MatchesFilter("/\u00E9T\u00C9", new PropertyBag()));
81+
Assert.IsFalse(nonAsciiFilter.MatchesFilter("/Ete", new PropertyBag()));
82+
}
83+
84+
[TestMethod]
85+
public void Segment_WithNewLine_MatchesLikeRegex()
86+
{
87+
// '$' matches before a final new line, and '.' doesn't match a new line.
88+
Assert.IsTrue(new TreeNodeFilter("/A").MatchesFilter("/A\n", new PropertyBag()));
89+
Assert.IsFalse(new TreeNodeFilter("/A").MatchesFilter("/A\nB", new PropertyBag()));
90+
Assert.IsTrue(new TreeNodeFilter("/*").MatchesFilter("/A\n", new PropertyBag()));
91+
Assert.IsFalse(new TreeNodeFilter("/*").MatchesFilter("/A\nB", new PropertyBag()));
92+
}
93+
94+
[TestMethod]
95+
public void LiteralSegment_TurkishCulture_MatchesLikeRegex()
96+
{
97+
CultureInfo originalCulture = CultureInfo.CurrentCulture;
98+
try
99+
{
100+
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
101+
TreeNodeFilter filter = new("/file");
102+
bool regexMatches = new Regex("^file$", RegexOptions.IgnoreCase).IsMatch("FILE");
103+
104+
Assert.AreEqual(regexMatches, filter.MatchesFilter("/FILE", new PropertyBag()));
105+
Assert.IsTrue(filter.MatchesFilter("/file", new PropertyBag()));
106+
}
107+
finally
108+
{
109+
CultureInfo.CurrentCulture = originalCulture;
110+
}
111+
}
112+
113+
[TestMethod]
114+
public void LiteralSegment_CultureChangedToTurkishAfterConstruction_MatchesLikeRegex()
115+
{
116+
CultureInfo originalCulture = CultureInfo.CurrentCulture;
117+
try
118+
{
119+
CultureInfo.CurrentCulture = new CultureInfo("en-US");
120+
TreeNodeFilter filter = new("/file");
121+
Regex regex = new("^file$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
122+
123+
// On .NET Framework, the regex uses the current culture when matching, so 'I' no longer matches 'i'.
124+
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
125+
126+
Assert.AreEqual(regex.IsMatch("FILE"), filter.MatchesFilter("/FILE", new PropertyBag()));
127+
Assert.IsTrue(filter.MatchesFilter("/file", new PropertyBag()));
128+
}
129+
finally
130+
{
131+
CultureInfo.CurrentCulture = originalCulture;
132+
}
133+
}
134+
135+
[TestMethod]
136+
public void WildcardSegment_CultureChangedToTurkishBeforeFirstMatch_MatchesLikeRegex()
137+
{
138+
CultureInfo originalCulture = CultureInfo.CurrentCulture;
139+
try
140+
{
141+
CultureInfo.CurrentCulture = new CultureInfo("en-US");
142+
TreeNodeFilter filter = new("/FILE*");
143+
Regex regex = new("^FILE.*$", RegexOptions.IgnoreCase | RegexOptions.Compiled);
144+
145+
// The filter's regex is created on first use, but must still use the culture the filter was created under.
146+
CultureInfo.CurrentCulture = new CultureInfo("tr-TR");
147+
148+
Assert.IsTrue(regex.IsMatch("file1"));
149+
Assert.IsTrue(filter.MatchesFilter("/file1", new PropertyBag()));
150+
}
151+
finally
152+
{
153+
CultureInfo.CurrentCulture = originalCulture;
154+
}
155+
}
156+
51157
[TestMethod]
52158
public void EscapeSequences_SupportsWildcard()
53159
{

0 commit comments

Comments
 (0)