mirror of
https://github.com/apple/swift-collections
synced 2026-11-22 04:20:40 +00:00
Test Producer.reduce with a throwing closure over noncopyable items
Check that reduce(_:_:) and reduce(into:_:) rethrow the closure's error, stop calling it after it throws, and leak nothing. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
88754449ab
commit
598f867179
1 file changed
+48
@@ -24,6 +24,10 @@ import ContainersPreview
|
||||
|
||||
#if compiler(>=6.4) && UnstableContainersPreview
|
||||
|
||||
private struct ClosureError: Error, Equatable {
|
||||
let value: Int
|
||||
}
|
||||
|
||||
@available(SwiftStdlib 6.4, *)
|
||||
final class ProducerTests: CollectionTestCase {
|
||||
/// A producer over `0 ..< count`.
|
||||
@@ -85,6 +89,50 @@ final class ProducerTests: CollectionTestCase {
|
||||
expectEqual(range(100).filter { $0 % 2 == 0 }.reduce(0, +), 2450)
|
||||
}
|
||||
|
||||
func test_reduce_throwing_closure() {
|
||||
withEvery("failAt", in: [0, 1, 7, 8, 9, 15, 16, 19]) { failAt in
|
||||
withLifetimeTracking { tracker in
|
||||
var seen: [Int] = []
|
||||
do throws(ClosureError) {
|
||||
_ = try CustomProducer<LifetimeTrackedStruct<Int>, ClosureError> {
|
||||
$0 < 20 ? tracker.structInstance(for: $0) : nil
|
||||
}
|
||||
.reduce(0) { count, item throws(ClosureError) in
|
||||
seen.append(item.payload)
|
||||
if item.payload == failAt { throw ClosureError(value: failAt) }
|
||||
return count + 1
|
||||
}
|
||||
expectFailure("reduce did not throw")
|
||||
} catch {
|
||||
expectEqual(error, ClosureError(value: failAt))
|
||||
}
|
||||
expectEqual(seen, Array(0 ... failAt))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_reduce_into_throwing_closure() {
|
||||
withEvery("failAt", in: [0, 1, 7, 8, 9, 15, 16, 19]) { failAt in
|
||||
withLifetimeTracking { tracker in
|
||||
var seen: [Int] = []
|
||||
do throws(ClosureError) {
|
||||
_ = try CustomProducer<LifetimeTrackedStruct<Int>, ClosureError> {
|
||||
$0 < 20 ? tracker.structInstance(for: $0) : nil
|
||||
}
|
||||
.reduce(into: 0) { count, item throws(ClosureError) in
|
||||
seen.append(item.payload)
|
||||
if item.payload == failAt { throw ClosureError(value: failAt) }
|
||||
count += 1
|
||||
}
|
||||
expectFailure("reduce(into:) did not throw")
|
||||
} catch {
|
||||
expectEqual(error, ClosureError(value: failAt))
|
||||
}
|
||||
expectEqual(seen, Array(0 ... failAt))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func test_default_skip_by_does_not_overshoot() {
|
||||
withEvery("n", in: [1, 5, 8, 10, 16, 40, 100, 150]) { n in
|
||||
var p = range(100).filter { $0 % 2 == 0 }
|
||||
|
||||
Reference in new issue
Block a user