Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
82 changes: 79 additions & 3 deletions src/TestFramework/TestFramework/Assertions/Assert.Matches.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

namespace Microsoft.VisualStudio.TestTools.UnitTesting;
Expand All @@ -7,6 +7,12 @@ namespace Microsoft.VisualStudio.TestTools.UnitTesting;

public sealed partial class Assert
{
// Match the runtime's default static Regex cache size while bounding retained user-provided pattern text.
private const int RegexCacheSize = 15;
private const int MaximumCachedRegexPatternLength = 512;

private static readonly BoundedRegexCache RegexCache = new();

#region MatchesRegex

/// <summary>
Expand Down Expand Up @@ -195,9 +201,79 @@ public static void DoesNotMatchRegex([NotNull] string? pattern, [NotNull] string

#endregion // DoesNotMatchRegex

private static Regex? ToRegex([NotNull] string? pattern)
private static Regex ToRegex([NotNull] string? pattern)
{
CheckParameterNotNull(pattern, "Assert.MatchesRegex", "pattern");
return new Regex(pattern);
if (pattern.Length > MaximumCachedRegexPatternLength)
{
return new Regex(pattern);
}

string cultureName = CultureInfo.CurrentCulture.Name;
if (RegexCache.TryGet(pattern, cultureName, out Regex? cachedRegex))
{
return cachedRegex;
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
}

Regex regex = new(pattern);
return RegexCache.AddOrGetExisting(pattern, cultureName, regex);
}

private sealed class BoundedRegexCache
{
#if NET9_0_OR_GREATER
private readonly Lock _lock = new();
#else
private readonly object _lock = new();
#endif

private readonly RegexCacheEntry?[] _entries = new RegexCacheEntry[RegexCacheSize];

private int _nextInsertionIndex;

public bool TryGet(string pattern, string cultureName, [NotNullWhen(true)] out Regex? regex)
{
int nextInsertionIndex = Volatile.Read(ref _nextInsertionIndex);
for (int offset = 1; offset <= RegexCacheSize; offset++)
{
int index = (nextInsertionIndex - offset + RegexCacheSize) % RegexCacheSize;
RegexCacheEntry? entry = Volatile.Read(ref _entries[index]);
if (entry is not null
&& string.Equals(entry.Pattern, pattern, StringComparison.Ordinal)
&& string.Equals(entry.CultureName, cultureName, StringComparison.Ordinal))
{
regex = entry.Regex;
return true;
}
}

regex = null;
return false;
}

public Regex AddOrGetExisting(string pattern, string cultureName, Regex regex)
{
lock (_lock)
{
if (TryGet(pattern, cultureName, out Regex? cachedRegex))
{
return cachedRegex;
Comment thread
github-code-quality[bot] marked this conversation as resolved.
Fixed
}

int insertionIndex = _nextInsertionIndex;
Volatile.Write(ref _entries[insertionIndex], new RegexCacheEntry(pattern, cultureName, regex));
Volatile.Write(ref _nextInsertionIndex, (insertionIndex + 1) % RegexCacheSize);
return regex;
}
}
}

private sealed class RegexCacheEntry(string pattern, string cultureName, Regex regex)
{
public string Pattern { get; } = pattern;

public string CultureName { get; } = cultureName;

public Regex Regex { get; } = regex;
}
}
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// 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.Text.RegularExpressions;
Expand All @@ -9,6 +9,21 @@ namespace Microsoft.VisualStudio.TestPlatform.TestFramework.UnitTests;

public partial class AssertTests
{
private static readonly int RegexCacheSize =
(int)typeof(Assert)
.GetField("RegexCacheSize", BindingFlags.Static | BindingFlags.NonPublic)!
.GetRawConstantValue()!;

private static readonly int MaximumCachedRegexPatternLength =
(int)typeof(Assert)
.GetField("MaximumCachedRegexPatternLength", BindingFlags.Static | BindingFlags.NonPublic)!
.GetRawConstantValue()!;

private static readonly Func<string?, Regex> ToRegex =
(Func<string?, Regex>)typeof(Assert)
.GetMethod("ToRegex", BindingFlags.Static | BindingFlags.NonPublic)!
.CreateDelegate(typeof(Func<string?, Regex>));

public void MatchesRegex_WithRegexPattern_OnSuccess_DoesNotThrow()
=> FluentActions.Invoking(() => Assert.MatchesRegex(new Regex("^he"), "hello"))
.Should().NotThrow();
Expand All @@ -17,6 +32,105 @@ public void MatchesRegex_WithStringPattern_OnSuccess_DoesNotThrow()
=> FluentActions.Invoking(() => Assert.MatchesRegex("^he", "hello"))
.Should().NotThrow();

public void MatchesRegex_WithRepeatedStringPattern_ReusesRegex()
{
string pattern = $"^{Guid.NewGuid():N}$";

ToRegex(pattern).Should().BeSameAs(ToRegex(pattern));
}
Comment thread
Evangelink marked this conversation as resolved.
Resolved

public void MatchesRegex_WithMoreThanCacheSizeDistinctStringPatterns_EvictsOldestRegex()
{
string patternPrefix = Guid.NewGuid().ToString("N");
string oldestPattern = $"^{patternPrefix}-oldest$";
Regex oldestRegex = ToRegex(oldestPattern);

for (int i = 0; i < RegexCacheSize; i++)
{
_ = ToRegex($"^{patternPrefix}-{i}$");
}

ToRegex(oldestPattern).Should().NotBeSameAs(oldestRegex);
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}

public void MatchesRegex_WithLongStringPattern_DoesNotCacheRegex()
{
string pattern = new('a', MaximumCachedRegexPatternLength + 1);

ToRegex(pattern).Should().NotBeSameAs(ToRegex(pattern));
Comment thread
Evangelink marked this conversation as resolved.
Resolved
}

public void MatchesRegex_WithCultureSensitivePattern_DoesNotReuseRegexAcrossCultures()
{
const string Pattern = "(?i)^i$";
CultureInfo originalCulture = CultureInfo.CurrentCulture;

try
{
CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("en-US");
Regex enUsRegex = ToRegex(Pattern);
enUsRegex.IsMatch("I").Should().BeTrue();

CultureInfo.CurrentCulture = CultureInfo.GetCultureInfo("tr-TR");
Regex trTrRegex = ToRegex(Pattern);
trTrRegex.Should().NotBeSameAs(enUsRegex);
trTrRegex.IsMatch("I").Should().BeFalse();
}
finally
{
CultureInfo.CurrentCulture = originalCulture;
}
}

public void MatchesRegex_WithSameStringPatternConcurrently_ReusesThreadSafeRegex()
{
string pattern = $"^{Guid.NewGuid():N}$";
var regexes = new Regex[64];

Parallel.For(0, regexes.Length, i => regexes[i] = ToRegex(pattern));
Comment thread
Evangelink marked this conversation as resolved.
Resolved

regexes.Should().OnlyContain(regex => ReferenceEquals(regexes[0], regex));
}

public void MatchesRegex_WithInvalidStringPatternAndNullValue_ThrowsPatternExceptionFirst()
{
Action action = () => Assert.MatchesRegex("[", null);

action.Should().Throw<ArgumentException>();
}

public void DoesNotMatchRegex_WithInvalidStringPatternAndNullValue_ThrowsPatternExceptionFirst()
{
Action action = () => Assert.DoesNotMatchRegex("[", null);

action.Should().Throw<ArgumentException>();
}

public void MatchesRegex_WithValidStringPatternAndNullValue_ThrowsAssertFailedException()
{
Action action = () => Assert.MatchesRegex("valid", null);

action.Should().Throw<AssertFailedException>();
}

public void DoesNotMatchRegex_WithValidStringPatternAndNullValue_ThrowsAssertFailedException()
{
Action action = () => Assert.DoesNotMatchRegex("valid", null);

action.Should().Throw<AssertFailedException>();
}

public void MatchesRegex_WithRegexPattern_BypassesStringPatternCache()
{
const string Pattern = "^abc$";
Regex cachedRegex = ToRegex(Pattern);
var suppliedRegex = new Regex(Pattern, RegexOptions.IgnoreCase);

Assert.MatchesRegex(suppliedRegex, "ABC");
ToRegex(Pattern).Should().BeSameAs(cachedRegex);
suppliedRegex.Should().NotBeSameAs(cachedRegex);
}

public void MatchesRegex_WithRegexPattern_OnFailure_UsesStructuredMessageAndPayload()
{
Action action = () => Assert.MatchesRegex(new Regex("^foo"), "hello", "User-provided message");
Expand Down
Loading