Hi! I have some tests that are using pattern matching to derive some state (and then testing the value of that state). Here is an example:
enum E {
case a(x: Int, y: Int)
case b
}
@Test func t1() throws {
let e = E.a(x: 1, y: 1)
let (x, y) = try #require(
{
switch e {
case .a(x: let x, y: let y):
return (x, y)
default:
return nil
}
}()
)
#expect(x == 1)
#expect(y == 1)
}
@Test func t2() throws {
let e = E.a(x: 1, y: 1)
let (x, y) = try #require(
{
if case .a(x: let x, y: let y) = e {
return (x, y)
}
return nil
}()
)
#expect(x == 1)
#expect(y == 1)
}
I want to (first of all) test that my state matches the correct pattern (and throw an error or fail if not). I want to next test that the value of that state is what I expect it to be.
Both of these tests work… but it's a little clunky and bulky and I am wondering if there are any shortcuts or modern language features that might clean these up (either from swift
or from swift-testing
).
I do have the option to try and roll my own case detection helpers:
extension E {
var asA: (x: Int, y: Int)? {
if case .a(x: let x, y: let y) = self {
return (x, y)
}
return nil
}
}
@Test func t4() throws {
let e = E.a(x: 1, y: 1)
let (x, y) = try #require(e.asA)
#expect(x == 1)
#expect(y == 1)
}
This works… but AFAIK there is no way to get these case-detection helpers automatically from the compiler. There is an option to use something like a TestUtils
macro (similar to CaseDetectionMacro
)… but I am also wondering and brainstorming what else might be out there in terms of shortcuts for these pattern matching tests. Thanks!