forked from dotnet/runtime
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRegex.Ctor.Tests.cs
More file actions
293 lines (257 loc) · 15.1 KB
/
Regex.Ctor.Tests.cs
File metadata and controls
293 lines (257 loc) · 15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Threading;
using Microsoft.DotNet.RemoteExecutor;
using Xunit;
namespace System.Text.RegularExpressions.Tests
{
public class RegexConstructorTests
{
public static IEnumerable<object[]> Ctor_TestData()
{
if (PlatformDetection.IsNetCore)
{
yield return new object[] { "foo", RegexHelpers.RegexOptionNonBacktracking, Regex.InfiniteMatchTimeout };
yield return new object[] { "foo", RegexHelpers.RegexOptionNonBacktracking, new TimeSpan(1) };
}
yield return new object[] { "foo", RegexOptions.None, Regex.InfiniteMatchTimeout };
yield return new object[] { "foo", RegexOptions.RightToLeft, Regex.InfiniteMatchTimeout };
yield return new object[] { "foo", RegexOptions.Compiled, Regex.InfiniteMatchTimeout };
yield return new object[] { "foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant, Regex.InfiniteMatchTimeout };
yield return new object[] { "foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Compiled, Regex.InfiniteMatchTimeout };
yield return new object[] { "foo", RegexOptions.None, new TimeSpan(1) };
yield return new object[] { "foo", RegexOptions.None, TimeSpan.FromMilliseconds(int.MaxValue - 1) };
}
[Theory]
[MemberData(nameof(Ctor_TestData))]
public static void Ctor(string pattern, RegexOptions options, TimeSpan matchTimeout)
{
if (matchTimeout == Regex.InfiniteMatchTimeout)
{
if (options == RegexOptions.None)
{
Regex regex1 = new Regex(pattern);
Assert.Equal(pattern, regex1.ToString());
Assert.Equal(options, regex1.Options);
Assert.False(regex1.RightToLeft);
Assert.Equal(matchTimeout, regex1.MatchTimeout);
}
Regex regex2 = new Regex(pattern, options);
Assert.Equal(pattern, regex2.ToString());
Assert.Equal(options, regex2.Options);
Assert.Equal((options & RegexOptions.RightToLeft) != 0, regex2.RightToLeft);
Assert.Equal(matchTimeout, regex2.MatchTimeout);
}
Regex regex3 = new Regex(pattern, options, matchTimeout);
Assert.Equal(pattern, regex3.ToString());
Assert.Equal(options, regex3.Options);
Assert.Equal((options & RegexOptions.RightToLeft) != 0, regex3.RightToLeft);
Assert.Equal(matchTimeout, regex3.MatchTimeout);
}
public static IEnumerable<object[]> NoneCompiledBacktracking()
{
yield return new object[] { RegexOptions.None };
yield return new object[] { RegexOptions.Compiled };
if (PlatformDetection.IsNetCore)
{
yield return new object[] { RegexHelpers.RegexOptionNonBacktracking };
}
}
[Theory]
[MemberData(nameof(NoneCompiledBacktracking))]
public void CtorDebugInvoke(RegexOptions options)
{
Regex r;
r = new Regex("[abc]def(ghi|jkl)", options | RegexHelpers.RegexOptionDebug);
Assert.False(r.Match("a").Success);
Assert.True(r.Match("adefghi").Success);
string repl = r.Replace("123adefghi78bdefjkl9", "###");
Assert.Equal("123###78###9", repl);
r = new Regex("(ghi|jkl)*ghi", options | RegexHelpers.RegexOptionDebug);
Assert.False(r.Match("jkl").Success);
Assert.True(r.Match("ghi").Success);
Assert.Equal("123456789", r.Replace("123ghi789", "456"));
r = new Regex("(ghi|jkl)*ghi", options | RegexHelpers.RegexOptionDebug, TimeSpan.FromDays(1));
Assert.False(r.Match("jkl").Success);
Assert.True(r.Match("ghi").Success);
Assert.Equal("123456789", r.Replace("123ghi789", "456"));
}
[Fact]
public static void Ctor_Invalid()
{
if (PlatformDetection.IsNetCore)
{
// NonBacktracking option is not supported together with these other options
Assert.Throws<NotSupportedException>(() => new Regex("abc", RegexOptions.ECMAScript | RegexHelpers.RegexOptionNonBacktracking));
Assert.Throws<NotSupportedException>(() => new Regex("abc", RegexOptions.RightToLeft | RegexHelpers.RegexOptionNonBacktracking));
// NonBacktracking option is not supported for these constructs
Assert.Throws<NotSupportedException>(() => new Regex("(?=a)", RegexHelpers.RegexOptionNonBacktracking));
Assert.Throws<NotSupportedException>(() => new Regex("(?!a)", RegexHelpers.RegexOptionNonBacktracking));
Assert.Throws<NotSupportedException>(() => new Regex("(?<=a)", RegexHelpers.RegexOptionNonBacktracking));
Assert.Throws<NotSupportedException>(() => new Regex("(?<!a)", RegexHelpers.RegexOptionNonBacktracking));
Assert.Throws<NotSupportedException>(() => new Regex(@"(?(0)ab)", RegexHelpers.RegexOptionNonBacktracking));
Assert.Throws<NotSupportedException>(() => new Regex(@"([ab])\1", RegexHelpers.RegexOptionNonBacktracking));
}
// Pattern is null
AssertExtensions.Throws<ArgumentNullException>("pattern", () => new Regex(null));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => new Regex(null, RegexOptions.None));
AssertExtensions.Throws<ArgumentNullException>("pattern", () => new Regex(null, RegexOptions.None, new TimeSpan()));
// Options are invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)(-1)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)(-1), new TimeSpan()));
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)0x800));
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", (RegexOptions)0x800, new TimeSpan()));
if (PlatformDetection.IsNetFramework)
{
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexHelpers.RegexOptionNonBacktracking));
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexHelpers.RegexOptionNonBacktracking, new TimeSpan()));
}
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.RightToLeft));
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.ExplicitCapture));
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.Singleline));
AssertExtensions.Throws<ArgumentOutOfRangeException>("options", () => new Regex("foo", RegexOptions.ECMAScript | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.CultureInvariant | RegexOptions.IgnorePatternWhitespace));
// MatchTimeout is invalid
AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, new TimeSpan(-1)));
AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, TimeSpan.Zero));
AssertExtensions.Throws<ArgumentOutOfRangeException>("matchTimeout", () => new Regex("foo", RegexOptions.None, TimeSpan.FromMilliseconds(int.MaxValue)));
}
/// <summary>
/// Nonsupported cases for the NonBacktracking option
/// </summary>
public static IEnumerable<object[]> Ctor_Invalid_NonBacktracking_Data()
{
yield return new object[] { @"(?<cat-0>cat)", RegexOptions.None, "balancing group" };
yield return new object[] { @"(?<cat>cat)\w+(?<dog-0>dog)", RegexOptions.None, "balancing group"};
yield return new object[] { @"(?<cat>cat)\w+(?<dog-cat>dog)", RegexOptions.None, "balancing group" };
yield return new object[] { @"abc", RegexOptions.RightToLeft, "RightToLeft" };
yield return new object[] { @"abc", RegexOptions.ECMAScript, "ECMAScript" };
yield return new object[] { @"^(a)?(?(1)a|b)+$", RegexOptions.None, "conditional" };
yield return new object[] { @"(abc)\1", RegexOptions.None, "backreference" };
yield return new object[] { @"a(?=d).", RegexOptions.None, "positive lookahead" };
yield return new object[] { @"a(?!b).", RegexOptions.None, "negative lookahead" };
yield return new object[] { @"(?<=a)b", RegexOptions.None, "positive lookbehind" };
yield return new object[] { @"(?<!c)b", RegexOptions.None, "negative lookbehind" };
yield return new object[] { @"(?>(abc)*).", RegexOptions.None, "atomic" };
yield return new object[] { @"\G(\w+\s?\w*),?", RegexOptions.None, "contiguous" };
yield return new object[] { @"(?>a*).", RegexOptions.None, "atomic" };
yield return new object[] { @"(?(A)B|C)", RegexOptions.None, "conditional" };
}
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Doesn't support NonBacktracking")]
[Theory]
[MemberData(nameof(Ctor_Invalid_NonBacktracking_Data))]
public void Ctor_Invalid_NonBacktracking(string pattern, RegexOptions options, string expected_word_in_error_message)
{
string actual = string.Empty;
try
{
new Regex(pattern, options | RegexHelpers.RegexOptionNonBacktracking);
}
catch (NotSupportedException e)
{
actual = e.Message;
}
Assert.Contains(expected_word_in_error_message, actual);
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void StaticCtor_InvalidTimeoutObject_ExceptionThrown()
{
RemoteExecutor.Invoke(() =>
{
AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, true);
Assert.Throws<TypeInitializationException>(() => Regex.InfiniteMatchTimeout);
}).Dispose();
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
public static void StaticCtor_InvalidTimeoutRange_ExceptionThrown()
{
RemoteExecutor.Invoke(() =>
{
AppDomain.CurrentDomain.SetData(RegexHelpers.DefaultMatchTimeout_ConfigKeyName, TimeSpan.Zero);
Assert.Throws<TypeInitializationException>(() => Regex.InfiniteMatchTimeout);
}).Dispose();
}
[Fact]
public void InitializeReferences_OnlyInvokedOnce()
{
var r = new DerivedRegex();
r.InitializeReferences();
if (PlatformDetection.IsNetFramework)
{
Assert.Throws<NotSupportedException>(() => r.InitializeReferences());
}
else
{
// As of .NET 7, this method is a nop.
r.InitializeReferences();
}
}
[Fact]
public void Ctor_CapNames_ReturnsDefaultValues()
{
var r = new DerivedRegex(@"(?<Name>\w*)");
Assert.Null(r.Caps);
IDictionary capNames = r.CapNames;
Assert.NotNull(capNames);
Assert.Same(capNames, r.CapNames);
Assert.True(capNames.Contains("Name"));
AssertExtensions.Throws<ArgumentNullException>("value", () => r.Caps = null);
AssertExtensions.Throws<ArgumentNullException>("value", () => r.CapNames = null);
r.Caps = new Dictionary<string, string>();
Assert.IsType<Hashtable>(r.Caps);
r.CapNames = new Dictionary<string, string>();
Assert.IsType<Hashtable>(r.CapNames);
var newHashtable = new Hashtable();
r.CapNames = newHashtable;
Assert.Same(newHashtable, r.CapNames);
r.Caps = newHashtable;
Assert.Same(newHashtable, r.Caps);
}
private sealed class DerivedRegex : Regex
{
public DerivedRegex() { }
public DerivedRegex(string pattern) : base(pattern) { }
public new void InitializeReferences() => base.InitializeReferences();
public new IDictionary Caps { get => base.Caps; set => base.Caps = value; }
public new IDictionary CapNames { get => base.CapNames; set => base.CapNames = value; }
}
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void Serialization_ThrowsNotSupported()
{
var r = new SerializableDerivedRegex();
Assert.Throws<PlatformNotSupportedException>(() => new SerializableDerivedRegex(default, default));
Assert.Throws<PlatformNotSupportedException>(() => ((ISerializable)r).GetObjectData(default, default));
}
[Serializable]
private sealed class SerializableDerivedRegex : Regex
{
public SerializableDerivedRegex() : base("") { }
public SerializableDerivedRegex(SerializationInfo info, StreamingContext context) : base(info, context) { }
}
[ConditionalFact(typeof(RemoteExecutor), nameof(RemoteExecutor.IsSupported))]
[SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework)]
public void Ctor_PatternInName()
{
RemoteExecutor.Invoke(() =>
{
// Just make sure setting the environment variable doesn't cause problems.
Environment.SetEnvironmentVariable("DOTNET_SYSTEM_TEXT_REGULAREXPRESSIONS_PATTERNINNAME", "1");
// Short pattern
var r = new Regex("abc", RegexOptions.Compiled);
Assert.True(r.IsMatch("123abc456"));
// Long pattern
string pattern = string.Concat(Enumerable.Repeat("1234567890", 20));
r = new Regex(pattern, RegexOptions.Compiled);
Assert.True(r.IsMatch("abc" + pattern + "abc"));
}).Dispose();
}
}
}