home ~ projects ~ socials

My Rust Nom Parsing Combinator Test Setup

As of Nov. 2024

This is what I've refined down to for testing my nom parsers. You send an input and an expected output. If the parser works and the proper remainder shows up, it passes. Otherwise it shows you either the parsing error or the incorrect remainder.

There is also a test for things that shouldn't parse. If they do, it triggers a failure and prints out what parsed that shouldn't have.

#[cfg(test)]
mod test {
    use super::*;
    use rstest::rstest;

    #[rstest]
    #[case("source plus remainder", "remainder")]
    fn solo_valid_cases_with_remainders(#[case] source: &str, #[case] remainder: &str) {
        let results = parser_to_test_goes_here(source);
        match results {
            Ok(result) => {
                if result.0 == remainder {
                    assert!(true);
                } else {
                    assert!(
                        false,
                        "Remainder should have been '{}' but got '{}'",
                        &remainder, result.0
                    );
                }
            }
            Err(e) => {
                assert!(false, "{}", e)
            }
        }
    }

    #[rstest]
    #[case("something that should be invalid")]
    fn test_invalid_cases(#[case] source: &str) {
        let results = parser_to_test_goes_here(source);
        match results {
            Ok(_) => {
                assert!(false, "This should not have parsed but it did: {}", source);
            }
            Err(_) => {
                assert!(true);
            }
        }
    }
}
-- end of line --

Footnotes

1 ⤴

This is what I'm using for Neopoligen