From 66a611fa6efcdf55d3cb9f71c0150c8f2fec0c9e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Maxime=20=E2=80=9Cpep=E2=80=9D=20Buquet?= Date: Fri, 13 Jan 2023 21:38:36 +0100 Subject: [PATCH] Add failure tests for parse_meta MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: Maxime “pep” Buquet --- src/lib.rs | 53 +++++++++++++++++++++++++++++++++++++++++------------ 1 file changed, 41 insertions(+), 12 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 202b26d..4e6fe84 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -176,23 +176,15 @@ fn parse_meta(s: Span) -> IResult { delimited(tag("#"), take_while1(|c| c != '#' && c != '\n'), tag("\n")), ))(s)?; - let optdesc = opt(tuple(( + let (s, optdesc) = opt(tuple(( position, delimited(tag("#"), take_while1(|c| c != '#' && c != '\n'), tag("\n")), )))(s)?; - - let mut desc: Option<&str> = None; - let s = match optdesc { - (s, Some((_pos, val))) => { - desc = Some(val.trim()); - s - } - (s, None) => s, - }; + let description = optdesc.map(|(_pos, d)| String::from(d.trim())); let (s, tags) = parse_meta_tags(s)?; - let meta = Metadata::new(title.trim(), desc).with_tags(tags); + let meta = Metadata::new(title.trim(), description).with_tags(tags); Ok((s, meta)) } @@ -390,7 +382,7 @@ mod tests { } #[test] - fn test_meta() { + fn test_meta_success() { let buf1 = "# Title.\n"; let buf2 = "#Foo\n# Desc\n"; let buf3 = "#Foo\n# Desc\n## tag1\n"; @@ -400,20 +392,57 @@ mod tests { parse_meta(buf1.into()).unwrap().1, Metadata::new("Title.", None::) ); + assert_eq!( parse_meta(buf2.into()).unwrap().1, Metadata::new("Foo", Some("Desc")) ); + assert_eq!( parse_meta(buf3.into()).unwrap().1, Metadata::new("Foo", Some("Desc")).with_tags(vec![String::from("tag1")]) ); + assert_eq!( parse_meta(buf4.into()).unwrap().1, Metadata::new("Foo", None::).with_tags(vec![String::from("tag1")]) ); } + #[test] + fn test_meta_failure() { + let buf1 = "# Title."; + let buf2 = "// Foo Title\n# Desc\n"; + let buf3 = "##Foo\n# Desc\n## tag1\n"; + + // Missing newline + match parse_meta(buf1.into()) { + Err(nom::Err::Error(nom::error::Error { input, .. })) => { + assert_eq!(input.location_offset(), 8); + assert_eq!(input.location_line(), 1); + } + err => panic!("Expected Err, found: {err:?}"), + } + + // Invalid starting tag (// not #) + match parse_meta(buf2.into()) { + Err(nom::Err::Error(nom::error::Error { input, .. })) => { + assert_eq!(input.location_offset(), 0); + assert_eq!(input.location_line(), 1); + } + err => panic!("Expected Err, found: {err:?}"), + } + + // Only taga, missing title + match parse_meta(buf3.into()) { + Err(nom::Err::Error(nom::error::Error { input, .. })) => { + assert_eq!(input.location_offset(), 1); + assert_eq!(input.location_line(), 1); + } + err => panic!("Expected Err, found: {err:?}"), + } + } + #[test] fn test_client() { let buf1 = "[Client] louise\n\tjid: louise@localhost\n\tpassword: password\n";