Skip to content

Commit

Permalink
add throwing support to WithRandomGenerator (#232)
Browse files Browse the repository at this point in the history
  • Loading branch information
samisuteria committed Jun 28, 2024
1 parent b074ba7 commit b059fc3
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,9 @@ public final class WithRandomNumberGenerator: @unchecked Sendable {
self.generator = generator
}

public func callAsFunction<R>(_ work: (inout any RandomNumberGenerator & Sendable) -> R) -> R {
return work(&self.generator)
public func callAsFunction<R>(_ work: (inout any RandomNumberGenerator & Sendable) throws -> R)
rethrows -> R
{
return try work(&self.generator)
}
}
28 changes: 28 additions & 0 deletions Tests/DependenciesTests/WithRandomNumberGeneratorTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,34 @@ final class WithRandomNumberGeneratorDependencyTests: XCTestCase {
}
}
}

struct ExpectedError: Error {}

func testWithRandomNumberGeneratorThrowing() throws {
try XCTAssertThrowsError(
{
try withDependencies {
$0.withRandomNumberGenerator = .init(LCRNG(seed: 0))
} operation: {
try self.withRandomNumberGenerator { generator -> Void in
// NB: Wasm has different behavior here.
#if os(WASI)
let sequence = [5, 6, 5, 4, 4]
#else
let sequence = [1, 3, 6, 3, 2]
#endif
for expected in sequence {
if expected == 6 {
throw ExpectedError()
}
XCTAssertEqual(.random(in: 1...6, using: &generator), expected)
}

}
}

}(), "Expected error should be thrown")
}
}

private struct LCRNG: RandomNumberGenerator {
Expand Down

0 comments on commit b059fc3

Please sign in to comment.