Apply formatting

This commit is contained in:
Franz Busch authored and Franz Busch committed 2025-03-28 21:59:41 +01:00
1 parent ba33a225e9
commit d5b49aab17
97 files changed
+5078 -4440

No files matched your search

@@ -13,169 +13,169 @@ import AsyncAlgorithms
import XCTest
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]()
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_every() async {
let source = [1, 2, 3, 4, 5, 6, 7, 8]
let expected = [1, 2, 3, 0, 4, 5, 6, 0, 7, 8]
let sequence = source.async.interspersed(every: 3, 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_closure() 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_async_closure() async {
let source = [1, 2, 3, 4, 5]
let expected = [1, 0, 2, 0, 3, 0, 4, 0, 5]
let sequence = source.async.interspersed {
try! await Task.sleep(nanoseconds: 1000)
return 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_throwing_closure() async {
let source = [1, 2]
let expected = [1]
var actual = [Int]()
let sequence = source.async.interspersed(with: { throw Failure() })
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_interspersed_async_throwing_closure() async {
let source = [1, 2]
let expected = [1]
var actual = [Int]()
let sequence = source.async.interspersed {
try await Task.sleep(nanoseconds: 1000)
throw Failure()
}
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_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]
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 lockStepChannel = AsyncChannel<Void>()
await withTaskGroup(of: Void.self) { group in
group.addTask {
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_every() async {
let source = [1, 2, 3, 4, 5, 6, 7, 8]
let expected = [1, 2, 3, 0, 4, 5, 6, 0, 7, 8]
let sequence = source.async.interspersed(every: 3, 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_closure() 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_async_closure() async {
let source = [1, 2, 3, 4, 5]
let expected = [1, 0, 2, 0, 3, 0, 4, 0, 5]
let sequence = source.async.interspersed {
try! await Task.sleep(nanoseconds: 1000)
return 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_throwing_closure() async {
let source = [1, 2]
let expected = [1]
var actual = [Int]()
let sequence = source.async.interspersed(with: { throw Failure() })
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_interspersed_async_throwing_closure() async {
let source = [1, 2]
let expected = [1]
var actual = [Int]()
let sequence = source.async.interspersed {
try await Task.sleep(nanoseconds: 1000)
throw Failure()
}
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_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]
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 lockStepChannel = AsyncChannel<Void>()
await withTaskGroup(of: Void.self) { group in
group.addTask {
var iterator = sequence.makeAsyncIterator()
let _ = await iterator.next()
// Information the parent task that we are consuming
await lockStepChannel.send(())
while let _ = await iterator.next() {}
await lockStepChannel.send(())
}
// Waiting until the child task started consuming
_ = await lockStepChannel.first { _ in true }
// Now we cancel the child
group.cancelAll()
await group.waitForAll()
}
let _ = await iterator.next()
// Information the parent task that we are consuming
await lockStepChannel.send(())
while let _ = await iterator.next() {}
await lockStepChannel.send(())
}
// Waiting until the child task started consuming
_ = await lockStepChannel.first { _ in true }
// Now we cancel the child
group.cancelAll()
await group.waitForAll()
}
}
}
@@ -17,12 +17,12 @@ import XCTest
public struct InfiniteAsyncSequence<Value: Sendable>: AsyncSequence, Sendable {
public typealias Element = Value
let value: Value
public struct AsyncIterator : AsyncIteratorProtocol, Sendable {
public struct AsyncIterator: AsyncIteratorProtocol, Sendable {
@usableFromInline
let value: Value
@inlinable
public mutating func next() async throws -> Element? {
guard !Task.isCancelled else {
@@ -38,21 +38,33 @@ public struct InfiniteAsyncSequence<Value: Sendable>: AsyncSequence, Sendable {
final class _ThroughputMetric: NSObject, XCTMetric, @unchecked Sendable {
var eventCount = 0
override init() { }
func reportMeasurements(from startTime: XCTPerformanceMeasurementTimestamp, to endTime: XCTPerformanceMeasurementTimestamp) throws -> [XCTPerformanceMeasurement] {
return [XCTPerformanceMeasurement(identifier: "com.swift.AsyncAlgorithms.Throughput", displayName: "Throughput", doubleValue: Double(eventCount) / (endTime.date.timeIntervalSinceReferenceDate - startTime.date.timeIntervalSinceReferenceDate), unitSymbol: " Events/sec", polarity: .prefersLarger)]
override init() {}
func reportMeasurements(
from startTime: XCTPerformanceMeasurementTimestamp,
to endTime: XCTPerformanceMeasurementTimestamp
) throws -> [XCTPerformanceMeasurement] {
return [
XCTPerformanceMeasurement(
identifier: "com.swift.AsyncAlgorithms.Throughput",
displayName: "Throughput",
doubleValue: Double(eventCount)
/ (endTime.date.timeIntervalSinceReferenceDate - startTime.date.timeIntervalSinceReferenceDate),
unitSymbol: " Events/sec",
polarity: .prefersLarger
)
]
}
func copy(with zone: NSZone? = nil) -> Any {
return self
}
func willBeginMeasuring() {
eventCount = 0
}
func didStopMeasuring() { }
func didStopMeasuring() {}
}
extension XCTestCase {
@@ -85,7 +97,9 @@ extension XCTestCase {
}
}
public func measureThrowingChannelThroughput<Output: Sendable>(output: @Sendable @escaping @autoclosure () -> Output) async {
public func measureThrowingChannelThroughput<Output: Sendable>(
output: @Sendable @escaping @autoclosure () -> Output
) async {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
@@ -114,14 +128,17 @@ extension XCTestCase {
}
}
public func measureSequenceThroughput<S: AsyncSequence, Output>( output: @autoclosure () -> Output, _ sequenceBuilder: (InfiniteAsyncSequence<Output>) -> S) async where S: Sendable {
public func measureSequenceThroughput<S: AsyncSequence, Output>(
output: @autoclosure () -> Output,
_ sequenceBuilder: (InfiniteAsyncSequence<Output>) -> S
) async where S: Sendable {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
measure(metrics: [metric]) {
let infSeq = InfiniteAsyncSequence(value: output())
let seq = sequenceBuilder(infSeq)
let exp = self.expectation(description: "Finished")
let iterTask = Task<Int, Error> {
var eventCount = 0
@@ -137,16 +154,20 @@ extension XCTestCase {
self.wait(for: [exp], timeout: sampleTime * 2)
}
}
public func measureSequenceThroughput<S: AsyncSequence, Output>(firstOutput: @autoclosure () -> Output, secondOutput: @autoclosure () -> Output, _ sequenceBuilder: (InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>) -> S) async where S: Sendable {
public func measureSequenceThroughput<S: AsyncSequence, Output>(
firstOutput: @autoclosure () -> Output,
secondOutput: @autoclosure () -> Output,
_ sequenceBuilder: (InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>) -> S
) async where S: Sendable {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
measure(metrics: [metric]) {
let firstInfSeq = InfiniteAsyncSequence(value: firstOutput())
let secondInfSeq = InfiniteAsyncSequence(value: secondOutput())
let seq = sequenceBuilder(firstInfSeq, secondInfSeq)
let exp = self.expectation(description: "Finished")
let iterTask = Task<Int, Error> {
var eventCount = 0
@@ -162,17 +183,23 @@ extension XCTestCase {
self.wait(for: [exp], timeout: sampleTime * 2)
}
}
public func measureSequenceThroughput<S: AsyncSequence, Output>(firstOutput: @autoclosure () -> Output, secondOutput: @autoclosure () -> Output, thirdOutput: @autoclosure () -> Output, _ sequenceBuilder: (InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>) -> S) async where S: Sendable {
public func measureSequenceThroughput<S: AsyncSequence, Output>(
firstOutput: @autoclosure () -> Output,
secondOutput: @autoclosure () -> Output,
thirdOutput: @autoclosure () -> Output,
_ sequenceBuilder: (InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>, InfiniteAsyncSequence<Output>)
-> S
) async where S: Sendable {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
measure(metrics: [metric]) {
let firstInfSeq = InfiniteAsyncSequence(value: firstOutput())
let secondInfSeq = InfiniteAsyncSequence(value: secondOutput())
let thirdInfSeq = InfiniteAsyncSequence(value: thirdOutput())
let seq = sequenceBuilder(firstInfSeq, secondInfSeq, thirdInfSeq)
let exp = self.expectation(description: "Finished")
let iterTask = Task<Int, Error> {
var eventCount = 0
@@ -187,16 +214,19 @@ extension XCTestCase {
iterTask.cancel()
self.wait(for: [exp], timeout: sampleTime * 2)
}
}
public func measureSequenceThroughput<S: AsyncSequence, Source: AsyncSequence>( source: Source, _ sequenceBuilder: (Source) -> S) async where S: Sendable, Source: Sendable {
}
public func measureSequenceThroughput<S: AsyncSequence, Source: AsyncSequence>(
source: Source,
_ sequenceBuilder: (Source) -> S
) async where S: Sendable, Source: Sendable {
let metric = _ThroughputMetric()
let sampleTime: Double = 0.1
measure(metrics: [metric]) {
let infSeq = source
let seq = sequenceBuilder(infSeq)
let exp = self.expectation(description: "Finished")
let iterTask = Task<Int, Error> {
var eventCount = 0
@@ -215,26 +245,26 @@ extension XCTestCase {
}
final class TestMeasurements: XCTestCase {
struct PassthroughSequence<S: AsyncSequence> : AsyncSequence, Sendable where S : Sendable, S.AsyncIterator : Sendable {
struct PassthroughSequence<S: AsyncSequence>: AsyncSequence, Sendable where S: Sendable, S.AsyncIterator: Sendable {
typealias Element = S.Element
struct AsyncIterator : AsyncIteratorProtocol, Sendable {
struct AsyncIterator: AsyncIteratorProtocol, Sendable {
@usableFromInline
var base : S.AsyncIterator
var base: S.AsyncIterator
@inlinable
mutating func next() async throws -> Element? {
return try await base.next()
}
}
let base : S
let base: S
func makeAsyncIterator() -> AsyncIterator {
.init(base: base.makeAsyncIterator())
}
}
public func testThroughputTesting() async {
await self.measureSequenceThroughput(output: 1) {
PassthroughSequence(base: $0)
@@ -11,7 +11,7 @@
import XCTest
fileprivate enum _XCTAssertion {
private enum _XCTAssertion {
case equal
case equalWithAccuracy
case identical
@@ -30,9 +30,9 @@ fileprivate enum _XCTAssertion {
case fail
case throwsError
case noThrow
var name: String? {
switch(self) {
switch self {
case .equal: return "XCTAssertEqual"
case .equalWithAccuracy: return "XCTAssertEqual"
case .identical: return "XCTAssertIdentical"
@@ -55,18 +55,18 @@ fileprivate enum _XCTAssertion {
}
}
fileprivate enum _XCTAssertionResult {
private enum _XCTAssertionResult {
case success
case expectedFailure(String?)
case unexpectedFailure(Swift.Error)
var isExpected: Bool {
switch self {
case .unexpectedFailure(_): return false
default: return true
}
}
func failureDescription(_ assertion: _XCTAssertion) -> String {
let explanation: String
switch self {
@@ -75,23 +75,28 @@ fileprivate enum _XCTAssertionResult {
case .expectedFailure(_): explanation = "failed"
case .unexpectedFailure(let error): explanation = "threw error \"\(error)\""
}
if let name = assertion.name {
return "\(name) \(explanation)"
} else {
guard let name = assertion.name else {
return explanation
}
return "\(name) \(explanation)"
}
}
private func _XCTEvaluateAssertion(_ assertion: _XCTAssertion, message: () -> String, file: StaticString, line: UInt, expression: () throws -> _XCTAssertionResult) {
private func _XCTEvaluateAssertion(
_ assertion: _XCTAssertion,
message: () -> String,
file: StaticString,
line: UInt,
expression: () throws -> _XCTAssertionResult
) {
let result: _XCTAssertionResult
do {
result = try expression()
} catch {
result = .unexpectedFailure(error)
}
switch result {
case .success:
return
@@ -100,22 +105,34 @@ private func _XCTEvaluateAssertion(_ assertion: _XCTAssertion, message: () -> St
}
}
fileprivate func _XCTAssertEqual<T>(_ expression1: () throws -> T, _ expression2: () throws -> T, _ equal: (T, T) -> Bool, _ message: () -> String, file: StaticString = #filePath, line: UInt = #line) {
private func _XCTAssertEqual<T>(
_ expression1: () throws -> T,
_ expression2: () throws -> T,
_ equal: (T, T) -> Bool,
_ message: () -> String,
file: StaticString = #filePath,
line: UInt = #line
) {
_XCTEvaluateAssertion(.equal, message: message, file: file, line: line) {
let (value1, value2) = (try expression1(), try expression2())
if equal(value1, value2) {
return .success
} else {
guard equal(value1, value2) else {
return .expectedFailure("(\"\(value1)\") is not equal to (\"\(value2)\")")
}
return .success
}
}
public func XCTAssertEqual<A: Equatable, B: Equatable>(_ expression1: @autoclosure () throws -> (A, B), _ expression2: @autoclosure () throws -> (A, B), _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line) {
public func XCTAssertEqual<A: Equatable, B: Equatable>(
_ expression1: @autoclosure () throws -> (A, B),
_ expression2: @autoclosure () throws -> (A, B),
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) {
_XCTAssertEqual(expression1, expression2, { $0 == $1 }, message, file: file, line: line)
}
fileprivate func ==<A: Equatable, B: Equatable>(_ lhs: [(A, B)], _ rhs: [(A, B)]) -> Bool {
private func == <A: Equatable, B: Equatable>(_ lhs: [(A, B)], _ rhs: [(A, B)]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
@@ -127,15 +144,27 @@ fileprivate func ==<A: Equatable, B: Equatable>(_ lhs: [(A, B)], _ rhs: [(A, B)]
return true
}
public func XCTAssertEqual<A: Equatable, B: Equatable>(_ expression1: @autoclosure () throws -> [(A, B)], _ expression2: @autoclosure () throws -> [(A, B)], _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line) {
public func XCTAssertEqual<A: Equatable, B: Equatable>(
_ expression1: @autoclosure () throws -> [(A, B)],
_ expression2: @autoclosure () throws -> [(A, B)],
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) {
_XCTAssertEqual(expression1, expression2, { $0 == $1 }, message, file: file, line: line)
}
public func XCTAssertEqual<A: Equatable, B: Equatable, C: Equatable>(_ expression1: @autoclosure () throws -> (A, B, C), _ expression2: @autoclosure () throws -> (A, B, C), _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line) {
public func XCTAssertEqual<A: Equatable, B: Equatable, C: Equatable>(
_ expression1: @autoclosure () throws -> (A, B, C),
_ expression2: @autoclosure () throws -> (A, B, C),
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) {
_XCTAssertEqual(expression1, expression2, { $0 == $1 }, message, file: file, line: line)
}
fileprivate func ==<A: Equatable, B: Equatable, C: Equatable>(_ lhs: [(A, B, C)], _ rhs: [(A, B, C)]) -> Bool {
private func == <A: Equatable, B: Equatable, C: Equatable>(_ lhs: [(A, B, C)], _ rhs: [(A, B, C)]) -> Bool {
guard lhs.count == rhs.count else {
return false
}
@@ -147,48 +176,58 @@ fileprivate func ==<A: Equatable, B: Equatable, C: Equatable>(_ lhs: [(A, B, C)]
return true
}
public func XCTAssertEqual<A: Equatable, B: Equatable, C: Equatable>(_ expression1: @autoclosure () throws -> [(A, B, C)], _ expression2: @autoclosure () throws -> [(A, B, C)], _ message: @autoclosure () -> String = "", file: StaticString = #filePath, line: UInt = #line) {
public func XCTAssertEqual<A: Equatable, B: Equatable, C: Equatable>(
_ expression1: @autoclosure () throws -> [(A, B, C)],
_ expression2: @autoclosure () throws -> [(A, B, C)],
_ message: @autoclosure () -> String = "",
file: StaticString = #filePath,
line: UInt = #line
) {
_XCTAssertEqual(expression1, expression2, { $0 == $1 }, message, file: file, line: line)
}
@available(macOS 10.15, iOS 13.0, watchOS 6.0, tvOS 13.0, *)
internal func XCTAssertThrowsError<T>(
_ expression: @autoclosure () async throws -> T,
file: StaticString = #file,
line: UInt = #line,
verify: (Error) -> Void = { _ in }
_ expression: @autoclosure () async throws -> T,
file: StaticString = #file,
line: UInt = #line,
verify: (Error) -> Void = { _ in }
) async {
do {
_ = try await expression()
XCTFail("Expression did not throw error", file: file, line: line)
} catch {
verify(error)
}
do {
_ = try await expression()
XCTFail("Expression did not throw error", file: file, line: line)
} catch {
verify(error)
}
}
class WaiterDelegate: NSObject, XCTWaiterDelegate {
let state: ManagedCriticalState<UnsafeContinuation<Void, Never>?> = ManagedCriticalState(nil)
init(_ continuation: UnsafeContinuation<Void, Never>) {
state.withCriticalRegion { $0 = continuation }
}
func waiter(_ waiter: XCTWaiter, didFulfillInvertedExpectation expectation: XCTestExpectation) {
resume()
}
func waiter(_ waiter: XCTWaiter, didTimeoutWithUnfulfilledExpectations unfulfilledExpectations: [XCTestExpectation]) {
resume()
}
func waiter(_ waiter: XCTWaiter, fulfillmentDidViolateOrderingConstraintsFor expectation: XCTestExpectation, requiredExpectation: XCTestExpectation) {
func waiter(
_ waiter: XCTWaiter,
fulfillmentDidViolateOrderingConstraintsFor expectation: XCTestExpectation,
requiredExpectation: XCTestExpectation
) {
resume()
}
func nestedWaiter(_ waiter: XCTWaiter, wasInterruptedByTimedOutWaiter outerWaiter: XCTWaiter) {
}
func resume() {
let continuation = state.withCriticalRegion { continuation in
defer { continuation = nil }
@@ -200,7 +239,13 @@ class WaiterDelegate: NSObject, XCTWaiterDelegate {
extension XCTestCase {
@_disfavoredOverload
func fulfillment(of expectations: [XCTestExpectation], timeout: TimeInterval, enforceOrder: Bool = false, file: StaticString = #file, line: Int = #line) async {
func fulfillment(
of expectations: [XCTestExpectation],
timeout: TimeInterval,
enforceOrder: Bool = false,
file: StaticString = #file,
line: Int = #line
) async {
return await withUnsafeContinuation { continuation in
let delegate = WaiterDelegate(continuation)
let waiter = XCTWaiter(delegate: delegate)
@@ -9,7 +9,7 @@
//
//===----------------------------------------------------------------------===//
struct Failure: Error, Equatable { }
struct Failure: Error, Equatable {}
func throwOn<T: Equatable>(_ toThrowOn: T, _ value: T) throws -> T {
if value == toThrowOn {
@@ -17,9 +17,9 @@ public struct Gate: Sendable {
case open
case pending(UnsafeContinuation<Void, Never>)
}
let state = ManagedCriticalState(State.closed)
public func `open`() {
state.withCriticalRegion { state -> UnsafeContinuation<Void, Never>? in
switch state {
@@ -34,7 +34,7 @@ public struct Gate: Sendable {
}
}?.resume()
}
public func enter() async {
var other: UnsafeContinuation<Void, Never>?
await withUnsafeContinuation { (continuation: UnsafeContinuation<Void, Never>) in
@@ -45,7 +45,7 @@ public struct Gate: Sendable {
return nil
case .open:
state = .closed
return continuation
return continuation
case .pending(let existing):
other = existing
state = .pending(continuation)
@@ -13,7 +13,7 @@ public struct GatedSequence<Element> {
let elements: [Element]
let gates: [Gate]
var index = 0
public mutating func advance() {
defer { index += 1 }
guard index < gates.count else {
@@ -21,7 +21,7 @@ public struct GatedSequence<Element> {
}
gates[index].open()
}
public init(_ elements: [Element]) {
self.elements = elements
self.gates = elements.map { _ in Gate() }
@@ -31,11 +31,11 @@ public struct GatedSequence<Element> {
extension GatedSequence: AsyncSequence {
public struct Iterator: AsyncIteratorProtocol {
var gatedElements: [(Element, Gate)]
init(elements: [Element], gates: [Gate]) {
gatedElements = Array(zip(elements, gates))
}
public mutating func next() async -> Element? {
guard gatedElements.count > 0 else {
return nil
@@ -45,10 +45,10 @@ extension GatedSequence: AsyncSequence {
return element
}
}
public func makeAsyncIterator() -> Iterator {
Iterator(elements: elements, gates: gates)
}
}
extension GatedSequence: Sendable where Element: Sendable { }
extension GatedSequence: Sendable where Element: Sendable {}
@@ -11,11 +11,11 @@
struct Indefinite<Element: Sendable>: Sequence, IteratorProtocol, Sendable {
let value: Element
func next() -> Element? {
return value
}
func makeIterator() -> Indefinite<Element> {
self
}
@@ -14,78 +14,78 @@ import AsyncAlgorithms
public struct ManualClock: Clock {
public struct Step: DurationProtocol {
fileprivate var rawValue: Int
fileprivate init(_ rawValue: Int) {
self.rawValue = rawValue
}
public static func + (lhs: ManualClock.Step, rhs: ManualClock.Step) -> ManualClock.Step {
return .init(lhs.rawValue + rhs.rawValue)
}
public static func - (lhs: ManualClock.Step, rhs: ManualClock.Step) -> ManualClock.Step {
.init(lhs.rawValue - rhs.rawValue)
}
public static func / (lhs: ManualClock.Step, rhs: Int) -> ManualClock.Step {
.init(lhs.rawValue / rhs)
}
public static func * (lhs: ManualClock.Step, rhs: Int) -> ManualClock.Step {
.init(lhs.rawValue * rhs)
}
public static func / (lhs: ManualClock.Step, rhs: ManualClock.Step) -> Double {
Double(lhs.rawValue) / Double(rhs.rawValue)
}
public static func < (lhs: ManualClock.Step, rhs: ManualClock.Step) -> Bool {
lhs.rawValue < rhs.rawValue
}
public static var zero: ManualClock.Step { .init(0) }
public static func steps(_ amount: Int) -> Step {
return Step(amount)
}
}
public struct Instant: InstantProtocol, CustomStringConvertible {
public typealias Duration = Step
internal let rawValue: Int
internal init(_ rawValue: Int) {
self.rawValue = rawValue
}
public static func < (lhs: ManualClock.Instant, rhs: ManualClock.Instant) -> Bool {
return lhs.rawValue < rhs.rawValue
}
public func advanced(by duration: ManualClock.Step) -> ManualClock.Instant {
.init(rawValue + duration.rawValue)
}
public func duration(to other: ManualClock.Instant) -> ManualClock.Step {
.init(other.rawValue - rawValue)
}
public var description: String {
return "tick \(rawValue)"
}
}
fileprivate struct Wakeup {
let generation: Int
let continuation: UnsafeContinuation<Void, Error>
let deadline: Instant
}
fileprivate enum Scheduled: Hashable, Comparable, CustomStringConvertible {
case cancelled(Int)
case wakeup(Wakeup)
func hash(into hasher: inout Hasher) {
switch self {
case .cancelled(let generation):
@@ -94,14 +94,14 @@ public struct ManualClock: Clock {
hasher.combine(wakeup.generation)
}
}
var description: String {
switch self {
case .cancelled: return "Cancelled wakeup"
case .wakeup(let wakeup): return "Wakeup at \(wakeup.deadline)"
}
}
static func == (_ lhs: Scheduled, _ rhs: Scheduled) -> Bool {
switch (lhs, rhs) {
case (.cancelled(let lhsGen), .cancelled(let rhsGen)):
@@ -114,7 +114,7 @@ public struct ManualClock: Clock {
return lhs.generation == rhs.generation
}
}
static func < (lhs: ManualClock.Scheduled, rhs: ManualClock.Scheduled) -> Bool {
switch (lhs, rhs) {
case (.cancelled(let lhsGen), .cancelled(let rhsGen)):
@@ -127,14 +127,14 @@ public struct ManualClock: Clock {
return lhs.generation < rhs.generation
}
}
var deadline: Instant? {
switch self {
case .cancelled: return nil
case .wakeup(let wakeup): return wakeup.deadline
}
}
func resume() {
switch self {
case .wakeup(let wakeup):
@@ -144,54 +144,52 @@ public struct ManualClock: Clock {
}
}
}
fileprivate struct State {
var generation = 0
var scheduled = Set<Scheduled>()
var now = Instant(0)
var hasSleepers = false
}
fileprivate let state = ManagedCriticalState(State())
public var now: Instant {
state.withCriticalRegion { $0.now }
}
public var minimumResolution: Step { return .zero }
public init() { }
public init() {}
fileprivate func cancel(_ generation: Int) {
state.withCriticalRegion { state -> UnsafeContinuation<Void, Error>? in
if let existing = state.scheduled.remove(.cancelled(generation)) {
switch existing {
case .wakeup(let wakeup):
return wakeup.continuation
default:
return nil
}
} else {
guard let existing = state.scheduled.remove(.cancelled(generation)) else {
// insert the cancelled state for when it comes in to be scheduled as a wakeup
state.scheduled.insert(.cancelled(generation))
return nil
}
switch existing {
case .wakeup(let wakeup):
return wakeup.continuation
default:
return nil
}
}?.resume(throwing: CancellationError())
}
var hasSleepers: Bool {
state.withCriticalRegion { $0.hasSleepers }
}
public func advance() {
let pending = state.withCriticalRegion { state -> Set<Scheduled> in
state.now = state.now.advanced(by: .steps(1))
let pending = state.scheduled.filter { item in
if let deadline = item.deadline {
return deadline <= state.now
} else {
guard let deadline = item.deadline else {
return false
}
return deadline <= state.now
}
state.scheduled.subtract(pending)
if pending.count > 0 {
@@ -203,42 +201,40 @@ public struct ManualClock: Clock {
item.resume()
}
}
public func advance(by steps: Step) {
for _ in 0..<steps.rawValue {
advance()
}
}
fileprivate func schedule(_ generation: Int, continuation: UnsafeContinuation<Void, Error>, deadline: Instant) {
let resumption = state.withCriticalRegion { state -> (UnsafeContinuation<Void, Error>, Result<Void, Error>)? in
let wakeup = Wakeup(generation: generation, continuation: continuation, deadline: deadline)
if let existing = state.scheduled.remove(.wakeup(wakeup)) {
switch existing {
case .wakeup:
fatalError()
case .cancelled:
// dont bother adding it back because it has been cancelled before we got here
return (continuation, .failure(CancellationError()))
}
} else {
guard let existing = state.scheduled.remove(.wakeup(wakeup)) else {
// there is no cancelled placeholder so let it run free
if deadline > state.now {
// the deadline is in the future so run it then
state.hasSleepers = true
state.scheduled.insert(.wakeup(wakeup))
return nil
} else {
guard deadline > state.now else {
// the deadline is now or in the past so run it immediately
return (continuation, .success(()))
}
// the deadline is in the future so run it then
state.hasSleepers = true
state.scheduled.insert(.wakeup(wakeup))
return nil
}
switch existing {
case .wakeup:
fatalError()
case .cancelled:
// dont bother adding it back because it has been cancelled before we got here
return (continuation, .failure(CancellationError()))
}
}
if let resumption = resumption {
resumption.0.resume(with: resumption.1)
}
}
public func sleep(until deadline: Instant, tolerance: Step? = nil) async throws {
let generation = state.withCriticalRegion { state -> Int in
defer { state.generation += 1 }
@@ -13,7 +13,7 @@ final class ReportingSequence<Element>: Sequence, IteratorProtocol {
enum Event: Equatable, CustomStringConvertible {
case next
case makeIterator
var description: String {
switch self {
case .next: return "next()"
@@ -21,14 +21,14 @@ final class ReportingSequence<Element>: Sequence, IteratorProtocol {
}
}
}
var events = [Event]()
var elements: [Element]
init(_ elements: [Element]) {
self.elements = elements
}
func next() -> Element? {
events.append(.next)
guard elements.count > 0 else {
@@ -36,7 +36,7 @@ final class ReportingSequence<Element>: Sequence, IteratorProtocol {
}
return elements.removeFirst()
}
func makeIterator() -> ReportingSequence {
events.append(.makeIterator)
return self
@@ -47,7 +47,7 @@ final class ReportingAsyncSequence<Element: Sendable>: AsyncSequence, AsyncItera
enum Event: Equatable, CustomStringConvertible {
case next
case makeAsyncIterator
var description: String {
switch self {
case .next: return "next()"
@@ -55,14 +55,14 @@ final class ReportingAsyncSequence<Element: Sendable>: AsyncSequence, AsyncItera
}
}
}
var events = [Event]()
var elements: [Element]
init(_ elements: [Element]) {
self.elements = elements
}
func next() async -> Element? {
events.append(.next)
guard elements.count > 0 else {
@@ -70,7 +70,7 @@ final class ReportingAsyncSequence<Element: Sendable>: AsyncSequence, AsyncItera
}
return elements.removeFirst()
}
func makeAsyncIterator() -> ReportingAsyncSequence {
events.append(.makeAsyncIterator)
return self
@@ -17,17 +17,17 @@ public struct Validator<Element: Sendable>: Sendable {
case ready
case pending(UnsafeContinuation<Void, Never>)
}
private struct State: Sendable {
var collected = [Element]()
var failure: Error?
var ready: Ready = .idle
}
private struct Envelope<Contents>: @unchecked Sendable {
var contents: Contents
}
private let state = ManagedCriticalState(State())
private func ready(_ apply: (inout State) -> Void) {
@@ -45,7 +45,7 @@ public struct Validator<Element: Sendable>: Sendable {
}
}?.resume()
}
internal func step() async {
await withUnsafeContinuation { (continuation: UnsafeContinuation<Void, Never>) in
state.withCriticalRegion { state -> UnsafeContinuation<Void, Never>? in
@@ -64,17 +64,20 @@ public struct Validator<Element: Sendable>: Sendable {
}
let onEvent: (@Sendable (Result<Element?, Error>) async -> Void)?
init(onEvent: @Sendable @escaping (Result<Element?, Error>) async -> Void) {
self.onEvent = onEvent
}
public init() {
self.onEvent = nil
}
public func test<S: AsyncSequence>(_ sequence: S, onFinish: @Sendable @escaping (inout S.AsyncIterator) async -> Void) where S.Element == Element {
public func test<S: AsyncSequence>(
_ sequence: S,
onFinish: @Sendable @escaping (inout S.AsyncIterator) async -> Void
) where S.Element == Element {
let envelope = Envelope(contents: sequence)
Task {
var iterator = envelope.contents.makeAsyncIterator()
@@ -97,18 +100,18 @@ public struct Validator<Element: Sendable>: Sendable {
await onFinish(&iterator)
}
}
public func validate() async -> [Element] {
await step()
return current
}
public var current: [Element] {
return state.withCriticalRegion { state in
return state.collected
}
}
public var failure: Error? {
return state.withCriticalRegion { state in
return state.failure
@@ -13,7 +13,7 @@ extension AsyncSequence {
func violatingSpecification(returningPastEndIteration element: Element) -> SpecificationViolatingSequence<Self> {
SpecificationViolatingSequence(self, kind: .producing(element))
}
func violatingSpecification(throwingPastEndIteration error: Error) -> SpecificationViolatingSequence<Self> {
SpecificationViolatingSequence(self, kind: .throwing(error))
}
@@ -24,10 +24,10 @@ struct SpecificationViolatingSequence<Base: AsyncSequence> {
case producing(Base.Element)
case throwing(Error)
}
let base: Base
let kind: Kind
init(_ base: Base, kind: Kind) {
self.base = base
self.kind = kind
@@ -36,13 +36,13 @@ struct SpecificationViolatingSequence<Base: AsyncSequence> {
extension SpecificationViolatingSequence: AsyncSequence {
typealias Element = Base.Element
struct Iterator: AsyncIteratorProtocol {
var iterator: Base.AsyncIterator
let kind: Kind
var finished = false
var violated = false
mutating func next() async throws -> Element? {
if finished {
if violated {
@@ -66,7 +66,7 @@ extension SpecificationViolatingSequence: AsyncSequence {
}
}
}
func makeAsyncIterator() -> Iterator {
Iterator(iterator: base.makeAsyncIterator(), kind: kind)
}
@@ -86,9 +86,9 @@ final class TestAdjacentPairs: XCTestCase {
}
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
+8 -2
View File
@@ -172,7 +172,10 @@ final class TestBuffer: XCTestCase {
}
}
func test_given_a_buffered_with_unbounded_sequence_when_cancelling_consumer_then_the_iteration_finishes_and_the_base_is_cancelled() async {
func
test_given_a_buffered_with_unbounded_sequence_when_cancelling_consumer_then_the_iteration_finishes_and_the_base_is_cancelled()
async
{
// Given
let buffered = Indefinite(value: 1).async.buffer(policy: .unbounded)
@@ -292,7 +295,10 @@ final class TestBuffer: XCTestCase {
XCTAssertNil(pastFailure)
}
func test_given_a_buffered_bounded_sequence_when_cancelling_consumer_then_the_iteration_finishes_and_the_base_is_cancelled() async {
func
test_given_a_buffered_bounded_sequence_when_cancelling_consumer_then_the_iteration_finishes_and_the_base_is_cancelled()
async
{
// Given
let buffered = Indefinite(value: 1).async.buffer(policy: .bounded(3))
@@ -15,16 +15,16 @@ import AsyncAlgorithms
final class TestBufferedByteIterator: XCTestCase {
actor Isolated<T: Sendable> {
var value: T
init(_ value: T) {
self.value = value
}
func update(_ value: T) async {
self.value = value
}
}
func test_immediately_empty() async throws {
let reloaded = Isolated(false)
var iterator = AsyncBufferedByteIterator(capacity: 3) { buffer in
@@ -39,7 +39,7 @@ final class TestBufferedByteIterator: XCTestCase {
wasReloaded = await reloaded.value
XCTAssertTrue(wasReloaded)
}
func test_one_pass() async throws {
let reloaded = Isolated(0)
var iterator = AsyncBufferedByteIterator(capacity: 3) { buffer in
@@ -52,7 +52,7 @@ final class TestBufferedByteIterator: XCTestCase {
buffer.copyBytes(from: [1, 2, 3])
return 3
}
var reloadCount = await reloaded.value
XCTAssertEqual(reloadCount, 0)
var byte = try await iterator.next()
@@ -76,7 +76,7 @@ final class TestBufferedByteIterator: XCTestCase {
reloadCount = await reloaded.value
XCTAssertEqual(reloadCount, 2)
}
func test_three_pass() async throws {
let reloaded = Isolated(0)
var iterator = AsyncBufferedByteIterator(capacity: 3) { buffer in
@@ -89,10 +89,10 @@ final class TestBufferedByteIterator: XCTestCase {
buffer.copyBytes(from: [1, 2, 3])
return 3
}
var reloadCount = await reloaded.value
XCTAssertEqual(reloadCount, 0)
for n in 1...3 {
var byte = try await iterator.next()
XCTAssertEqual(byte, 1)
@@ -107,8 +107,7 @@ final class TestBufferedByteIterator: XCTestCase {
reloadCount = await reloaded.value
XCTAssertEqual(reloadCount, n)
}
var byte = try await iterator.next()
XCTAssertNil(byte)
reloadCount = await reloaded.value
@@ -118,7 +117,7 @@ final class TestBufferedByteIterator: XCTestCase {
reloadCount = await reloaded.value
XCTAssertEqual(reloadCount, 4)
}
func test_three_pass_throwing() async throws {
let reloaded = Isolated(0)
var iterator = AsyncBufferedByteIterator(capacity: 3) { buffer in
@@ -134,10 +133,10 @@ final class TestBufferedByteIterator: XCTestCase {
buffer.copyBytes(from: [1, 2, 3])
return 3
}
var reloadCount = await reloaded.value
XCTAssertEqual(reloadCount, 0)
for n in 1...3 {
do {
var byte = try await iterator.next()
@@ -156,10 +155,9 @@ final class TestBufferedByteIterator: XCTestCase {
XCTAssertEqual(n, 3)
break
}
}
var byte = try await iterator.next()
XCTAssertNil(byte)
reloadCount = await reloaded.value
@@ -169,11 +167,11 @@ final class TestBufferedByteIterator: XCTestCase {
reloadCount = await reloaded.value
XCTAssertEqual(reloadCount, 3)
}
func test_cancellation() async {
struct RepeatingBytes: AsyncSequence {
typealias Element = UInt8
func makeAsyncIterator() -> AsyncBufferedByteIterator {
AsyncBufferedByteIterator(capacity: 3) { buffer in
buffer.copyBytes(from: [1, 2, 3])
+7 -7
View File
@@ -29,7 +29,7 @@ final class TestChain2: XCTestCase {
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_chain2_outputs_elements_from_first_sequence_and_throws_when_first_throws() async throws {
let chained = chain([1, 2, 3].async.map { try throwOn(3, $0) }, [4, 5, 6].async)
var iterator = chained.makeAsyncIterator()
@@ -48,7 +48,7 @@ final class TestChain2: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_chain2_outputs_elements_from_sequences_and_throws_when_second_throws() async throws {
let chained = chain([1, 2, 3].async, [4, 5, 6].async.map { try throwOn(5, $0) })
var iterator = chained.makeAsyncIterator()
@@ -67,7 +67,7 @@ final class TestChain2: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_chain2_finishes_when_task_is_cancelled() async {
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
@@ -115,7 +115,7 @@ final class TestChain3: XCTestCase {
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_chain3_outputs_elements_from_first_sequence_and_throws_when_first_throws() async throws {
let chained = chain([1, 2, 3].async.map { try throwOn(3, $0) }, [4, 5, 6].async, [7, 8, 9].async)
var iterator = chained.makeAsyncIterator()
@@ -134,7 +134,7 @@ final class TestChain3: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_chain3_outputs_elements_from_sequences_and_throws_when_second_throws() async throws {
let chained = chain([1, 2, 3].async, [4, 5, 6].async.map { try throwOn(5, $0) }, [7, 8, 9].async)
var iterator = chained.makeAsyncIterator()
@@ -153,7 +153,7 @@ final class TestChain3: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_chain3_outputs_elements_from_sequences_and_throws_when_third_throws() async throws {
let chained = chain([1, 2, 3].async, [4, 5, 6].async, [7, 8, 9].async.map { try throwOn(8, $0) })
var iterator = chained.makeAsyncIterator()
@@ -172,7 +172,7 @@ final class TestChain3: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_chain3_finishes_when_task_is_cancelled() async {
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
+40 -14
View File
@@ -123,7 +123,9 @@ final class TestChunk: XCTestCase {
}
func test_time_equalChunks() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"ABC- DEF- GHI- |"
$0.inputs[0].chunked(by: .repeating(every: .steps(4), clock: $0.clock)).map(concatCharacters)
@@ -132,7 +134,9 @@ final class TestChunk: XCTestCase {
}
func test_time_unequalChunks() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"AB------ A------- ABCDEFG- |"
$0.inputs[0].chunked(by: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
@@ -141,7 +145,9 @@ final class TestChunk: XCTestCase {
}
func test_time_emptyChunks() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"-- 1- --|"
$0.inputs[0].chunked(by: .repeating(every: .steps(2), clock: $0.clock)).map(concatCharacters)
@@ -150,7 +156,9 @@ final class TestChunk: XCTestCase {
}
func test_time_error() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"AB^"
$0.inputs[0].chunked(by: .repeating(every: .steps(5), clock: $0.clock)).map(concatCharacters)
@@ -159,7 +167,9 @@ final class TestChunk: XCTestCase {
}
func test_time_unsignaledTrailingChunk() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"111-111|"
$0.inputs[0].chunked(by: .repeating(every: .steps(4), clock: $0.clock)).map(sumCharacters)
@@ -168,7 +178,9 @@ final class TestChunk: XCTestCase {
}
func test_timeAndCount_timeAlwaysPrevails() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"AB------ A------- ABCDEFG- |"
$0.inputs[0].chunks(ofCount: 42, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
@@ -177,7 +189,9 @@ final class TestChunk: XCTestCase {
}
func test_timeAndCount_countAlwaysPrevails() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"AB --A-B -|"
$0.inputs[0].chunks(ofCount: 2, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
@@ -186,7 +200,9 @@ final class TestChunk: XCTestCase {
}
func test_timeAndCount_countResetsAfterCount() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"ABCDE --- ABCDE |"
$0.inputs[0].chunks(ofCount: 5, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
@@ -195,7 +211,9 @@ final class TestChunk: XCTestCase {
}
func test_timeAndCount_countResetsAfterSignal() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"AB------ ABCDE |"
$0.inputs[0].chunks(ofCount: 5, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
@@ -204,7 +222,9 @@ final class TestChunk: XCTestCase {
}
func test_timeAndCount_error() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"ABC^"
$0.inputs[0].chunks(ofCount: 5, or: .repeating(every: .steps(8), clock: $0.clock)).map(concatCharacters)
@@ -279,7 +299,9 @@ final class TestChunk: XCTestCase {
func test_projection() {
validate {
"A'Aa''ab' b'BB''bb' 'cc''CC' |"
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map { concatCharacters($0.1.map( {String($0.first!)} ) ) }
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map {
concatCharacters($0.1.map({ String($0.first!) }))
}
"-- - 'AAa' - - 'bBb' - ['cC'|]"
}
}
@@ -287,7 +309,9 @@ final class TestChunk: XCTestCase {
func test_projection_singleValue() {
validate {
"A----|"
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map { concatCharacters($0.1.map( {String($0.first!)} ) ) }
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map {
concatCharacters($0.1.map({ String($0.first!) }))
}
"-----[A|]"
}
}
@@ -295,7 +319,7 @@ final class TestChunk: XCTestCase {
func test_projection_singleGroup() {
validate {
"ABCDE|"
$0.inputs[0].chunked(on: { _ in 42 }).map { concatCharacters($0.1.map( {String($0.first!)} ) ) }
$0.inputs[0].chunked(on: { _ in 42 }).map { concatCharacters($0.1.map({ String($0.first!) })) }
"-----['ABCDE'|]"
}
}
@@ -303,7 +327,9 @@ final class TestChunk: XCTestCase {
func test_projection_error() {
validate {
"Aa^"
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map { concatCharacters($0.1.map( {String($0.first!)} ) ) }
$0.inputs[0].chunked(on: { $0.first!.lowercased() }).map {
concatCharacters($0.1.map({ String($0.first!) }))
}
"--^"
}
}
@@ -20,7 +20,7 @@ final class TestCombineLatest2: XCTestCase {
let actual = await Array(sequence)
XCTAssertGreaterThanOrEqual(actual.count, 3)
}
func test_throwing_combineLatest1() async {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
@@ -33,7 +33,7 @@ final class TestCombineLatest2: XCTestCase {
XCTAssertEqual(error as? Failure, Failure())
}
}
func test_throwing_combineLatest2() async {
let a = [1, 2, 3]
let b = ["a", "b", "c"]
@@ -46,7 +46,7 @@ final class TestCombineLatest2: XCTestCase {
XCTAssertEqual(error as? Failure, Failure())
}
}
func test_ordering1() async {
var a = GatedSequence([1, 2, 3])
var b = GatedSequence(["a", "b", "c"])
@@ -64,31 +64,31 @@ final class TestCombineLatest2: XCTestCase {
value = validator.current
XCTAssertEqual(value, [])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a"), (2, "b")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a"), (2, "b"), (3, "b")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a"), (2, "b"), (3, "b"), (3, "c")])
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (2, "a"), (2, "b"), (3, "b"), (3, "c")])
}
func test_ordering2() async {
var a = GatedSequence([1, 2, 3])
var b = GatedSequence(["a", "b", "c"])
@@ -106,31 +106,31 @@ final class TestCombineLatest2: XCTestCase {
value = validator.current
XCTAssertEqual(value, [])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b"), (2, "b")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b"), (2, "b"), (2, "c")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c")])
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (1, "b"), (2, "b"), (2, "c"), (3, "c")])
}
func test_ordering3() async {
var a = GatedSequence([1, 2, 3])
var b = GatedSequence(["a", "b", "c"])
@@ -148,31 +148,31 @@ final class TestCombineLatest2: XCTestCase {
value = validator.current
XCTAssertEqual(value, [])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a"), (3, "a")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a"), (3, "a"), (3, "b")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a"), (3, "a"), (3, "b"), (3, "c")])
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (2, "a"), (3, "a"), (3, "b"), (3, "c")])
}
func test_ordering4() async {
var a = GatedSequence([1, 2, 3])
var b = GatedSequence(["a", "b", "c"])
@@ -190,31 +190,31 @@ final class TestCombineLatest2: XCTestCase {
value = validator.current
XCTAssertEqual(value, [])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b"), (1, "c")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b"), (1, "c"), (2, "c")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b"), (1, "c"), (2, "c"), (3, "c")])
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (1, "b"), (1, "c"), (2, "c"), (3, "c")])
}
func test_throwing_ordering1() async {
var a = GatedSequence([1, 2, 3])
var b = GatedSequence(["a", "b", "c"])
@@ -236,25 +236,25 @@ final class TestCombineLatest2: XCTestCase {
value = validator.current
XCTAssertEqual(value, [])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (1, "b")])
XCTAssertEqual(validator.failure as? Failure, Failure())
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (1, "b")])
}
func test_throwing_ordering2() async {
var a = GatedSequence([1, 2, 3])
var b = GatedSequence(["a", "b", "c"])
@@ -276,25 +276,25 @@ final class TestCombineLatest2: XCTestCase {
value = validator.current
XCTAssertEqual(value, [])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a")])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a")])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a"), (2, "a")])
XCTAssertEqual(validator.failure as? Failure, Failure())
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a"), (2, "a")])
}
func test_cancellation() async {
let source1 = Indefinite(value: "test1")
let source2 = Indefinite(value: "test2")
@@ -319,15 +319,15 @@ final class TestCombineLatest2: XCTestCase {
await fulfillment(of: [finished], timeout: 1.0)
}
func test_combineLatest_when_cancelled() async {
let t = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
let c1 = Indefinite(value: "test1").async
let c2 = Indefinite(value: "test1").async
for await _ in combineLatest(c1, c2) {}
}
t.cancel()
func test_combineLatest_when_cancelled() async {
let t = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
let c1 = Indefinite(value: "test1").async
let c2 = Indefinite(value: "test1").async
for await _ in combineLatest(c1, c2) {}
}
t.cancel()
}
}
final class TestCombineLatest3: XCTestCase {
@@ -339,7 +339,7 @@ final class TestCombineLatest3: XCTestCase {
let actual = await Array(sequence)
XCTAssertGreaterThanOrEqual(actual.count, 3)
}
func test_ordering1() async {
var a = GatedSequence([1, 2, 3])
var b = GatedSequence(["a", "b", "c"])
@@ -361,36 +361,42 @@ final class TestCombineLatest3: XCTestCase {
value = validator.current
XCTAssertEqual(value, [])
c.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a", 4)])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4)])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4), (2, "b", 4)])
c.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5)])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5), (3, "b", 5)])
b.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5), (3, "b", 5), (3, "c", 5)])
c.advance()
value = await validator.validate()
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5), (3, "b", 5), (3, "c", 5), (3, "c", 6)])
XCTAssertEqual(
value,
[(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5), (3, "b", 5), (3, "c", 5), (3, "c", 6)]
)
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5), (3, "b", 5), (3, "c", 5), (3, "c", 6)])
XCTAssertEqual(
value,
[(1, "a", 4), (2, "a", 4), (2, "b", 4), (2, "b", 5), (3, "b", 5), (3, "c", 5), (3, "c", 6)]
)
}
}
@@ -23,7 +23,7 @@ final class TestCompacted: XCTestCase {
}
XCTAssertEqual(expected, actual)
}
func test_compacted_produces_nil_next_element_when_iteration_is_finished() async {
let source = [1, 2, nil, 3, 4, nil, 5]
let expected = source.compactMap { $0 }
@@ -37,7 +37,7 @@ final class TestCompacted: XCTestCase {
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_compacted_is_equivalent_to_compactMap_when_input_as_no_nil_elements() async {
let source: [Int?] = [1, 2, 3, 4, 5]
let expected = source.compactMap { $0 }
@@ -48,7 +48,7 @@ final class TestCompacted: XCTestCase {
}
XCTAssertEqual(expected, actual)
}
func test_compacted_throws_when_root_sequence_throws() async throws {
let sequence = [1, nil, 3, 4, 5, nil, 7].async.map { try throwOn(4, $0) }.compacted()
var iterator = sequence.makeAsyncIterator()
@@ -65,7 +65,7 @@ final class TestCompacted: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_compacted_finishes_when_iteration_task_is_cancelled() async {
let value: String? = "test"
let source = Indefinite(value: value)
+37 -24
View File
@@ -14,7 +14,9 @@ import AsyncAlgorithms
final class TestDebounce: XCTestCase {
func test_delayingValues() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcd----e---f-g----|"
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
@@ -23,7 +25,9 @@ final class TestDebounce: XCTestCase {
}
func test_delayingValues_dangling_last() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcd----e---f-g-|"
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
@@ -31,27 +35,32 @@ final class TestDebounce: XCTestCase {
}
}
func test_finishDoesntDebounce() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"a|"
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
"-[a|]"
}
}
func test_throwDoesntDebounce() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"a^"
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
"-^"
}
}
func test_noValues() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"----|"
$0.inputs[0].debounce(for: .steps(3), clock: $0.clock)
@@ -59,24 +68,28 @@ final class TestDebounce: XCTestCase {
}
}
func test_Rethrows() async throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
let debounce = [1].async.debounce(for: .zero, clock: ContinuousClock())
for await _ in debounce {}
let throwingDebounce = [1].async.map { try throwOn(2, $0) }.debounce(for: .zero, clock: ContinuousClock())
for try await _ in throwingDebounce {}
func test_Rethrows() async throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
func test_debounce_when_cancelled() async throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
let debounce = [1].async.debounce(for: .zero, clock: ContinuousClock())
for await _ in debounce {}
let t = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
let c1 = Indefinite(value: "test1").async
for await _ in c1.debounce(for: .seconds(1), clock: .continuous) {}
}
t.cancel()
let throwingDebounce = [1].async.map { try throwOn(2, $0) }.debounce(for: .zero, clock: ContinuousClock())
for try await _ in throwingDebounce {}
}
func test_debounce_when_cancelled() async throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
let t = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
let c1 = Indefinite(value: "test1").async
for await _ in c1.debounce(for: .seconds(1), clock: .continuous) {}
}
t.cancel()
}
}
@@ -19,7 +19,7 @@ final class TestDictionary: XCTestCase {
let actual = await Dictionary(uniqueKeysWithValues: source.async)
XCTAssertEqual(expected, actual)
}
func test_throwing_uniqueKeysAndValues() async {
let source = Array([1, 2, 3, 4, 5, 6])
let input = source.async.map { (value: Int) async throws -> (Int, Int) in
@@ -33,14 +33,14 @@ final class TestDictionary: XCTestCase {
XCTAssertEqual((error as NSError).code, -1)
}
}
func test_uniquingWith() async {
let source = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
let expected = Dictionary(source) { first, _ in first }
let actual = await Dictionary(source.async) { first, _ in first }
XCTAssertEqual(expected, actual)
}
func test_throwing_uniquingWith() async {
let source = Array([1, 2, 3, 4, 5, 6])
let input = source.async.map { (value: Int) async throws -> (Int, Int) in
@@ -54,16 +54,16 @@ final class TestDictionary: XCTestCase {
XCTAssertEqual((error as NSError).code, -1)
}
}
func test_grouping() async {
let source = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let expected = Dictionary(grouping: source, by: { $0.first! })
let actual = await Dictionary(grouping: source.async, by: { $0.first! })
XCTAssertEqual(expected, actual)
}
func test_throwing_grouping() async {
let source = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let source = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
let input = source.async.map { (value: String) async throws -> String in
if value == "Kweku" { throw NSError(domain: NSCocoaErrorDomain, code: -1, userInfo: nil) }
return value
+7 -5
View File
@@ -13,8 +13,10 @@ import XCTest
import AsyncAlgorithms
extension Sequence where Element: Sequence, Element.Element: Equatable & Sendable {
func nestedAsync(throwsOn bad: Element.Element) -> AsyncSyncSequence<[AsyncThrowingMapSequence<AsyncSyncSequence<Element>,Element.Element>]> {
let array: [AsyncThrowingMapSequence<AsyncSyncSequence<Element>,Element.Element>] = self.map { $0.async }.map {
func nestedAsync(
throwsOn bad: Element.Element
) -> AsyncSyncSequence<[AsyncThrowingMapSequence<AsyncSyncSequence<Element>, Element.Element>]> {
let array: [AsyncThrowingMapSequence<AsyncSyncSequence<Element>, Element.Element>] = self.map { $0.async }.map {
$0.map { try throwOn(bad, $0) }
}
return array.async
@@ -22,7 +24,7 @@ extension Sequence where Element: Sequence, Element.Element: Equatable & Sendabl
}
extension Sequence where Element: Sequence, Element.Element: Sendable {
var nestedAsync : AsyncSyncSequence<[AsyncSyncSequence<Element>]> {
var nestedAsync: AsyncSyncSequence<[AsyncSyncSequence<Element>]> {
return self.map { $0.async }.async
}
}
@@ -105,7 +107,7 @@ final class TestJoinedBySeparator: XCTestCase {
}
func test_cancellation() async {
let source : AsyncSyncSequence<[AsyncSyncSequence<Indefinite<String>>]> = [Indefinite(value: "test").async].async
let source: AsyncSyncSequence<[AsyncSyncSequence<Indefinite<String>>]> = [Indefinite(value: "test").async].async
let sequence = source.joined(separator: ["past indefinite"].async)
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
@@ -189,7 +191,7 @@ final class TestJoined: XCTestCase {
}
func test_cancellation() async {
let source : AsyncSyncSequence<[AsyncSyncSequence<Indefinite<String>>]> = [Indefinite(value: "test").async].async
let source: AsyncSyncSequence<[AsyncSyncSequence<Indefinite<String>>]> = [Indefinite(value: "test").async].async
let sequence = source.joined()
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
+12 -12
View File
@@ -21,34 +21,34 @@ final class TestLazy: XCTestCase {
for await item in sequence {
collected.append(item)
}
XCTAssertEqual(expected, collected)
}
func test_lazy_outputs_elements_and_finishes_when_source_is_set() async {
let expected: Set = [1, 2, 3, 4]
let sequence = expected.async
var collected = Set<Int>()
for await item in sequence {
collected.insert(item)
}
XCTAssertEqual(expected, collected)
}
func test_lazy_finishes_without_elements_when_source_is_empty() async {
let expected = [Int]()
let sequence = expected.async
var collected = [Int]()
for await item in sequence {
collected.append(item)
}
XCTAssertEqual(expected, collected)
}
func test_lazy_triggers_expected_iterator_events_when_source_is_iterated() async {
let expected = [1, 2, 3]
let expectedEvents = [
@@ -56,7 +56,7 @@ final class TestLazy: XCTestCase {
.next,
.next,
.next,
.next
.next,
]
let source = ReportingSequence(expected)
let sequence = source.async
@@ -71,7 +71,7 @@ final class TestLazy: XCTestCase {
XCTAssertEqual(expected, collected)
XCTAssertEqual(expectedEvents, source.events)
}
func test_lazy_stops_triggering_iterator_events_when_source_is_pastEnd() async {
let expected = [1, 2, 3]
let expectedEvents = [
@@ -79,7 +79,7 @@ final class TestLazy: XCTestCase {
.next,
.next,
.next,
.next
.next,
]
let source = ReportingSequence(expected)
let sequence = source.async
@@ -101,7 +101,7 @@ final class TestLazy: XCTestCase {
// ensure that iterating past the end does not invoke next again
XCTAssertEqual(expectedEvents, source.events)
}
func test_lazy_finishes_when_task_is_cancelled() async {
let finished = expectation(description: "finished")
let iterated = expectation(description: "iterated")
@@ -32,7 +32,7 @@ final class TestManualClock: XCTestCase {
await fulfillment(of: [afterSleep], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
}
func test_sleep_cancel() async {
let clock = ManualClock()
let start = clock.now
@@ -55,7 +55,7 @@ final class TestManualClock: XCTestCase {
XCTAssertTrue(state.withCriticalRegion { $0 })
XCTAssertTrue(failure.withCriticalRegion { $0 is CancellationError })
}
func test_sleep_cancel_before_advance() async {
let clock = ManualClock()
let start = clock.now
+83 -56
View File
@@ -30,7 +30,7 @@ final class TestMerge2: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(Set(collected).sorted(), expected)
}
func test_merge_makes_sequence_with_elements_from_sources_when_first_is_longer() async {
let first = [1, 2, 3, 4, 5, 6, 7]
let second = [8, 9, 10]
@@ -48,7 +48,7 @@ final class TestMerge2: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(Set(collected).sorted(), expected)
}
func test_merge_makes_sequence_with_elements_from_sources_when_second_is_longer() async {
let first = [1, 2, 3]
let second = [4, 5, 6, 7]
@@ -66,8 +66,10 @@ final class TestMerge2: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(Set(collected).sorted(), expected)
}
func test_merge_produces_three_elements_from_first_and_throws_when_first_is_longer_and_throws_after_three_elements() async throws {
func test_merge_produces_three_elements_from_first_and_throws_when_first_is_longer_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3, 4, 5]
let second = [6, 7, 8]
@@ -89,8 +91,11 @@ final class TestMerge2: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_produces_three_elements_from_first_and_throws_when_first_is_shorter_and_throws_after_three_elements() async throws {
func
test_merge_produces_three_elements_from_first_and_throws_when_first_is_shorter_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3, 4, 5]
let second = [6, 7, 8, 9, 10, 11]
@@ -112,8 +117,11 @@ final class TestMerge2: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_produces_three_elements_from_second_and_throws_when_second_is_longer_and_throws_after_three_elements() async throws {
func
test_merge_produces_three_elements_from_second_and_throws_when_second_is_longer_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3]
let second = [4, 5, 6, 7, 8]
@@ -135,8 +143,11 @@ final class TestMerge2: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_produces_three_elements_from_second_and_throws_when_second_is_shorter_and_throws_after_three_elements() async throws {
func
test_merge_produces_three_elements_from_second_and_throws_when_second_is_shorter_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3, 4, 5, 6, 7]
let second = [7, 8, 9, 10, 11]
@@ -158,7 +169,7 @@ final class TestMerge2: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_makes_sequence_with_ordered_elements_when_sources_follow_a_timeline() {
validate {
"a-c-e-g-|"
@@ -167,7 +178,7 @@ final class TestMerge2: XCTestCase {
"abcdefgh|"
}
}
func test_merge_finishes_when_iteration_task_is_cancelled() async {
let source1 = Indefinite(value: "test1")
let source2 = Indefinite(value: "test2")
@@ -192,15 +203,15 @@ final class TestMerge2: XCTestCase {
await fulfillment(of: [finished], timeout: 1.0)
}
func test_merge_when_cancelled() async {
let t = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
let c1 = Indefinite(value: "test1").async
let c2 = Indefinite(value: "test1").async
for await _ in merge(c1, c2) {}
}
t.cancel()
func test_merge_when_cancelled() async {
let t = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
let c1 = Indefinite(value: "test1").async
let c2 = Indefinite(value: "test1").async
for await _ in merge(c1, c2) {}
}
t.cancel()
}
}
final class TestMerge3: XCTestCase {
@@ -279,7 +290,7 @@ final class TestMerge3: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(Set(collected).sorted(), expected)
}
func test_merge_makes_sequence_with_elements_from_sources_when_first_and_second_are_longer() async {
let first = [1, 2, 3, 4, 5]
let second = [6, 7, 8, 9]
@@ -337,7 +348,9 @@ final class TestMerge3: XCTestCase {
XCTAssertEqual(Set(collected).sorted(), expected)
}
func test_merge_produces_three_elements_from_first_and_throws_when_first_is_longer_and_throws_after_three_elements() async throws {
func test_merge_produces_three_elements_from_first_and_throws_when_first_is_longer_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3, 4, 5]
let second = [6, 7, 8]
let third = [9, 10, 11]
@@ -361,7 +374,10 @@ final class TestMerge3: XCTestCase {
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_produces_three_elements_from_first_and_throws_when_first_is_shorter_and_throws_after_three_elements() async throws {
func
test_merge_produces_three_elements_from_first_and_throws_when_first_is_shorter_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3, 4, 5]
let second = [6, 7, 8, 9, 10, 11]
let third = [12, 13, 14]
@@ -385,7 +401,10 @@ final class TestMerge3: XCTestCase {
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_produces_three_elements_from_second_and_throws_when_second_is_longer_and_throws_after_three_elements() async throws {
func
test_merge_produces_three_elements_from_second_and_throws_when_second_is_longer_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3]
let second = [4, 5, 6, 7, 8]
let third = [9, 10, 11]
@@ -409,7 +428,10 @@ final class TestMerge3: XCTestCase {
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_produces_three_elements_from_second_and_throws_when_second_is_shorter_and_throws_after_three_elements() async throws {
func
test_merge_produces_three_elements_from_second_and_throws_when_second_is_shorter_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3, 4, 5, 6, 7]
let second = [7, 8, 9, 10, 11]
let third = [12, 13, 14]
@@ -432,8 +454,10 @@ final class TestMerge3: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_produces_three_elements_from_third_and_throws_when_third_is_longer_and_throws_after_three_elements() async throws {
func test_merge_produces_three_elements_from_third_and_throws_when_third_is_longer_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3]
let second = [4, 5, 6]
let third = [7, 8, 9, 10, 11]
@@ -457,7 +481,10 @@ final class TestMerge3: XCTestCase {
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_produces_three_elements_from_third_and_throws_when_third_is_shorter_and_throws_after_three_elements() async throws {
func
test_merge_produces_three_elements_from_third_and_throws_when_third_is_shorter_and_throws_after_three_elements()
async throws
{
let first = [1, 2, 3, 4, 5, 6, 7]
let second = [7, 8, 9, 10, 11]
let third = [12, 13, 14, 15]
@@ -480,7 +507,7 @@ final class TestMerge3: XCTestCase {
XCTAssertNil(pastEnd)
XCTAssertEqual(collected.intersection(expected), expected)
}
func test_merge_makes_sequence_with_ordered_elements_when_sources_follow_a_timeline() {
validate {
"a---e---|"
@@ -516,43 +543,43 @@ final class TestMerge3: XCTestCase {
await fulfillment(of: [finished], timeout: 1.0)
}
// MARK: - IteratorInitialized
// MARK: - IteratorInitialized
func testIteratorInitialized_whenInitial() async throws {
let reportingSequence1 = ReportingAsyncSequence([1])
let reportingSequence2 = ReportingAsyncSequence([2])
let merge = merge(reportingSequence1, reportingSequence2)
func testIteratorInitialized_whenInitial() async throws {
let reportingSequence1 = ReportingAsyncSequence([1])
let reportingSequence2 = ReportingAsyncSequence([2])
let merge = merge(reportingSequence1, reportingSequence2)
_ = merge.makeAsyncIterator()
_ = merge.makeAsyncIterator()
// We need to give the task that consumes the upstream
// a bit of time to make the iterators
try await Task.sleep(nanoseconds: 1000000)
// We need to give the task that consumes the upstream
// a bit of time to make the iterators
try await Task.sleep(nanoseconds: 1_000_000)
XCTAssertEqual(reportingSequence1.events, [])
XCTAssertEqual(reportingSequence2.events, [])
}
XCTAssertEqual(reportingSequence1.events, [])
XCTAssertEqual(reportingSequence2.events, [])
}
// MARK: - IteratorDeinitialized
// MARK: - IteratorDeinitialized
func testIteratorDeinitialized_whenMerging() async throws {
let merge = merge([1].async, [2].async)
func testIteratorDeinitialized_whenMerging() async throws {
let merge = merge([1].async, [2].async)
var iterator: _! = merge.makeAsyncIterator()
var iterator: _! = merge.makeAsyncIterator()
let nextValue = await iterator.next()
XCTAssertNotNil(nextValue)
let nextValue = await iterator.next()
XCTAssertNotNil(nextValue)
iterator = nil
}
iterator = nil
}
func testIteratorDeinitialized_whenFinished() async throws {
let merge = merge(Array<Int>().async, [].async)
func testIteratorDeinitialized_whenFinished() async throws {
let merge = merge([Int]().async, [].async)
var iterator: _? = merge.makeAsyncIterator()
let firstValue = await iterator?.next()
XCTAssertNil(firstValue)
var iterator: _? = merge.makeAsyncIterator()
let firstValue = await iterator?.next()
XCTAssertNil(firstValue)
iterator = nil
}
iterator = nil
}
}
@@ -19,28 +19,28 @@ final class TestRangeReplaceableCollection: XCTestCase {
let actual = await String(source.async)
XCTAssertEqual(expected, actual)
}
func test_Data() async {
let source = Data([1, 2, 3])
let expected = source
let actual = await Data(source.async)
XCTAssertEqual(expected, actual)
}
func test_ContiguousArray() async {
let source = ContiguousArray([1, 2, 3])
let expected = source
let actual = await ContiguousArray(source.async)
XCTAssertEqual(expected, actual)
}
func test_Array() async {
let source = Array([1, 2, 3])
let expected = source
let actual = await Array(source.async)
XCTAssertEqual(expected, actual)
}
func test_throwing() async {
let source = Array([1, 2, 3, 4, 5, 6])
let input = source.async.map { (value: Int) async throws -> Int in
+11 -11
View File
@@ -26,7 +26,7 @@ final class TestReductions: XCTestCase {
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_inclusive_reductions() async {
let sequence = [1, 2, 3, 4].async.reductions { $0 + $1 }
var iterator = sequence.makeAsyncIterator()
@@ -38,7 +38,7 @@ final class TestReductions: XCTestCase {
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throw_upstream_reductions() async throws {
let sequence = [1, 2, 3, 4].async
.map { try throwOn(3, $0) }
@@ -59,7 +59,7 @@ final class TestReductions: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throw_upstream_inclusive_reductions() async throws {
let sequence = [1, 2, 3, 4].async
.map { try throwOn(3, $0) }
@@ -78,7 +78,7 @@ final class TestReductions: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_reductions() async throws {
let sequence = [1, 2, 3, 4].async.reductions("") { (partial, value) throws -> String in
partial + "\(value)"
@@ -92,7 +92,7 @@ final class TestReductions: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_inclusive_reductions() async throws {
let sequence = [1, 2, 3, 4].async.reductions { (lhs, rhs) throws -> Int in
lhs + rhs
@@ -106,7 +106,7 @@ final class TestReductions: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throw_upstream_reductions_throws() async throws {
let sequence = [1, 2, 3, 4].async
.map { try throwOn(3, $0) }
@@ -127,7 +127,7 @@ final class TestReductions: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throw_upstream_inclusive_reductions_throws() async throws {
let sequence = [1, 2, 3, 4].async
.map { try throwOn(3, $0) }
@@ -148,7 +148,7 @@ final class TestReductions: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_reductions_into() async {
let sequence = [1, 2, 3, 4].async.reductions(into: "") { partial, value in
partial.append("\(value)")
@@ -162,7 +162,7 @@ final class TestReductions: XCTestCase {
let pastEnd = await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_reductions_into() async throws {
let sequence = [1, 2, 3, 4].async.reductions(into: "") { (partial, value) throws -> Void in
partial.append("\(value)")
@@ -176,7 +176,7 @@ final class TestReductions: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_throwing_reductions_into_throws() async throws {
let sequence = [1, 2, 3, 4].async.reductions(into: "") { partial, value in
_ = try throwOn("12", partial)
@@ -196,7 +196,7 @@ final class TestReductions: XCTestCase {
let pastEnd = try await iterator.next()
XCTAssertNil(pastEnd)
}
func test_cancellation() async {
let source = Indefinite(value: "test")
let sequence = source.async.reductions(into: "") { partial, value in
@@ -27,7 +27,7 @@ final class TestRemoveDuplicates: XCTestCase {
func test_removeDuplicates_with_closure() async {
let source = [1, 2.001, 2.005, 2.011, 3, 4, 5, 6, 5, 5]
let expected = [1, 2.001, 2.011, 3, 4, 5, 6, 5]
let sequence = source.async.removeDuplicates() { abs($0 - $1) < 0.01 }
let sequence = source.async.removeDuplicates { abs($0 - $1) < 0.01 }
var actual = [Double]()
for await item in sequence {
actual.append(item)
@@ -39,7 +39,7 @@ final class TestRemoveDuplicates: XCTestCase {
let source = [1, 2, 2, 2, 3, -1, 5, 6, 5, 5]
let expected = [1, 2, 3]
var actual = [Int]()
let sequence = source.async.removeDuplicates() { prev, next in
let sequence = source.async.removeDuplicates { prev, next in
let next = try throwOn(-1, next)
return prev == next
}
@@ -59,12 +59,14 @@ final class TestRemoveDuplicates: XCTestCase {
let source = [1, 2, 2, 2, 3, -1, 5, 6, 5, 5]
let expected = [1, 2, 3]
var actual = [Int]()
let throwingSequence = source.async.map ({
if $0 < 0 {
throw NSError(domain: NSCocoaErrorDomain, code: -1, userInfo: nil)
}
return $0
} as @Sendable (Int) throws -> Int)
let throwingSequence = source.async.map(
{
if $0 < 0 {
throw NSError(domain: NSCocoaErrorDomain, code: -1, userInfo: nil)
}
return $0
} as @Sendable (Int) throws -> Int
)
do {
for try await item in throwingSequence.removeDuplicates() {
@@ -19,21 +19,21 @@ final class TestSetAlgebra: XCTestCase {
let actual = await Set(source.async)
XCTAssertEqual(expected, actual)
}
func test_Set_duplicate() async {
let source = [1, 2, 3, 3]
let expected = Set(source)
let actual = await Set(source.async)
XCTAssertEqual(expected, actual)
}
func test_IndexSet() async {
let source = [1, 2, 3]
let expected = IndexSet(source)
let actual = await IndexSet(source.async)
XCTAssertEqual(expected, actual)
}
func test_throwing() async {
let source = Array([1, 2, 3, 4, 5, 6])
let input = source.async.map { (value: Int) async throws -> Int in
+71 -39
View File
@@ -14,146 +14,178 @@ import AsyncAlgorithms
final class TestThrottle: XCTestCase {
func test_rate_0() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijk|"
$0.inputs[0]._throttle(for: .steps(0), clock: $0.clock)
"abcdefghijk|"
}
}
func test_rate_0_leading_edge() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijk|"
$0.inputs[0]._throttle(for: .steps(0), clock: $0.clock, latest: false)
"abcdefghijk|"
}
}
func test_rate_1() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijk|"
$0.inputs[0]._throttle(for: .steps(1), clock: $0.clock)
"abcdefghijk|"
}
}
func test_rate_1_leading_edge() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijk|"
$0.inputs[0]._throttle(for: .steps(1), clock: $0.clock, latest: false)
"abcdefghijk|"
}
}
func test_rate_2() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijk|"
$0.inputs[0]._throttle(for: .steps(2), clock: $0.clock)
"a-c-e-g-i-k|"
}
}
func test_rate_2_leading_edge() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijk|"
$0.inputs[0]._throttle(for: .steps(2), clock: $0.clock, latest: false)
"a-b-d-f-h-j|"
}
}
func test_rate_3() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijk|"
$0.inputs[0]._throttle(for: .steps(3), clock: $0.clock)
"a--d--g--j--[k|]"
}
}
func test_rate_3_leading_edge() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijk|"
$0.inputs[0]._throttle(for: .steps(3), clock: $0.clock, latest: false)
"a--b--e--h--[k|]"
}
}
func test_throwing() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdef^hijk|"
$0.inputs[0]._throttle(for: .steps(2), clock: $0.clock)
"a-c-e-^"
}
}
func test_throwing_leading_edge() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdef^hijk|"
$0.inputs[0]._throttle(for: .steps(2), clock: $0.clock, latest: false)
"a-b-d-^"
}
}
func test_emission_2_rate_1() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"-a-b-c-d-e-f-g-h-i-j-k-|"
$0.inputs[0]._throttle(for: .steps(1), clock: $0.clock)
"-a-b-c-d-e-f-g-h-i-j-k-|"
}
}
func test_emission_2_rate_2() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"-a-b-c-d-e-f-g-h-i-j-k-|"
$0.inputs[0]._throttle(for: .steps(2), clock: $0.clock)
"-a-b-c-d-e-f-g-h-i-j-k-|"
}
}
func test_emission_3_rate_2() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"--a--b--c--d--e--f--g|"
$0.inputs[0]._throttle(for: .steps(2), clock: $0.clock)
"--a--b--c--d--e--f--g|"
}
}
func test_emission_2_rate_3() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"-a-b-c-d-e-f-g-h-i-j-k-|"
$0.inputs[0]._throttle(for: .steps(3), clock: $0.clock)
"-a---c---e---g---i---k-|"
}
}
func test_trailing_delay_without_latest() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijkl|"
$0.inputs[0]._throttle(for: .steps(3), clock: $0.clock, latest: false)
"a--b--e--h--[k|]"
}
"abcdefghijkl|"
$0.inputs[0]._throttle(for: .steps(3), clock: $0.clock, latest: false)
"a--b--e--h--[k|]"
}
}
func test_trailing_delay_with_latest() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"abcdefghijkl|"
$0.inputs[0]._throttle(for: .steps(3), clock: $0.clock, latest: true)
"a--d--g--j--[l|]"
}
"abcdefghijkl|"
$0.inputs[0]._throttle(for: .steps(3), clock: $0.clock, latest: true)
"a--d--g--j--[l|]"
}
}
}
@@ -52,7 +52,9 @@ final class TestThrowingChannel: XCTestCase {
XCTAssertEqual(collected, expected)
}
func test_asyncThrowingChannel_resumes_producers_and_discards_additional_elements_when_finish_is_called() async throws {
func test_asyncThrowingChannel_resumes_producers_and_discards_additional_elements_when_finish_is_called()
async throws
{
// Given: an AsyncThrowingChannel
let sut = AsyncThrowingChannel<Int, Error>()
@@ -139,7 +141,6 @@ final class TestThrowingChannel: XCTestCase {
return try await iterator.next()
}
// When: finishing the channel
sut.finish()
+15 -7
View File
@@ -15,31 +15,39 @@ import AsyncSequenceValidation
final class TestTimer: XCTestCase {
func test_tick1() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
AsyncTimerSequence(interval: .steps(1), clock: $0.clock).map { _ in "x" }
"xxxxxxx[;|]"
}
}
func test_tick2() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
AsyncTimerSequence(interval: .steps(2), clock: $0.clock).map { _ in "x" }
"-x-x-x-[;|]"
}
}
func test_tick3() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
AsyncTimerSequence(interval: .steps(3), clock: $0.clock).map { _ in "x" }
"--x--x-[;|]"
}
}
func test_tick2_event_skew3() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate { diagram in
AsyncTimerSequence(interval: .steps(2), clock: diagram.clock).map { [diagram] (_) -> String in
try? await diagram.clock.sleep(until: diagram.clock.now.advanced(by: .steps(3)))
@@ -22,7 +22,7 @@ final class TestValidationDiagram: XCTestCase {
"A--B--C---|"
}
}
func test_diagram_space_noop() {
validate {
" a -- b -- c ---|"
@@ -30,7 +30,7 @@ final class TestValidationDiagram: XCTestCase {
" A- - B - - C - -- | "
}
}
func test_diagram_string_input() {
validate {
"'foo''bar''baz'|"
@@ -38,7 +38,7 @@ final class TestValidationDiagram: XCTestCase {
"fbb|"
}
}
func test_diagram_string_input_expectation() {
validate {
"'foo''bar''baz'|"
@@ -46,7 +46,7 @@ final class TestValidationDiagram: XCTestCase {
"'foo''bar''baz'|"
}
}
func test_diagram_string_dsl_contents() {
validate {
"'foo-''bar^''baz|'|"
@@ -54,7 +54,7 @@ final class TestValidationDiagram: XCTestCase {
"'foo-''bar^''baz|'|"
}
}
func test_diagram_grouping_source() {
validate {
"[abc]def|"
@@ -62,7 +62,7 @@ final class TestValidationDiagram: XCTestCase {
"[abc]def|"
}
}
func test_diagram_groups_of_one() {
validate {
" a b c def|"
@@ -70,7 +70,7 @@ final class TestValidationDiagram: XCTestCase {
"[a][b][c]def|"
}
}
func test_diagram_emoji() {
struct EmojiTokens: AsyncSequenceValidationTheme {
func token(_ character: Character, inValue: Bool) -> AsyncSequenceValidationDiagram.Token {
@@ -85,7 +85,7 @@ final class TestValidationDiagram: XCTestCase {
default: return .value(String(character))
}
}
func description(for token: AsyncSequenceValidationDiagram.Token) -> String {
switch token {
case .step: return "➖"
@@ -102,14 +102,14 @@ final class TestValidationDiagram: XCTestCase {
}
}
}
validate(theme: EmojiTokens()) {
"➖🔴➖🟠➖🟡➖🟢➖❌"
$0.inputs[0]
"➖🔴➖🟠➖🟡➖🟢➖❌"
}
}
func test_cancel_event() {
validate {
"a--b- - c--|"
@@ -117,7 +117,7 @@ final class TestValidationDiagram: XCTestCase {
"a--b-[;|]"
}
}
func test_diagram_failure_mismatch_value() {
validate(expectedFailures: ["expected \"X\" but got \"C\" at tick 6"]) {
"a--b--c---|"
@@ -125,25 +125,29 @@ final class TestValidationDiagram: XCTestCase {
"A--B--X---|"
}
}
func test_diagram_failure_value_for_finish() {
validate(expectedFailures: ["expected finish but got \"C\" at tick 6",
"unexpected finish at tick 10"]) {
validate(expectedFailures: [
"expected finish but got \"C\" at tick 6",
"unexpected finish at tick 10",
]) {
"a--b--c---|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--|"
}
}
func test_diagram_failure_finish_for_value() {
validate(expectedFailures: ["expected \"C\" but got finish at tick 6",
"expected finish at tick 7"]) {
validate(expectedFailures: [
"expected \"C\" but got finish at tick 6",
"expected finish at tick 7",
]) {
"a--b--|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--C|"
}
}
func test_diagram_failure_finish_for_error() {
validate(expectedFailures: ["expected failure but got finish at tick 6"]) {
"a--b--|"
@@ -151,7 +155,7 @@ final class TestValidationDiagram: XCTestCase {
"A--B--^"
}
}
func test_diagram_failure_error_for_finish() {
validate(expectedFailures: ["expected finish but got failure at tick 6"]) {
"a--b--^"
@@ -159,25 +163,29 @@ final class TestValidationDiagram: XCTestCase {
"A--B--|"
}
}
func test_diagram_failure_value_for_error() {
validate(expectedFailures: ["expected failure but got \"C\" at tick 6",
"unexpected finish at tick 7"]) {
validate(expectedFailures: [
"expected failure but got \"C\" at tick 6",
"unexpected finish at tick 7",
]) {
"a--b--c|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--^"
}
}
func test_diagram_failure_error_for_value() {
validate(expectedFailures: ["expected \"C\" but got failure at tick 6",
"expected finish at tick 7"]) {
validate(expectedFailures: [
"expected \"C\" but got failure at tick 6",
"expected finish at tick 7",
]) {
"a--b--^"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--C|"
}
}
func test_diagram_failure_expected_value() {
validate(expectedFailures: ["expected \"C\" at tick 6"]) {
"a--b---|"
@@ -185,16 +193,18 @@ final class TestValidationDiagram: XCTestCase {
"A--B--C|"
}
}
func test_diagram_failure_expected_failure() {
validate(expectedFailures: ["expected failure at tick 6",
"unexpected finish at tick 7"]) {
validate(expectedFailures: [
"expected failure at tick 6",
"unexpected finish at tick 7",
]) {
"a--b---|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B--^"
}
}
func test_diagram_failure_unexpected_value() {
validate(expectedFailures: ["unexpected \"C\" at tick 6"]) {
"a--b--c|"
@@ -202,16 +212,18 @@ final class TestValidationDiagram: XCTestCase {
"A--B---|"
}
}
func test_diagram_failure_unexpected_failure() {
validate(expectedFailures: ["unexpected failure at tick 6",
"expected finish at tick 7"]) {
validate(expectedFailures: [
"unexpected failure at tick 6",
"expected finish at tick 7",
]) {
"a--b--^|"
$0.inputs[0].map { item in await Task { item.capitalized }.value }
"A--B---|"
}
}
func test_diagram_parse_failure_unbalanced_group() {
validate(expectedFailures: ["validation diagram unbalanced grouping"]) {
" ab|"
@@ -219,7 +231,7 @@ final class TestValidationDiagram: XCTestCase {
"[ab|"
}
}
func test_diagram_parse_failure_unbalanced_group_input() {
validate(expectedFailures: ["validation diagram unbalanced grouping"]) {
"[ab|"
@@ -227,7 +239,7 @@ final class TestValidationDiagram: XCTestCase {
" ab|"
}
}
func test_diagram_parse_failure_nested_group() {
validate(expectedFailures: ["validation diagram nested grouping"]) {
" ab|"
@@ -235,7 +247,7 @@ final class TestValidationDiagram: XCTestCase {
"[[ab|"
}
}
func test_diagram_parse_failure_nested_group_input() {
validate(expectedFailures: ["validation diagram nested grouping"]) {
"[[ab|"
@@ -243,7 +255,7 @@ final class TestValidationDiagram: XCTestCase {
" ab|"
}
}
func test_diagram_parse_failure_step_in_group() {
validate(expectedFailures: ["validation diagram step symbol in group"]) {
" ab|"
@@ -251,7 +263,7 @@ final class TestValidationDiagram: XCTestCase {
"[a-]b|"
}
}
func test_diagram_parse_failure_step_in_group_input() {
validate(expectedFailures: ["validation diagram step symbol in group"]) {
"[a-]b|"
@@ -259,7 +271,7 @@ final class TestValidationDiagram: XCTestCase {
" ab|"
}
}
func test_diagram_specification_produce_past_end() {
validate(expectedFailures: ["specification violation got \"d\" after iteration terminated at tick 9"]) {
"a--b--c--|"
@@ -267,7 +279,7 @@ final class TestValidationDiagram: XCTestCase {
"a--b--c--|"
}
}
func test_diagram_specification_throw_past_end() {
validate(expectedFailures: ["specification violation got failure after iteration terminated at tick 9"]) {
"a--b--c--|"
@@ -275,7 +287,7 @@ final class TestValidationDiagram: XCTestCase {
"a--b--c--|"
}
}
func test_delayNext() {
validate {
"xxx--- |"
@@ -293,7 +305,9 @@ final class TestValidationDiagram: XCTestCase {
}
func test_delayNext_into_emptyTick() throws {
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else { throw XCTSkip("Skipped due to Clock/Instant/Duration availability") }
guard #available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *) else {
throw XCTSkip("Skipped due to Clock/Instant/Duration availability")
}
validate {
"xx|"
LaggingAsyncSequence($0.inputs[0], delayBy: .steps(3), using: $0.clock)
@@ -311,20 +325,19 @@ final class TestValidationDiagram: XCTestCase {
}
@available(macOS 13.0, iOS 16.0, watchOS 9.0, tvOS 16.0, *)
struct LaggingAsyncSequence<Base: AsyncSequence, C: Clock> : AsyncSequence {
struct LaggingAsyncSequence<Base: AsyncSequence, C: Clock>: AsyncSequence {
typealias Element = Base.Element
struct Iterator : AsyncIteratorProtocol {
struct Iterator: AsyncIteratorProtocol {
var base: Base.AsyncIterator
let delay: C.Instant.Duration
let clock: C
mutating func next() async throws -> Element? {
if let value = try await base.next() {
try await clock.sleep(until: clock.now.advanced(by: delay), tolerance: nil)
return value
} else {
guard let value = try await base.next() else {
return nil
}
try await clock.sleep(until: clock.now.advanced(by: delay), tolerance: nil)
return value
}
}
@@ -27,13 +27,13 @@ final class TestValidator: XCTestCase {
await fulfillment(of: [entered], timeout: 1.0)
XCTAssertTrue(state.withCriticalRegion { $0 })
}
func test_gatedSequence() async {
var gated = GatedSequence([1, 2, 3])
let expectations = [
expectation(description: "item 1"),
expectation(description: "item 2"),
expectation(description: "item 3")
expectation(description: "item 3"),
]
let started = expectation(description: "started")
let finished = expectation(description: "finished")
@@ -65,7 +65,7 @@ final class TestValidator: XCTestCase {
XCTAssertEqual(state.withCriticalRegion { $0 }, [1, 2, 3])
await fulfillment(of: [finished], timeout: 1.0)
}
func test_gatedSequence_throwing() async {
var gated = GatedSequence([1, 2, 3])
let expectations = [
@@ -104,7 +104,7 @@ final class TestValidator: XCTestCase {
XCTAssertEqual(state.withCriticalRegion { $0 }, [1])
XCTAssertEqual(failure.withCriticalRegion { $0 as? Failure }, Failure())
}
func test_validator() async {
var a = GatedSequence([1, 2, 3])
let finished = expectation(description: "finished")
@@ -118,19 +118,19 @@ final class TestValidator: XCTestCase {
var value = await validator.validate()
XCTAssertEqual(value, [])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [2])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [2, 3])
a.advance()
value = await validator.validate()
XCTAssertEqual(value, [2, 3, 4])
a.advance()
await fulfillment(of: [finished], timeout: 1.0)
value = validator.current
XCTAssertEqual(value, [2, 3, 4])
+7 -7
View File
@@ -160,13 +160,13 @@ final class TestZip2: XCTestCase {
}
func test_zip_when_cancelled() async {
let t = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
let c1 = Indefinite(value: "test1").async
let c2 = Indefinite(value: "test1").async
for await _ in zip(c1, c2) {}
}
t.cancel()
let t = Task {
try? await Task.sleep(nanoseconds: 1_000_000_000)
let c1 = Indefinite(value: "test1").async
let c2 = Indefinite(value: "test1").async
for await _ in zip(c1, c2) {}
}
t.cancel()
}
}