From 00fed975d459a52a8f1642174456d873b7f7dc14 Mon Sep 17 00:00:00 2001 From: Sam Vente Date: Fri, 5 Jul 2024 22:51:18 +0200 Subject: [PATCH] fix: fix fail_fast tests --- src/bin/cmb.rs | 17 ++++-- src/bin/mdbook-bin.rs | 6 ++- src/ops/bibligraphy.rs | 22 ++++++-- src/parsing/entry.rs | 2 - tests/cmb_bin_test.rs | 4 +- tests/mdbook_bin_test.rs | 112 +++++++++++++++++++++++++++++++++++++++ 6 files changed, 149 insertions(+), 14 deletions(-) diff --git a/src/bin/cmb.rs b/src/bin/cmb.rs index 82df2a6..e366ee5 100644 --- a/src/bin/cmb.rs +++ b/src/bin/cmb.rs @@ -30,7 +30,7 @@ struct Args { #[arg(short, long, value_name = "INPLACE_FILE", conflicts_with = "keys")] inplace_file: Option, - #[arg(long, default_value_t = true)] + #[arg(long, default_value_t = false)] fail_fast: bool, /// Do not pring warnings when citation keys are not found @@ -41,8 +41,11 @@ struct Args { fn main() -> Result<()> { let args = Args::parse(); - env_logger::init(); - + env_logger::builder() + .filter_level(log::LevelFilter::Debug) + .format_target(false) + .format_timestamp(None) + .init(); let mut bibliography = Bibliography::default(); for p in args.bib_files.clone() { @@ -65,8 +68,12 @@ fn main() -> Result<()> { .for_each(|f| println!("{}", f)); Ok(()) } else { - let (formatted, unknown_keys) = - bibliography.fmt_entries_filtered(args.style, args.format, args.keys.clone()); + let (formatted, unknown_keys) = bibliography.fmt_entries_filtered( + args.style, + args.format, + args.keys.clone(), + args.fail_fast, + )?; if formatted.is_empty() && !args.quiet { Err(anyhow!( "none of the keys {:?} found in bib file(s) {:?}", diff --git a/src/bin/mdbook-bin.rs b/src/bin/mdbook-bin.rs index e72de18..3995d2d 100644 --- a/src/bin/mdbook-bin.rs +++ b/src/bin/mdbook-bin.rs @@ -31,7 +31,11 @@ fn main() { } fn handle_preprocessing(pre: &dyn Preprocessor) -> Result<(), Error> { - env_logger::init(); + env_logger::builder() + .filter_level(log::LevelFilter::Debug) + .format_target(false) + .format_timestamp(None) + .init(); let (ctx, book) = CmdPreprocessor::parse_input(io::stdin())?; let book_version = Version::parse(&ctx.mdbook_version)?; diff --git a/src/ops/bibligraphy.rs b/src/ops/bibligraphy.rs index f115c86..fa25b1d 100644 --- a/src/ops/bibligraphy.rs +++ b/src/ops/bibligraphy.rs @@ -36,14 +36,28 @@ impl Bibliography { style: ReferenceStyle, format: Format, keys: Vec, - ) -> (Vec, Vec) { + fail_fast: bool, + ) -> Result<(Vec, Vec)> { let (known_keys, unknown_keys): (Vec, Vec) = keys.into_iter().partition(|e| self.has_key(e)); let formatted: Vec = known_keys .into_iter() - .map(|b| style.fmt_reference(self.get_entry(b).unwrap(), format)) - .collect(); - (formatted, unknown_keys) + .map(|b| { + let entry = self.get_entry(b.clone()); + match entry { + Some(e) => Ok(style.fmt_reference(e, format)), + None => { + if fail_fast { + Err(anyhow::Error::msg(format!("key {} not found", b))) + } else { + warn!("key {} not found", b.clone()); + Ok(b) + } + } + } + }) + .collect::>>()?; + Ok((formatted, unknown_keys)) } pub fn expand_file_citations_inplace( diff --git a/src/parsing/entry.rs b/src/parsing/entry.rs index dddc076..a20cb42 100644 --- a/src/parsing/entry.rs +++ b/src/parsing/entry.rs @@ -93,8 +93,6 @@ pub fn citation(input: &str) -> IResult<&str, &str> { pub fn next_citation(input: &str) -> IResult<&str, (&str, &str)> { let (tail, unmodified) = take_until("\\cite")(input)?; let (tail, citation_key) = citation(tail)?; - dbg!(&unmodified); - dbg!(&citation_key); Ok((tail, (unmodified, citation_key))) } diff --git a/tests/cmb_bin_test.rs b/tests/cmb_bin_test.rs index 8dc0cbb..8160152 100644 --- a/tests/cmb_bin_test.rs +++ b/tests/cmb_bin_test.rs @@ -178,8 +178,8 @@ fn run_no_warning_on_quiet() { #[test] fn exists_on_fail_fast() { let output = run_cmb() - .args(["-b", "cite.bib", "asdf", "--fail-fast"]) + .args(["-b", "cite.bib", "asdf", "book", "--fail-fast"]) .output() .expect("error running binary"); - assert!(!ExitStatus::success(&output.status), "{:?}", &output); + assert!(&output.status.success(), "{:?}", &output); } diff --git a/tests/mdbook_bin_test.rs b/tests/mdbook_bin_test.rs index e32632a..16b3ed7 100644 --- a/tests/mdbook_bin_test.rs +++ b/tests/mdbook_bin_test.rs @@ -146,6 +146,118 @@ fn errors_on_no_config() -> Result<()> { assert!(!ExitStatus::success(&exit_code)); Ok(()) } +#[test] +fn errors_on_fail_fast() -> Result<()> { + let input_json = r##"[ + { + "root": "/path/to/book", + "config": { + "book": { + "authors": ["AUTHOR"], + "language": "en", + "multilingual": false, + "src": "src", + "title": "TITLE" + }, + "preprocessor": { + "citations": {"bibfile":"cite.bib", "fail_fast":"true"} + } + }, + "renderer": "html", + "mdbook_version": "0.4.20" + }, + { + "sections": [ + { + "Chapter": { + "name": "Chapter 1", + "content": "\cite{asdfasdf}", + "number": [1], + "sub_items": [], + "path": "chapter_1.md", + "source_path": "chapter_1.md", + "parent_names": [] + } + } + ], + "__non_exhaustive": null + } + ]"##; + + let mut child = run_bin() + .stdin(Stdio::piped()) + .spawn() + .expect("failed to run bsinary"); + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(input_json.as_bytes())?; + drop(stdin); + let exit_code = child.wait().expect("DOH!+"); + assert!(!ExitStatus::success(&exit_code)); + Ok(()) +} +#[test] +fn warns_without_fail_fast() -> Result<()> { + let input_json = r##"[ + { + "root": "/path/to/book", + "config": { + "book": { + "authors": ["AUTHOR"], + "language": "en", + "multilingual": false, + "src": "src", + "title": "TITLE" + }, + "preprocessor": { + "citations": {"bibfile":"cite.bib", "fail_fast":"false"} + } + }, + "renderer": "html", + "mdbook_version": "0.4.40" + }, + { + "sections": [ + { + "Chapter": { + "name": "Chapter 1", + "content": "\\cite{asdfasdf}", + "number": [1], + "sub_items": [], + "path": "chapter_1.md", + "source_path": "chapter_1.md", + "parent_names": [] + } + } + ], + "__non_exhaustive": null + } + ]"##; + let expected_output_json = r##"{"sections":[{"Chapter":{"name":"Chapter 1","content":"\\cite{asdfasdf}","number":[1],"sub_items":[],"path":"chapter_1.md","source_path":"chapter_1.md","parent_names":[]}}],"__non_exhaustive":null}"##; + + let expected_warning = "[WARN ] Key asdfasdf in text was not found, skipping...\n"; + let mut child = run_bin() + .stdin(Stdio::piped()) + .stderr(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("failed to run bsinary"); + let mut stdin = child.stdin.take().unwrap(); + stdin.write_all(input_json.as_bytes())?; + drop(stdin); + let exit_code = child.wait().expect("DOH!+"); + let mut output = String::new(); + let mut warnings = String::new(); + let mut stderr = child.stderr.unwrap(); + let mut stdout = child.stdout.unwrap(); + stdout.read_to_string(&mut output)?; + stderr.read_to_string(&mut warnings)?; + drop(stderr); + drop(stdout); + assert_eq!(warnings, expected_warning); + assert!(&exit_code.success(), "{}", exit_code); + assert_eq!(output, expected_output_json); + Ok(()) +} #[test] fn run_without_citations_is_noop() -> Result<()> {