-
-
Notifications
You must be signed in to change notification settings - Fork 896
Expand file tree
/
Copy pathAsyncExample.swift
More file actions
279 lines (234 loc) · 10.8 KB
/
AsyncExample.swift
File metadata and controls
279 lines (234 loc) · 10.8 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
import Foundation
import XCTest
public class AsyncExample: ExampleBase {
weak internal var group: AsyncExampleGroup?
private let internalDescription: String
private let closure: () async throws -> Void
internal init(description: String, callsite: Callsite, flags: FilterFlags, closure: @escaping () async throws -> Void) {
self.internalDescription = description
self.closure = closure
super.init(callsite: callsite, flags: flags)
}
public override var description: String {
return internalDescription
}
/**
The example name. A name is a concatenation of the name of
the example group the example belongs to, followed by the
description of the example itself.
The example name is used to generate a test method selector
to be displayed in Xcode's test navigator.
*/
public override var name: String {
guard let groupName = group?.name else { return description }
return "\(groupName), \(description)"
}
public func run() async {
let asyncWorld = AsyncWorld.sharedWorld
let world = World.sharedWorld
if world.numberOfExamplesRun == 0 {
await MainActor.run {
world.suiteHooks.executeBefores()
}
}
let exampleMetadata = AsyncExampleMetadata(group: group!, example: self, exampleIndex: asyncWorld.numberOfAsyncExamplesRun)
asyncWorld.currentExampleMetadata = exampleMetadata
defer {
asyncWorld.currentExampleMetadata = nil
}
group!.phase = .beforesExecuting
let runExample: () async -> Void = { [closure, name, callsite] in
self.group!.phase = .beforesFinished
do {
try await closure()
} catch {
self.handleErrorInTest(error, name: name, callsite: callsite)
}
self.group!.phase = .aftersExecuting
}
var cancelTests = false
let handleThrowingClosure: (@escaping () async throws -> Void) -> () async -> Void = { [name, callsite] (closure: @escaping () async throws -> Void) in
{
if cancelTests { return }
do {
try await closure()
} catch {
self.handleErrorInTest(error, name: name, callsite: callsite)
cancelTests = true
}
}
}
let allJustBeforeEachStatements = group!.justBeforeEachStatements + asyncWorld.exampleHooks.justBeforeEachStatements
let justBeforeEachExample = allJustBeforeEachStatements.reduce(runExample as () async throws -> Void) { closure, wrapper in
return { try await wrapper(exampleMetadata, handleThrowingClosure(closure)) }
}
let allWrappers = group!.wrappers + asyncWorld.exampleHooks.wrappers
let wrappedExample = allWrappers.reduce(justBeforeEachExample) { closure, wrapper in
return { try await wrapper(exampleMetadata, handleThrowingClosure(closure)) }
}
do {
try await wrappedExample()
} catch {
self.handleErrorInTest(error, name: name, callsite: callsite)
}
group!.phase = .aftersFinished
asyncWorld.numberOfAsyncExamplesRun += 1
if !asyncWorld.isRunningAdditionalSuites && world.numberOfExamplesRun >= world.cachedIncludedExampleCount {
await MainActor.run {
world.suiteHooks.executeAfters()
}
}
}
public func runSkippedTest() async {
let asyncWorld = AsyncWorld.sharedWorld
let world = World.sharedWorld
if world.numberOfExamplesRun == 0 {
await MainActor.run {
world.suiteHooks.executeBefores()
}
}
reportSkippedTest(XCTSkip("Test was filtered out."), name: name, callsite: callsite)
asyncWorld.numberOfAsyncExamplesRun += 1
if !asyncWorld.isRunningAdditionalSuites && world.numberOfExamplesRun >= world.cachedIncludedExampleCount {
await MainActor.run {
world.suiteHooks.executeAfters()
}
}
}
/**
Evaluates the filter flags set on this example and on the example groups
this example belongs to. Flags set on the example are trumped by flags on
the example group it belongs to. Flags on inner example groups are trumped
by flags on outer example groups.
*/
internal override var filterFlags: FilterFlags {
var aggregateFlags = flags
for (key, value) in group!.filterFlags {
aggregateFlags[key] = value
}
return aggregateFlags
}
#if canImport(Darwin)
static internal let recordSkipSelector = NSSelectorFromString("recordSkipWithDescription:sourceCodeContext:")
#endif
internal func handleErrorInTest(_ error: Error, name: String, callsite: Callsite) {
if let stopTestError = error as? StopTest {
self.reportStoppedTest(stopTestError)
} else if let testSkippedError = error as? XCTSkip {
self.reportSkippedTest(testSkippedError, name: name, callsite: callsite)
} else {
self.reportFailedTest(error, name: name, callsite: callsite)
}
}
internal func reportSkippedTest(_ testSkippedError: XCTSkip, name: String, callsite: Callsite) {
#if !canImport(Darwin)
return // This functionality is only supported by Apple's proprietary XCTest, not by swift-corelibs-xctest
#else // `NSSelectorFromString` requires the Objective-C runtime, which is not available on Linux.
let messageSuffix = """
\n
If nobody else has done so yet, please submit an issue to https://github.com/Quick/Quick/issues
For now, we'll just benignly ignore skipped tests.
"""
guard let testRun = AsyncSpec.current?.testRun else {
print("""
[Quick Warning]: `AsyncSpec.current?.testRun` was unexpectededly `nil`.
""" + messageSuffix)
return
}
guard let skippedTestContextAny = testSkippedError.errorUserInfo["XCTestErrorUserInfoKeySkippedTestContext"] else {
print("""
[Quick Warning]: The internals of Apple's XCTestCaseRun have changed.
We expected the `errorUserInfo` dictionary of the XCTSKip error to contain a value for the key
"XCTestErrorUserInfoKeySkippedTestContext", but it didn't.
""" + messageSuffix)
return
}
// Uses an internal type "XCTSkippedTestContext", but "NSObject" will be sufficient for `perform(_:with:_with:)`.
guard let skippedTestContext = skippedTestContextAny as? NSObject else {
print("""
[Quick Warning]: The internals of Apple's XCTestCaseRun have changed.
We expected `skippedTestContextAny` to have type `NSObject`,
but we got an object of type \(type(of: skippedTestContextAny))
""" + messageSuffix)
return
}
guard let sourceCodeContextAny = skippedTestContext.value(forKey: "sourceCodeContext") else {
print("""
[Quick Warning]: The internals of Apple's XCTestCaseRun have changed.
We expected `XCTSkippedTestContext` to have a `sourceCodeContext` property, but it did not.
""" + messageSuffix)
return
}
guard let sourceCodeContext = sourceCodeContextAny as? XCTSourceCodeContext else {
print("""
[Quick Warning]: The internals of Apple's XCTestCaseRun have changed.
We expected `XCTSkippedTestContext.sourceCodeContext` to have type `XCTSourceCodeContext`,
but we got an object of type \(type(of: sourceCodeContextAny)).
""" + messageSuffix)
return
}
guard testRun.responds(to: Self.recordSkipSelector) else {
print("""
[Quick Warning]: The internals of Apple's XCTestCaseRun have changed, as it no longer responds to
the -[XCTSkip \(NSStringFromSelector(Self.recordSkipSelector))] message necessary to report skipped tests to Xcode.
""" + messageSuffix)
return
}
testRun.perform(Self.recordSkipSelector, with: testSkippedError.message, with: sourceCodeContext)
#endif
}
internal func reportFailedTest(_ error: Error, name: String, callsite: Callsite) {
let description = "Test \(name) threw unexpected error: \(error.localizedDescription)"
#if canImport(Darwin)
let file = callsite.file
let location = XCTSourceCodeLocation(filePath: file, lineNumber: Int(callsite.line))
let sourceCodeContext = XCTSourceCodeContext(location: location)
let issue = XCTIssue(
type: .thrownError,
compactDescription: description,
sourceCodeContext: sourceCodeContext
)
AsyncSpec.current?.record(issue)
#else
let file = callsite.file.description
AsyncSpec.current?.recordFailure(
withDescription: description,
inFile: file,
atLine: Int(callsite.line),
expected: false
)
#endif
}
internal func reportStoppedTest(_ stopTestError: StopTest) {
guard stopTestError.reportError else { return }
let callsite = stopTestError.callsite
#if canImport(Darwin)
let file = callsite.file
let location = XCTSourceCodeLocation(filePath: file, lineNumber: Int(callsite.line))
let sourceCodeContext = XCTSourceCodeContext(location: location)
let issue = XCTIssue(
type: .assertionFailure,
compactDescription: stopTestError.failureDescription,
sourceCodeContext: sourceCodeContext
)
AsyncSpec.current?.record(issue)
#else
let file = callsite.file.description
AsyncSpec.current?.recordFailure(
withDescription: stopTestError.failureDescription,
inFile: file,
atLine: Int(callsite.line),
expected: true
)
#endif
}
}
extension AsyncExample {
/**
Returns a boolean indicating whether two Example objects are equal.
If two examples are defined at the exact same callsite, they must be equal.
*/
@nonobjc public static func == (lhs: AsyncExample, rhs: AsyncExample) -> Bool {
return lhs.callsite == rhs.callsite
}
}