forked from nunit/nunit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
RegexConstraint.cs
75 lines (68 loc) · 2.49 KB
/
RegexConstraint.cs
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
// Copyright (c) Charlie Poole, Rob Prouse and Contributors. MIT License - see LICENSE.txt
using System.Diagnostics.CodeAnalysis;
using System.Text.RegularExpressions;
namespace NUnit.Framework.Constraints
{
/// <summary>
/// RegexConstraint can test whether a string matches
/// the pattern provided.
/// </summary>
public class RegexConstraint : Constraint
{
private Regex _regex;
/// <summary>
/// The Description of what this constraint tests, for
/// use in messages and in the ConstraintResult.
/// </summary>
public override string Description
{
get
{
var description = $"String matching \"{_regex}\"";
var caseInsensitive = (_regex.Options & RegexOptions.IgnoreCase) == RegexOptions.IgnoreCase;
if (caseInsensitive)
{
description += ", ignoring case";
}
return description;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="RegexConstraint"/> class.
/// </summary>
/// <param name="pattern">The pattern.</param>
public RegexConstraint([StringSyntax(StringSyntaxAttribute.Regex)] string pattern) : base(pattern)
{
_regex = new Regex(pattern);
}
/// <summary>
/// Initializes a new instance of the <see cref="RegexConstraint"/> class.
/// </summary>
/// <param name="regex">The Regex pattern object.</param>
public RegexConstraint(Regex regex) : base(regex.ToString())
{
_regex = regex;
}
/// <summary>
/// Modify the constraint to ignore case in matching.
/// </summary>
public RegexConstraint IgnoreCase
{
get
{
_regex = new Regex(_regex.ToString(), _regex.Options | RegexOptions.IgnoreCase);
return this;
}
}
/// <summary>
/// Applies the regex constraint to an actual value, returning a ConstraintResult.
/// </summary>
/// <param name="actual">The string to be tested.</param>
/// <returns>True for success, false for failure.</returns>
public override ConstraintResult ApplyTo<TActual>(TActual actual)
{
return new ConstraintResult(this, actual,
actual is string actualString && _regex.Match(actualString).Success);
}
}
}