/
TestFilterParser.cs
307 lines (244 loc) · 10 KB
/
TestFilterParser.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
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
// ***********************************************************************
// Copyright (c) 2020 Charlie Poole, Terje Sandstrom
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
// ***********************************************************************
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
// Missing XML Docs
#pragma warning disable 1591
namespace NUnit.VisualStudio.TestAdapter.TestFilterConverter
{
public class TestFilterParser
{
private Tokenizer _tokenizer;
private static readonly Token LPAREN = new (TokenKind.Symbol, "(");
private static readonly Token RPAREN = new (TokenKind.Symbol, ")");
private static readonly Token AND_OP = new (TokenKind.Symbol, "&");
private static readonly Token OR_OP = new (TokenKind.Symbol, "|");
private static readonly Token NOT_OP = new (TokenKind.Symbol, "!");
private static readonly Token EQ_OP = new (TokenKind.Symbol, "=");
private static readonly Token NE_OP = new (TokenKind.Symbol, "!=");
private static readonly Token CONTAINS_OP = new (TokenKind.Symbol, "~");
private static readonly Token NOTCONTAINS_OP = new (TokenKind.Symbol, "!~");
private static readonly Token[] AND_OPS = { AND_OP };
private static readonly Token[] OR_OPS = { OR_OP };
private static readonly Token[] EQ_OPS = { EQ_OP };
private static readonly Token[] REL_OPS = { EQ_OP, NE_OP, CONTAINS_OP, NOTCONTAINS_OP };
private static readonly Token EOF = new (TokenKind.Eof);
public string Parse(string input)
{
_tokenizer = new Tokenizer(input);
if (_tokenizer.LookAhead == EOF)
throw new TestFilterParserException("No input provided for test selection.");
var result = ParseFilterExpression();
Expect(EOF);
result = $"<filter>{result}</filter>";
return result;
}
/// <summary>
/// Parse a single term or an or expression, returning the xml.
/// </summary>
public string ParseFilterExpression()
{
var terms = new List<string> { ParseFilterTerm() };
while (LookingAt(OR_OPS))
{
NextToken();
terms.Add(ParseFilterTerm());
}
if (terms.Count == 1)
return terms[0];
var sb = new StringBuilder("<or>");
foreach (var term in terms)
sb.Append(term);
sb.Append("</or>");
return sb.ToString();
}
/// <summary>
/// Parse a single element or an and expression and return the xml.
/// </summary>
public string ParseFilterTerm()
{
var elements = new List<string> { ParseFilterCondition() };
while (LookingAt(AND_OPS))
{
NextToken();
elements.Add(ParseFilterCondition());
}
if (elements.Count == 1)
return elements[0];
var sb = new StringBuilder("<and>");
foreach (var element in elements)
sb.Append(element);
sb.Append("</and>");
return sb.ToString();
}
/// <summary>
/// Parse a single filter element such as a category expression
/// and return the xml representation of the filter.
/// </summary>
public string ParseFilterCondition()
{
if (LookingAt(LPAREN, NOT_OP))
return ParseExpressionInParentheses();
var lhs = Expect(TokenKind.Word);
if (!LookingAt(REL_OPS))
return EmitFullNameFilter(CONTAINS_OP, lhs.Text);
var op = Expect(REL_OPS);
Token rhs;
switch (lhs.Text)
{
case "FullyQualifiedName":
rhs = Expect(TokenKind.FQN, TokenKind.Word);
return EmitFullNameFilter(op, rhs.Text);
case "TestCategory":
rhs = Expect(TokenKind.Word);
return EmitCategoryFilter(op, rhs.Text);
case "Priority":
rhs = Expect(TokenKind.Word);
return EmitPropertyFilter(op, lhs.Text, rhs.Text);
case "Name":
rhs = Expect(TokenKind.FQN, TokenKind.Word);
return EmitNameFilter(op, rhs.Text);
default:
// Assume it's a property name
rhs = Expect(TokenKind.String, TokenKind.Word);
return EmitPropertyFilter(op, lhs.Text, rhs.Text);
}
}
private static string EmitFullNameFilter(Token op, string value)
{
return EmitFilter("test", op, value);
}
private static string EmitCategoryFilter(Token op, string value)
{
return EmitFilter("cat", op, value);
}
private static string EmitNameFilter(Token op, string value)
{
return EmitFilter("name", op, value);
}
private static string EmitFilter(string lhs, Token op, string rhs)
{
rhs = EscapeRhsValue(op, rhs);
if (op == EQ_OP)
return $"<{lhs}>{rhs}</{lhs}>";
if (op == NE_OP)
return $"<not><{lhs}>{rhs}</{lhs}></not>";
if (op == CONTAINS_OP)
return $"<{lhs} re='1'>{rhs}</{lhs}>";
if (op == NOTCONTAINS_OP)
return $"<not><{lhs} re='1'>{rhs}</{lhs}></not>";
throw new TestFilterParserException($"Invalid operator {op.Text} at position {op.Pos}");
}
private static string EmitPropertyFilter(Token op, string name, string value)
{
value = EscapeRhsValue(op, value);
if (op == EQ_OP)
return $"<prop name='{name}'>{value}</prop>";
if (op == NE_OP)
return $"<not><prop name='{name}'>{value}</prop></not>";
if (op == CONTAINS_OP)
return $"<prop name='{name}' re='1'>{value}</prop>";
if (op == NOTCONTAINS_OP)
return $"<not><prop name='{name}' re='1'>{value}</prop></not>";
throw new TestFilterParserException($"Invalid operator {op.Text} at position {op.Pos}");
}
private static string EscapeRhsValue(Token op, string rhs)
{
if (op == CONTAINS_OP || op == NOTCONTAINS_OP)
rhs = EscapeRegexChars(rhs);
return XmlEscape(rhs);
}
private string ParseExpressionInParentheses()
{
var op = Expect(LPAREN, NOT_OP);
if (op == NOT_OP) Expect(LPAREN);
var result = ParseFilterExpression();
Expect(RPAREN);
if (op == NOT_OP)
result = "<not>" + result + "</not>";
return result;
}
// Require a token of one or more kinds
private Token Expect(params TokenKind[] kinds)
{
var token = NextToken();
if (kinds.Any(kind => token.Kind == kind))
{
return token;
}
throw InvalidTokenError(token);
}
// Require a token from a list of tokens
private Token Expect(params Token[] valid)
{
var token = NextToken();
if (valid.Any(item => token == item))
{
return token;
}
throw InvalidTokenError(token);
}
private Exception InvalidTokenError(Token token)
{
return new TestFilterParserException(string.Format(
$"Unexpected {token.Kind} '{token.Text}' at position {token.Pos} in selection expression."));
}
private Token LookAhead => _tokenizer.LookAhead;
private bool LookingAt(params Token[] tokens)
{
return tokens.Any(token => LookAhead == token);
}
private Token NextToken()
{
return _tokenizer.NextToken();
}
// Since we use a regular expression to implement
// the contains operator, we must escape all chars
// that have a special meaning in a regex.
private const string REGEX_CHARS = @".[]{}()*+?|^$\";
private static string EscapeRegexChars(string input)
{
var sb = new StringBuilder();
foreach (var c in input)
{
if (REGEX_CHARS.Contains(c))
sb.Append('\\');
sb.Append(c);
}
return sb.ToString();
}
// Since the NUnit filter is represented in XML
// contents of each element must be escaped.
private static string XmlEscape(string text)
{
return text
.Replace("&", "&")
.Replace("\"", """)
.Replace("<", "<")
.Replace(">", ">")
.Replace("'", "'");
}
}
}