Skip to content

Commit 46ec7a9

Browse files
committed
Swift: Add the InlineExpectationsTest framework.
1 parent 69564d2 commit 46ec7a9

File tree

2 files changed

+400
-0
lines changed

2 files changed

+400
-0
lines changed
Lines changed: 377 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,377 @@
1+
/**
2+
* Provides a library for writing QL tests whose success or failure is based on expected results
3+
* embedded in the test source code as comments, rather than the contents of an `.expected` file
4+
* (in that the `.expected` file should always be empty).
5+
*
6+
* To add this framework to a new language:
7+
* - Add a file `InlineExpectationsTestPrivate.qll` that defines a `ExpectationComment` class. This class
8+
* must support a `getContents` method that returns the contents of the given comment, _excluding_
9+
* the comment indicator itself. It should also define `toString` and `getLocation` as usual.
10+
*
11+
* To create a new inline expectations test:
12+
* - Declare a class that extends `InlineExpectationsTest`. In the characteristic predicate of the
13+
* new class, bind `this` to a unique string (usually the name of the test).
14+
* - Override the `hasActualResult()` predicate to produce the actual results of the query. For each
15+
* result, specify a `Location`, a text description of the element for which the result was
16+
* reported, a short string to serve as the tag to identify expected results for this test, and the
17+
* expected value of the result.
18+
* - Override `getARelevantTag()` to return the set of tags that can be produced by
19+
* `hasActualResult()`. Often this is just a single tag.
20+
*
21+
* Example:
22+
* ```ql
23+
* class ConstantValueTest extends InlineExpectationsTest {
24+
* ConstantValueTest() { this = "ConstantValueTest" }
25+
*
26+
* override string getARelevantTag() {
27+
* // We only use one tag for this test.
28+
* result = "const"
29+
* }
30+
*
31+
* override predicate hasActualResult(
32+
* Location location, string element, string tag, string value
33+
* ) {
34+
* exists(Expr e |
35+
* tag = "const" and // The tag for this test.
36+
* value = e.getValue() and // The expected value. Will only hold for constant expressions.
37+
* location = e.getLocation() and // The location of the result to be reported.
38+
* element = e.toString() // The display text for the result.
39+
* )
40+
* }
41+
* }
42+
* ```
43+
*
44+
* There is no need to write a `select` clause or query predicate. All of the differences between
45+
* expected results and actual results will be reported in the `failures()` query predicate.
46+
*
47+
* To annotate the test source code with an expected result, place a comment starting with a `$` on the
48+
* same line as the expected result, with text of the following format as the body of the comment:
49+
*
50+
* `tag=expected-value`
51+
*
52+
* Where `tag` is the value of the `tag` parameter from `hasActualResult()`, and `expected-value` is
53+
* the value of the `value` parameter from `hasActualResult()`. The `=expected-value` portion may be
54+
* omitted, in which case `expected-value` is treated as the empty string. Multiple expectations may
55+
* be placed in the same comment. Any actual result that
56+
* appears on a line that does not contain a matching expected result comment will be reported with
57+
* a message of the form "Unexpected result: tag=value". Any expected result comment for which there
58+
* is no matching actual result will be reported with a message of the form
59+
* "Missing result: tag=expected-value".
60+
*
61+
* Example:
62+
* ```cpp
63+
* int i = x + 5; // $ const=5
64+
* int j = y + (7 - 3) // $ const=7 const=3 const=4 // The result of the subtraction is a constant.
65+
* ```
66+
*
67+
* For tests that contain known missing and spurious results, it is possible to further
68+
* annotate that a particular expected result is known to be spurious, or that a particular
69+
* missing result is known to be missing:
70+
*
71+
* `$ SPURIOUS: tag=expected-value` // Spurious result
72+
* `$ MISSING: tag=expected-value` // Missing result
73+
*
74+
* A spurious expectation is treated as any other expected result, except that if there is no
75+
* matching actual result, the message will be of the form "Fixed spurious result: tag=value". A
76+
* missing expectation is treated as if there were no expected result, except that if a
77+
* matching expected result is found, the message will be of the form
78+
* "Fixed missing result: tag=value".
79+
*
80+
* A single line can contain all the expected, spurious and missing results of that line. For instance:
81+
* `$ tag1=value1 SPURIOUS: tag2=value2 MISSING: tag3=value3`.
82+
*
83+
* If the same result value is expected for two or more tags on the same line, there is a shorthand
84+
* notation available:
85+
*
86+
* `tag1,tag2=expected-value`
87+
*
88+
* is equivalent to:
89+
*
90+
* `tag1=expected-value tag2=expected-value`
91+
*/
92+
93+
private import InlineExpectationsTestPrivate
94+
95+
/**
96+
* The base class for tests with inline expectations. The test extends this class to provide the actual
97+
* results of the query, which are then compared with the expected results in comments to produce a
98+
* list of failure messages that point out where the actual results differ from the expected
99+
* results.
100+
*/
101+
abstract class InlineExpectationsTest extends string {
102+
bindingset[this]
103+
InlineExpectationsTest() { any() }
104+
105+
/**
106+
* Returns all tags that can be generated by this test. Most tests will only ever produce a single
107+
* tag. Any expected result comments for a tag that is not returned by the `getARelevantTag()`
108+
* predicate for an active test will be ignored. This makes it possible to write multiple tests in
109+
* different `.ql` files that all query the same source code.
110+
*/
111+
abstract string getARelevantTag();
112+
113+
/**
114+
* Returns the actual results of the query that is being tested. Each result consist of the
115+
* following values:
116+
* - `location` - The source code location of the result. Any expected result comment must appear
117+
* on the start line of this location.
118+
* - `element` - Display text for the element on which the result is reported.
119+
* - `tag` - The tag that marks this result as coming from this test. This must be one of the tags
120+
* returned by `getARelevantTag()`.
121+
* - `value` - The value of the result, which will be matched against the value associated with
122+
* `tag` in any expected result comment on that line.
123+
*/
124+
abstract predicate hasActualResult(Location location, string element, string tag, string value);
125+
126+
/**
127+
* Holds if there is an optional result on the specified location.
128+
*
129+
* This is similar to `hasActualResult`, but returns results that do not require a matching annotation.
130+
* A failure will still arise if there is an annotation that does not match any results, but not vice versa.
131+
* Override this predicate to specify optional results.
132+
*/
133+
predicate hasOptionalResult(Location location, string element, string tag, string value) {
134+
none()
135+
}
136+
137+
final predicate hasFailureMessage(FailureLocatable element, string message) {
138+
exists(ActualResult actualResult |
139+
actualResult.getTest() = this and
140+
element = actualResult and
141+
(
142+
exists(FalseNegativeExpectation falseNegative |
143+
falseNegative.matchesActualResult(actualResult) and
144+
message = "Fixed missing result:" + falseNegative.getExpectationText()
145+
)
146+
or
147+
not exists(ValidExpectation expectation | expectation.matchesActualResult(actualResult)) and
148+
message = "Unexpected result: " + actualResult.getExpectationText() and
149+
not actualResult.isOptional()
150+
)
151+
)
152+
or
153+
exists(ValidExpectation expectation |
154+
not exists(ActualResult actualResult | expectation.matchesActualResult(actualResult)) and
155+
expectation.getTag() = getARelevantTag() and
156+
element = expectation and
157+
(
158+
expectation instanceof GoodExpectation and
159+
message = "Missing result:" + expectation.getExpectationText()
160+
or
161+
expectation instanceof FalsePositiveExpectation and
162+
message = "Fixed spurious result:" + expectation.getExpectationText()
163+
)
164+
)
165+
or
166+
exists(InvalidExpectation expectation |
167+
element = expectation and
168+
message = "Invalid expectation syntax: " + expectation.getExpectation()
169+
)
170+
}
171+
}
172+
173+
/**
174+
* RegEx pattern to match a comment containing one or more expected results. The comment must have
175+
* `$` as its first non-whitespace character. Any subsequent character
176+
* is treated as part of the expected results, except that the comment may contain a `//` sequence
177+
* to treat the remainder of the line as a regular (non-interpreted) comment.
178+
*/
179+
private string expectationCommentPattern() { result = "\\s*\\$((?:[^/]|/[^/])*)(?://.*)?" }
180+
181+
/**
182+
* The possible columns in an expectation comment. The `TDefaultColumn` branch represents the first
183+
* column in a comment. This column is not precedeeded by a name. `TNamedColumn(name)` represents a
184+
* column containing expected results preceded by the string `name:`.
185+
*/
186+
private newtype TColumn =
187+
TDefaultColumn() or
188+
TNamedColumn(string name) { name = ["MISSING", "SPURIOUS"] }
189+
190+
bindingset[start, content]
191+
private int getEndOfColumnPosition(int start, string content) {
192+
result =
193+
min(string name, int cand |
194+
exists(TNamedColumn(name)) and
195+
cand = content.indexOf(name + ":") and
196+
cand >= start
197+
|
198+
cand
199+
)
200+
or
201+
not exists(string name |
202+
exists(TNamedColumn(name)) and
203+
content.indexOf(name + ":") >= start
204+
) and
205+
result = content.length()
206+
}
207+
208+
private predicate getAnExpectation(
209+
ExpectationComment comment, TColumn column, string expectation, string tags, string value
210+
) {
211+
exists(string content |
212+
content = comment.getContents().regexpCapture(expectationCommentPattern(), 1) and
213+
(
214+
column = TDefaultColumn() and
215+
exists(int end |
216+
end = getEndOfColumnPosition(0, content) and
217+
expectation = content.prefix(end).regexpFind(expectationPattern(), _, _).trim()
218+
)
219+
or
220+
exists(string name, int start, int end |
221+
column = TNamedColumn(name) and
222+
start = content.indexOf(name + ":") + name.length() + 1 and
223+
end = getEndOfColumnPosition(start, content) and
224+
expectation = content.substring(start, end).regexpFind(expectationPattern(), _, _).trim()
225+
)
226+
)
227+
) and
228+
tags = expectation.regexpCapture(expectationPattern(), 1) and
229+
if exists(expectation.regexpCapture(expectationPattern(), 2))
230+
then value = expectation.regexpCapture(expectationPattern(), 2)
231+
else value = ""
232+
}
233+
234+
private string getColumnString(TColumn column) {
235+
column = TDefaultColumn() and result = ""
236+
or
237+
column = TNamedColumn(result)
238+
}
239+
240+
/**
241+
* RegEx pattern to match a single expected result, not including the leading `$`. It consists of one or
242+
* more comma-separated tags optionally followed by `=` and the expected value.
243+
*
244+
* Tags must be only letters, digits, `-` and `_` (note that the first character
245+
* must not be a digit), but can contain anything enclosed in a single set of
246+
* square brackets.
247+
*
248+
* Examples:
249+
* - `tag`
250+
* - `tag=value`
251+
* - `tag,tag2=value`
252+
* - `tag[foo bar]=value`
253+
*
254+
* Not allowed:
255+
* - `tag[[[foo bar]`
256+
*/
257+
private string expectationPattern() {
258+
exists(string tag, string tags, string value |
259+
tag = "[A-Za-z-_](?:[A-Za-z-_0-9]|\\[[^\\]\\]]*\\])*" and
260+
tags = "((?:" + tag + ")(?:\\s*,\\s*" + tag + ")*)" and
261+
// In Python, we allow both `"` and `'` for strings, as well as the prefixes `bru`.
262+
// For example, `b"foo"`.
263+
value = "((?:[bru]*\"[^\"]*\"|[bru]*'[^']*'|\\S+)*)" and
264+
result = tags + "(?:=" + value + ")?"
265+
)
266+
}
267+
268+
private newtype TFailureLocatable =
269+
TActualResult(
270+
InlineExpectationsTest test, Location location, string element, string tag, string value,
271+
boolean optional
272+
) {
273+
test.hasActualResult(location, element, tag, value) and
274+
optional = false
275+
or
276+
test.hasOptionalResult(location, element, tag, value) and optional = true
277+
} or
278+
TValidExpectation(ExpectationComment comment, string tag, string value, string knownFailure) {
279+
exists(TColumn column, string tags |
280+
getAnExpectation(comment, column, _, tags, value) and
281+
tag = tags.splitAt(",") and
282+
knownFailure = getColumnString(column)
283+
)
284+
} or
285+
TInvalidExpectation(ExpectationComment comment, string expectation) {
286+
getAnExpectation(comment, _, expectation, _, _) and
287+
not expectation.regexpMatch(expectationPattern())
288+
}
289+
290+
class FailureLocatable extends TFailureLocatable {
291+
string toString() { none() }
292+
293+
Location getLocation() { none() }
294+
295+
final string getExpectationText() { result = getTag() + "=" + getValue() }
296+
297+
string getTag() { none() }
298+
299+
string getValue() { none() }
300+
}
301+
302+
class ActualResult extends FailureLocatable, TActualResult {
303+
InlineExpectationsTest test;
304+
Location location;
305+
string element;
306+
string tag;
307+
string value;
308+
boolean optional;
309+
310+
ActualResult() { this = TActualResult(test, location, element, tag, value, optional) }
311+
312+
override string toString() { result = element }
313+
314+
override Location getLocation() { result = location }
315+
316+
InlineExpectationsTest getTest() { result = test }
317+
318+
override string getTag() { result = tag }
319+
320+
override string getValue() { result = value }
321+
322+
predicate isOptional() { optional = true }
323+
}
324+
325+
abstract private class Expectation extends FailureLocatable {
326+
ExpectationComment comment;
327+
328+
override string toString() { result = comment.toString() }
329+
330+
override Location getLocation() { result = comment.getLocation() }
331+
}
332+
333+
private class ValidExpectation extends Expectation, TValidExpectation {
334+
string tag;
335+
string value;
336+
string knownFailure;
337+
338+
ValidExpectation() { this = TValidExpectation(comment, tag, value, knownFailure) }
339+
340+
override string getTag() { result = tag }
341+
342+
override string getValue() { result = value }
343+
344+
string getKnownFailure() { result = knownFailure }
345+
346+
predicate matchesActualResult(ActualResult actualResult) {
347+
getLocation().getStartLine() = actualResult.getLocation().getStartLine() and
348+
getLocation().getFile() = actualResult.getLocation().getFile() and
349+
getTag() = actualResult.getTag() and
350+
getValue() = actualResult.getValue()
351+
}
352+
}
353+
354+
/* Note: These next three classes correspond to all the possible values of type `TColumn`. */
355+
class GoodExpectation extends ValidExpectation {
356+
GoodExpectation() { getKnownFailure() = "" }
357+
}
358+
359+
class FalsePositiveExpectation extends ValidExpectation {
360+
FalsePositiveExpectation() { getKnownFailure() = "SPURIOUS" }
361+
}
362+
363+
class FalseNegativeExpectation extends ValidExpectation {
364+
FalseNegativeExpectation() { getKnownFailure() = "MISSING" }
365+
}
366+
367+
class InvalidExpectation extends Expectation, TInvalidExpectation {
368+
string expectation;
369+
370+
InvalidExpectation() { this = TInvalidExpectation(comment, expectation) }
371+
372+
string getExpectation() { result = expectation }
373+
}
374+
375+
query predicate failures(FailureLocatable element, string message) {
376+
exists(InlineExpectationsTest test | test.hasFailureMessage(element, message))
377+
}

0 commit comments

Comments
 (0)