Skip to content

Commit

Permalink
Allow OneOfPolicies and AllOfPolicies to take throwing policy builder…
Browse files Browse the repository at this point in the history
…s, to match Verifier (#173)

* Allow OneOfPolicies and AllOfPolicies to take throwing policy builders, to match Verifier

* add tests

* avoid api break

* soundness

* fix

---------

Co-authored-by: Cory Benfield <lukasa@apple.com>
  • Loading branch information
hamzahrmalik and Lukasa committed May 17, 2024
1 parent 6f2dc4a commit d93756b
Show file tree
Hide file tree
Showing 3 changed files with 58 additions and 0 deletions.
5 changes: 5 additions & 0 deletions Sources/X509/Verifier/AllOfPolicies.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ public struct AllOfPolicies<Policy: VerifierPolicy>: VerifierPolicy {
@usableFromInline
var policy: Policy

@inlinable
public init(@PolicyBuilder policy: () throws -> Policy) throws {
self.policy = try policy()
}

@inlinable
public init(@PolicyBuilder policy: () -> Policy) {
self.policy = policy()
Expand Down
5 changes: 5 additions & 0 deletions Sources/X509/Verifier/OneOfPolicies.swift
Original file line number Diff line number Diff line change
Expand Up @@ -176,6 +176,11 @@ public struct OneOfPolicies<Policy: VerifierPolicy>: VerifierPolicy {
@usableFromInline
var policy: Policy

@inlinable
public init(@OneOfPolicyBuilder policy: () throws -> Policy) throws {
self.policy = try policy()
}

@inlinable
public init(@OneOfPolicyBuilder policy: () -> Policy) {
self.policy = policy()
Expand Down
48 changes: 48 additions & 0 deletions Tests/X509Tests/PolicyBuilderTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -576,4 +576,52 @@ final class PolicyBuilderTests: XCTestCase {
}
}
}

func testAllOfPoliciesThrowing() {
// Creating a AllOfPolicies which throws an error inside will itself throw
struct TestError: Error {}
func throwingPolicyBuilder() throws -> Policy {
throw TestError()
}

XCTAssertThrowsError(
try AllOfPolicies {
try throwingPolicyBuilder()
}
) { error in
XCTAssertTrue(error is TestError)
}
}

func testAllOfPoliciesNonThrowing() {
// creating a AllOfPolicies with a non-throwing closure can't throw
// This is tested at compile time (lack of `try` keyword)
_ = AllOfPolicies {
Policy(result: .meetsPolicy)
}
}

func testOneOfPoliciesThrowing() {
// Creating a OneOfPolicies which throws an error inside will itself throw
struct TestError: Error {}
func throwingPolicyBuilder() throws -> Policy {
throw TestError()
}

XCTAssertThrowsError(
try OneOfPolicies {
try throwingPolicyBuilder()
}
) { error in
XCTAssertTrue(error is TestError)
}
}

func testOneOfPoliciesNonThrowing() {
// creating a OneOfPolicies with a non-throwing closure can't throw
// This is tested at compile time (lack of `try` keyword)
_ = OneOfPolicies {
Policy(result: .meetsPolicy)
}
}
}

0 comments on commit d93756b

Please sign in to comment.