macro_rules! has_structure { ( $variant:path { $( $field:ident : $matcher:expr ),* $(,)* } ) => { ... }; ( $variant:path [ $( $matchers:expr ),* ] ) => { ... }; }
Expand description
Write patterns of structs/enums which use Matcher
s instead of field values.
When providing matchers for multiple fields, not that all matchers will be evaluated.
Even if one of them returns MatchResult::Failed
.
For struct-like structs/enum-variants not all fields need to be listed in the pattern.
Unwanted fields can safely be ommitted. For tuple-like structs/enum-variants all fields
need to be listed in the correct order. Although you can use any_value()
to effectively ignore the field.
Note that the correct brace/bracket style for tuple-like structs/enums is Variant[any_value(), any_value()]
not Variant(any_value(), any_value())
. This discrepancy is due to macro parsing reasons.
#Examples
// Matching a struct-like ...
use galvanic_assert::matchers::*;
struct Foo { x: i32, y: f64 }
let foo = Foo { x: 12, y: 23.4 };
assert_that!(&foo, has_structure!(Foo {
x: eq(12),
y: lt(25.0)
}));
assert_that!(&foo, has_structure!(Foo {
y: lt(25.0) // not all fields need to be given for struct-likes
}));
// Matching a tuple-like ...
struct Bar(i32, f64);
let bar = Bar(12, 23.4);
assert_that!(&bar, has_structure!(Bar[ eq(12), lt(25.0) ]));
// Matching enum variants ...
enum Baz {
Var1 { x: i32, y: f64 },
Var2(i32, f64)
}
let var1 = Baz::Var1 { x: 12, y: 23.4 };
assert_that!(&var1, has_structure!(Baz::Var1 {
x: eq(12),
y: lt(25.0)
}));
let var2 = Baz::Var2(12, 23.4);
assert_that!(&var2, has_structure!(Baz::Var2 [eq(12), lt(25.0)] ));