Swift-testing and Errors with associated types

I'm pretty new to swift-testing and it's pretty new so I'm not sure I follow everything you're saying but between your and grynspan's tips I'm ending up with something that doesn't feel that terrible to me!

Maybe I have low standards ;)

I even got a self contained function that I might move up to the Suite level out of it! Thanks!

Now to replace that random with parameterization!

        #expect(errorContainedIn(range:20...49, with:Int.random(in: 20...49), from: throwsCode))
        
        func errorContainedIn(range:ClosedRange<Int>, with:Int,
            from function:(Int) throws -> Void) -> Bool {
            //note: build fails with require
            guard case .codedError(let code) = (#expect(throws: ExampleError.self) {
                try function(with)
            }) else { return false }
            return range.contains(code)
        }

ETA: see also Comparing enum cases while ignoring associated values - #24 by tera

ETA: async compatible version

    #expect(await errorContainedIn(range:20...49, with:Int.random(in: 20...49), from: throwsCode))

    func errorContainedIn(range:ClosedRange<Int>, with:Int,
        from function:(Int) async throws -> Void) async -> Bool {
        guard case .codedError(let code) = (await #expect(throws: ExampleError.self) {
            try await function(with)
        }) else { return false }
        return range.contains(code)
    }
1 Like