-
Notifications
You must be signed in to change notification settings - Fork 152
/
TestInterspersed.swift
91 lines (81 loc) · 2.68 KB
/
TestInterspersed.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
//===----------------------------------------------------------------------===//
//
// 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 XCTest
import AsyncAlgorithms
final class TestInterspersed: XCTestCase {
func test_interspersed() async {
let source = [1, 2, 3, 4, 5]
let expected = [1, 0, 2, 0, 3, 0, 4, 0, 5]
let sequence = source.async.interspersed(with: 0)
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_empty() async {
let source = [Int]()
let expected = [Int]()
let sequence = source.async.interspersed(with: 0)
var actual = [Int]()
var iterator = sequence.makeAsyncIterator()
while let item = await iterator.next() {
actual.append(item)
}
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_interspersed_with_throwing_upstream() async {
let source = [1, 2, 3, -1, 4, 5]
let expected = [1, 0, 2, 0, 3, 0]
var actual = [Int]()
let sequence = source.async.map {
try throwOn(-1, $0)
}.interspersed(with: 0)
var iterator = sequence.makeAsyncIterator()
do {
while let item = try await iterator.next() {
actual.append(item)
}
XCTFail()
} catch {
XCTAssertEqual(Failure(), error as? Failure)
}
let pastEnd = try! await iterator.next()
XCTAssertNil(pastEnd)
XCTAssertEqual(actual, expected)
}
func test_cancellation() async {
let source = Indefinite(value: "test")
let sequence = source.async.interspersed(with: "sep")
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
let task = Task {
var iterator = sequence.makeAsyncIterator()
let _ = await iterator.next()
iterated.fulfill()
while let _ = await iterator.next() { }
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
finished.fulfill()
}
// ensure the other task actually starts
wait(for: [iterated], timeout: 1.0)
// cancellation should ensure the loop finishes
// without regards to the remaining underlying sequence
task.cancel()
wait(for: [finished], timeout: 1.0)
}
}