-
Notifications
You must be signed in to change notification settings - Fork 161
/
Copy pathTestMapError.swift
105 lines (91 loc) · 2.89 KB
/
TestMapError.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
import AsyncAlgorithms
import XCTest
#if compiler(>=6.0)
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
final class TestMapError: XCTestCase {
func test_mapError() async throws {
let array: [Any] = [1, 2, 3, MyAwesomeError.originalError, 4, 5, 6]
let sequence = array.async
.map {
if let error = $0 as? Error {
throw error
} else {
$0 as! Int
}
}
.mapError { _ in
MyAwesomeError.mappedError
}
var results: [Int] = []
do {
for try await number in sequence {
results.append(number)
}
XCTFail("sequence should throw")
} catch {
XCTAssertEqual(error, .mappedError)
}
XCTAssertEqual(results, [1, 2, 3])
}
func test_mapError_cancellation() async throws {
let value = "test"
let source = Indefinite(value: value).async
let sequence = source
.map {
if $0 == "just to trick compiler that this may throw" {
throw MyAwesomeError.originalError
} else {
$0
}
}
.mapError { _ in
MyAwesomeError.mappedError
}
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
let task = Task {
var firstIteration = false
for try await el in sequence {
XCTAssertEqual(el, value)
if !firstIteration {
firstIteration = true
iterated.fulfill()
}
}
finished.fulfill()
}
// ensure the other task actually starts
await fulfillment(of: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
await fulfillment(of: [finished], timeout: 1.0)
}
func test_mapError_empty() async throws {
let array: [String] = []
let sequence = array.async
.map {
if $0 == "just to trick compiler that this may throw" {
throw MyAwesomeError.originalError
} else {
$0
}
}
.mapError { _ in
MyAwesomeError.mappedError
}
var results: [String] = []
for try await value in sequence {
results.append(value)
}
XCTAssert(results.isEmpty)
}
}
@available(macOS 15.0, iOS 18.0, watchOS 11.0, tvOS 18.0, visionOS 2.0, *)
private extension TestMapError {
enum MyAwesomeError: Error {
case originalError
case mappedError
}
}
#endif