forked from apple/swift-async-algorithms
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathTest.swift
377 lines (342 loc) · 13 KB
/
Test.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
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
import _CAsyncSequenceValidationSupport
import AsyncAlgorithms
@_silgen_name("swift_job_run")
@usableFromInline
internal func _swiftJobRun(
_ job: UnownedJob,
_ executor: UnownedSerialExecutor
) -> ()
public protocol AsyncSequenceValidationTest: Sendable {
var inputs: [AsyncSequenceValidationDiagram.Specification] { get }
var output: AsyncSequenceValidationDiagram.Specification { get }
func test<C: TestClock>(with clock: C, activeTicks: [C.Instant], output: AsyncSequenceValidationDiagram.Specification, _ event: (String) -> Void) async throws
}
extension AsyncSequenceValidationDiagram {
struct Test<Operation: AsyncSequence>: AsyncSequenceValidationTest, @unchecked Sendable where Operation.Element == String {
let inputs: [Specification]
let sequence: Operation
let output: Specification
func test<C: TestClock>(with clock: C, activeTicks: [C.Instant], output: Specification, _ event: (String) -> Void) async throws {
var iterator = sequence.makeAsyncIterator()
do {
for tick in activeTicks {
if tick != clock.now {
try await clock.sleep(until: tick, tolerance: nil)
}
if let item = try await iterator.next() {
event(item)
} else {
break
}
}
do {
if let pastEnd = try await iterator.next(){
let failure = ExpectationFailure(
when: Context.clock!.now,
kind: .specificationViolationGotValueAfterIteration(pastEnd),
specification: output)
Context.specificationFailures.append(failure)
}
} catch {
let failure = ExpectationFailure(
when: Context.clock!.now,
kind: .specificationViolationGotFailureAfterIteration(error),
specification: output)
Context.specificationFailures.append(failure)
}
} catch {
throw error
}
}
}
struct Context {
final class ClockExecutor: SerialExecutor {
@available(macOS 14.0, iOS 17.0, watchOS 10.0, tvOS 17.0, *)
func enqueue(_ job: __owned ExecutorJob) {
job.runSynchronously(on: asUnownedSerialExecutor())
}
@available(*, deprecated) // known deprecation warning
func enqueue(_ job: UnownedJob) {
job._runSynchronously(on: asUnownedSerialExecutor())
}
func asUnownedSerialExecutor() -> UnownedSerialExecutor {
UnownedSerialExecutor(ordinary: self)
}
}
static var clock: Clock?
static let executor = ClockExecutor()
static var driver: TaskDriver?
static var currentJob: Job?
static var specificationFailures = [ExpectationFailure]()
}
enum ActualResult {
case success(String?)
case failure(Error)
case none
init(_ result: Result<String?, Error>?) {
if let result = result {
switch result {
case .success(let value):
self = .success(value)
case .failure(let error):
self = .failure(error)
}
} else {
self = .none
}
}
}
static func validate<Theme: AsyncSequenceValidationTheme>(
inputs: [Specification],
output: Specification,
theme: Theme,
expected: [ExpectationResult.Event],
actual: [(Clock.Instant, Result<String?, Error>)]
) -> (ExpectationResult, [ExpectationFailure]) {
let result = ExpectationResult(expected: expected, actual: actual)
var failures = Context.specificationFailures
Context.specificationFailures.removeAll()
let actualTimes = actual.map { when, _ in when }
let expectedTimes = expected.map { $0.when }
var expectedMap = [Clock.Instant: [ExpectationResult.Event]]()
var actualMap = [Clock.Instant: [Result<String?, Error>]]()
for event in expected {
expectedMap[event.when, default: []].append(event)
}
for (when, result) in actual {
actualMap[when, default: []].append(result)
}
let allTimes = Set(actualTimes + expectedTimes).sorted()
for when in allTimes {
let expectedResults = expectedMap[when] ?? []
let actualResults = actualMap[when] ?? []
var expectedIterator = expectedResults.makeIterator()
var actualIterator = actualResults.makeIterator()
while let expectedEvent = expectedIterator.next() {
let actualResult = ActualResult(actualIterator.next())
switch (expectedEvent.result, actualResult) {
case (.success(let expected), .success(let actual)):
switch (expected, actual) {
case (.some(let expected), .some(let actual)):
if expected != actual {
let failure = ExpectationFailure(
when: when,
kind: .expectedMismatch(expected, actual),
specification: output,
index: expectedEvent.offset)
failures.append(failure)
}
case (.none, .some(let actual)):
let failure = ExpectationFailure(
when: when,
kind: .expectedFinishButGotValue(actual),
specification: output)
failures.append(failure)
case (.some(let expected), .none):
let failure = ExpectationFailure(
when: when,
kind: .expectedValueButGotFinished(expected),
specification: output,
index: expectedEvent.offset)
failures.append(failure)
case (.none, .none):
break
}
case (.success(let expected), .failure(let actual)):
if let expected = expected {
let failure = ExpectationFailure(
when: when,
kind: .expectedValueButGotFailure(expected, actual),
specification: output,
index: expectedEvent.offset)
failures.append(failure)
} else {
let failure = ExpectationFailure(
when: when,
kind: .expectedFinishButGotFailure(actual),
specification: output,
index: expectedEvent.offset)
failures.append(failure)
}
case (.success(let expected), .none):
switch expected {
case .some(let expected):
let failure = ExpectationFailure(
when: when,
kind: .expectedValue(expected),
specification: output,
index: expectedEvent.offset)
failures.append(failure)
case .none:
let failure = ExpectationFailure(
when: when,
kind: .expectedFinish,
specification: output,
index: expectedEvent.offset)
failures.append(failure)
}
case (.failure(let expected), .success(let actual)):
if let actual = actual {
let failure = ExpectationFailure(
when: when,
kind: .expectedFailureButGotValue(expected, actual),
specification: output,
index: expectedEvent.offset)
failures.append(failure)
} else {
let failure = ExpectationFailure(
when: when,
kind: .expectedFailureButGotFinish(expected),
specification: output,
index: expectedEvent.offset)
failures.append(failure)
}
case (.failure, .failure):
break
case (.failure(let expected), .none):
let failure = ExpectationFailure(
when: when,
kind: .expectedFailure(expected),
specification: output,
index: expectedEvent.offset)
failures.append(failure)
}
}
while let unexpectedResult = actualIterator.next() {
switch unexpectedResult {
case .success(let actual):
switch actual {
case .some(let actual):
let failure = ExpectationFailure(
when: when,
kind: .unexpectedValue(actual),
specification: output)
failures.append(failure)
case .none:
let failure = ExpectationFailure(
when: when,
kind: .unexpectedFinish,
specification: output)
failures.append(failure)
}
case .failure(let actual):
let failure = ExpectationFailure(
when: when,
kind: .unexpectedFailure(actual),
specification: output)
failures.append(failure)
}
}
}
return (result, failures)
}
public static func test<Test: AsyncSequenceValidationTest, Theme: AsyncSequenceValidationTheme>(
theme: Theme,
@AsyncSequenceValidationDiagram _ build: (AsyncSequenceValidationDiagram) -> Test
) throws -> (ExpectationResult, [ExpectationFailure]) {
let diagram = AsyncSequenceValidationDiagram()
let clock = diagram._clock
let test = build(diagram)
for index in 0..<test.inputs.count {
// fault in all inputs
_ = diagram.inputs[index]
}
for (index, input) in diagram.inputs.enumerated() {
let inputSpecification = test.inputs[index]
try input.parse(inputSpecification.specification, theme: theme, location: inputSpecification.location)
}
let parsedOutput = try Event.parse(test.output.specification, theme: theme, location: test.output.location)
let cancelEvents = Set(parsedOutput.filter { when, event in
switch event {
case .cancel: return true
default: return false
}
}.map { when, _ in return when })
let activeTicks = parsedOutput.reduce(into: [Clock.Instant.init(when: .zero)]) { events, thisEvent in
switch thisEvent {
case (let when, .delayNext(_)):
events.removeLast()
events.append(when.advanced(by: .steps(1)))
case (let when, _):
events.append(when)
}
}
var expected = [ExpectationResult.Event]()
for (when, event) in parsedOutput {
for result in event.results {
expected.append(ExpectationResult.Event(when: when, result: result, offset: event.index))
}
}
let times = parsedOutput.map { when, _ in when }
guard let end = (times + diagram.inputs.compactMap { $0.end }).max() else {
return (ExpectationResult(expected: [], actual: []), [])
}
let actual = ManagedCriticalState([(Clock.Instant, Result<String?, Error>)]())
Context.clock = clock
Context.specificationFailures.removeAll()
// This all needs to be isolated from potential Tasks (the caller function might be async!)
Context.driver = TaskDriver(queue: diagram.queue) { driver in
swift_task_enqueueGlobal_hook = { job, original in
Context.driver?.enqueue(job)
}
let runner = Task {
do {
try await test.test(with: clock, activeTicks: activeTicks, output: test.output) { event in
actual.withCriticalRegion { values in
values.append((clock.now, .success(event)))
}
}
actual.withCriticalRegion { values in
values.append((clock.now, .success(nil)))
}
} catch {
actual.withCriticalRegion { values in
values.append((clock.now, .failure(error)))
}
}
}
// Drain off any initial work. Work may spawn additional work to be done.
// If the driver ever becomes blocked on the clock, exit early out of that
// drain, because the drain cant make any forward progress if it is blocked
// by a needed clock advancement.
diagram.queue.drain()
// Next make sure to iterate a decent amount past the end of the maximum
// scheduled things (that way we ensure any reasonable errors are caught)
for _ in 0..<(end.when.rawValue * 2) {
if cancelEvents.contains(diagram.queue.now.advanced(by: .steps(1))) {
runner.cancel()
}
diagram.queue.advance()
}
runner.cancel()
Context.clock = nil
swift_task_enqueueGlobal_hook = nil
}
Context.driver?.start()
// This is only valid since we are doing tests here
// else wise this would cause QoS inversions
Context.driver?.join()
Context.driver = nil
return validate(
inputs: test.inputs,
output: test.output,
theme: theme,
expected: expected,
actual: actual.withCriticalRegion { $0 })
}
public static func test<Test: AsyncSequenceValidationTest>(
@AsyncSequenceValidationDiagram _ build: (AsyncSequenceValidationDiagram) -> Test
) throws -> (ExpectationResult, [ExpectationFailure]) {
try self.test(theme: .ascii, build)
}
}