Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

add throwing support to WithRandomGenerator #232

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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