Debian Codegraph @

src/tests.rs

raw
1 use pretty_assertions::assert_eq;
2 use std::collections::HashMap;
3 use std::panic;
4
5 #[cfg(feature = "attributes")]
6 use crate::nodes::Attributes;
7 use crate::nodes::{Node, NodeValue, Sourcepos};
8 use crate::options;
9 use crate::*;
10
11 mod alerts;
12 mod attributes;
13 mod autolink;
14 mod block_directive;
15 mod cjk_friendly_emphasis;
16 mod code;
17 mod commonmark;
18 mod compact_html;
19 mod core;
20 mod description_lists;
21 mod empty;
22 mod escape;
23 mod escaped_char_spans;
24 mod footnotes;
25 mod front_matter;
26 mod fuzz;
27 mod greentext;
28 mod header_id_prefix;
29 mod highlight;
30 #[path = "tests/html.rs"]
31 mod html_;
32 mod inline_footnotes;
33 mod insert;
34 mod math;
35 mod multiline_block_quotes;
36 #[path = "tests/options.rs"]
37 mod options_;
38 mod pathological;
39 mod phoenix_heex;
40 mod plugins;
41 mod raw;
42 mod regressions;
43 mod rewriter;
44 mod shortcodes;
45 #[path = "tests/sourcepos.rs"]
46 mod sourcepos_;
47 mod sourcepos_chars;
48 mod spoiler;
49 mod strikethrough;
50 mod subscript;
51 mod subtext;
52 mod supersubscript;
53 mod table;
54 mod tagfilter;
55 mod tasklist;
56 mod underline;
57 mod wikilinks;
58 mod xml;
59
60 #[track_caller]
61 fn compare_strs(output: &str, expected: &str, kind: &str, original_input: &str) {
62 if output != expected {
63 println!("Running {} test", kind);
64 println!("Original Input:");
65 println!("==============================");
66 println!("{}", original_input);
67 println!("==============================");
68 println!("Got:");
69 println!("==============================");
70 println!("{}", output);
71 println!("==============================");
72 println!();
73 println!("Expected:");
74 println!("==============================");
75 println!("{}", expected);
76 println!("==============================");
77 println!();
78 }
79 assert_eq!(output, expected);
80 }
81
82 #[track_caller]
83 fn commonmark(input: &str, expected: &str, opts: Option<&Options>) {
84 let arena = Arena::new();
85 let defaults = Options::default();
86 let options = opts.unwrap_or(&defaults);
87
88 let root = parse_document(&arena, input, options);
89 let mut output = String::new();
90 cm::format_document(root, options, &mut output).unwrap();
91 compare_strs(&output, expected, "regular", input);
92 }
93
94 #[track_caller]
95 pub fn html(input: &str, expected: &str) {
96 html_opts_i(input, expected, true, |_| ());
97 }
98
99 #[track_caller]
100 fn html_opts_i<'c, F>(input: &str, expected: &str, roundtrip: bool, opts: F)
101 where
102 F: FnOnce(&mut Options<'c>),
103 {
104 let mut options = Options::default();
105 opts(&mut options);
106
107 html_opts_w(input, expected, roundtrip, &options);
108 }
109
110 #[track_caller]
111 fn html_opts_w(input: &str, expected: &str, roundtrip: bool, options: &Options) {
112 let arena = Arena::new();
113
114 let root = parse_document(&arena, input, options);
115 let mut output = String::new();
116 html::format_document(root, options, &mut output).unwrap();
117 compare_strs(&output, expected, "regular", input);
118
119 if !roundtrip {
120 return;
121 }
122
123 let mut md = String::new();
124 cm::format_document(root, options, &mut md).unwrap();
125
126 let root = parse_document(&arena, &md, options);
127 let mut output_from_rt = String::new();
128 html::format_document(root, options, &mut output_from_rt).unwrap();
129
130 let expected_no_sourcepos = remove_sourcepos(expected);
131 let actual_no_sourcepos = remove_sourcepos(&output_from_rt);
132
133 compare_strs(
134 &actual_no_sourcepos,
135 &expected_no_sourcepos,
136 "roundtrip",
137 &md,
138 );
139 }
140
141 fn remove_sourcepos(i: &str) -> String {
142 const S: &str = " data-sourcepos=\"";
143
144 let mut r = i.to_string();
145 while let Some(start_ix) = r.find(S) {
146 let end_offset = start_ix + S.len();
147 let end_ix = r.get(start_ix + S.len()..).unwrap().find('"').unwrap();
148 r.replace_range(start_ix..end_offset + end_ix + 1, "");
149 }
150
151 r
152 }
153
154 macro_rules! html_opts {
155 ([$($optclass:ident.$optname:ident),*], $input:expr, $expected:expr) => {
156 html_opts!([$($optclass.$optname),*], $input, $expected,)
157 };
158 ([$($optclass:ident.$optname:ident = $val:expr),*], $input:expr, $expected:expr) => {
159 html_opts!([$($optclass.$optname = $val),*], $input, $expected,)
160 };
161 ([$($optclass:ident.$optname:ident),*], $input:expr, $expected:expr,) => {
162 html_opts!([$($optclass.$optname),*], $input, $expected, roundtrip)
163 };
164 ([$($optclass:ident.$optname:ident = $val:expr),*], $input:expr, $expected:expr,) => {
165 html_opts!([$($optclass.$optname = $val),*], $input, $expected, roundtrip)
166 };
167 ([$($optclass:ident.$optname:ident),*], $input:expr, $expected:expr, $rt:ident) => {
168 html_opts!([$($optclass.$optname),*], $input, $expected, $rt,)
169 };
170 ([$($optclass:ident.$optname:ident = $val:expr),*], $input:expr, $expected:expr, $rt:ident) => {
171 html_opts!([$($optclass.$optname = $val),*], $input, $expected, $rt,)
172 };
173 ([$($optclass:ident.$optname:ident),*], $input:expr, $expected:expr, roundtrip,) => {
174 html_opts!([$($optclass.$optname = true),*], $input, $expected, roundtrip,)
175 };
176 ([$($optclass:ident.$optname:ident = $val:expr),*], $input:expr, $expected:expr, roundtrip,) => {
177 $crate::tests::html_opts_i($input, $expected, true, |opts| {
178 $(opts.$optclass.$optname = $val;)*
179 });
180 };
181 ([$($optclass:ident.$optname:ident),*], $input:expr, $expected:expr, no_roundtrip,) => {
182 html_opts!([$($optclass.$optname = true),*], $input, $expected, no_roundtrip,)
183 };
184 ([$($optclass:ident.$optname:ident = $val:expr),*], $input:expr, $expected:expr, no_roundtrip,) => {
185 $crate::tests::html_opts_i($input, $expected, false, |opts| {
186 $(opts.$optclass.$optname = $val;)*
187 });
188 };
189 }
190
191 pub(crate) use html_opts;
192
193 #[track_caller]
194 fn html_plugins(input: &str, expected: &str, plugins: &options::Plugins) {
195 let arena = Arena::new();
196 let options = Options::default();
197
198 let root = parse_document(&arena, input, &options);
199 let mut output = String::new();
200 html::format_document_with_plugins(root, &options, &mut output, plugins).unwrap();
201 compare_strs(&output, expected, "regular", input);
202
203 let mut md = String::new();
204 cm::format_document(root, &options, &mut md).unwrap();
205
206 let root = parse_document(&arena, &md, &options);
207 let mut output_from_rt = String::new();
208 html::format_document_with_plugins(root, &options, &mut output_from_rt, plugins).unwrap();
209 compare_strs(&output_from_rt, expected, "roundtrip", &md);
210 }
211
212 #[track_caller]
213 fn xml(input: &str, expected: &str) {
214 xml_opts(input, expected, |_| ());
215 }
216
217 #[track_caller]
218 fn xml_opts<F>(input: &str, expected: &str, opts: F)
219 where
220 F: Fn(&mut Options),
221 {
222 let arena = Arena::new();
223 let mut options = Options::default();
224 opts(&mut options);
225
226 let root = parse_document(&arena, input, &options);
227 let mut output = String::new();
228 crate::xml::format_document(root, &options, &mut output).unwrap();
229 compare_strs(&output, expected, "regular", input);
230
231 if options.render.sourcepos {
232 return;
233 }
234
235 let mut md = String::new();
236 cm::format_document(root, &options, &mut md).unwrap();
237
238 let root = parse_document(&arena, &md, &options);
239 let mut output_from_rt = String::new();
240 crate::xml::format_document(root, &options, &mut output_from_rt).unwrap();
241 compare_strs(&output_from_rt, expected, "roundtrip", &md);
242 }
243
244 fn assert_node_eq(node: Node<'_>, location: &[usize], expected: &NodeValue) {
245 let node = location
246 .iter()
247 .fold(node, |node, &n| node.children().nth(n).unwrap());
248
249 let data = node.data();
250 let actual = format!("{:?}", data.value);
251 let expected = format!("{:?}", expected);
252
253 compare_strs(&actual, &expected, "ast comparison", "ast node");
254 }
255
256 macro_rules! sourcepos {
257 (($spsl:literal:$spsc:literal-$spel:literal:$spec:literal)) => {
258 $crate::nodes::Sourcepos {
259 start: $crate::nodes::LineColumn {
260 line: $spsl,
261 column: $spsc,
262 },
263 end: $crate::nodes::LineColumn {
264 line: $spel,
265 column: $spec,
266 },
267 }
268 };
269 ((XXX)) => {
270 $crate::tests::sourcepos!((0:1-0:1))
271 };
272 }
273
274 pub(crate) use sourcepos;
275
276 macro_rules! ast {
277 (($name:tt $sp:tt $( $content:tt )*)) => ({
278 #[allow(unused_mut)]
279 let mut matches = vec![];
280 $crate::tests::ast_content!(matches ~ $( $content )*);
281
282 $crate::tests::AstMatchTree {
283 name: stringify!($name).to_string(),
284 sourcepos: $crate::tests::sourcepos!($sp),
285 matches,
286 }
287 });
288 }
289
290 macro_rules! ast_content {
291 ($matches:ident ~ $text:literal $( $rest:tt )*) => {
292 $matches.push($crate::tests::AstMatchContent::Text($text.to_string()));
293 $crate::tests::ast_content!($matches ~ $( $rest )*);
294 };
295 ($matches:ident ~ [ $( $children:tt )* ] $( $rest:tt )*) => {
296 $matches.push($crate::tests::AstMatchContent::Children(vec![ $( $crate::tests::ast!($children), )* ]));
297 $crate::tests::ast_content!($matches ~ $( $rest )*);
298 };
299 ($matches:ident ~ info:$info:literal $( $rest:tt )*) => {
300 $matches.push($crate::tests::AstMatchContent::Info($info.to_string()));
301 $crate::tests::ast_content!($matches ~ $( $rest )*);
302 };
303
304 // Are you reading this comment right now?
305 //
306 // Can you see that the following definition forces test authors to specify
307 // attributes in the order "id, classes, key/value pairs", even though in
308 // the actual syntax, that's not necessary? (Indeed, you could have multiple
309 // ids in real syntax; the last one wins.)
310 //
311 // It's VERY possible to rewrite this to allow parsing them in any order, just
312 // like the actual syntax. Feel free to try it and open a PR, and you can ask for help.
313 //
314 // Hint: look at how ast_content itself is implemented; recursion is the trick!
315 //
316 // Extra credit: at the moment, we only support x="y" syntax for pairs.
317 // The above change would let us easily support both that *and* x=y syntax
318 // (when there's no 'need' to quote the value).
319 ($matches:ident ~ { $( # $id:ident )? $( . $class:ident )* $( $key:ident = $value:literal )* } $( $rest:tt )*) => {
320 #[allow(unused_mut)]
321 let mut attrs = $crate::nodes::Attributes::default();
322 $( attrs.id = Some(stringify!($id).to_string()); )?
323 $( attrs.classes.push(stringify!($class).to_string()); )*
324 $( attrs.pairs.push((stringify!($key).to_string(), $value.to_string())); )*
325 $matches.push($crate::tests::AstMatchContent::Attributes(attrs));
326 $crate::tests::ast_content!($matches ~ $( $rest )*);
327 };
328
329 ($matches:ident ~) => {};
330 }
331
332 pub(crate) use ast;
333 pub(crate) use ast_content;
334
335 #[track_caller]
336 fn assert_ast_match_i<F>(md: &str, amt: AstMatchTree, opts: F)
337 where
338 F: Fn(&mut Options),
339 {
340 let mut options = Options::default();
341 options.render.sourcepos = true;
342 opts(&mut options);
343
344 let result = panic::catch_unwind(|| {
345 let arena = Arena::new();
346 let root = parse_document(&arena, md, &options);
347
348 amt.assert_match(root);
349 });
350
351 if let Err(err) = result {
352 let arena = Arena::new();
353 let root = parse_document(&arena, md, &options);
354
355 let mut output = String::new();
356 // Show escaped nodes in debugging XML where they exist.
357 options.render.escaped_char_spans = true;
358 format_xml(root, &options, &mut output).unwrap();
359 eprintln!("{output}");
360
361 panic::resume_unwind(err)
362 }
363 }
364
365 macro_rules! assert_ast_match_set_opt_single {
366 ($opts:ident; $optclass:ident.$optname:ident = $val:expr) => {
367 $opts.$optclass.$optname = $val;
368 };
369 ($opts:ident; $optclass:ident.$optname:ident) => {
370 $opts.$optclass.$optname = true;
371 };
372 }
373
374 pub(crate) use assert_ast_match_set_opt_single;
375
376 macro_rules! assert_ast_match {
377 ([ $( $optclass:ident.$optname:ident ),* ], $( $md:literal )+, $amt:tt,) => {
378 $crate::tests::assert_ast_match!(
379 [ $( $optclass.$optname ),* ],
380 $( $md )+,
381 $amt
382 )
383 };
384 ([ $( $optclass:ident.$optname:ident = $val:expr ),* ], $( $md:literal )+, $amt:tt) => {
385 $crate::tests::assert_ast_match_i(
386 concat!( $( $md ),+ ),
387 $crate::tests::ast!($amt),
388 |#[allow(unused_variables)] opts| {$(opts.$optclass.$optname = $val;)*},
389 );
390 };
391 ([ $( $optclass:ident.$optname:ident $(= $val:expr)? ),* ], $( $md:literal )+, $amt:tt) => {
392 $crate::tests::assert_ast_match_i(
393 concat!( $( $md ),+ ),
394 $crate::tests::ast!($amt),
395 |#[allow(unused_variables)] opts| { $( $crate::tests::assert_ast_match_set_opt_single!(opts; $optclass.$optname $(= $val)? ); )* },
396 );
397 };
398 ([ $( $optclass:ident.$optname:ident ),* ], $( $md:literal )+, $amt:tt) => {
399 $crate::tests::assert_ast_match!(
400 [ $( $optclass.$optname = true),* ],
401 $( $md )+,
402 $amt
403 )
404 };
405 }
406
407 pub(crate) use assert_ast_match;
408
409 enum AstMatchContent {
410 Text(String),
411 Info(String),
412 Children(Vec<AstMatchTree>),
413 #[cfg(feature = "attributes")]
414 Attributes(Attributes),
415 }
416
417 struct AstMatchTree {
418 name: String,
419 sourcepos: Sourcepos,
420 matches: Vec<AstMatchContent>,
421 }
422
423 impl AstMatchTree {
424 #[track_caller]
425 fn assert_match(&self, node: Node<'_>) {
426 let ast = node.data();
427 assert_eq!(self.name, ast.value.xml_node_name(), "node type matches");
428 assert_eq!(self.sourcepos, ast.sourcepos, "sourcepos are equal");
429
430 let mut asserted_text = false;
431 let mut asserted_info = false;
432 let mut asserted_children = false;
433 #[cfg(feature = "attributes")]
434 let mut asserted_attributes = false;
435
436 for m in &self.matches {
437 match m {
438 AstMatchContent::Text(text) => match ast.value {
439 NodeValue::Math(ref nm) => {
440 assert_eq!(text, &nm.literal, "Math literal should match");
441 asserted_text = true;
442 }
443 NodeValue::CodeBlock(ref ncb) => {
444 assert_eq!(text, &ncb.literal, "CodeBlock literal should match");
445 asserted_text = true;
446 }
447 NodeValue::Code(ref nc) => {
448 assert_eq!(text, &nc.literal, "Code literal should match");
449 asserted_text = true;
450 }
451 #[cfg(feature = "shortcodes")]
452 NodeValue::ShortCode(ref nsc) => {
453 assert_eq!(text, &nsc.code, "Shortcode code should match");
454 asserted_text = true;
455 }
456 NodeValue::HtmlBlock(ref nhb) => {
457 assert_eq!(text, &nhb.literal, "HtmlBlock literal should match");
458 asserted_text = true;
459 }
460 #[cfg(feature = "phoenix_heex")]
461 NodeValue::HeexBlock(ref nhb) => {
462 assert_eq!(text, &nhb.literal, "HeexBlock literal should match");
463 asserted_text = true;
464 }
465 NodeValue::HtmlInline(ref nhi) => {
466 assert_eq!(text, nhi, "HtmlInline content should match");
467 asserted_text = true;
468 }
469 #[cfg(feature = "phoenix_heex")]
470 NodeValue::HeexInline(ref nhi) => {
471 assert_eq!(text, nhi, "HeexInline content should match");
472 asserted_text = true;
473 }
474 NodeValue::Text(ref nt) => {
475 assert_eq!(text, nt, "Text content should match");
476 asserted_text = true;
477 }
478 NodeValue::Link(ref nl) => {
479 assert_eq!(text, &nl.url, "Link destination should match");
480 asserted_text = true;
481 }
482 NodeValue::Image(ref ni) => {
483 assert_eq!(text, &ni.url, "Image source should match");
484 asserted_text = true;
485 }
486 NodeValue::FrontMatter(ref nfm) => {
487 assert_eq!(text, nfm, "Front matter content should match");
488 asserted_text = true;
489 }
490 _ => panic!(
491 "no text content matcher for this node type: {:?}",
492 ast.value
493 ),
494 },
495 AstMatchContent::Info(info) => match ast.value {
496 NodeValue::CodeBlock(ref ncb) => {
497 assert_eq!(info, &ncb.info, "CodeBlock info should match");
498 asserted_info = true;
499 }
500 _ => panic!("no info matcher for this node type: {:?}", ast.value),
501 },
502 AstMatchContent::Children(children) => {
503 assert_eq!(
504 children.len(),
505 node.children().count(),
506 "children count should match ({:?})",
507 node
508 );
509 for (e, a) in children.iter().zip(node.children()) {
510 e.assert_match(a);
511 }
512 asserted_children = true;
513 }
514 #[cfg(feature = "attributes")]
515 AstMatchContent::Attributes(attrs) => {
516 assert!(ast.attrs.is_some());
517 assert_eq!(attrs, &**ast.attrs.as_ref().unwrap());
518 asserted_attributes = true;
519 }
520 }
521 }
522
523 assert!(
524 asserted_children || node.children().count() == 0,
525 "children were not asserted"
526 );
527 assert!(
528 asserted_info
529 || match ast.value {
530 NodeValue::CodeBlock(ref ncb) => ncb.info.is_empty(),
531 _ => true,
532 },
533 "info string was not asserted"
534 );
535 #[cfg(feature = "attributes")]
536 assert!(
537 asserted_attributes || ast.attrs.is_none(),
538 "attributes were not asserted"
539 );
540 assert!(
541 asserted_text
542 || !matches!(
543 ast.value,
544 NodeValue::Math(_)
545 | NodeValue::CodeBlock(_)
546 | NodeValue::Text(_)
547 | NodeValue::Link(_)
548 | NodeValue::Image(_)
549 | NodeValue::FrontMatter(_)
550 | NodeValue::HtmlBlock(_)
551 | NodeValue::HtmlInline(_)
552 ),
553 "text wasn't asserted"
554 );
555 }
556 }