-
Notifications
You must be signed in to change notification settings - Fork 103
/
Copy pathEventRecorderTests.swift
486 lines (414 loc) · 14.3 KB
/
EventRecorderTests.swift
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
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for Swift project authors
//
@testable @_spi(Experimental) @_spi(ForToolsIntegrationOnly) import Testing
#if !os(Windows)
import RegexBuilder
#endif
#if canImport(Foundation)
import Foundation
#endif
#if canImport(FoundationXML)
import FoundationXML
#endif
#if FIXED_118452948
@Suite("Event Recorder Tests")
#endif
struct EventRecorderTests {
final class Stream: TextOutputStream, Sendable {
let buffer = Locked<String>(rawValue: "")
@Sendable func write(_ string: String) {
buffer.withLock {
$0.append(string)
}
}
}
private static var optionCombinations: [(useSFSymbols: Bool, ansiColorBitDepth: Int8?)] {
var result: [(useSFSymbols: Bool, ansiColorBitDepth: Int8?)] = [
(false, nil), (false, 1), (false, 4), (false, 8), (false, 24),
]
#if os(macOS)
result += [
(true, nil), (true, 1), (true, 4), (true, 8), (true, 24),
]
#endif
return result
}
@Test("Writing events", arguments: optionCombinations)
func writingToStream(useSFSymbols: Bool, ansiColorBitDepth: Int8?) async throws {
let stream = Stream()
var options = Event.ConsoleOutputRecorder.Options()
#if os(macOS)
options.useSFSymbols = useSFSymbols
#endif
if let ansiColorBitDepth {
options.useANSIEscapeCodes = true
options.ansiColorBitDepth = ansiColorBitDepth
}
var configuration = Configuration()
configuration.deliverExpectationCheckedEvents = true
let eventRecorder = Event.ConsoleOutputRecorder(options: options, writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await runTest(for: WrittenTests.self, configuration: configuration)
let buffer = stream.buffer.rawValue
#expect(buffer.contains("failWhale"))
#expect(buffer.contains("Whales fail."))
#if !SWT_NO_UNSTRUCTURED_TASKS
#expect(buffer.contains("Whales fail asynchronously."))
#endif
#expect(buffer.contains("\"abc\" == \"xyz\""))
#expect(buffer.contains("Not A Lobster"))
#expect(buffer.contains("i → 5"))
#expect(buffer.contains("Ocelots don't like the number 3."))
if let ansiColorBitDepth, ansiColorBitDepth > 1 {
#expect(buffer.contains("\u{001B}["))
#expect(buffer.contains("●"))
} else {
#expect(!buffer.contains("\u{001B}["))
#expect(!buffer.contains("●"))
}
#expect(buffer.contains("inserted ["))
if testsWithSignificantIOAreEnabled {
print(buffer, terminator: "")
}
}
@Test("Verbose output")
func verboseOutput() async throws {
let stream = Stream()
var options = Event.ConsoleOutputRecorder.Options()
options.verbosity = 1
var configuration = Configuration()
configuration.deliverExpectationCheckedEvents = true
let eventRecorder = Event.ConsoleOutputRecorder(options: options, writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await runTest(for: WrittenTests.self, configuration: configuration)
let buffer = stream.buffer.rawValue
#expect(buffer.contains(#"\#(Event.Symbol.details.unicodeCharacter) "abc": Swift.String"#))
#expect(buffer.contains(#"\#(Event.Symbol.details.unicodeCharacter) lhs: Swift.String → "987""#))
#expect(buffer.contains(#""Animal Crackers" (aka 'WrittenTests')"#))
#expect(buffer.contains(#""Not A Lobster" (aka 'actuallyCrab()')"#))
if testsWithSignificantIOAreEnabled {
print(buffer, terminator: "")
}
}
@Test("Quiet output")
func quietOutput() async throws {
let stream = Stream()
var options = Event.ConsoleOutputRecorder.Options()
options.verbosity = -1
var configuration = Configuration()
configuration.deliverExpectationCheckedEvents = true
let eventRecorder = Event.ConsoleOutputRecorder(options: options, writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await runTest(for: WrittenTests.self, configuration: configuration)
let buffer = stream.buffer.rawValue
#expect(!buffer.contains(#"\#(Event.Symbol.details.unicodeCharacter) Test run started."#))
#expect(!buffer.contains(#"\#(Event.Symbol.default.unicodeCharacter) Passing"#))
if testsWithSignificantIOAreEnabled {
print(buffer, terminator: "")
}
}
@Test("Output with prefix on each line")
func prefixedOutput() async throws {
let stream = Stream()
let prefix = ">>What Fools These Prefixes Be<<"
var options = Event.ConsoleOutputRecorder.Options()
options.prefix = prefix
var configuration = Configuration()
configuration.deliverExpectationCheckedEvents = true
let eventRecorder = Event.ConsoleOutputRecorder(options: options, writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await runTest(for: WrittenTests.self, configuration: configuration)
let buffer = stream.buffer.rawValue
#expect(buffer.contains(prefix))
if testsWithSignificantIOAreEnabled {
print(buffer, terminator: "")
}
}
#if !os(Windows)
@available(_regexAPI, *)
@Test(
"Titles of messages ('Test' vs. 'Suite') are determined correctly",
arguments: [
("f()", false),
("g()", false),
("PredictablyFailingTests", true),
]
)
func messageTitles(testName: String, isSuite: Bool) async throws {
let stream = Stream()
var configuration = Configuration()
let eventRecorder = Event.ConsoleOutputRecorder(writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await runTest(for: PredictablyFailingTests.self, configuration: configuration)
let buffer = stream.buffer.rawValue
if testsWithSignificantIOAreEnabled {
print(buffer, terminator: "")
}
let testFailureRegex = Regex {
One(.anyGraphemeCluster)
" \(isSuite ? "Suite" : "Test") \(testName) started."
}
#expect(
try buffer
.split(whereSeparator: \.isNewline)
.compactMap(testFailureRegex.wholeMatch(in:))
.first != nil
)
}
@available(_regexAPI, *)
@Test(
"Issue counts are summed correctly on test end",
arguments: [
("f()", false, (total: 5, expected: 3)),
("g()", false, (total: 2, expected: 1)),
("PredictablyFailingTests", true, (total: 7, expected: 4)),
]
)
func issueCountSummingAtTestEnd(testName: String, isSuite: Bool, issueCount: (total: Int, expected: Int)) async throws {
let stream = Stream()
var configuration = Configuration()
let eventRecorder = Event.ConsoleOutputRecorder(writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await runTest(for: PredictablyFailingTests.self, configuration: configuration)
let buffer = stream.buffer.rawValue
if testsWithSignificantIOAreEnabled {
print(buffer, terminator: "")
}
let testFailureRegex = Regex {
One(.anyGraphemeCluster)
" \(isSuite ? "Suite" : "Test") \(testName) failed "
ZeroOrMore(.any)
" with "
Capture { OneOrMore(.digit) } transform: { Int($0) }
" issue"
Optionally("s")
" (including "
Capture { OneOrMore(.digit) } transform: { Int($0) }
" known issue"
Optionally("s")
")."
}
let match = try #require(
buffer
.split(whereSeparator: \.isNewline)
.compactMap(testFailureRegex.wholeMatch(in:))
.first
)
#expect(issueCount.total == match.output.1)
#expect(issueCount.expected == match.output.2)
}
#endif
@available(_regexAPI, *)
@Test("Issue counts are omitted on a successful test")
func issueCountOmittedForPassingTest() async throws {
let stream = Stream()
var configuration = Configuration()
let eventRecorder = Event.ConsoleOutputRecorder(writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await Test(name: "Innocuous Test Name") {
}.run(configuration: configuration)
let buffer = stream.buffer.rawValue
if testsWithSignificantIOAreEnabled {
print(buffer, terminator: "")
}
#expect(!buffer.contains("issue"))
}
#if !os(Windows)
@available(_regexAPI, *)
@Test("Issue counts are summed correctly on run end")
func issueCountSummingAtRunEnd() async throws {
let stream = Stream()
var configuration = Configuration()
let eventRecorder = Event.ConsoleOutputRecorder(writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await runTest(for: PredictablyFailingTests.self, configuration: configuration)
let buffer = stream.buffer.rawValue
if testsWithSignificantIOAreEnabled {
print(buffer, terminator: "")
}
let runFailureRegex = Regex {
One(.anyGraphemeCluster)
" Test run with "
OneOrMore(.digit)
" test"
Optionally("s")
" failed "
ZeroOrMore(.any)
" with "
Capture { OneOrMore(.digit) } transform: { Int($0) }
" issue"
Optionally("s")
" (including "
Capture { OneOrMore(.digit) } transform: { Int($0) }
" known issue"
Optionally("s")
")."
}
let match = try #require(
buffer
.split(whereSeparator: \.isNewline)
.compactMap(runFailureRegex.wholeMatch(in:))
.first
)
#expect(match.output.1 == 7)
#expect(match.output.2 == 4)
}
#endif
#if canImport(Foundation) || canImport(FoundationXML)
@Test(
"JUnitXMLRecorder outputs valid XML",
.bug("https://github.com/apple/swift-testing/issues/254")
)
func junitXMLIsValid() async throws {
let stream = Stream()
var configuration = Configuration()
configuration.deliverExpectationCheckedEvents = true
let eventRecorder = Event.JUnitXMLRecorder(writingUsing: stream.write)
configuration.eventHandler = { event, context in
eventRecorder.record(event, in: context)
}
await runTest(for: WrittenTests.self, configuration: configuration)
// There is no formal schema for us to test against, so we're mostly just
// testing that the XML can be parsed by Foundation.
let xmlString = stream.buffer.rawValue
#expect(xmlString.hasPrefix("<?xml"))
let xmlData = try #require(xmlString.data(using: .utf8))
#expect(xmlData.count > 1024)
let parser = XMLParser(data: xmlData)
// Set up a delegate that can look for particular XML tags of interest. Keep
// in mind that the delegate pattern necessarily means that some of the
// testing occurs out of source order.
final class JUnitDelegate: NSObject, XMLParserDelegate {
var caughtError: (any Error)?
func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName qName: String?, attributes attributeDict: [String : String] = [:]) {
if elementName == "testsuite" {
do {
let testCountString = try #require(attributeDict["tests"])
let testCount = try #require(Int(testCountString))
#expect(testCount > 0)
} catch {
caughtError = error
}
}
}
}
let delegate = JUnitDelegate()
parser.delegate = delegate
// Perform the parsing and propagate any errors that occurred.
#expect(parser.parse())
if let error = parser.parserError {
throw error
}
if let caughtError = delegate.caughtError {
throw caughtError
}
}
#endif
}
// MARK: - Fixtures
@Suite("Animal Crackers", .hidden) struct WrittenTests {
@Test(.hidden) func failWhale() async {
Issue.record("Whales fail.")
await { () async in
_ = Issue.record("Whales fail asynchronously.")
}()
}
@Test(.hidden) func expectantKangaroo() {
#expect("abc" == "xyz")
}
@Test(.hidden) func nonbindingBear() {
let lhs = "987"
let rhs = "123"
#expect(lhs == rhs)
}
@Test(.hidden) func successBadger() {}
@Test(.hidden, .tags(.red, .orange, .green), arguments: 0 ..< 10) func severalLarks(i: Int) {}
@Test(.hidden, .tags(.purple), arguments: 0 ..< 100) func multitudeOcelot(i: Int) {
if i == 3 {
Issue.record("Ocelots don't like the number 3.")
}
}
@Test("Not A Lobster", .hidden) func actuallyCrab() {}
@Test("Avoid the Komodo", .hidden, .disabled(), .tags(.red, .orange, .yellow, .green, .blue, .purple))
func angeredKomodo() {}
@Test("Incensed Quail", .hidden)
func incensedQuail() throws {
withKnownIssue {
struct QuailError: Error {}
throw QuailError()
}
}
@Test("Unavailable Pigeon", .hidden)
@available(*, unavailable)
func unavailablePigeon() {}
@Test("Future Grouse", .hidden)
@available(macOS 999.0, iOS 999.0, watchOS 999.0, tvOS 999.0, *)
func futureGrouse() {}
@Test("Future Goose", .hidden)
@available(macOS 999, iOS 999, watchOS 999, tvOS 999, *)
func futureGoose() {}
@Test("Future Mouse", .hidden)
@available(macOS, introduced: 999.0)
func futureMouse() {}
@Test("Future Moose", .hidden)
@available(macOS, introduced: 999.0.0)
func futureMoose() {}
@Test(.hidden, .comment("No comment"), .comment("Well, maybe"))
func commented() {
Issue.record()
}
@Test(.hidden) func diffyDuck() {
#expect([1, 2, 3] as Array == [1, 2] as Array)
}
@Test(.hidden) func woefulWombat() {
#expect(throws: MyError.self) {
throw MyDescriptiveError(description: "Woe!")
}
}
@Test(.hidden) func quotationalQuokka() throws {
throw MyDescriptiveError(description: #""Quotation marks!""#)
}
@Test(.hidden) func cornyUnicorn🦄() throws {
throw MyDescriptiveError(description: #"🦄"#)
}
}
@Suite(.hidden) struct PredictablyFailingTests {
@Test(.hidden) func f() {
#expect(Bool(false))
#expect(Bool(false))
withKnownIssue {
#expect(Bool(false))
#expect(Bool(false))
#expect(Bool(false))
}
}
@Test(.hidden) func g() {
#expect(Bool(false))
withKnownIssue {
#expect(Bool(false))
}
}
}