Debian Codegraph @

tests/testsuite/book_test.rs

raw
1 //! Utility for building and running tests against mdbook.
2
3 use mdbook_core::utils::fs;
4 use mdbook_driver::MDBook;
5 use mdbook_driver::init::BookBuilder;
6 use snapbox::IntoData;
7 use std::collections::BTreeMap;
8 use std::path::{Path, PathBuf};
9 use std::process::Command;
10 use std::sync::atomic::{AtomicU32, Ordering};
11
12 /// Test number used for generating unique temp directory names.
13 static NEXT_TEST_ID: AtomicU32 = AtomicU32::new(0);
14
15 #[derive(Clone, Copy, Eq, PartialEq)]
16 enum StatusCode {
17 Success,
18 Failure,
19 Code(i32),
20 }
21
22 /// Main helper for driving mdbook tests.
23 pub struct BookTest {
24 /// The temp directory where the test should perform its work.
25 pub dir: PathBuf,
26 /// The original source directory if created from [`BookTest::from_dir`].
27 original_source: Option<PathBuf>,
28 /// Snapshot assertion support.
29 pub assert: snapbox::Assert,
30 /// This indicates whether or not the book has been built.
31 built: bool,
32 }
33
34 impl BookTest {
35 /// Creates a new test, copying the contents from the given directory into
36 /// a temp directory.
37 pub fn from_dir(dir: &str) -> BookTest {
38 // Copy this test book to a temp directory.
39 let dir = Path::new("tests/testsuite").join(dir);
40 assert!(dir.exists(), "{dir:?} should exist");
41 let tmp = Self::new_tmp();
42 mdbook_core::utils::fs::copy_files_except_ext(
43 &dir,
44 &tmp,
45 true,
46 Some(&PathBuf::from("book")),
47 &[],
48 )
49 .unwrap_or_else(|e| panic!("failed to copy test book {dir:?} to {tmp:?}: {e:?}"));
50 Self::new(tmp, Some(dir))
51 }
52
53 /// Creates a new test with an empty temp directory.
54 pub fn empty() -> BookTest {
55 Self::new(Self::new_tmp(), None)
56 }
57
58 /// Creates a new test with the given function to initialize a new book.
59 ///
60 /// The book itself is not built.
61 pub fn init(f: impl Fn(&mut BookBuilder)) -> BookTest {
62 let tmp = Self::new_tmp();
63 let mut bb = MDBook::init(&tmp);
64 f(&mut bb);
65 bb.build()
66 .unwrap_or_else(|e| panic!("failed to initialize book at {tmp:?}: {e:?}"));
67 Self::new(tmp, None)
68 }
69
70 fn new_tmp() -> PathBuf {
71 let id = NEXT_TEST_ID.fetch_add(1, Ordering::SeqCst);
72 let tmp = Path::new(env!("CARGO_TARGET_TMPDIR"))
73 .join("ts")
74 .join(format!("t{id}"));
75 if tmp.exists() {
76 std::fs::remove_dir_all(&tmp)
77 .unwrap_or_else(|e| panic!("failed to remove {tmp:?}: {e:?}"));
78 }
79 fs::create_dir_all(&tmp).unwrap();
80 tmp
81 }
82
83 fn new(dir: PathBuf, original_source: Option<PathBuf>) -> BookTest {
84 let assert = assert(&dir);
85 BookTest {
86 dir,
87 original_source,
88 assert,
89 built: false,
90 }
91 }
92
93 /// Checks the contents of an HTML file that it has the given contents
94 /// between the `<main>` tag.
95 ///
96 /// Normally the contents outside of the `<main>` tag aren't interesting,
97 /// and they add a significant amount of noise.
98 #[track_caller]
99 pub fn check_main_file(&mut self, path: &str, expected: impl IntoData) -> &mut Self {
100 if !self.built {
101 self.build();
102 }
103 let full_path = self.dir.join(path);
104 let actual = read_to_string(&full_path);
105 let start = actual
106 .find("<main>")
107 .unwrap_or_else(|| panic!("didn't find <main> for `{full_path:?}` in:\n{actual}"));
108 let end = actual.find("</main>").unwrap();
109 let contents = actual[start + 6..end - 7].trim();
110 self.assert.eq(contents, expected);
111 self
112 }
113
114 /// Verifies the HTML output of all chapters in a book.
115 ///
116 /// This calls [`BookTest::check_main_file`] for every `.html` file
117 /// generated by building the book. All of expected files are stored in a
118 /// director called "expected" in the original book source directory.
119 ///
120 /// This only works when created with [`BookTest::from_dir`].
121 ///
122 /// `404.html`, `print.html`, and `toc.html` are not validated. The root
123 /// `index.html` is also not validated (since it is often duplicated with
124 /// the first chapter). If you need to validate it, call
125 /// [`BookTest::check_main_file`] directly.
126 #[track_caller]
127 pub fn check_all_main_files(&mut self) -> &mut Self {
128 if !self.built {
129 self.build();
130 }
131 let book_root = self.dir.join("book");
132 let mut files = list_all_files(&book_root);
133 files.retain(|file| {
134 file.extension().is_some_and(|ext| ext == "html")
135 && !matches!(
136 file.to_str().unwrap(),
137 "index.html" | "404.html" | "print.html" | "toc.html"
138 )
139 });
140 let expected_path = self
141 .original_source
142 .as_ref()
143 .expect("created with BookTest::from_dir")
144 .join("expected");
145 let mut expected_list = list_all_files(&expected_path);
146 for file in &files {
147 let expected = expected_path.join(file);
148 let data = snapbox::Data::read_from(&expected, None);
149 self.check_main_file(book_root.join(file).to_str().unwrap(), data);
150 if let Some(i) = expected_list.iter().position(|p| p == file) {
151 expected_list.remove(i);
152 }
153 }
154 // Verify there aren't any unused expected files.
155 if !expected_list.is_empty() {
156 panic!(
157 "extra expected files found in `{expected_path:?}:\n\
158 {expected_list:#?}\n\
159 Verify that these files are no longer needed and delete them."
160 );
161 }
162 self
163 }
164
165 /// Checks the summary contents of `toc.js` against the expected value.
166 #[track_caller]
167 pub fn check_toc_js(&mut self, expected: impl IntoData) -> &mut Self {
168 if !self.built {
169 self.build();
170 }
171 let inner = self.toc_js_html();
172 // Would be nice if this were prettified, but a primitive wrapping will do for now.
173 let inner = inner.replace("><", ">\n<");
174 self.assert.eq(inner, expected);
175 self
176 }
177
178 /// Returns the summary contents from `toc.js`.
179 #[track_caller]
180 pub fn toc_js_html(&self) -> String {
181 let toc_path = glob_one(&self.dir, "book/toc*.js");
182 let actual = read_to_string(&toc_path);
183 let inner = actual
184 .lines()
185 .filter_map(|line| {
186 let line = line.trim().strip_prefix("this.innerHTML = '")?;
187 let line = line.strip_suffix("';")?;
188 Some(line)
189 })
190 .next()
191 .expect("should have innerHTML");
192 inner.to_string()
193 }
194
195 /// Checks that the contents of the given file matches the expected value.
196 ///
197 /// The path can use glob-style wildcards, but it must match only a single file.
198 #[track_caller]
199 pub fn check_file(&mut self, path_pattern: &str, expected: impl IntoData) -> &mut Self {
200 if !self.built {
201 self.build();
202 }
203 let path = glob_one(&self.dir, path_pattern);
204 let actual = read_to_string(&path);
205 self.assert.eq(actual, expected);
206 self
207 }
208
209 /// Checks that the given file contains the given [`snapbox::Assert`] pattern somewhere.
210 ///
211 /// The path can use glob-style wildcards, but it must match only a single file.
212 #[track_caller]
213 pub fn check_file_contains(&mut self, path_pattern: &str, expected: &str) -> &mut Self {
214 if !self.built {
215 self.build();
216 }
217 let path = glob_one(&self.dir, path_pattern);
218 let actual = read_to_string(&path);
219 let expected = format!("...\n[..]{expected}[..]\n...\n");
220 self.assert.eq(actual, expected);
221 self
222 }
223
224 /// Checks that the given file does not contain the given string anywhere.
225 ///
226 /// Beware that using this is fragile, as it may be unable to catch
227 /// regressions (it can't tell the difference between success, or the
228 /// string being looked for changed).
229 ///
230 /// The path can use glob-style wildcards, but it must match only a single file.
231 #[track_caller]
232 pub fn check_file_doesnt_contain(&mut self, path_pattern: &str, string: &str) -> &mut Self {
233 if !self.built {
234 self.build();
235 }
236 let path = glob_one(&self.dir, path_pattern);
237 let actual = read_to_string(&path);
238 assert!(
239 !actual.contains(string),
240 "Unexpectedly found {string:?} in {path:?}\n\n{actual}",
241 );
242 self
243 }
244
245 /// Checks that the list of files at the given path matches the given value.
246 #[track_caller]
247 pub fn check_file_list(&mut self, path: &str, expected: impl IntoData) -> &mut Self {
248 let mut all_paths: Vec<_> = walkdir::WalkDir::new(&self.dir.join(path))
249 .into_iter()
250 // Skip the outer directory.
251 .skip(1)
252 .map(|e| {
253 e.unwrap()
254 .into_path()
255 .strip_prefix(&self.dir)
256 .unwrap()
257 .to_str()
258 .unwrap()
259 .replace('\\', "/")
260 })
261 .collect();
262 all_paths.sort();
263 let actual = all_paths.join("\n");
264 self.assert.eq(actual, expected);
265 self
266 }
267
268 /// Loads an [`MDBook`] from the temp directory.
269 pub fn load_book(&self) -> MDBook {
270 MDBook::load(&self.dir).unwrap_or_else(|e| panic!("book failed to load: {e:?}"))
271 }
272
273 /// Builds the book in the temp directory.
274 pub fn build(&mut self) -> &mut Self {
275 let book = self.load_book();
276 book.build()
277 .unwrap_or_else(|e| panic!("book failed to build: {e:?}"));
278 self.built = true;
279 self
280 }
281
282 /// Runs the `mdbook` binary in the temp directory.
283 ///
284 /// This runs `mdbook` with the given args. The args are split on spaces
285 /// (if you need args with spaces, use the `args` method). The given
286 /// callback receives a [`BookCommand`] for you to customize how the
287 /// executable is run.
288 pub fn run(&mut self, args: &str, f: impl Fn(&mut BookCommand)) -> &mut Self {
289 let mut cmd = BookCommand {
290 assert: self.assert.clone(),
291 dir: self.dir.clone(),
292 args: split_args(args),
293 env: BTreeMap::new(),
294 expect_status: StatusCode::Success,
295 expect_stderr_data: None,
296 expect_stdout_data: None,
297 debug: None,
298 };
299 f(&mut cmd);
300 cmd.run();
301 // Ensure that `built` gets set if a build command is used so that all
302 // the `check` methods do not overwrite the contents of what was just
303 // built.
304 if cmd.args.first().map(String::as_str) == Some("build") {
305 self.built = true
306 }
307 self
308 }
309
310 /// Change a file's contents in the given path.
311 pub fn change_file(&mut self, path: impl AsRef<Path>, body: &str) -> &mut Self {
312 let path = self.dir.join(path);
313 fs::write(&path, body).unwrap();
314 self
315 }
316
317 /// Removes a file or directory relative to the test root.
318 pub fn rm_r(&mut self, path: impl AsRef<Path>) -> &mut Self {
319 let path = self.dir.join(path.as_ref());
320 let meta = match path.symlink_metadata() {
321 Ok(meta) => meta,
322 Err(e) => panic!("failed to remove {path:?}, could not read: {e:?}"),
323 };
324 // There is a race condition between fetching the metadata and
325 // actually performing the removal, but we don't care all that much
326 // for our tests.
327 if meta.is_dir() {
328 if let Err(e) = std::fs::remove_dir_all(&path) {
329 panic!("failed to remove {path:?}: {e:?}");
330 }
331 } else if let Err(e) = std::fs::remove_file(&path) {
332 panic!("failed to remove {path:?}: {e:?}")
333 }
334 self
335 }
336
337 /// Builds a Rust program with the given src.
338 ///
339 /// The given path should be the path where to output the executable in
340 /// the temp directory.
341 pub fn rust_program(&mut self, path: &str, src: &str) -> &mut Self {
342 let rs = self.dir.join(path).with_extension("rs");
343 let parent = rs.parent().unwrap();
344 if !parent.exists() {
345 fs::create_dir_all(&parent).unwrap();
346 }
347 fs::write(&rs, src).unwrap();
348 let status = std::process::Command::new("rustc")
349 .arg(&rs)
350 .current_dir(&parent)
351 .status()
352 .expect("rustc should run");
353 assert!(status.success());
354 self
355 }
356 }
357
358 /// A builder for preparing to run the `mdbook` executable.
359 ///
360 /// By default, it expects the process to succeed.
361 pub struct BookCommand {
362 pub dir: PathBuf,
363 assert: snapbox::Assert,
364 args: Vec<String>,
365 env: BTreeMap<String, Option<String>>,
366 expect_status: StatusCode,
367 expect_stderr_data: Option<snapbox::Data>,
368 expect_stdout_data: Option<snapbox::Data>,
369 debug: Option<String>,
370 }
371
372 impl BookCommand {
373 /// Indicates that the process should fail.
374 pub fn expect_failure(&mut self) -> &mut Self {
375 self.expect_status = StatusCode::Failure;
376 self
377 }
378
379 /// Indicates the process should fail with the given exit code.
380 pub fn expect_code(&mut self, code: i32) -> &mut Self {
381 self.expect_status = StatusCode::Code(code);
382 self
383 }
384
385 /// Verifies that stderr matches the given value.
386 pub fn expect_stderr(&mut self, expected: impl snapbox::IntoData) -> &mut Self {
387 self.expect_stderr_data = Some(expected.into_data());
388 self
389 }
390
391 /// Verifies that stdout matches the given value.
392 pub fn expect_stdout(&mut self, expected: impl snapbox::IntoData) -> &mut Self {
393 self.expect_stdout_data = Some(expected.into_data());
394 self
395 }
396
397 /// Adds arguments to the command to run.
398 pub fn args(&mut self, args: &[&str]) -> &mut Self {
399 self.args.extend(args.into_iter().map(|t| t.to_string()));
400 self
401 }
402
403 /// Specifies an environment variable to set on the executable.
404 pub fn env<T: Into<String>>(&mut self, key: &str, value: T) -> &mut Self {
405 self.env.insert(key.to_string(), Some(value.into()));
406 self
407 }
408
409 /// Sets the directory used for running the command.
410 pub fn current_dir<S: AsRef<std::path::Path>>(&mut self, path: S) -> &mut Self {
411 self.dir = self.dir.join(path.as_ref());
412 self
413 }
414
415 /// Use this to debug a command.
416 ///
417 /// Pass the value that you would normally pass to `MDBOOK_LOG`, and this
418 /// will enable logging, print the command that runs and its output.
419 ///
420 /// This will fail if you use it in CI.
421 #[allow(unused)]
422 pub fn debug(&mut self, value: &str) -> &mut Self {
423 if std::env::var_os("CI").is_some() {
424 panic!("debug is not allowed on CI");
425 }
426 self.debug = Some(value.into());
427 self
428 }
429
430 /// Runs the command, and verifies the output.
431 fn run(&mut self) {
432 let mut cmd = Command::new(env!("CARGO_BIN_EXE_mdbook"));
433 cmd.current_dir(&self.dir)
434 .args(&self.args)
435 .env_remove("MDBOOK_LOG")
436 // Don't read the system git config which is out of our control.
437 .env("GIT_CONFIG_NOSYSTEM", "1")
438 .env("GIT_CONFIG_GLOBAL", &self.dir)
439 .env("GIT_CONFIG_SYSTEM", &self.dir)
440 .env_remove("GIT_AUTHOR_EMAIL")
441 .env_remove("GIT_AUTHOR_NAME")
442 .env_remove("GIT_COMMITTER_EMAIL")
443 .env_remove("GIT_COMMITTER_NAME");
444
445 if let Some(debug) = &self.debug {
446 cmd.env("MDBOOK_LOG", debug);
447 }
448
449 for (k, v) in &self.env {
450 match v {
451 Some(v) => cmd.env(k, v),
452 None => cmd.env_remove(k),
453 };
454 }
455
456 if self.debug.is_some() {
457 eprintln!("running {cmd:#?}");
458 }
459 let output = cmd.output().expect("mdbook should be runnable");
460 let stdout = std::str::from_utf8(&output.stdout).expect("stdout is not utf8");
461 let stderr = std::str::from_utf8(&output.stderr).expect("stderr is not utf8");
462 let render_output = || format!("\n--- stdout\n{stdout}\n--- stderr\n{stderr}");
463 match (self.expect_status, output.status.success()) {
464 (StatusCode::Success, false) => {
465 panic!("mdbook failed, but expected success{}", render_output())
466 }
467 (StatusCode::Failure, true) => {
468 panic!("mdbook succeeded, but expected failure{}", render_output())
469 }
470 (StatusCode::Code(expected), _) => match output.status.code() {
471 Some(actual) => assert_eq!(
472 actual, expected,
473 "process exit code did not match as expected"
474 ),
475 None => panic!("process exited via signal {:?}", output.status),
476 },
477 _ => {}
478 }
479 if self.debug.is_some() {
480 eprintln!("{}", render_output());
481 }
482 self.expect_status = StatusCode::Success; // Reset to default.
483 if let Some(expect_stderr_data) = &self.expect_stderr_data {
484 if let Err(e) = self.assert.try_eq(
485 Some(&"stderr"),
486 stderr.into_data(),
487 expect_stderr_data.clone(),
488 ) {
489 panic!("{e}");
490 }
491 }
492 if let Some(expect_stdout_data) = &self.expect_stdout_data {
493 if let Err(e) = self.assert.try_eq(
494 Some(&"stdout"),
495 stdout.into_data(),
496 expect_stdout_data.clone(),
497 ) {
498 panic!("{e}");
499 }
500 }
501 }
502 }
503
504 fn split_args(s: &str) -> Vec<String> {
505 s.split_whitespace()
506 .map(|arg| {
507 if arg.contains(&['"', '\''][..]) {
508 panic!("shell-style argument parsing is not supported");
509 }
510 String::from(arg)
511 })
512 .collect()
513 }
514
515 static LITERAL_REDACTIONS: &[(&str, &str)] = &[
516 // Unix message for an entity was not found
517 ("[NOT_FOUND]", "No such file or directory (os error 2)"),
518 // Windows message for an entity was not found
519 (
520 "[NOT_FOUND]",
521 "The system cannot find the file specified. (os error 2)",
522 ),
523 (
524 "[NOT_FOUND]",
525 "The system cannot find the path specified. (os error 3)",
526 ),
527 ("[NOT_FOUND]", "program not found"),
528 // Unix message for exit status
529 ("[EXIT_STATUS]", "exit status"),
530 // Windows message for exit status
531 ("[EXIT_STATUS]", "exit code"),
532 ("[TAB]", "\t"),
533 ("[EXE]", std::env::consts::EXE_SUFFIX),
534 ];
535
536 fn assert(root: &Path) -> snapbox::Assert {
537 let mut subs = snapbox::Redactions::new();
538 subs.insert("[ROOT]", root.to_path_buf()).unwrap();
539 subs.insert("[VERSION]", mdbook_core::MDBOOK_VERSION)
540 .unwrap();
541
542 subs.extend(LITERAL_REDACTIONS.into_iter().cloned())
543 .unwrap();
544
545 snapbox::Assert::new()
546 .action_env(snapbox::assert::DEFAULT_ACTION_ENV)
547 .redact_with(subs)
548 }
549
550 /// Helper to read a string from the filesystem.
551 #[track_caller]
552 pub fn read_to_string<P: AsRef<Path>>(path: P) -> String {
553 let path = path.as_ref();
554 fs::read_to_string(path).unwrap()
555 }
556
557 /// Returns the first path from the given glob pattern.
558 pub fn glob_one<P: AsRef<Path>>(path: P, pattern: &str) -> PathBuf {
559 let path = path.as_ref();
560 let mut matches = glob::glob(path.join(pattern).to_str().unwrap()).unwrap();
561 let Some(first) = matches.next() else {
562 panic!("expected at least one file at `{path:?}` with pattern `{pattern}`, found none");
563 };
564 let first = first.unwrap();
565 if let Some(next) = matches.next() {
566 panic!(
567 "expected only one file for pattern `{pattern}` in `{path:?}`, \
568 found `{first:?}` and `{:?}`",
569 next.unwrap()
570 );
571 }
572 first
573 }
574
575 /// Lists all files at the given directory.
576 ///
577 /// Recursively walks the tree. Paths are relative to the directory.
578 pub fn list_all_files(dir: &Path) -> Vec<PathBuf> {
579 walkdir::WalkDir::new(dir)
580 .sort_by_file_name()
581 .into_iter()
582 // Skip the outer directory.
583 .skip(1)
584 .map(|entry| {
585 let entry = entry.unwrap();
586 let path = entry.path();
587 path.strip_prefix(dir).unwrap().to_path_buf()
588 })
589 .collect()
590 }