-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathAsyncSequence+ShareTests.swift
86 lines (74 loc) · 2.47 KB
/
AsyncSequence+ShareTests.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
//
// AsyncSequence+ShareTests.swift
//
//
// Created by Thibault Wittemberg on 03/03/2022.
//
import AsyncExtensions
import XCTest
private extension DispatchTimeInterval {
var nanoseconds: UInt64 {
switch self {
case .nanoseconds(let value) where value >= 0: return UInt64(value)
case .microseconds(let value) where value >= 0: return UInt64(value) * 1000
case .milliseconds(let value) where value >= 0: return UInt64(value) * 1_000_000
case .seconds(let value) where value >= 0: return UInt64(value) * 1_000_000_000
case .never: return .zero
default: return .zero
}
}
}
private struct LongAsyncSequence<Element>: AsyncSequence, AsyncIteratorProtocol {
typealias Element = Element
typealias AsyncIterator = LongAsyncSequence
var elements: IndexingIterator<[Element]>
let interval: DispatchTimeInterval
var currentIndex = -1
let failAt: Int?
var hasEmitted = false
let onCancel: () -> Void
init(elements: [Element], interval: DispatchTimeInterval = .seconds(0), failAt: Int? = nil, onCancel: @escaping () -> Void = {}) {
self.onCancel = onCancel
self.elements = elements.makeIterator()
self.failAt = failAt
self.interval = interval
}
mutating func next() async throws -> Element? {
return try await withTaskCancellationHandler {
try await Task.sleep(nanoseconds: self.interval.nanoseconds)
self.currentIndex += 1
if self.currentIndex == self.failAt {
throw MockError(code: 0)
}
return self.elements.next()
} onCancel: {[onCancel] in
onCancel()
}
}
func makeAsyncIterator() -> AsyncIterator {
self
}
}
final class AsyncSequence_ShareTests: XCTestCase {
func test_share_multicasts_values_to_clientLoops() {
let tasksHaveFinishedExpectation = expectation(description: "the tasks have finished")
tasksHaveFinishedExpectation.expectedFulfillmentCount = 2
let sut = LongAsyncSequence(
elements: ["1", "2", "3"],
interval: .milliseconds(200)
).share()
Task(priority: .high) {
var received = [String]()
try await sut.collect { received.append($0) }
XCTAssertEqual(received, ["1", "2", "3"])
tasksHaveFinishedExpectation.fulfill()
}
Task(priority: .high) {
var received = [String]()
try await sut.collect { received.append($0) }
XCTAssertEqual(received, ["1", "2", "3"])
tasksHaveFinishedExpectation.fulfill()
}
waitForExpectations(timeout: 5)
}
}