1use crate::markdown::{CodeBlock, Doc};
7
8pub const GENERATED_HEADER: &str = "// @generated by `cargo soothfast docs gen-tests`";
11
12pub fn sanitized_stem(rel_path: &str) -> String {
14 let stem = rel_path.trim_end_matches(".md");
15 let san: String = stem
16 .chars()
17 .map(|c| {
18 if c.is_ascii_alphanumeric() {
19 c.to_ascii_lowercase()
20 } else {
21 '_'
22 }
23 })
24 .collect();
25 san.trim_matches('_').to_string()
26}
27
28fn indent(code: &str, pad: &str) -> String {
29 code.lines()
30 .map(|l| {
31 if l.is_empty() {
32 String::new()
33 } else {
34 format!("{pad}{l}")
35 }
36 })
37 .collect::<Vec<_>>()
38 .join("\n")
39}
40
41#[derive(Debug, Clone, PartialEq)]
43pub struct Generated {
44 pub path: String,
46 pub content: String,
48}
49
50const VERBATIM: &str =
55 "macro_rules! verbatim {\n ($($tokens:tt)*) => {\n $($tokens)*\n };\n}\n";
56
57pub const DOC_TESTS_DIR: &str = "tests/soothfast_docs";
59
60pub const OWNED: &[(&str, &str, Option<&str>)] = &[
67 ("tests", "soothfast_doc_", Some(DOC_TESTS_DIR)),
68 (DOC_TESTS_DIR, "", None),
69 ("examples", "soothfast_capture_", Some(CAPTURE_DIR)),
70 (CAPTURE_DIR, "", None),
71];
72
73pub fn recorded_source(content: &str) -> Option<(&str, Option<usize>)> {
76 let source = content.lines().nth(1)?.strip_prefix("// source: ")?;
77 match source.rsplit_once(" line ") {
78 Some((page, line)) => match line.parse::<usize>() {
79 Ok(line) => Some((page, Some(line))),
80 Err(_) => Some((source, None)),
81 },
82 None => Some((source, None)),
83 }
84}
85
86pub fn doc_test_set<'a>(
91 docs: impl IntoIterator<Item = (&'a str, &'a Doc)>,
92) -> Result<Vec<Generated>, String> {
93 let docs: Vec<(&str, &Doc)> = docs.into_iter().collect();
94 one_global_allocator(&docs, CodeBlock::is_testable_rust)?;
95 let mut pages: Vec<(String, &str, String)> = Vec::new();
96 for (rel_path, doc) in docs {
97 if let Some(content) = test_file(rel_path, doc) {
98 pages.push((
99 format!("doc_{}", sanitized_stem(rel_path)),
100 rel_path,
101 content,
102 ));
103 }
104 }
105 pages.sort_by(|a, b| a.1.cmp(b.1));
106 for (i, (module, path, _)) in pages.iter().enumerate() {
107 if let Some((_, other, _)) = pages[..i].iter().find(|(m, _, _)| m == module) {
108 return Err(format!(
109 "{other} and {path} both generate doc-test module `{module}`; rename one"
110 ));
111 }
112 }
113 if pages.is_empty() {
114 return Ok(Vec::new());
115 }
116 let mods: String = pages
117 .iter()
118 .map(|(m, _, _)| format!("mod {m};\n"))
119 .collect();
120 let main =
121 format!("{GENERATED_HEADER}\n#![allow(unused)]\n\n{VERBATIM}\nverbatim! {{\n{mods}}}\n");
122 let mut set = vec![Generated {
123 path: format!("{DOC_TESTS_DIR}/main.rs"),
124 content: main,
125 }];
126 set.extend(pages.into_iter().map(|(module, _, content)| Generated {
127 path: format!("{DOC_TESTS_DIR}/{module}.rs"),
128 content,
129 }));
130 Ok(set)
131}
132
133fn one_global_allocator(
136 docs: &[(&str, &Doc)],
137 in_target: fn(&CodeBlock) -> bool,
138) -> Result<(), String> {
139 let mut found = docs.iter().flat_map(|(page, doc)| {
140 doc.blocks
141 .iter()
142 .filter(move |b| in_target(b))
143 .filter(|b| b.code.contains("#[global_allocator]") || b.code.contains("bench_main!"))
144 .map(move |b| format!("{page} line {}", b.line))
145 });
146 match (found.next(), found.next()) {
147 (Some(first), Some(second)) => Err(format!(
148 "{first} and {second} both install a global allocator, and the blocks of a package compile into one crate; mark one `ignore` or `no_run` in another package"
149 )),
150 _ => Ok(()),
151 }
152}
153
154pub fn owning_target(rel_path: &str) -> Option<(&'static str, bool)> {
159 let (dir, name) = rel_path.rsplit_once('/').unwrap_or(("", rel_path));
160 if !name.ends_with(".rs") {
161 return None;
162 }
163 OWNED
164 .iter()
165 .find(|(d, prefix, _)| *d == dir && name.starts_with(prefix))
166 .map(|(dir, _, replaced_by)| (replaced_by.unwrap_or(dir), replaced_by.is_some()))
167}
168
169pub fn test_file(rel_path: &str, doc: &Doc) -> Option<String> {
172 let testable: Vec<&CodeBlock> = doc.blocks.iter().filter(|b| b.is_testable_rust()).collect();
173 if testable.is_empty() {
174 return None;
175 }
176 let mut out = format!("{GENERATED_HEADER}\n// source: {rel_path}\n#![allow(unused)]\n");
177 for block in testable {
178 let body = indent(&block.code, " ");
179 let call_main = if block.code.lines().any(|l| top_level_main(l).is_some()) {
181 "\n main();"
182 } else {
183 ""
184 };
185 let cfg = match block.feature_cfg() {
187 Some(pred) => format!("#[cfg({pred})]\n"),
188 None => String::new(),
189 };
190 if block.has_tag("no_run") {
194 out.push_str(&format!(
195 "\n// line {}: compile-only (no_run)\n{cfg}#[rustfmt::skip]\n#[allow(dead_code)]\nfn doc_block_line_{}() {{\n{body}\n}}\n",
196 block.line, block.line
197 ));
198 } else {
199 out.push_str(&format!(
200 "\n// line {}\n{cfg}#[rustfmt::skip]\n#[test]\nfn doc_block_line_{}() {{\n{body}{call_main}\n}}\n",
201 block.line, block.line
202 ));
203 }
204 }
205 Some(out)
206}
207
208#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
210pub struct PageCounts {
211 pub executed: usize,
213 pub compile_only: usize,
216 pub binds: usize,
218 pub claims: usize,
220}
221
222impl PageCounts {
223 pub fn unanchored(&self) -> bool {
225 self.binds == 0 && self.claims == 0
226 }
227}
228
229pub fn page_counts(doc: &Doc) -> PageCounts {
233 let mut counts = PageCounts {
234 binds: doc.binds.len(),
235 claims: doc.claims.len(),
236 ..PageCounts::default()
237 };
238 for block in doc
239 .blocks
240 .iter()
241 .filter(|b| b.is_rust_example() && !b.is_capture())
242 {
243 if block.is_testable_rust() && !block.has_tag("no_run") {
244 counts.executed += 1;
245 } else {
246 counts.compile_only += 1;
247 }
248 }
249 counts
250}
251
252pub const CAPTURE_DIR: &str = "examples/soothfast_capture";
254
255pub const CAPTURE_EXAMPLE: &str = "soothfast_capture";
257
258pub const CAPTURE_UNKNOWN: (i32, &str) = (2, "soothfast_capture: unknown block");
260
261pub const CAPTURE_DISABLED: (i32, &str) = (3, "soothfast_capture: disabled block");
264
265pub fn capture_ids(rel_path: &str, doc: &Doc) -> Vec<String> {
268 let stem = sanitized_stem(rel_path);
269 let count = doc.blocks.iter().filter(|b| b.is_capture()).count();
270 (1..=count).map(|n| format!("{stem}_{n}")).collect()
271}
272
273pub fn capture_set<'a>(
286 docs: impl IntoIterator<Item = (&'a str, &'a Doc)>,
287) -> Result<Vec<Generated>, String> {
288 let docs: Vec<(&str, &Doc)> = docs.into_iter().collect();
289 one_global_allocator(&docs, CodeBlock::is_capture)?;
290 let mut blocks: Vec<(String, &str, Option<String>, String)> = Vec::new();
291 let mut stems: Vec<(String, &str)> = Vec::new();
292 for (rel_path, doc) in docs {
293 let ids = capture_ids(rel_path, doc);
294 if ids.is_empty() {
295 continue;
296 }
297 let stem = sanitized_stem(rel_path);
298 if let Some((_, other)) = stems.iter().find(|(s, _)| *s == stem) {
299 return Err(format!(
300 "{other} and {rel_path} both generate capture blocks `{stem}_N`; rename one"
301 ));
302 }
303 stems.push((stem, rel_path));
304 let captures = doc.blocks.iter().filter(|b| b.is_capture());
305 for (id, block) in ids.into_iter().zip(captures) {
306 let body = capture_module(block)
307 .map_err(|e| format!("{rel_path} line {}: {e}", block.line))?;
308 let content = format!(
309 "{GENERATED_HEADER}\n// source: {rel_path} line {}\n{body}",
310 block.line
311 );
312 blocks.push((id, rel_path, block.feature_cfg(), content));
313 }
314 }
315 if blocks.is_empty() {
316 return Ok(Vec::new());
317 }
318 blocks.sort_by(|a, b| a.1.cmp(b.1));
319 let mut set = vec![Generated {
320 path: format!("{CAPTURE_DIR}/main.rs"),
321 content: capture_main(&blocks),
322 }];
323 set.extend(blocks.into_iter().map(|(id, _, _, content)| Generated {
324 path: format!("{CAPTURE_DIR}/block_{id}.rs"),
325 content,
326 }));
327 Ok(set)
328}
329
330fn capture_main(blocks: &[(String, &str, Option<String>, String)]) -> String {
331 let mut mods = String::new();
332 let mut arms = String::new();
333 for (id, _, cfg, _) in blocks {
334 let run = format!("\"{id}\" => run(block_{id}::main),\n");
335 match cfg {
336 Some(pred) => {
337 mods.push_str(&format!("#[cfg({pred})]\nmod block_{id};\n"));
338 arms.push_str(&format!(" #[cfg({pred})]\n {run}"));
339 arms.push_str(&format!(
340 " #[cfg(not({pred}))]\n \"{id}\" => exit(CAPTURE_DISABLED, &id),\n"
341 ));
342 }
343 None => {
344 mods.push_str(&format!("mod block_{id};\n"));
345 arms.push_str(&format!(" {run}"));
346 }
347 }
348 }
349 let (unknown, unknown_msg) = CAPTURE_UNKNOWN;
350 let (disabled, disabled_msg) = CAPTURE_DISABLED;
351 format!(
352 "{GENERATED_HEADER}\n#![allow(dead_code, unused_imports)]\n\n\
353 use std::process::{{ExitCode, Termination}};\n\n\
354 {VERBATIM}\n\
355 verbatim! {{\n{mods}}}\n\n\
356 const CAPTURE_UNKNOWN: (u8, &str) = ({unknown}, \"{unknown_msg}\");\n\
357 const CAPTURE_DISABLED: (u8, &str) = ({disabled}, \"{disabled_msg}\");\n\n\
358 fn main() -> ExitCode {{\n \
359 let id = std::env::args().nth(1).unwrap_or_default();\n \
360 verbatim! {{\n \
361 match id.as_str() {{\n{arms} \
362 _ => exit(CAPTURE_UNKNOWN, &id),\n \
363 }}\n \
364 }}\n\
365 }}\n\n\
366 fn run<T: Termination>(main: fn() -> T) -> ExitCode {{\n \
367 main().report()\n\
368 }}\n\n\
369 fn exit((code, sentinel): (u8, &str), id: &str) -> ExitCode {{\n \
370 eprintln!(\"{{sentinel}} {{id}}\");\n \
371 ExitCode::from(code)\n\
372 }}\n"
373 )
374}
375
376fn capture_module(block: &CodeBlock) -> Result<String, String> {
378 let lines: Vec<&str> = block.code.lines().collect();
379 let Some(at) = lines.iter().position(|l| top_level_main(l).is_some()) else {
380 return Ok(format!(
381 "pub fn main() {{\n{}\n}}\n",
382 indent(&block.code, " ")
383 ));
384 };
385 for (i, line) in lines.iter().enumerate() {
386 let next = lines[i + 1..].iter().find(|l| !l.trim().is_empty());
387 if line.starts_with("#![") && !is_lint_attribute(line) {
388 return Err(
389 "a capture block cannot use a crate-level attribute (`#![...]`) other than a lint level"
390 .into(),
391 );
392 }
393 if line.starts_with("#[macro_use]") && next.is_some_and(|l| l.starts_with("extern crate")) {
394 return Err("a capture block cannot use `#[macro_use] extern crate`".into());
395 }
396 }
397 let mut out: Vec<String> = lines.iter().map(|l| l.to_string()).collect();
398 if top_level_main(lines[at]) == Some(false) {
399 out[at] = format!("pub {}", lines[at]);
400 }
401 Ok(format!("{}\n", out.join("\n")))
402}
403
404fn is_lint_attribute(line: &str) -> bool {
407 ["allow", "warn", "deny", "forbid", "expect"]
408 .iter()
409 .any(|lint| {
410 line.strip_prefix("#![")
411 .is_some_and(|a| a.starts_with(&format!("{lint}(")))
412 })
413}
414
415fn top_level_main(line: &str) -> Option<bool> {
418 let restricted = line
419 .strip_prefix("pub(")
420 .and_then(|rest| rest.split_once(") ").map(|(_, rest)| rest));
421 let (public, rest) = match restricted.or_else(|| line.strip_prefix("pub ")) {
422 Some(rest) => (true, rest),
423 None => (false, line),
424 };
425 let rest = rest.strip_prefix("async ").unwrap_or(rest);
426 let after = rest.strip_prefix("fn main")?;
427 (!after.starts_with(|c: char| c.is_alphanumeric() || c == '_')).then_some(public)
428}
429
430#[cfg(test)]
431mod tests {
432 use super::*;
433 use crate::markdown;
434
435 #[test]
436 fn page_counts_split_executed_from_compile_only() {
437 let md = "<!-- soothfast:bind item=a::b -->\n```rust\nlet x = 1;\n```\n```rust no_run\nloop {}\n```\n```rust ignore\nx();\n```\n```rust,compile_fail\nbad;\n```\n```rust capture-output\nprintln!(\"h\");\n```\n```console\n$ ls\n```\n";
438 let counts = page_counts(&markdown::scan(md).unwrap());
439 assert_eq!((counts.executed, counts.compile_only), (1, 3));
440 assert_eq!((counts.binds, counts.claims), (1, 0));
441 assert!(!counts.unanchored());
442 }
443
444 #[test]
445 fn a_page_with_no_markers_is_unanchored() {
446 let counts = page_counts(&markdown::scan("```rust\nlet x = 1;\n```\n").unwrap());
447 assert!(counts.unanchored());
448 }
449
450 #[test]
451 fn generates_tests_and_examples() {
452 let md = "```rust\nlet x = 1;\n```\n```rust no_run\nloop {}\n```\n```rust capture-output\nprintln!(\"h\");\n```\n";
453 let doc = markdown::scan(md).unwrap();
454 let tests = test_file("docs/a.md", &doc).unwrap();
455 assert!(tests.contains("#[test]"));
456 assert!(tests.contains("compile-only"));
457 assert!(!tests.contains("println!")); assert_eq!(capture_ids("docs/a.md", &doc), ["docs_a_1"]);
459 }
460
461 #[test]
462 fn doc_tests_compile_into_one_target_with_a_module_per_page() {
463 let a = markdown::scan("```rust\nlet x = 1;\n```\n").unwrap();
464 let b = markdown::scan("```rust\nlet y = 2;\n```\n").unwrap();
465 let none = markdown::scan("```rust ignore\nnope();\n```\n").unwrap();
466 let set = doc_test_set([
467 ("docs/b.md", &b),
468 ("README.md", &a),
469 ("docs/skip.md", &none),
470 ])
471 .unwrap();
472 let paths: Vec<&str> = set.iter().map(|g| g.path.as_str()).collect();
473 assert_eq!(
474 paths,
475 [
476 "tests/soothfast_docs/main.rs",
477 "tests/soothfast_docs/doc_readme.rs",
478 "tests/soothfast_docs/doc_docs_b.rs"
479 ]
480 );
481 assert!(set[0].content.starts_with(GENERATED_HEADER));
482 assert!(
483 set[0]
484 .content
485 .ends_with("verbatim! {\nmod doc_readme;\nmod doc_docs_b;\n}\n")
486 );
487 assert_eq!(set[1].content, test_file("README.md", &a).unwrap());
488 }
489
490 #[test]
491 fn no_testable_page_means_no_doc_test_target() {
492 let none = markdown::scan("```rust ignore\nnope();\n```\n").unwrap();
493 assert!(doc_test_set([("README.md", &none)]).unwrap().is_empty());
494 }
495
496 #[test]
497 fn two_pages_on_one_module_name_are_an_error_naming_both() {
498 let a = markdown::scan("```rust\nlet x = 1;\n```\n").unwrap();
499 let e = doc_test_set([("docs/a-b.md", &a), ("docs/a_b.md", &a)]).unwrap_err();
500 assert!(
501 e.contains("docs/a-b.md") && e.contains("docs/a_b.md"),
502 "{e}"
503 );
504 }
505
506 #[test]
507 fn owned_places_cover_both_layouts_and_nothing_else() {
508 assert_eq!(
509 owning_target("tests/soothfast_doc_readme.rs"),
510 Some((DOC_TESTS_DIR, true))
511 );
512 assert_eq!(
513 owning_target("tests/soothfast_docs/main.rs"),
514 Some((DOC_TESTS_DIR, false))
515 );
516 assert_eq!(
517 owning_target("examples/soothfast_capture_readme_1.rs"),
518 Some((CAPTURE_DIR, true))
519 );
520 assert_eq!(
521 owning_target("examples/soothfast_capture/block_readme_1.rs"),
522 Some((CAPTURE_DIR, false))
523 );
524 assert_eq!(owning_target("tests/integration.rs"), None);
525 assert_eq!(owning_target("tests/soothfast_docs/data.json"), None);
526 assert_eq!(owning_target("src/soothfast_doc_x.rs"), None);
527 }
528
529 #[test]
530 fn all_ignored_means_no_test_file() {
531 let doc = markdown::scan("```rust ignore\nfictional();\n```\n").unwrap();
532 assert!(test_file("README.md", &doc).is_none());
533 }
534
535 #[test]
536 fn feature_tag_gates_generated_test() {
537 let md =
538 "```rust feature=risk\nlet x = 1;\n```\n```rust no_run feature=risk\nloop {}\n```\n";
539 let doc = markdown::scan(md).unwrap();
540 let tests = test_file("docs/r.md", &doc).unwrap();
541 assert_eq!(tests.matches("#[cfg(feature = \"risk\")]").count(), 2);
542 }
543
544 #[test]
545 fn comma_separated_feature_tag_gates_on_all_of_them() {
546 let md = "```rust no_run feature=risk,polygon\nloop {}\n```\n";
550 let doc = markdown::scan(md).unwrap();
551 let tests = test_file("docs/r.md", &doc).unwrap();
552 assert!(tests.contains("#[cfg(all(feature = \"risk\", feature = \"polygon\"))]"));
553 }
554
555 fn capture(md: &str) -> Vec<Generated> {
556 capture_set([("docs/c.md", &markdown::scan(md).unwrap())]).unwrap()
557 }
558
559 #[test]
560 fn capture_blocks_compile_into_one_example_with_a_module_per_block() {
561 let set = capture(
562 "```rust capture-output\nprintln!(\"a\");\n```\n```rust capture-output\nprintln!(\"b\");\n```\n",
563 );
564 let paths: Vec<&str> = set.iter().map(|g| g.path.as_str()).collect();
565 assert_eq!(
566 paths,
567 [
568 "examples/soothfast_capture/main.rs",
569 "examples/soothfast_capture/block_docs_c_1.rs",
570 "examples/soothfast_capture/block_docs_c_2.rs",
571 ]
572 );
573 let main = &set[0].content;
574 assert!(main.contains("mod block_docs_c_1;\nmod block_docs_c_2;\n"));
575 assert!(main.contains("\"docs_c_2\" => run(block_docs_c_2::main),"));
576 assert!(main.contains("_ => exit(CAPTURE_UNKNOWN, &id),"));
577 assert!(
578 set[1]
579 .content
580 .contains("pub fn main() {\n println!(\"a\");\n}")
581 );
582 assert_eq!(
583 recorded_source(&set[1].content),
584 Some(("docs/c.md", Some(1)))
585 );
586 }
587
588 #[test]
589 fn no_capture_block_means_no_capture_example() {
590 assert!(capture("```rust\nlet x = 1;\n```\n").is_empty());
591 }
592
593 #[test]
594 fn feature_tag_gates_the_module_and_dispatches_disabled_without_it() {
595 let set = capture("```rust capture-output feature=risk,polygon\nprintln!(\"hi\");\n```\n");
596 let main = &set[0].content;
597 let pred = "all(feature = \"risk\", feature = \"polygon\")";
598 assert!(main.contains(&format!("#[cfg({pred})]\nmod block_docs_c_1;")));
599 assert!(main.contains(&format!(
600 "#[cfg({pred})]\n \"docs_c_1\" => run(block_docs_c_1::main),"
601 )));
602 assert!(main.contains(&format!(
603 "#[cfg(not({pred}))]\n \"docs_c_1\" => exit(CAPTURE_DISABLED, &id),"
604 )));
605 assert!(main.contains(
606 "const CAPTURE_DISABLED: (u8, &str) = (3, \"soothfast_capture: disabled block\");"
607 ));
608 }
609
610 #[test]
611 fn a_blocks_own_top_level_main_becomes_pub_and_keeps_its_attributes() {
612 let md = "```rust capture-output\n// fn main is below\nuse std::fmt;\n\n#[tokio::main]\nasync fn main() -> Result<(), Box<dyn std::error::Error>> {\n fn main_helper() {}\n Ok(())\n}\n```\n";
613 let block = &capture(md)[1].content;
614 assert!(block.contains("// fn main is below\nuse std::fmt;"));
615 assert!(block.contains("#[tokio::main]\npub async fn main() -> Result<"));
616 assert!(block.contains(" fn main_helper() {}"));
617 assert_eq!(block.matches("fn main(").count(), 1);
618 }
619
620 #[test]
621 fn an_already_pub_main_is_left_alone() {
622 let block = &capture("```rust capture-output\npub fn main() {}\n```\n")[1].content;
623 assert!(block.ends_with("\npub fn main() {}\n"), "{block}");
624 }
625
626 #[test]
627 fn crate_level_attributes_in_a_capture_block_are_an_error() {
628 for code in [
629 "#![feature(test)]\nfn main() {}",
630 "#[macro_use]\nextern crate serde;\nfn main() {}",
631 ] {
632 let doc = markdown::scan(&format!("```rust capture-output\n{code}\n```\n")).unwrap();
633 let e = capture_set([("docs/c.md", &doc)]).unwrap_err();
634 assert!(
635 e.starts_with("docs/c.md line 1: a capture block cannot"),
636 "{e}"
637 );
638 }
639 }
640
641 #[test]
642 fn two_pages_on_one_capture_stem_are_an_error_naming_both() {
643 let a = markdown::scan("```rust capture-output\nlet x = 1;\n```\n").unwrap();
644 let e = capture_set([("docs/a-b.md", &a), ("docs/a_b.md", &a)]).unwrap_err();
645 assert!(
646 e.contains("docs/a-b.md") && e.contains("docs/a_b.md"),
647 "{e}"
648 );
649 }
650
651 #[test]
652 fn recorded_source_reads_page_with_or_without_a_line() {
653 let h = GENERATED_HEADER;
654 assert_eq!(
655 recorded_source(&format!("{h}\n// source: README.md\n")),
656 Some(("README.md", None))
657 );
658 assert_eq!(
659 recorded_source(&format!("{h}\n// source: docs/a line b.md line 41\n")),
660 Some(("docs/a line b.md", Some(41)))
661 );
662 assert_eq!(
663 recorded_source(&format!("{h}\n// source: docs/a line b.md\n")),
664 Some(("docs/a line b.md", None))
665 );
666 assert_eq!(recorded_source(&format!("{h}\nfn main() {{}}\n")), None);
667 }
668
669 #[test]
670 fn a_lint_level_inner_attribute_is_allowed_in_a_capture_block() {
671 for attr in ["allow(dead_code)", "warn(missing_docs)", "expect(unused)"] {
672 let md = format!("```rust capture-output\n#![{attr}]\nfn main() {{}}\n```\n");
673 let block = &capture(&md)[1].content;
674 assert!(
675 block.contains(&format!("#![{attr}]\npub fn main() {{}}")),
676 "{block}"
677 );
678 }
679 }
680
681 #[test]
682 fn a_restricted_visibility_main_is_the_blocks_own_main() {
683 for vis in ["pub(crate)", "pub(super)"] {
684 let md = format!("```rust capture-output\n{vis} fn main() {{}}\n```\n");
685 let block = &capture(&md)[1].content;
686 assert!(
687 block.ends_with(&format!("\n{vis} fn main() {{}}\n")),
688 "{block}"
689 );
690 }
691 }
692
693 #[test]
694 fn only_a_top_level_main_is_called_by_a_doc_test() {
695 let md = "```rust\n// fn main is not here\nfn main_loop() {}\nlet s = \"fn main\";\n```\n```rust\nfn main() {}\n```\n";
696 let tests = test_file("docs/m.md", &markdown::scan(md).unwrap()).unwrap();
697 assert_eq!(tests.matches(" main();").count(), 1, "{tests}");
698 }
699
700 #[test]
701 fn two_blocks_installing_a_global_allocator_are_an_error_naming_both() {
702 let a = markdown::scan("```rust no_run\nsoothfast::bench_main!();\n```\n").unwrap();
703 let b =
704 markdown::scan("```rust no_run\n#[global_allocator]\nstatic A: X = X;\n```\n").unwrap();
705 let e = doc_test_set([("docs/a.md", &a), ("docs/b.md", &b)]).unwrap_err();
706 assert!(
707 e.starts_with("docs/a.md line 1 and docs/b.md line 1 both install"),
708 "{e}"
709 );
710 assert!(doc_test_set([("docs/a.md", &a)]).is_ok());
711 }
712
713 fn assert_rustfmt_leaves_alone(name: &str, set: &[Generated], root: &str) {
716 let dir = std::env::temp_dir().join(format!("soothfast-fmt-{name}-{}", std::process::id()));
717 let _ = std::fs::remove_dir_all(&dir);
718 for g in set {
719 let path = dir.join(&g.path);
720 std::fs::create_dir_all(path.parent().unwrap()).unwrap();
721 std::fs::write(path, &g.content).unwrap();
722 }
723 for edition in ["2015", "2021", "2024"] {
724 let out = std::process::Command::new("rustfmt")
725 .args(["--check", "--edition", edition])
726 .arg(dir.join(root).join("main.rs"))
727 .output()
728 .unwrap();
729 assert!(
730 out.status.success(),
731 "edition {edition}:\n{}",
732 String::from_utf8_lossy(&out.stdout)
733 );
734 }
735 let _ = std::fs::remove_dir_all(&dir);
736 }
737
738 fn rustfmt_present() -> bool {
739 std::process::Command::new("rustfmt")
740 .arg("--version")
741 .output()
742 .is_ok_and(|o| o.status.success())
743 }
744
745 #[test]
746 fn generated_targets_are_already_rustfmt_clean() {
747 if !rustfmt_present() {
748 return;
749 }
750 let long =
751 "docs/library/an_unusually_long_page_name_for_a_reference_section_of_the_library.md";
752 let mut capture_md = String::new();
753 for n in 0..12 {
754 let tag = if n % 3 == 0 {
755 " feature=risk,polygon,indicators,backtesting"
756 } else {
757 ""
758 };
759 capture_md.push_str(&format!(
760 "```rust capture-output{tag}\nprintln!(\"{n}\");\n```\n"
761 ));
762 }
763 let md = format!("```rust\nlet x = 1;\n```\n{capture_md}");
764 let pages: Vec<(&str, Doc)> = [
765 long,
766 "docs/b.md",
767 "docs/a_10.md",
768 "docs/a_2.md",
769 "README.md",
770 ]
771 .into_iter()
772 .map(|p| (p, markdown::scan(&md).unwrap()))
773 .collect();
774 let docs = || pages.iter().map(|(p, d)| (*p, d));
775 assert_rustfmt_leaves_alone("tests", &doc_test_set(docs()).unwrap(), DOC_TESTS_DIR);
776 assert_rustfmt_leaves_alone("capture", &capture_set(docs()).unwrap(), CAPTURE_DIR);
777 }
778}