Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_austenite/tests/stand_ins.rs

16.7 KiB, 1 run

created by r1870400018:62393, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Every place page building sets a stand-in for what a construct asked for -- an image that will not load,
2//! a logo, a cover, a reference to a label nothing carries, a citation nothing resolves, a bibliography or a
3//! terms file that is not there -- is reported as a warning at the site that asked, so a strict compile
4//! refuses it. Driven through the same `compile` functions the wasm `DaimondTypst` calls, with the source
5//! map installed as it installs one.
6
7use oxedyne_fe2o3_austenite::compile::{
8 self,
9 Diagnostic,
10 DiagnosticKind,
11 Report,
12 Severity,
13};
14use oxedyne_fe2o3_austenite::fonts;
15use oxedyne_fe2o3_austenite::memo::Memo;
16use oxedyne_fe2o3_austenite::vfs;
17
18use oxedyne_fe2o3_core::prelude::*;
19use oxedyne_fe2o3_graphics::colour::Rgba;
20use oxedyne_fe2o3_graphics::pixmap::Pixmap;
21
22use std::collections::HashMap;
23use std::path::{
24 Path,
25 PathBuf,
26};
27use std::sync::{
28 Arc,
29 Mutex,
30 MutexGuard,
31};
32
33// The source map is a process global, so the tests that install one take turns.
34static VFS_TURN: Mutex<()> = Mutex::new(());
35
36fn turn() -> MutexGuard<'static, ()> {
37 VFS_TURN.lock().unwrap_or_else(|p| p.into_inner())
38}
39
40const MAIN: &str = "/proj/main.typ";
41
42/// Installs `files`, compiles `main` as the wasm surface does -- through the memo when one is given -- and
43/// returns the report, clearing the map either way.
44fn report_of(main: &str, files: &[(&str, &[u8])], memo: Option<&mut Memo>) -> Outcome<Report> {
45 let mut map: HashMap<PathBuf, Vec<u8>> = HashMap::new();
46 for (p, b) in files {
47 map.insert(PathBuf::from(p), b.to_vec());
48 }
49 res!(vfs::install(map));
50 let main = PathBuf::from(main);
51 let fonts = Arc::new(res!(fonts::libertinus()));
52 let run = || -> Outcome<Report> {
53 let assembled = res!(compile::assemble(&main, || Ok(fonts.clone())));
54 let empty = assembled.blocks.is_empty();
55 let rendered = res!(compile::author_and_run_memo(assembled, memo));
56 Ok(Report::new(rendered.out.pages.len(), &rendered.refusals, empty))
57 };
58 let out = run();
59 res!(vfs::clear());
60 out
61}
62
63/// The warnings whose message holds `needle`.
64fn sites<'a>(report: &'a Report, needle: &str) -> Vec<&'a Diagnostic> {
65 report.diagnostics.iter().filter(|d| d.message.contains(needle)).collect()
66}
67
68/// The one warning whose message holds `needle`.
69fn site<'a>(report: &'a Report, needle: &str) -> Outcome<&'a Diagnostic> {
70 let found = sites(report, needle);
71 match found.as_slice() {
72 [d] => Ok(d),
73 _ => Err(err!("Expected one site naming {:?}, found {:?}.", needle, report.diagnostics; Test, Mismatch)),
74 }
75}
76
77/// A file with a PNG's signature and nothing a decoder can read after it.
78const BAD_PNG: &[u8] = b"\x89PNG\r\n\x1a\nthis is no image data";
79
80/// A figure image, a plain `#image` and a section banner's logo that are there but will not load are each
81/// set with a stand-in and reported at their own line as `unsupported`, not `missing_file`, so a strict
82/// compile refuses the document; a GIF and a WebP, types this build does not read, and an SVG that is not
83/// well-formed are reported the same.
84#[test]
85fn an_image_that_will_not_load_is_reported_where_it_is_named() -> Outcome<()> {
86 let _turn = turn();
87 let src = b"= H\n\n#figure(image(\"bad.png\"), caption: [Corrupt.])\n\n#image(\"anim.gif\")\n\n\
88 #section-banner(\"broken.png\")\n\n#image(\"pic.webp\")\n\n#image(\"bad.svg\")\n\nBody.\n";
89 let files: [(&str, &[u8]); 6] = [
90 (MAIN, &src[..]),
91 ("/proj/bad.png", BAD_PNG),
92 ("/proj/anim.gif", b"GIF89a\x01\x00\x01\x00\x00\x00\x00;"),
93 ("/proj/broken.png", BAD_PNG),
94 ("/proj/pic.webp", b"RIFF\x0c\x00\x00\x00WEBPVP8 "),
95 ("/proj/bad.svg", b"<svg width=\"10\""),
96 ];
97 let report = res!(report_of(MAIN, &files, None));
98 for (needle, line, stand_in) in [
99 ("\"bad.png\"", 3, "a placeholder is set"),
100 ("\"anim.gif\"", 5, "a placeholder is set"),
101 ("\"broken.png\"", 7, "the banner is drawn without it"),
102 ("\"pic.webp\"", 9, "a placeholder is set"),
103 ("\"bad.svg\"", 11, "a placeholder is set"),
104 ] {
105 let d = res!(site(&report, needle));
106 assert_eq!((d.severity, d.kind, d.file.as_str(), d.line), (Severity::Warning, DiagnosticKind::Unsupported, MAIN, line), "{}", d);
107 assert!(d.message.contains("will not load") && d.message.contains(stand_in), "{}", d);
108 }
109 assert_eq!(report.skipped, None, "a stand-in is not a construct skipped: {:?}", report.skipped);
110 let head = match report.strict_failure(Path::new(MAIN)) {
111 Some(h) => h,
112 None => return Err(err!("strict must refuse an image that will not load"; Test)),
113 };
114 assert_eq!((head.kind, head.line), (DiagnosticKind::Unsupported, 3), "{}", head);
115 assert!(head.hint.as_deref().map_or(false, |h| h.starts_with("substituted: ")), "{:?}", head.hint);
116 Ok(())
117}
118
119/// A block the authoring memo serves from cache reports the stand-in it set when it was authored, so the
120/// delta path's second compile is no quieter than its first.
121#[test]
122fn a_memo_hit_reports_its_stand_in_again() -> Outcome<()> {
123 let _turn = turn();
124 let src = b"= H\n\n#figure(image(\"bad.png\"), caption: [Corrupt.])\n\nBody.\n";
125 let files: [(&str, &[u8]); 2] = [(MAIN, &src[..]), ("/proj/bad.png", BAD_PNG)];
126 let mut memo = Memo::new();
127 let first = res!(report_of(MAIN, &files, Some(&mut memo)));
128 memo.sweep();
129 let second = res!(report_of(MAIN, &files, Some(&mut memo)));
130 assert_eq!(sites(&first, "\"bad.png\"").len(), 1, "{:?}", first.diagnostics);
131 assert_eq!(sites(&second, "\"bad.png\"").len(), 1, "the hit reports it again: {:?}", second.diagnostics);
132 Ok(())
133}
134
135/// A documentation tree's title-page and footer logos that are not in the project are set without, and
136/// each is reported as `missing_file` at the field of the template call that names it.
137#[test]
138fn a_documents_logos_are_reported_at_the_fields_that_name_them() -> Outcome<()> {
139 let _turn = turn();
140 let root = b"#show: doc.with(\n title: [Logos],\n title-top-logo-path: \"/assets/top.svg\",\n \
141 title-bottom-logo-path: \"/assets/bottom.svg\",\n footer-left-logo-path: \"/assets/foot.svg\",\n)\n\n\
142 = First\n\nBody.\n\n#include \"a.typ\"\n";
143 let files: [(&str, &[u8]); 2] = [(MAIN, &root[..]), ("/proj/a.typ", b"== A\n\nText.\n")];
144 let report = res!(report_of(MAIN, &files, None));
145 for (needle, line, stand_in) in [
146 ("\"/assets/top.svg\"", 3, "the title page is set without it"),
147 ("\"/assets/bottom.svg\"", 4, "the title page is set without it"),
148 ("\"/assets/foot.svg\"", 5, "the footers are set without it"),
149 ] {
150 let d = res!(site(&report, needle));
151 assert_eq!((d.severity, d.kind, d.file.as_str(), d.line), (Severity::Warning, DiagnosticKind::MissingFile, MAIN, line), "{}", d);
152 assert!(d.message.contains("is not in the project") && d.message.contains(stand_in), "{}", d);
153 }
154 assert!(report.strict_failure(Path::new(MAIN)).is_some(), "strict refuses a missing logo");
155 Ok(())
156}
157
158/// The five Libertinus faces a book's own font tree ships, read from the crate's copies.
159fn libertinus_tree(dir: &str) -> Outcome<Vec<(String, Vec<u8>)>> {
160 let fonts = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("fonts");
161 let mut out = Vec::new();
162 for f in ["LibertinusSerif-Regular.otf", "LibertinusSerif-Bold.otf", "LibertinusSerif-Italic.otf",
163 "LibertinusSerif-BoldItalic.otf", "LibertinusMono-Regular.otf"]
164 {
165 out.push((fmt!("{}/{}", dir, f), res!(std::fs::read(fonts.join(f)))));
166 }
167 Ok(out)
168}
169
170/// A book's cover, named in its config, is reported at the config's line when it is not there; its title
171/// logo, there but not a raster this path reads, at the root's field; and a bibliography the root names but
172/// the project lacks at its field, with every citation then reported where it is written.
173#[test]
174fn a_books_cover_logo_and_bibliography_are_reported_at_their_fields() -> Outcome<()> {
175 let _turn = turn();
176 let main = "/b/book/main.typ";
177 let root = b"#show: book.with(\n title: [A Book],\n title-logo-path: \"/assets/logo.png\",\n \
178 meta-data: (\n bibliography: \"/missing.bib\",\n ),\n)\n\n#include \"ch1.typ\"\n";
179 let config = b"#let format = \"a5\"\n#let mode = \"dev\"\n#let cover-image-path = if format == \"a5\" { \"/assets/cover.png\" }\n";
180 let chapter = b"= One\n\nAs argued #cite(<smith>).\n";
181 let tree = res!(libertinus_tree("/b/assets/fonts/libertinus"));
182 let mut files: Vec<(&str, &[u8])> = vec![
183 (main, &root[..]),
184 ("/b/book/config.typ", &config[..]),
185 ("/b/book/ch1.typ", &chapter[..]),
186 ("/b/assets/logo.png", BAD_PNG),
187 ];
188 for (p, b) in &tree {
189 files.push((p.as_str(), b.as_slice()));
190 }
191 let report = res!(report_of(main, &files, None));
192
193 let d = res!(site(&report, "\"/assets/cover.png\""));
194 assert_eq!((d.kind, d.file.as_str(), d.line), (DiagnosticKind::MissingFile, "/b/book/config.typ", 3), "{}", d);
195 assert!(d.message.contains("no cover page is set"), "{}", d);
196 let d = res!(site(&report, "\"/assets/logo.png\""));
197 assert_eq!((d.kind, d.file.as_str(), d.line), (DiagnosticKind::Unsupported, main, 3), "{}", d);
198 assert!(d.message.contains("the title page is set without it"), "{}", d);
199 let d = res!(site(&report, "\"/missing.bib\""));
200 assert_eq!((d.kind, d.file.as_str(), d.line), (DiagnosticKind::MissingFile, main, 5), "{}", d);
201 assert!(d.message.contains("no reference list is set"), "{}", d);
202 let d = res!(site(&report, "#cite(<smith>)"));
203 assert_eq!((d.kind, d.file.as_str(), d.line), (DiagnosticKind::Unsupported, "/b/book/ch1.typ", 3), "{}", d);
204 assert!(d.message.contains("no bibliography"), "{}", d);
205 Ok(())
206}
207
208/// A reference to a label nothing in the document carries, and a citation with no bibliography to resolve
209/// against, are each set with a stand-in and reported at their paragraph; a reference to a label that is
210/// there is reported nowhere.
211#[test]
212fn an_unplaced_label_and_an_unresolved_citation_are_reported() -> Outcome<()> {
213 let _turn = turn();
214 let src = b"= Heading <sec>\n\nSee @sec and @nolabel.\n\nAs argued #cite(<nobib>).\n";
215 let report = res!(report_of(MAIN, &[(MAIN, &src[..])], None));
216 let d = res!(site(&report, "@nolabel"));
217 assert_eq!((d.severity, d.kind, d.line), (Severity::Warning, DiagnosticKind::Unsupported, 3), "{}", d);
218 assert!(d.message.contains("names no label"), "{}", d);
219 assert!(sites(&report, "@sec").is_empty(), "a placed label is not reported: {:?}", report.diagnostics);
220 let d = res!(site(&report, "#cite(<nobib>)"));
221 assert_eq!((d.kind, d.line), (DiagnosticKind::Unsupported, 5), "{}", d);
222 assert!(d.message.contains("no bibliography"), "{}", d);
223 assert!(report.strict_failure(Path::new(MAIN)).is_some(), "strict refuses both");
224 Ok(())
225}
226
227/// With a bibliography found beside the file, a citation of a key it holds resolves and is reported
228/// nowhere, and one of a key it lacks is reported at its paragraph.
229#[test]
230fn a_citation_key_the_bibliography_lacks_is_reported() -> Outcome<()> {
231 let _turn = turn();
232 let src = b"= H\n\nKnown #cite(<smith2020>).\n\nUnknown #cite(<jones1999>).\n";
233 let bib = b"@article{smith2020, author = {Smith, John}, title = {A Title}, year = {2020}, journal = {J}}\n";
234 let report = res!(report_of(MAIN, &[(MAIN, &src[..]), ("/proj/refs.bib", &bib[..])], None));
235 assert!(sites(&report, "smith2020").is_empty(), "a held key is not reported: {:?}", report.diagnostics);
236 let d = res!(site(&report, "#cite(<jones1999>)"));
237 assert_eq!((d.kind, d.line), (DiagnosticKind::Unsupported, 5), "{}", d);
238 assert!(d.message.contains("does not hold"), "{}", d);
239 Ok(())
240}
241
242/// A show rule whose transform sets more than the element -- here its body and a page number, where
243/// Austenite would set the heading unchanged -- is refused where it is written, not passed through.
244#[test]
245fn a_show_rule_this_reader_does_not_run_is_refused() -> Outcome<()> {
246 let _turn = turn();
247 let src = b"#show heading: it => [#it.body #here().page()]\n\n= Heading\n\n== Sub\n\nBody.\n";
248 let report = res!(report_of(MAIN, &[(MAIN, &src[..])], None));
249 let d = res!(site(&report, "#show heading"));
250 assert_eq!((d.severity, d.kind, d.file.as_str(), d.line), (Severity::Warning, DiagnosticKind::Unsupported, MAIN, 1), "{}", d);
251 assert!(report.strict_failure(Path::new(MAIN)).is_some(), "strict refuses it");
252 Ok(())
253}
254
255/// A `terms.typ` that is there but is not UTF-8 text is reported against the file, as `encoding`, where it
256/// once became an empty dictionary without a word.
257#[test]
258fn a_terms_file_that_will_not_read_is_reported() -> Outcome<()> {
259 let _turn = turn();
260 let src = b"= H\n\nThe #t(\"org\") view.\n";
261 let terms: &[u8] = b"#let term-dict = (\"org\": \"Oxedyne \xff\xfe\")\n";
262 let report = res!(report_of(MAIN, &[(MAIN, &src[..]), ("/proj/terms.typ", terms)], None));
263 let d = res!(site(&report, "terms.typ"));
264 assert_eq!((d.severity, d.kind, d.file.as_str()), (Severity::Warning, DiagnosticKind::Encoding, "/proj/terms.typ"), "{}", d);
265 assert!(d.message.contains("is not valid UTF-8"), "{}", d);
266 assert!(report.strict_failure(Path::new(MAIN)).is_some(), "strict refuses it");
267 Ok(())
268}
269
270/// A Fletcher edge written before any node, which the diagram has no node to draw from, is refused where
271/// the figure stands, so strict refuses a figure not drawn as written; the nodes are still drawn.
272#[test]
273fn an_edge_a_diagram_cannot_place_is_refused() -> Outcome<()> {
274 let _turn = turn();
275 let src = b"= H\n\n#figure(diagram(edge((0,0), (0,1), \"->\"), node((0,0), [A]), node((0,1), [B])), caption: [Flow.])\n";
276 let report = res!(report_of(MAIN, &[(MAIN, &src[..])], None));
277 let d = res!(site(&report, "#figure (diagram)"));
278 assert_eq!((d.severity, d.kind, d.line), (Severity::Warning, DiagnosticKind::Unsupported, 3), "{}", d);
279 assert!(d.message.contains("is drawn without an edge written before any node"), "{}", d);
280 assert!(report.strict_failure(Path::new(MAIN)).is_some(), "strict refuses it");
281 Ok(())
282}
283
284/// The live view's authoring memo keys a block by what the images it draws hold, not only by their names:
285/// an image deleted, corrupted or supplied again between two compiles through one memo is authored afresh
286/// and reported as it now stands, never served from a cache made when it was otherwise; an unchanged image
287/// is still served from the memo.
288#[test]
289fn a_memo_hit_follows_what_a_blocks_images_hold() -> Outcome<()> {
290 let _turn = turn();
291 let src = b"= H\n\n#figure(image(\"pic.png\"), caption: [Pic.])\n\nBody.\n";
292 let png = res!(res!(Pixmap::filled(8, 8, Rgba::opaque(200, 0, 0))).to_png());
293 let present: [(&str, &[u8]); 2] = [(MAIN, &src[..]), ("/proj/pic.png", &png[..])];
294 let deleted: [(&str, &[u8]); 1] = [(MAIN, &src[..])];
295 let corrupt: [(&str, &[u8]); 2] = [(MAIN, &src[..]), ("/proj/pic.png", BAD_PNG)];
296 let mut memo = Memo::new();
297
298 let first = res!(report_of(MAIN, &present, Some(&mut memo)));
299 memo.sweep();
300 assert!(first.diagnostics.is_empty(), "{:?}", first.diagnostics);
301 let hits = memo.block_hits;
302 let again = res!(report_of(MAIN, &present, Some(&mut memo)));
303 memo.sweep();
304 assert!(again.diagnostics.is_empty() && memo.block_hits > hits, "an unchanged image is served from the memo");
305
306 let gone = res!(report_of(MAIN, &deleted, Some(&mut memo)));
307 memo.sweep();
308 let d = res!(site(&gone, "\"pic.png\""));
309 assert_eq!(d.kind, DiagnosticKind::MissingFile, "a deleted image is missing, not served stale: {}", d);
310
311 let bad = res!(report_of(MAIN, &corrupt, Some(&mut memo)));
312 memo.sweep();
313 let d = res!(site(&bad, "\"pic.png\""));
314 assert!(d.kind == DiagnosticKind::Unsupported && d.message.contains("will not load"), "{}", d);
315
316 let back = res!(report_of(MAIN, &present, Some(&mut memo)));
317 assert!(back.diagnostics.is_empty(), "an image supplied again is drawn: {:?}", back.diagnostics);
318 Ok(())
319}
320
321/// A block served from the memo gives each answer again at its own ask in the block as it now stands: after
322/// a paragraph added above moves a list whose items ask for different things, each item's stand-in is
323/// reported at its own line, exactly as a fresh compile of the same source reports it.
324#[test]
325fn a_memo_hit_resites_each_answer_at_its_own_ask() -> Outcome<()> {
326 let _turn = turn();
327 let before = b"= H\n\nIntro.\n\n- first @gonea\n- second #cite(<nokey>)\n";
328 let after = b"= H\n\nA paragraph added above.\n\nIntro.\n\n- first @gonea\n- second #cite(<nokey>)\n";
329 let bib = b"@article{smith2020, author = {Smith, John}, title = {A Title}, year = {2020}, journal = {J}}\n";
330 let mut memo = Memo::new();
331 res!(report_of(MAIN, &[(MAIN, &before[..]), ("/proj/refs.bib", &bib[..])], Some(&mut memo)));
332 memo.sweep();
333 let hits = memo.block_hits;
334 let warm = res!(report_of(MAIN, &[(MAIN, &after[..]), ("/proj/refs.bib", &bib[..])], Some(&mut memo)));
335 assert!(memo.block_hits > hits, "the moved list is served from the memo");
336 let cold = res!(report_of(MAIN, &[(MAIN, &after[..]), ("/proj/refs.bib", &bib[..])], None));
337 let placed = |r: &Report| r.diagnostics.iter().map(|d| (d.line, d.col, d.message.clone())).collect::<Vec<_>>();
338 assert_eq!(placed(&warm), placed(&cold), "the hit reports what a fresh compile reports, where it reports it");
339 let lines: Vec<(usize, bool)> = cold.diagnostics.iter()
340 .map(|d| (d.line, d.message.starts_with("@gonea") || d.message.starts_with("#cite(<nokey>)")))
341 .collect();
342 assert_eq!(lines, [(7, true), (8, true)], "{:?}", cold.diagnostics);
343 Ok(())
344}