Skip to content

Commit

Permalink
fix: fix fail_fast tests
Browse files Browse the repository at this point in the history
  • Loading branch information
savente93 committed Jul 6, 2024
1 parent 93bf20a commit 00fed97
Show file tree
Hide file tree
Showing 6 changed files with 149 additions and 14 deletions.
17 changes: 12 additions & 5 deletions src/bin/cmb.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ struct Args {
#[arg(short, long, value_name = "INPLACE_FILE", conflicts_with = "keys")]
inplace_file: Option<PathBuf>,

#[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
Expand All @@ -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() {
Expand All @@ -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) {:?}",
Expand Down
6 changes: 5 additions & 1 deletion src/bin/mdbook-bin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)?;
Expand Down
22 changes: 18 additions & 4 deletions src/ops/bibligraphy.rs
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,28 @@ impl Bibliography {
style: ReferenceStyle,
format: Format,
keys: Vec<String>,
) -> (Vec<String>, Vec<String>) {
fail_fast: bool,
) -> Result<(Vec<String>, Vec<String>)> {
let (known_keys, unknown_keys): (Vec<String>, Vec<String>) =
keys.into_iter().partition(|e| self.has_key(e));
let formatted: Vec<String> = 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::<Result<Vec<String>>>()?;
Ok((formatted, unknown_keys))
}

pub fn expand_file_citations_inplace(
Expand Down
2 changes: 0 additions & 2 deletions src/parsing/entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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)))
}
Expand Down
4 changes: 2 additions & 2 deletions tests/cmb_bin_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
112 changes: 112 additions & 0 deletions tests/mdbook_bin_test.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<()> {
Expand Down

0 comments on commit 00fed97

Please sign in to comment.