Debian Codegraph @

tests/testsuite/renderer.rs

raw
1 //! Tests for custom renderers.
2
3 use crate::prelude::*;
4 use anyhow::Result;
5 use mdbook_renderer::{RenderContext, Renderer};
6 use snapbox::IntoData;
7 use std::fs::File;
8 use std::sync::{Arc, Mutex};
9
10 struct Spy(Arc<Mutex<Inner>>);
11
12 #[derive(Debug, Default)]
13 struct Inner {
14 run_count: usize,
15 }
16
17 impl Renderer for Spy {
18 fn name(&self) -> &str {
19 "dummy"
20 }
21
22 fn render(&self, _ctx: &RenderContext) -> Result<()> {
23 let mut inner = self.0.lock().unwrap();
24 inner.run_count += 1;
25 Ok(())
26 }
27 }
28
29 // Test that renderer gets run.
30 #[test]
31 fn runs_renderers() {
32 let test = BookTest::init(|_| {});
33 let spy: Arc<Mutex<Inner>> = Default::default();
34 let mut book = test.load_book();
35 book.with_renderer(Spy(Arc::clone(&spy)));
36 book.build().unwrap();
37
38 let inner = spy.lock().unwrap();
39 assert_eq!(inner.run_count, 1);
40 }
41
42 // Test renderer with a failing command fails.
43 #[test]
44 fn failing_command() {
45 BookTest::init(|_| {})
46 .rust_program(
47 "failing",
48 r#"
49 fn main() {
50 // Read from stdin to avoid random pipe failures on Linux.
51 use std::io::Read;
52 let mut s = String::new();
53 std::io::stdin().read_to_string(&mut s).unwrap();
54 std::process::exit(1);
55 }
56 "#,
57 )
58 .change_file(
59 "book.toml",
60 "[output.failing]\n\
61 command = './failing'\n",
62 )
63 .run("build", |cmd| {
64 cmd.expect_failure()
65 .expect_stdout(str![[""]])
66 .expect_stderr(str![[r#"
67 INFO Book building has started
68 INFO Running the failing backend
69 INFO Invoking the "failing" renderer
70 ERROR Renderer exited with non-zero return code.
71 ERROR Rendering failed
72 [TAB]Caused by: The "failing" renderer failed
73
74 "#]]);
75 });
76 }
77
78 // Renderer command is missing.
79 #[test]
80 fn missing_renderer() {
81 BookTest::from_dir("renderer/missing_renderer").run("build", |cmd| {
82 cmd.expect_failure()
83 .expect_stdout(str![[""]])
84 .expect_stderr(str![[r#"
85 INFO Book building has started
86 INFO Running the missing backend
87 INFO Invoking the "missing" renderer
88 ERROR The command `trduyvbhijnorgevfuhn` wasn't found, is the `missing` backend installed? If you want to ignore this error when the `missing` backend is not installed, set `optional = true` in the `[output.missing]` section of the book.toml configuration file.
89 ERROR Rendering failed
90 [TAB]Caused by: Unable to run the backend `missing`
91 [TAB]Caused by: [NOT_FOUND]
92
93 "#]]);
94 });
95 }
96
97 // Optional missing is not an error.
98 #[test]
99 fn missing_optional_not_fatal() {
100 BookTest::from_dir("renderer/missing_optional_not_fatal").run("build", |cmd| {
101 cmd.expect_stdout(str![[""]]).expect_stderr(str![[r#"
102 INFO Book building has started
103 INFO Running the missing backend
104 INFO Invoking the "missing" renderer
105 WARN The command `trduyvbhijnorgevfuhn` for backend `missing` was not found, but is marked as optional.
106
107 "#]]);
108 });
109 }
110
111 // Command can include arguments.
112 #[test]
113 fn renderer_with_arguments() {
114 BookTest::from_dir("renderer/renderer_with_arguments")
115 .rust_program(
116 "arguments",
117 r#"
118 fn main() {
119 let args: Vec<_> = std::env::args().skip(1).collect();
120 assert_eq!(args, &["arg1", "arg2"]);
121 println!("Hello World!");
122 use std::io::Read;
123 let mut s = String::new();
124 std::io::stdin().read_to_string(&mut s).unwrap();
125 }
126 "#,
127 )
128 .run("build", |cmd| {
129 cmd.expect_stdout(str![[r#"
130 Hello World!
131
132 "#]])
133 .expect_stderr(str![[r#"
134 INFO Book building has started
135 INFO Running the arguments backend
136 INFO Invoking the "arguments" renderer
137
138 "#]]);
139 });
140 }
141
142 // Checks the render context received by the renderer.
143 #[test]
144 fn backends_receive_render_context_via_stdin() {
145 let mut test = BookTest::from_dir("renderer/backends_receive_render_context_via_stdin");
146 test.rust_program(
147 "cat-to-file",
148 r#"
149 fn main() {
150 use std::io::Read;
151 let mut s = String::new();
152 std::io::stdin().read_to_string(&mut s).unwrap();
153 std::fs::write("out.txt", s).unwrap();
154 }
155 "#,
156 )
157 .run("build", |cmd| {
158 cmd.expect_stdout(str![[""]]).expect_stderr(str![[r#"
159 INFO Book building has started
160 INFO Running the cat-to-file backend
161 INFO Invoking the "cat-to-file" renderer
162
163 "#]]);
164 })
165 .check_file(
166 "book/out.txt",
167 str![[r##"
168 {
169 "book": {
170 "items": [
171 {
172 "Chapter": {
173 "content": "# Chapter 1\n",
174 "name": "Chapter 1",
175 "number": [
176 1
177 ],
178 "parent_names": [],
179 "path": "chapter_1.md",
180 "source_path": "chapter_1.md",
181 "sub_items": []
182 }
183 }
184 ]
185 },
186 "config": {
187 "book": {
188 "authors": [],
189 "description": null,
190 "language": "en",
191 "text-direction": null,
192 "title": null
193 },
194 "output": {
195 "cat-to-file": {
196 "command": "./cat-to-file"
197 }
198 }
199 },
200 "destination": "[ROOT]/book",
201 "root": "[ROOT]",
202 "version": "[VERSION]"
203 }
204 "##]]
205 .is_json(),
206 );
207
208 // Can round-trip.
209 let f = File::open(test.dir.join("book/out.txt")).unwrap();
210 RenderContext::from_json(f).unwrap();
211 }
212
213 // Verifies that a relative path for the renderer command is relative to the
214 // book root.
215 #[test]
216 fn relative_command_path() {
217 let mut test = BookTest::init(|_| {});
218 test.rust_program(
219 "renderers/myrenderer",
220 r#"
221 fn main() {
222 use std::io::Read;
223 let mut s = String::new();
224 std::io::stdin().read_to_string(&mut s).unwrap();
225 std::fs::write("output", "test").unwrap();
226 }
227 "#,
228 )
229 .change_file(
230 "book.toml",
231 "[output.myrenderer]\n\
232 command = 'renderers/myrenderer'\n",
233 )
234 .run("build", |cmd| {
235 cmd.expect_stdout(str![[""]]).expect_stderr(str![[r#"
236 INFO Book building has started
237 INFO Running the myrenderer backend
238 INFO Invoking the "myrenderer" renderer
239
240 "#]]);
241 })
242 .check_file("book/output", "test");
243 }
244
245 // with_renderer of an existing name.
246 #[test]
247 fn with_renderer_same_name() {
248 let mut test = BookTest::init(|_| {});
249 test.change_file(
250 "book.toml",
251 "[output.dummy]\n\
252 command = 'mdbook-renderer-does-not-exist'\n",
253 );
254 let spy: Arc<Mutex<Inner>> = Default::default();
255 let mut book = test.load_book();
256 book.with_renderer(Spy(Arc::clone(&spy)));
257 // Unfortunately this is unable to capture the output when using the API.
258 book.build().unwrap();
259 let inner = spy.lock().unwrap();
260 assert_eq!(inner.run_count, 1);
261 }