Skip to content

Commit ce9b9d8

Browse files
hovinenbcopybara-github
authored andcommitted
Support enum variants and structs with no fields in matches_pattern!.
Previously, attempting to match a pattern on an enum variant with no fields would not be matched by `matches_pattern!`, resulting in a recursion error during compilation: ``` enum MyEnum { A } verify_that!(value, matches_pattern!(MyEnum::A)) ^^^^^^^^^ Error! Maximum recursion depth exceeded. ``` The support had simply been omitted from `matches_pattern!`. This adds support for such cases to the macro, using the `predicate` matcher to handle them. PiperOrigin-RevId: 539567060
1 parent aea64c0 commit ce9b9d8

File tree

2 files changed

+50
-1
lines changed

2 files changed

+50
-1
lines changed

googletest/src/matchers/matches_pattern.rs

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -387,6 +387,16 @@ macro_rules! matches_pattern_internal {
387387
)
388388
};
389389

390+
(
391+
[$($struct_name:tt)*],
392+
) => {
393+
$crate::matchers::predicate(|v| matches!(v, $($struct_name)*))
394+
.with_description(
395+
concat!("is ", stringify!($($struct_name)*)),
396+
concat!("is not ", stringify!($($struct_name)*)),
397+
)
398+
};
399+
390400
(
391401
[$($struct_name:tt)*],
392402
($matcher:expr $(,)?)

googletest/tests/matches_pattern_test.rs

Lines changed: 40 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -366,7 +366,46 @@ fn matches_tuple_struct_with_two_fields_and_trailing_comma() -> Result<()> {
366366
}
367367

368368
#[test]
369-
fn matches_enum_value() -> Result<()> {
369+
fn matches_enum_without_field() -> Result<()> {
370+
#[derive(Debug)]
371+
enum AnEnum {
372+
A,
373+
}
374+
let actual = AnEnum::A;
375+
376+
verify_that!(actual, matches_pattern!(AnEnum::A))
377+
}
378+
379+
#[test]
380+
fn generates_correct_failure_output_when_enum_variant_without_field_is_not_matched() -> Result<()> {
381+
#[derive(Debug)]
382+
enum AnEnum {
383+
#[allow(unused)]
384+
A,
385+
B,
386+
}
387+
let actual = AnEnum::B;
388+
389+
let result = verify_that!(actual, matches_pattern!(AnEnum::A));
390+
391+
verify_that!(result, err(displays_as(contains_substring("is not AnEnum :: A"))))
392+
}
393+
394+
#[test]
395+
fn generates_correct_failure_output_when_enum_variant_without_field_is_matched() -> Result<()> {
396+
#[derive(Debug)]
397+
enum AnEnum {
398+
A,
399+
}
400+
let actual = AnEnum::A;
401+
402+
let result = verify_that!(actual, not(matches_pattern!(AnEnum::A)));
403+
404+
verify_that!(result, err(displays_as(contains_substring("is AnEnum :: A"))))
405+
}
406+
407+
#[test]
408+
fn matches_enum_with_field() -> Result<()> {
370409
#[derive(Debug)]
371410
enum AnEnum {
372411
A(u32),

0 commit comments

Comments
 (0)