Debian Codegraph @

tests/testsuite/preprocessor.rs

raw
1 //! Tests for custom preprocessors.
2
3 use crate::book_test::list_all_files;
4 use crate::prelude::*;
5 use anyhow::Result;
6 use mdbook_core::book::{Book, BookItem, Chapter};
7 use mdbook_driver::builtin_preprocessors::CmdPreprocessor;
8 use mdbook_preprocessor::{Preprocessor, PreprocessorContext};
9 use snapbox::IntoData;
10 use std::sync::{Arc, Mutex};
11
12 struct Spy(Arc<Mutex<Inner>>);
13
14 #[derive(Debug, Default)]
15 struct Inner {
16 run_count: usize,
17 rendered_with: Vec<String>,
18 }
19
20 impl Preprocessor for Spy {
21 fn name(&self) -> &str {
22 "dummy"
23 }
24
25 fn run(&self, ctx: &PreprocessorContext, book: Book) -> Result<Book> {
26 let mut inner = self.0.lock().unwrap();
27 inner.run_count += 1;
28 inner.rendered_with.push(ctx.renderer.clone());
29 Ok(book)
30 }
31 }
32
33 // Test that preprocessor gets run.
34 #[test]
35 fn runs_preprocessors() {
36 let test = BookTest::init(|_| {});
37 let spy: Arc<Mutex<Inner>> = Default::default();
38 let mut book = test.load_book();
39 book.with_preprocessor(Spy(Arc::clone(&spy)));
40 book.build().unwrap();
41
42 let inner = spy.lock().unwrap();
43 assert_eq!(inner.run_count, 1);
44 assert_eq!(inner.rendered_with, ["html"]);
45 }
46
47 // Run tests with a custom preprocessor.
48 #[test]
49 fn test_with_custom_preprocessor() {
50 let test = BookTest::init(|_| {});
51 let spy: Arc<Mutex<Inner>> = Default::default();
52 let mut book = test.load_book();
53 book.with_preprocessor(Spy(Arc::clone(&spy)));
54 book.test(vec![]).unwrap();
55
56 let inner = spy.lock().unwrap();
57 assert_eq!(inner.run_count, 1);
58 assert_eq!(inner.rendered_with, ["test"]);
59 }
60
61 // No-op preprocessor works.
62 #[test]
63 fn nop_preprocessor() {
64 BookTest::from_dir("preprocessor/nop_preprocessor").run("build", |cmd| {
65 cmd.expect_stdout(str![[""]]).expect_stderr(str![[r#"
66 INFO Book building has started
67 INFO Running the html backend
68 INFO HTML book written to `[ROOT]/book`
69
70 "#]]);
71 });
72 }
73
74 // Failing preprocessor generates an error.
75 #[test]
76 fn failing_preprocessor() {
77 BookTest::from_dir("preprocessor/failing_preprocessor").run("build", |cmd| {
78 cmd.expect_failure()
79 .expect_stdout(str![[""]])
80 .expect_stderr(str![[r#"
81 INFO Book building has started
82 Boom!!1!
83 ERROR The "nop-preprocessor" preprocessor exited unsuccessfully with [EXIT_STATUS]: 1 status
84
85 "#]]);
86 });
87 }
88
89 fn example() -> CmdPreprocessor {
90 CmdPreprocessor::new(
91 "nop-preprocessor".to_string(),
92 "cargo run --quiet --example nop-preprocessor --".to_string(),
93 std::env::current_dir().unwrap(),
94 false,
95 )
96 }
97
98 #[test]
99 fn example_supports_whatever() {
100 let cmd = example();
101
102 let got = cmd.supports_renderer("whatever").unwrap();
103
104 assert_eq!(got, true);
105 }
106
107 #[test]
108 fn example_doesnt_support_not_supported() {
109 let cmd = example();
110
111 let got = cmd.supports_renderer("not-supported").unwrap();
112
113 assert_eq!(got, false);
114 }
115
116 // Checks the behavior of a relative path to a preprocessor.
117 #[test]
118 fn relative_command_path() {
119 let mut test = BookTest::init(|_| {});
120 test.rust_program(
121 "preprocessors/my-preprocessor",
122 r#"
123 fn main() {
124 let mut args = std::env::args().skip(1);
125 if args.next().as_deref() == Some("supports") {
126 std::fs::write("support-check", args.next().unwrap()).unwrap();
127 return;
128 }
129 use std::io::Read;
130 let mut s = String::new();
131 std::io::stdin().read_to_string(&mut s).unwrap();
132 std::fs::write("preprocessor-ran", "test").unwrap();
133 println!("{{\"items\": []}}");
134 }
135 "#,
136 )
137 .change_file(
138 "book.toml",
139 "[preprocessor.my-preprocessor]\n\
140 command = 'preprocessors/my-preprocessor'\n",
141 )
142 .run("build", |cmd| {
143 cmd.expect_stdout(str![""]).expect_stderr(str![[r#"
144 INFO Book building has started
145 INFO Running the html backend
146 INFO HTML book written to `[ROOT]/book`
147
148 "#]]);
149 })
150 .check_file("support-check", "html")
151 .check_file("preprocessor-ran", "test")
152 // Try again, but outside of the book root to check relative path behavior.
153 .rm_r("support-check")
154 .rm_r("preprocessor-ran")
155 .run("build ..", |cmd| {
156 cmd.current_dir(cmd.dir.join("src"))
157 .expect_stdout(str![""])
158 .expect_stderr(str![[r#"
159 INFO Book building has started
160 INFO Running the html backend
161 INFO HTML book written to `[ROOT]/src/../book`
162
163 "#]]);
164 })
165 .check_file("support-check", "html")
166 .check_file("preprocessor-ran", "test");
167 }
168
169 // Preprocessor command is missing.
170 #[test]
171 fn missing_preprocessor() {
172 BookTest::from_dir("preprocessor/missing_preprocessor").run("build", |cmd| {
173 cmd.expect_failure()
174 .expect_stdout(str![[""]])
175 .expect_stderr(str![[r#"
176 INFO Book building has started
177 ERROR The command `trduyvbhijnorgevfuhn` wasn't found, is the `missing` preprocessor installed? If you want to ignore this error when the `missing` preprocessor is not installed, set `optional = true` in the `[preprocessor.missing]` section of the book.toml configuration file.
178 ERROR Unable to run the preprocessor `missing`
179 [TAB]Caused by: [NOT_FOUND]
180
181 "#]]);
182 });
183 }
184
185 // Optional missing is not an error.
186 #[test]
187 fn missing_optional_not_fatal() {
188 BookTest::from_dir("preprocessor/missing_optional_not_fatal").run("build", |cmd| {
189 cmd.expect_stdout(str![[""]]).expect_stderr(str![[r#"
190 INFO Book building has started
191 WARN The command `trduyvbhijnorgevfuhn` for preprocessor `missing` was not found, but is marked as optional.
192 INFO Running the html backend
193 INFO HTML book written to `[ROOT]/book`
194
195 "#]]);
196 });
197 }
198
199 // with_preprocessor of an existing name.
200 #[test]
201 fn with_preprocessor_same_name() {
202 let mut test = BookTest::init(|_| {});
203 test.change_file(
204 "book.toml",
205 "[preprocessor.dummy]\n\
206 command = 'mdbook-preprocessor-does-not-exist'\n",
207 );
208 let spy: Arc<Mutex<Inner>> = Default::default();
209 let mut book = test.load_book();
210 book.with_preprocessor(Spy(Arc::clone(&spy)));
211 // Unfortunately this is unable to capture the output when using the API.
212 book.build().unwrap();
213 let inner = spy.lock().unwrap();
214 assert_eq!(inner.run_count, 1);
215 assert_eq!(inner.rendered_with, ["html"]);
216 }
217
218 // Checks that the interface stays backwards compatible. The interface here
219 // should not be changed to fix a compatibility issue unless there is a
220 // major-semver version update to mdbook.
221 //
222 // Note that this tests both preprocessors and renderers. It's in this module
223 // for lack of a better location.
224 #[test]
225 fn extension_compatibility() {
226 // This is here to force you to look at this test if you alter any of
227 // these types such as adding new fields/variants. This test should be
228 // updated accordingly. For example, new `BookItem` variants should be
229 // added to the extension_compatibility book, or new fields should be
230 // added to the expected input/output. This is also a check that these
231 // should only be changed in a semver-breaking release
232 let chapter = Chapter {
233 name: "example".to_string(),
234 content: "content".to_string(),
235 number: None,
236 sub_items: Vec::new(),
237 path: None,
238 source_path: None,
239 parent_names: Vec::new(),
240 };
241 let item = BookItem::Chapter(chapter);
242 match &item {
243 BookItem::Chapter(_) => {}
244 BookItem::Separator => {}
245 BookItem::PartTitle(_) => {}
246 }
247 let items = vec![item];
248 let _book = Book { items };
249
250 let mut test = BookTest::from_dir("preprocessor/extension_compatibility");
251 // Run it once with the preprocessor disabled so that we can verify
252 // that the built book is identical with the preprocessor enabled.
253 test.run("build", |cmd| {
254 cmd.expect_stdout(str![[""]]).expect_stderr(str![[r#"
255 INFO Book building has started
256 WARN The command `./my-preprocessor` for preprocessor `my-preprocessor` was not found, but is marked as optional.
257 INFO Running the html backend
258 INFO HTML book written to `[ROOT]/book/html`
259 WARN The command `./my-preprocessor` for preprocessor `my-preprocessor` was not found, but is marked as optional.
260 INFO Running the my-renderer backend
261 INFO Invoking the "my-renderer" renderer
262 WARN The command `./my-renderer` for backend `my-renderer` was not found, but is marked as optional.
263
264 "#]]);
265 });
266 let orig_dir = test.dir.join("book.orig");
267 let pre_dir = test.dir.join("book");
268 std::fs::rename(&pre_dir, &orig_dir).unwrap();
269
270 // **CAUTION** DO NOT modify this value unless this is a major-semver change.
271 let book_output = serde_json::json!({
272 "items": [
273 {
274 "Chapter": {
275 "content": "# Prefix chapter\n",
276 "name": "Prefix chapter",
277 "number": null,
278 "parent_names": [],
279 "path": "prefix.md",
280 "source_path": "prefix.md",
281 "sub_items": []
282 }
283 },
284 {
285 "Chapter": {
286 "content": "# Chapter 1\n",
287 "name": "Chapter 1",
288 "number": [
289 1
290 ],
291 "parent_names": [],
292 "path": "chapter_1.md",
293 "source_path": "chapter_1.md",
294 "sub_items": []
295 }
296 },
297 {
298 "Chapter": {
299 "content": "",
300 "name": "Draft chapter",
301 "number": [
302 2
303 ],
304 "parent_names": [],
305 "path": null,
306 "source_path": null,
307 "sub_items": []
308 }
309 },
310 {
311 "PartTitle": "Part title"
312 },
313 {
314 "Chapter": {
315 "content": "# Part chapter\n",
316 "name": "Part chapter",
317 "number": [
318 3
319 ],
320 "parent_names": [],
321 "path": "part/chapter.md",
322 "source_path": "part/chapter.md",
323 "sub_items": [
324 {
325 "Chapter": {
326 "content": "# Part sub chapter\n",
327 "name": "Part sub chapter",
328 "number": [
329 3,
330 1
331 ],
332 "parent_names": [
333 "Part chapter"
334 ],
335 "path": "part/sub-chapter.md",
336 "source_path": "part/sub-chapter.md",
337 "sub_items": []
338 }
339 }
340 ]
341 }
342 },
343 "Separator",
344 {
345 "Chapter": {
346 "content": "# Suffix chapter\n",
347 "name": "Suffix chapter",
348 "number": null,
349 "parent_names": [],
350 "path": "suffix.md",
351 "source_path": "suffix.md",
352 "sub_items": []
353 }
354 }
355 ]
356 });
357 let output_str = serde_json::to_string(&book_output).unwrap();
358 // **CAUTION** The only updates allowed here in a semver-compatible
359 // release is to add new fields.
360 let expected_config = serde_json::json!({
361 "book": {
362 "authors": [],
363 "description": null,
364 "language": "en",
365 "text-direction": null,
366 "title": "extension_compatibility"
367 },
368 "output": {
369 "html": {},
370 "my-renderer": {
371 "command": "./my-renderer",
372 "custom-config": "renderer settings",
373 "custom-table": {
374 "extra": "xyz"
375 },
376 "optional": true
377 }
378 },
379 "preprocessor": {
380 "my-preprocessor": {
381 "command": "./my-preprocessor",
382 "custom-config": true,
383 "custom-table": {
384 "extra": "abc"
385 },
386 "optional": true
387 }
388 }
389 });
390
391 // **CAUTION** The only updates allowed here in a semver-compatible
392 // release is to add new fields. The output should not change.
393 let expected_preprocessor_input = serde_json::json!([
394 {
395 "config": expected_config,
396 "mdbook_version": "[VERSION]",
397 "renderer": "html",
398 "root": "[ROOT]"
399 },
400 book_output
401 ]);
402 let expected_renderer_input = serde_json::json!(
403 {
404 "version": "[VERSION]",
405 "root": "[ROOT]",
406 "book": book_output,
407 "config": expected_config,
408 "destination": "[ROOT]/book/my-renderer",
409 }
410 );
411
412 // This preprocessor writes its input to some files, and writes the
413 // hard-coded output specified above.
414 test.rust_program(
415 "my-preprocessor",
416 &r###"
417 use std::fs::OpenOptions;
418 use std::io::{Read, Write};
419 fn main() {
420 let mut args = std::env::args().skip(1);
421 if args.next().as_deref() == Some("supports") {
422 let mut file = OpenOptions::new()
423 .create(true)
424 .append(true)
425 .open("support-check")
426 .unwrap();
427 let renderer = args.next().unwrap();
428 writeln!(file, "{renderer}").unwrap();
429 if renderer != "html" {
430 std::process::exit(1);
431 }
432 return;
433 }
434 let mut s = String::new();
435 std::io::stdin().read_to_string(&mut s).unwrap();
436 std::fs::write("preprocessor-input", &s).unwrap();
437 let output = r##"OUTPUT_REPLACE"##;
438 println!("{output}");
439 }
440 "###
441 .replace("OUTPUT_REPLACE", &output_str),
442 )
443 // This renderer writes its input to a file.
444 .rust_program(
445 "my-renderer",
446 &r#"
447 fn main() {
448 use std::io::Read;
449 let mut s = String::new();
450 std::io::stdin().read_to_string(&mut s).unwrap();
451 std::fs::write("renderer-input", &s).unwrap();
452 }
453 "#,
454 )
455 .run("build", |cmd| {
456 cmd.expect_stdout(str![[""]]).expect_stderr(str![[r#"
457 INFO Book building has started
458 INFO Running the html backend
459 INFO HTML book written to `[ROOT]/book/html`
460 INFO Running the my-renderer backend
461 INFO Invoking the "my-renderer" renderer
462
463 "#]]);
464 })
465 .check_file("support-check", "html\nmy-renderer\n")
466 .check_file(
467 "preprocessor-input",
468 serde_json::to_string(&expected_preprocessor_input)
469 .unwrap()
470 .is_json(),
471 )
472 .check_file(
473 "book/my-renderer/renderer-input",
474 serde_json::to_string(&expected_renderer_input)
475 .unwrap()
476 .is_json(),
477 );
478 // Verify both directories have the exact same output.
479 test.rm_r("book/my-renderer/renderer-input");
480 let orig_files = list_all_files(&orig_dir);
481 let pre_files = list_all_files(&pre_dir);
482 assert_eq!(orig_files, pre_files);
483 for file in &orig_files {
484 let orig_path = orig_dir.join(file);
485 if orig_path.is_file() {
486 let orig = std::fs::read(&orig_path).unwrap();
487 let pre = std::fs::read(&pre_dir.join(file)).unwrap();
488 test.assert.eq(pre, orig);
489 }
490 }
491 }