-
Notifications
You must be signed in to change notification settings - Fork 350
Expand file tree
/
Copy pathCondition.cs
More file actions
393 lines (346 loc) · 12.6 KB
/
Condition.cs
File metadata and controls
393 lines (346 loc) · 12.6 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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
// 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;
using System.Collections.Generic;
using System.Globalization;
#if IS_VSTEST_REPO
using System.Diagnostics.CodeAnalysis;
#endif
using System.Linq;
using System.Text;
#if !IS_VSTEST_REPO
using Microsoft.CodeAnalysis;
#endif
#if IS_VSTEST_REPO
using Microsoft.VisualStudio.TestPlatform.ObjectModel;
#endif
using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities;
#if IS_VSTEST_REPO
using static Microsoft.VisualStudio.TestPlatform.Common.Resources.Resources;
#endif
namespace Microsoft.VisualStudio.TestPlatform.Common.Filtering;
#if !IS_VSTEST_REPO
[Embedded]
#endif
internal enum Operation
{
Equal,
NotEqual,
Contains,
NotContains
}
/// <summary>
/// Operator in order of precedence.
/// Precedence(And) > Precedence(Or)
/// Precedence of OpenBrace and CloseBrace operators is not used, instead parsing code takes care of same.
/// </summary>
#if !IS_VSTEST_REPO
[Embedded]
#endif
internal enum Operator
{
None,
Or,
And,
OpenBrace,
CloseBrace,
}
/// <summary>
/// Represents a condition in filter expression.
/// </summary>
#if !IS_VSTEST_REPO
[Embedded]
#endif
internal sealed class Condition
{
/// <summary>
/// Default property name which will be used when filter has only property value.
/// </summary>
public const string DefaultPropertyName = "FullyQualifiedName";
/// <summary>
/// Default operation which will be used when filter has only property value.
/// </summary>
public const Operation DefaultOperation = Operation.Contains;
#if !IS_VSTEST_REPO
private const string TestCaseFilterFormatException = "Incorrect format for TestCaseFilter {0}. Specify the correct format and try again. Note that the incorrect format can lead to no test getting executed.";
private const string InvalidCondition = "Error: Invalid Condition '{0}'";
private const string InvalidOperator = "Error: Invalid operator '{0}'";
#endif
internal Condition(string name, Operation operation, string value)
{
Name = name;
Operation = operation;
Value = value;
}
/// <summary>
/// Name of the property used in condition.
/// </summary>
internal string Name { get; }
/// <summary>
/// Value for the property.
/// </summary>
internal string Value { get; }
/// <summary>
/// Operation to be performed.
/// </summary>
internal Operation Operation { get; }
private bool EvaluateEqualOperation(string[]? multiValue)
{
// if any value in multi-valued property matches 'this.Value', for Equal to evaluate true.
if (multiValue != null)
{
foreach (string propertyValue in multiValue)
{
if (string.Equals(propertyValue, Value, StringComparison.OrdinalIgnoreCase))
{
return true;
}
}
}
return false;
}
private bool EvaluateContainsOperation(string[]? multiValue)
{
if (multiValue != null)
{
foreach (string propertyValue in multiValue)
{
#if IS_VSTEST_REPO
TPDebug.Assert(null != propertyValue, "PropertyValue can not be null.");
#endif
if (propertyValue!.IndexOf(Value, StringComparison.OrdinalIgnoreCase) != -1)
{
return true;
}
}
}
return false;
}
/// <summary>
/// Evaluate this condition for testObject.
/// </summary>
internal bool Evaluate(Func<string, object?> propertyValueProvider)
{
#if IS_VSTEST_REPO
ValidateArg.NotNull(propertyValueProvider, nameof(propertyValueProvider));
#endif
var multiValue = GetPropertyValue(propertyValueProvider);
var result = Operation switch
{
// if any value in multi-valued property matches 'this.Value', for Equal to evaluate true.
Operation.Equal => EvaluateEqualOperation(multiValue),
// all values in multi-valued property should not match 'this.Value' for NotEqual to evaluate true.
Operation.NotEqual => !EvaluateEqualOperation(multiValue),
// if any value in multi-valued property contains 'this.Value' for 'Contains' to be true.
Operation.Contains => EvaluateContainsOperation(multiValue),
// all values in multi-valued property should not contain 'this.Value' for NotContains to evaluate true.
Operation.NotContains => !EvaluateContainsOperation(multiValue),
_ => false,
};
return result;
}
/// <summary>
/// Returns a condition object after parsing input string of format '<propertyName>Operation</propertyName>'
/// </summary>
internal static Condition Parse(string? conditionString)
{
#if IS_VSTEST_REPO
if (conditionString.IsNullOrWhiteSpace())
#else
if (string.IsNullOrWhiteSpace(conditionString))
#endif
{
ThrownFormatExceptionForInvalidCondition(conditionString);
}
var parts = TokenizeFilterConditionString(conditionString!).ToArray();
if (parts.Length == 1)
{
// If only parameter values is passed, create condition with default property name,
// default operation and given condition string as parameter value.
return new Condition(DefaultPropertyName, DefaultOperation, FilterHelper.Unescape(conditionString!.Trim()));
}
if (parts.Length != 3)
{
ThrownFormatExceptionForInvalidCondition(conditionString);
}
for (int index = 0; index < 3; index++)
{
#if IS_VSTEST_REPO
if (parts[index].IsNullOrWhiteSpace())
#else
if (string.IsNullOrWhiteSpace(parts[index]))
#endif
{
ThrownFormatExceptionForInvalidCondition(conditionString);
}
parts[index] = parts[index].Trim();
}
Operation operation = GetOperator(parts[1]);
Condition condition = new(parts[0], operation, FilterHelper.Unescape(parts[2]));
return condition;
}
#if IS_VSTEST_REPO
[DoesNotReturn]
#endif
private static void ThrownFormatExceptionForInvalidCondition(string? conditionString)
{
throw new FormatException(string.Format(CultureInfo.CurrentCulture, TestCaseFilterFormatException,
string.Format(CultureInfo.CurrentCulture, InvalidCondition, conditionString)));
}
/// <summary>
/// Check if condition validates any property in properties.
/// </summary>
#if IS_VSTEST_REPO
internal bool ValidForProperties(IEnumerable<string> properties, Func<string, TestProperty?>? propertyProvider)
#else
internal bool ValidForProperties(IEnumerable<string> properties)
#endif
{
bool valid = false;
if (properties.Contains(Name, StringComparer.OrdinalIgnoreCase))
{
valid = true;
#if IS_VSTEST_REPO
// Check if operation ~ (Contains) is on property of type string.
if (Operation == Operation.Contains)
{
valid = ValidForContainsOperation(propertyProvider);
}
#endif
}
return valid;
}
#if IS_VSTEST_REPO
private bool ValidForContainsOperation(Func<string, TestProperty?>? propertyProvider)
{
bool valid = true;
// It is OK for propertyProvider to be null, no syntax check will happen.
// Check validity of operator only if related TestProperty is non-null.
// if null, it might be custom validation ignore it.
if (null != propertyProvider)
{
TestProperty? testProperty = propertyProvider(Name);
if (null != testProperty)
{
Type propertyType = testProperty.GetValueType();
valid = typeof(string) == propertyType ||
typeof(string[]) == propertyType;
}
}
return valid;
}
#endif
/// <summary>
/// Return Operation corresponding to the operationString
/// </summary>
private static Operation GetOperator(string operationString)
{
return operationString switch
{
"=" => Operation.Equal,
"!=" => Operation.NotEqual,
"~" => Operation.Contains,
"!~" => Operation.NotContains,
_ => throw new FormatException(string.Format(CultureInfo.CurrentCulture, TestCaseFilterFormatException, string.Format(CultureInfo.CurrentCulture, InvalidOperator, operationString))),
};
}
/// <summary>
/// Returns property value for Property using propertValueProvider.
/// </summary>
private string[]? GetPropertyValue(Func<string, object?> propertyValueProvider)
{
var propertyValue = propertyValueProvider(Name);
if (null != propertyValue)
{
if (propertyValue is not string[] multiValue)
{
multiValue = new string[1];
multiValue[0] = propertyValue.ToString()!;
}
return multiValue;
}
return null;
}
internal static IEnumerable<string> TokenizeFilterConditionString(string str)
{
return str == null ? throw new ArgumentNullException(nameof(str)) : TokenizeFilterConditionStringWorker(str);
static IEnumerable<string> TokenizeFilterConditionStringWorker(string s)
{
StringBuilder tokenBuilder = new();
var last = '\0';
for (int i = 0; i < s.Length; ++i)
{
var current = s[i];
if (last == FilterHelper.EscapeCharacter)
{
// Don't check if `current` is one of the special characters here.
// Instead, we blindly let any character follows '\' pass though and
// relies on `FilterHelpers.Unescape` to report such errors.
tokenBuilder.Append(current);
if (current == FilterHelper.EscapeCharacter)
{
// We just encountered double backslash (i.e. escaped '\'), therefore set `last` to '\0'
// so the second '\' (i.e. current) will not be treated as the prefix of escape sequence
// in next iteration.
current = '\0';
}
}
else
{
switch (current)
{
case '=':
if (tokenBuilder.Length > 0)
{
yield return tokenBuilder.ToString();
tokenBuilder.Clear();
}
yield return "=";
break;
case '!':
if (tokenBuilder.Length > 0)
{
yield return tokenBuilder.ToString();
tokenBuilder.Clear();
}
// Determine if this is a "!=" or "!~" or just a single "!".
var next = i + 1;
if (next < s.Length && s[next] == '=')
{
i = next;
current = '=';
yield return "!=";
}
else if (next < s.Length && s[next] == '~')
{
i = next;
current = '~';
yield return "!~";
}
else
{
yield return "!";
}
break;
case '~':
if (tokenBuilder.Length > 0)
{
yield return tokenBuilder.ToString();
tokenBuilder.Clear();
}
yield return "~";
break;
default:
tokenBuilder.Append(current);
break;
}
}
last = current;
}
if (tokenBuilder.Length > 0)
{
yield return tokenBuilder.ToString();
}
}
}
}