Skip to main content

devpage_core/
requirements.rs

1//! A site's requirements, checked against its tests: the `requirements`
2//! system extension. A page of type `constraint` is a requirement a test can
3//! check; a test points at it by its id — the `id` of the page's front matter
4//! — which the site's own pattern reads out of its test files. A constraint
5//! no test points at is a problem, and so is a test pointing at no
6//! constraint. Each suite's `run` command prints its results as JUnit XML,
7//! which [`junit`] reads; the command itself is run by the binary.
8//!
9//! A requirement belongs to a part: a page in `<part>/requirements/` is a
10//! requirement of the part whose folder that is, and of every part below
11//! it. [`listing`] is what the `Requirements` widget shows on a part's
12//! page, and [`save`] keeps the last run's results in `.devpage/`, so the
13//! widget can say whether each constraint is met.
14
15use std::collections::{BTreeMap, HashMap};
16use std::path::{Path, PathBuf};
17
18use anyhow::{Context, Result, bail};
19use globset::GlobSet;
20use regex::Regex;
21use serde::{Deserialize, Serialize};
22
23use crate::document::Document;
24use crate::folder::{ServedFolder, lexical};
25use crate::problem::Problem;
26
27/// The page type whose pages are constraints.
28const CONSTRAINT: &str = "constraint";
29
30/// The page types whose pages are requirements, each with what the
31/// `Requirements` widget calls it.
32const KINDS: &[(&str, &str)] = &[
33    (CONSTRAINT, "constraint"),
34    ("review-rule", "review rule"),
35    ("objective", "objective"),
36];
37
38/// The folder, in a part's folder, that holds the part's requirements.
39const FOLDER: &str = "requirements";
40
41/// `extensions: requirements: config:` as a site writes it.
42#[derive(Debug, Deserialize)]
43#[serde(deny_unknown_fields)]
44struct Config {
45    /// One entry per language or test framework.
46    tests: Vec<SuiteConfig>,
47}
48
49/// One suite of tests as written: where its files are, how a test names a
50/// constraint, and the command that runs it.
51#[derive(Debug, Deserialize)]
52#[serde(deny_unknown_fields)]
53struct SuiteConfig {
54    /// What the suite is called in problems.
55    name: String,
56    /// A glob of its test files, relative to the document file.
57    glob: String,
58    /// A regular expression whose first group is a constraint's id.
59    pattern: String,
60    /// The command that runs it and prints JUnit XML on standard output.
61    run: String,
62}
63
64/// A site's requirements as configured: its test suites.
65#[derive(Debug)]
66pub struct Requirements {
67    /// The suites, in the order written.
68    pub suites: Vec<Suite>,
69}
70
71/// One suite of tests, ready to be searched.
72#[derive(Debug)]
73pub struct Suite {
74    /// What the suite is called in problems.
75    pub name: String,
76    /// The command that runs it and prints JUnit XML on standard output.
77    pub run: String,
78    /// The folder its glob's files are under.
79    root: PathBuf,
80    /// Its glob, matched against absolute paths.
81    files: GlobSet,
82    /// How a test names a constraint: the first group is the id.
83    pattern: Regex,
84}
85
86/// A test pointing at a constraint: the id it names and where it does.
87#[derive(Debug, Clone, PartialEq, Eq)]
88pub struct Pointer {
89    /// The constraint id as the test file writes it.
90    pub id: String,
91    /// The test file.
92    pub file: PathBuf,
93    /// The line the id is on, counted from 1.
94    pub line: usize,
95}
96
97/// One test of a JUnit report.
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct Case {
100    /// Its name, with its class before it when the report gives one.
101    pub name: String,
102    /// Whether it failed or stopped on an error.
103    pub failed: bool,
104}
105
106impl Requirements {
107    /// Reads `config` — what a site writes under `extensions: requirements:
108    /// config:` — for the document file in `base`; an error names the field
109    /// that is wrong.
110    pub fn read(config: &serde_yaml::Value, base: &Path, served: &ServedFolder) -> Result<Self> {
111        let config: Config = serde_yaml::from_value(config.clone())?;
112        if config.tests.is_empty() {
113            bail!("tests lists no suite");
114        }
115        let mut suites = Vec::new();
116        for suite in config.tests {
117            let name = &suite.name;
118            let absolute = lexical(&base.join(&suite.glob));
119            if !served.contains(&absolute) {
120                bail!(
121                    "tests {name}: glob {} is outside the served folder",
122                    suite.glob
123                );
124            }
125            let root = crate::code::literal_prefix(&absolute);
126            let rest = absolute.strip_prefix(&root).unwrap_or(&absolute);
127            let text = if rest.as_os_str().is_empty() {
128                globset::escape(&crate::code::glob_path(&root))
129            } else {
130                format!(
131                    "{}/{}",
132                    globset::escape(crate::code::glob_path(&root).trim_end_matches('/')),
133                    crate::code::glob_path(rest)
134                )
135            };
136            let glob = globset::GlobBuilder::new(&text)
137                .literal_separator(true)
138                .build()
139                .with_context(|| format!("tests {name}: glob {}", suite.glob))?;
140            let pattern = Regex::new(&suite.pattern)
141                .with_context(|| format!("tests {name}: pattern {}", suite.pattern))?;
142            if pattern.captures_len() < 2 {
143                bail!(
144                    "tests {name}: pattern {} has no group — its first group is the constraint's id",
145                    suite.pattern
146                );
147            }
148            if suite.run.trim().is_empty() {
149                bail!("tests {name}: run is empty");
150            }
151            suites.push(Suite {
152                name: suite.name,
153                run: suite.run,
154                root,
155                files: GlobSet::builder().add(glob).build()?,
156                pattern,
157            });
158        }
159        Ok(Self { suites })
160    }
161
162    /// Every place a test file of any suite names a constraint, in path order.
163    pub fn pointers(&self) -> Vec<Pointer> {
164        let mut found = Vec::new();
165        for suite in &self.suites {
166            let mut files = Vec::new();
167            let walk = ignore::WalkBuilder::new(&suite.root)
168                .hidden(true)
169                .require_git(false)
170                .build();
171            for entry in walk.flatten() {
172                let path = entry.path();
173                if entry.file_type().is_some_and(|t| t.is_file())
174                    && suite.files.is_match(crate::code::glob_path(path))
175                {
176                    files.push(path.to_path_buf());
177                }
178            }
179            files.sort();
180            for file in files {
181                let Ok(source) = std::fs::read_to_string(&file) else {
182                    continue;
183                };
184                for captures in suite.pattern.captures_iter(&source) {
185                    let Some(id) = captures.get(1) else { continue };
186                    found.push(Pointer {
187                        id: id.as_str().to_string(),
188                        file: file.clone(),
189                        line: source[..id.start()].matches('\n').count() + 1,
190                    });
191                }
192            }
193        }
194        found
195    }
196}
197
198/// A site's constraint pages: every Markdown file in its folder whose
199/// `page-type` is `constraint`.
200struct Constraints {
201    /// The pages by the `id` their front matter gives; an id two pages share
202    /// keeps both, in path order.
203    by_id: BTreeMap<String, Vec<PathBuf>>,
204    /// The pages that give no `id`.
205    unnamed: Vec<PathBuf>,
206}
207
208/// Reads the site's constraint pages.
209fn constraints(document: &Document) -> Constraints {
210    let mut found = Constraints {
211        by_id: BTreeMap::new(),
212        unnamed: Vec::new(),
213    };
214    let walk = ignore::WalkBuilder::new(&document.base)
215        .hidden(true)
216        .require_git(false)
217        .build();
218    let mut pages = Vec::new();
219    for entry in walk.flatten() {
220        let path = entry.path();
221        if entry.file_type().is_some_and(|t| t.is_file())
222            && path.extension().is_some_and(|ext| ext == "md")
223        {
224            pages.push(path.to_path_buf());
225        }
226    }
227    pages.sort();
228    for page in pages {
229        let Ok(source) = std::fs::read_to_string(&page) else {
230            continue;
231        };
232        if crate::structure::page_type(&source).is_none_or(|(name, _)| name != CONSTRAINT) {
233            continue;
234        }
235        match crate::structure::front_matter(&source, "id") {
236            Some(id) => found.by_id.entry(id).or_default().push(page),
237            None => found.unnamed.push(page),
238        }
239    }
240    found
241}
242
243/// What is wrong between a site's constraints and its tests, without running
244/// one: a constraint with no id, a constraint no test points at, a test
245/// pointing at no constraint, and two constraints with one id. Nothing for a document with no requirements.
246pub fn problems(document: &Document) -> Vec<Problem> {
247    let Some(requirements) = &document.requirements else {
248        return Vec::new();
249    };
250    let problem = |file: &Path, line: Option<usize>, message: String| {
251        document.name(file).map(|file| Problem {
252            file,
253            line,
254            column: None,
255            message,
256            target: None,
257        })
258    };
259    let constraints = constraints(document);
260    let pointers = requirements.pointers();
261    let mut problems = Vec::new();
262    for page in &constraints.unnamed {
263        problems.extend(problem(
264            page,
265            None,
266            "a constraint has an id — its front matter has no id".to_string(),
267        ));
268    }
269    for (id, pages) in &constraints.by_id {
270        for page in &pages[1..] {
271            problems.extend(problem(
272                page,
273                None,
274                format!(
275                    "constraint id {id} is taken by {}",
276                    document.name(&pages[0]).unwrap_or_default()
277                ),
278            ));
279        }
280        if !pointers.iter().any(|pointer| pointer.id == *id) {
281            problems.extend(problem(
282                &pages[0],
283                None,
284                format!("no test points at this constraint — a test names it {id}"),
285            ));
286        }
287    }
288    for pointer in &pointers {
289        if !constraints.by_id.contains_key(&pointer.id) {
290            problems.extend(problem(
291                &pointer.file,
292                Some(pointer.line),
293                format!("{} — no constraint has this id", pointer.id),
294            ));
295        }
296    }
297    problems
298}
299
300/// The tests of a JUnit report: every `testcase`, failed when it holds a
301/// `failure` or an `error`. `text` is whatever a command printed: several
302/// reports one after another, as a command running several test binaries
303/// prints them, with anything else between them — a build's own output —
304/// passed over.
305pub fn junit(text: &str) -> Vec<Case> {
306    static CASE: std::sync::LazyLock<Regex> = std::sync::LazyLock::new(|| {
307        Regex::new(r"(?s)<testcase\b([^>]*?)(?:/>|>(.*?)</testcase>)").unwrap()
308    });
309    static ATTRIBUTE: std::sync::LazyLock<Regex> =
310        std::sync::LazyLock::new(|| Regex::new(r#"\b(classname|name)="([^"]*)""#).unwrap());
311    let unescaped = |value: &str| {
312        value
313            .replace("&lt;", "<")
314            .replace("&gt;", ">")
315            .replace("&quot;", "\"")
316            .replace("&apos;", "'")
317            .replace("&amp;", "&")
318    };
319    CASE.captures_iter(text)
320        .map(|case| {
321            let mut name = String::new();
322            let mut class = String::new();
323            for attribute in ATTRIBUTE.captures_iter(&case[1]) {
324                match &attribute[1] {
325                    "name" => name = unescaped(&attribute[2]),
326                    _ => class = unescaped(&attribute[2]),
327                }
328            }
329            let body = case.get(2).map_or("", |body| body.as_str());
330            Case {
331                name: if class.is_empty() {
332                    name
333                } else {
334                    format!("{class}::{name}")
335                },
336                failed: body.contains("<failure") || body.contains("<error"),
337            }
338        })
339        .collect()
340}
341
342/// What a suite's run shows is wrong, from what its command printed and how
343/// it exited: each failed test, that it printed no report at all, or that it
344/// failed though its report names no failed test. The
345/// problems are the document file's.
346pub fn run_problems(
347    document: &Document,
348    suite: &Suite,
349    printed: &str,
350    exit: Option<i32>,
351) -> Vec<Problem> {
352    let problem = |message: String| Problem {
353        file: document.part_name(&document.path()),
354        line: None,
355        column: None,
356        message,
357        target: None,
358    };
359    let cases = junit(printed);
360    if cases.is_empty() {
361        let exit = exit.map_or("no exit code".to_string(), |code| {
362            format!("exit code {code}")
363        });
364        return vec![problem(format!(
365            "tests {}: `{}` printed no JUnit report ({exit})",
366            suite.name, suite.run
367        ))];
368    }
369    let failed: Vec<Problem> = cases
370        .into_iter()
371        .filter(|case| case.failed)
372        .map(|case| problem(format!("tests {}: {} failed", suite.name, case.name)))
373        .collect();
374    // A command that failed without naming a failed test did not run them
375    // all: it stopped on a build error, or on a test binary that printed no
376    // report.
377    if failed.is_empty() && exit != Some(0) {
378        let exit = exit.map_or("no exit code".to_string(), |code| {
379            format!("exit code {code}")
380        });
381        return vec![problem(format!(
382            "tests {}: `{}` failed ({exit}) and its report names no failed test",
383            suite.name, suite.run
384        ))];
385    }
386    failed
387}
388
389/// How one test pointing at a constraint did in a run.
390#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
391#[serde(rename_all = "kebab-case")]
392pub enum Outcome {
393    /// The report has it, and it passed.
394    Passed,
395    /// The report has it, and it failed.
396    Failed,
397    /// The report has no test of its name.
398    NotRun,
399}
400
401/// A test pointing at a constraint, and how it did.
402#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
403pub struct Tested {
404    /// The test's name; where it points from, when the report has no test
405    /// after the pointer.
406    pub test: String,
407    /// How it did.
408    pub result: Outcome,
409}
410
411/// One run of a site's tests, as kept: when, and each constraint's tests.
412#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
413pub struct Results {
414    /// When the run ended, in seconds since 1970.
415    pub checked: u64,
416    /// Each constraint the site had, by id, with the tests pointing at it; a
417    /// constraint no test points at has none.
418    pub tests: BTreeMap<String, Vec<Tested>>,
419}
420
421/// Whether a constraint is met, by the last run kept.
422#[derive(Debug, Clone, Copy, PartialEq, Eq)]
423enum Status {
424    /// Every test pointing at it passed.
425    Met,
426    /// A test pointing at it failed.
427    NotMet,
428    /// No test points at it.
429    NoTest,
430    /// No run is kept, or the run did not have it or one of its tests.
431    NotChecked,
432}
433
434impl Results {
435    /// Whether the constraint `id` is met.
436    fn status(&self, id: &str) -> Status {
437        match self.tests.get(id) {
438            None => Status::NotChecked,
439            Some(tests) if tests.is_empty() => Status::NoTest,
440            Some(tests) if tests.iter().any(|t| t.result == Outcome::Failed) => Status::NotMet,
441            Some(tests) if tests.iter().any(|t| t.result == Outcome::NotRun) => Status::NotChecked,
442            Some(_) => Status::Met,
443        }
444    }
445}
446
447/// What a run of `document`'s tests, ended at `checked`, shows of each of
448/// its constraints: the tests pointing at it, each with how it did in
449/// `cases`. The test a pointer names is the first of the report's tests
450/// named after it in its file — the test the pointer is written on.
451pub fn results(document: &Document, cases: &[Case], checked: u64) -> Results {
452    let mut tests: BTreeMap<String, Vec<Tested>> = constraints(document)
453        .by_id
454        .into_keys()
455        .map(|id| (id, Vec::new()))
456        .collect();
457    let Some(requirements) = &document.requirements else {
458        return Results { checked, tests };
459    };
460    // A report names a test with its module before it; a file names it
461    // alone.
462    let mut failed: HashMap<&str, bool> = HashMap::new();
463    for case in cases {
464        let short = case
465            .name
466            .rsplit([':', '.', ' '])
467            .next()
468            .unwrap_or(&case.name);
469        *failed.entry(short).or_default() |= case.failed;
470    }
471    let mut sources: HashMap<PathBuf, String> = HashMap::new();
472    for pointer in requirements.pointers() {
473        let Some(found) = tests.get_mut(&pointer.id) else {
474            continue;
475        };
476        let source = sources
477            .entry(pointer.file.clone())
478            .or_insert_with(|| std::fs::read_to_string(&pointer.file).unwrap_or_default());
479        let after: usize = source
480            .split_inclusive('\n')
481            .take(pointer.line.saturating_sub(1))
482            .map(str::len)
483            .sum();
484        let named = source[after..]
485            .split(|c: char| !(c.is_alphanumeric() || c == '_'))
486            .find(|word| failed.contains_key(word));
487        found.push(match named {
488            Some(name) => Tested {
489                test: name.to_string(),
490                result: if failed[name] {
491                    Outcome::Failed
492                } else {
493                    Outcome::Passed
494                },
495            },
496            None => Tested {
497                test: format!(
498                    "{}:{}",
499                    document.name(&pointer.file).unwrap_or_default(),
500                    pointer.line
501                ),
502                result: Outcome::NotRun,
503            },
504        });
505    }
506    Results { checked, tests }
507}
508
509/// Where the last run of the document named `document` is kept:
510/// `.devpage/requirements/<document>.json` in the served folder.
511fn kept(served: &ServedFolder, document: &str) -> PathBuf {
512    served
513        .path()
514        .join(".devpage")
515        .join(FOLDER)
516        .join(format!("{document}.json"))
517}
518
519/// Keeps `results` as `document`'s last run, in the served folder's
520/// `.devpage/` — made, with the `.gitignore` that keeps git away from it,
521/// when it isn't there.
522pub fn save(document: &Document, results: &Results) -> Result<()> {
523    let name = document
524        .name(&document.path())
525        .context("the document file is outside the served folder")?;
526    let file = kept(&document.served, &name);
527    let root = document.served.path().join(".devpage");
528    std::fs::create_dir_all(file.parent().unwrap_or(&root))?;
529    let ignore = root.join(".gitignore");
530    if !ignore.exists() {
531        std::fs::write(ignore, "*\n")?;
532    }
533    std::fs::write(file, serde_json::to_string_pretty(results)?)?;
534    Ok(())
535}
536
537/// The last run kept for the document named `document`, if one is.
538fn saved(served: &ServedFolder, document: &str) -> Option<Results> {
539    serde_json::from_str(&std::fs::read_to_string(kept(served, document)).ok()?).ok()
540}
541
542/// One requirement page, as the widget lists it.
543struct Listed {
544    /// The page.
545    file: PathBuf,
546    /// Its heading.
547    title: String,
548    /// What its kind is called.
549    kind: &'static str,
550    /// Its `id`, when it is a constraint that gives one.
551    id: Option<String>,
552}
553
554/// The requirement pages of the part whose folder is `part`: the pages of
555/// its `requirements` folder whose type is a requirement's, in name order.
556fn listed(part: &Path) -> Vec<Listed> {
557    let mut files: Vec<PathBuf> = std::fs::read_dir(part.join(FOLDER))
558        .into_iter()
559        .flatten()
560        .flatten()
561        .map(|entry| entry.path())
562        .filter(|file| file.extension().is_some_and(|ext| ext == "md"))
563        .collect();
564    files.sort();
565    files
566        .into_iter()
567        .filter_map(|file| {
568            let source = std::fs::read_to_string(&file).ok()?;
569            let (name, _) = crate::structure::page_type(&source)?;
570            let (kind, called) = KINDS.iter().find(|(kind, _)| *kind == name)?;
571            Some(Listed {
572                title: crate::markup::title(&source, &file),
573                kind: called,
574                id: (*kind == CONSTRAINT)
575                    .then(|| crate::structure::front_matter(&source, "id"))
576                    .flatten(),
577                file,
578            })
579        })
580        .collect()
581}
582
583/// What the `Requirements` widget shows on `page`, a page of the site in
584/// `base` whose document is named `document`: a Markdown list of the
585/// requirements of the page's part — the pages in the `requirements` folder
586/// beside it — each a link, then ` — ` and whether it is met by the last run
587/// kept, or its kind when no test checks it; then, for each part above that
588/// has requirements, an item naming the part with its requirements listed
589/// under it. After the list, the time of the run, when one is kept.
590pub fn listing(served: &ServedFolder, base: &Path, document: &str, page: &Path) -> String {
591    let results = saved(served, document);
592    let Some(part) = page.parent().filter(|part| part.starts_with(base)) else {
593        return String::new();
594    };
595    let item = |listed: &Listed, up: &str, indent: &str| {
596        let status = match (&listed.id, listed.kind) {
597            (Some(id), _) => match results.as_ref().map(|r| r.status(id)) {
598                Some(Status::Met) => "met",
599                Some(Status::NotMet) => "not met",
600                Some(Status::NoTest) => "no test",
601                Some(Status::NotChecked) | None => "not checked",
602            },
603            (None, kind) => kind,
604        };
605        format!(
606            "{indent}- [{}]({up}{FOLDER}/{}) — {status}\n",
607            listed.title.replace('[', "\\[").replace(']', "\\]"),
608            listed
609                .file
610                .file_name()
611                .unwrap_or_default()
612                .to_string_lossy()
613        )
614    };
615    let mut out = String::new();
616    for listed in listed(part) {
617        out.push_str(&item(&listed, "", ""));
618    }
619    let mut up = String::new();
620    let mut above = part;
621    while above != base {
622        let Some(parent) = above.parent() else { break };
623        above = parent;
624        up.push_str("../");
625        let inherited = listed(above);
626        if inherited.is_empty() {
627            continue;
628        }
629        let top = above.join("README.md");
630        let title = std::fs::read_to_string(&top).map_or_else(
631            |_| {
632                above
633                    .file_name()
634                    .unwrap_or_default()
635                    .to_string_lossy()
636                    .into_owned()
637            },
638            |source| crate::markup::title(&source, &top),
639        );
640        out.push_str(&format!("- [{title}]({up}README.md)\n"));
641        for listed in inherited {
642            out.push_str(&item(&listed, &up, "  "));
643        }
644    }
645    if out.is_empty() {
646        return String::new();
647    }
648    if let Some(results) = results {
649        out.push_str(&format!(
650            "\n<span data-checked=\"{}\"></span>\n",
651            results.checked
652        ));
653    }
654    out
655}
656
657#[cfg(test)]
658mod tests {
659    use super::*;
660
661    /// A site named `name` whose requirements read `tests/*.sh` for
662    /// `# spec: <id>`, holding `files` — each a path in the site and its text.
663    fn site(name: &str, files: &[(&str, &str)]) -> Document {
664        let dir = std::env::temp_dir().join(format!("devpage-{name}-{}", std::process::id()));
665        let _ = std::fs::remove_dir_all(&dir);
666        std::fs::create_dir_all(&dir).unwrap();
667        std::fs::write(
668            dir.join("devpage.yml"),
669            "kind: site\ntitle: T\nroot: README.md\nextensions:\n  requirements:\n    config:\n      tests:\n        - name: shell\n          glob: \"tests/*.sh\"\n          pattern: '# spec: ([a-z0-9-]+)'\n          run: \"sh tests/run.sh\"\n",
670        )
671        .unwrap();
672        for (file, text) in files {
673            let file = dir.join(file);
674            std::fs::create_dir_all(file.parent().unwrap()).unwrap();
675            std::fs::write(file, text).unwrap();
676        }
677        Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap()
678    }
679
680    fn found(document: &Document) -> Vec<String> {
681        let mut found: Vec<String> = problems(document).iter().map(ToString::to_string).collect();
682        found.sort();
683        found
684    }
685
686    /// A constraint page whose id is `id`.
687    fn constraint(id: &str) -> String {
688        format!("---\npage-type: constraint\nid: {id}\n---\n# C\n")
689    }
690
691    #[test]
692    fn a_constraint_every_test_of_which_is_found_has_no_problem() {
693        let doc = site(
694            "requirements-ok",
695            &[
696                ("README.md", "# Home\n"),
697                ("rules/saving.md", &constraint("a-save-is-kept")),
698                (
699                    "rules/no-rework.md",
700                    "---\npage-type: review-rule\n---\n# R\n",
701                ),
702                (
703                    "tests/save.sh",
704                    "# spec: a-save-is-kept\none() { :; }\n# spec: a-save-is-kept\ntwo() { :; }\n",
705                ),
706            ],
707        );
708        assert_eq!(found(&doc), Vec::<String>::new());
709    }
710
711    #[test]
712    fn a_constraint_with_no_test_or_no_id_is_a_problem_on_its_page() {
713        let doc = site(
714            "requirements-untested",
715            &[
716                ("README.md", "# Home\n"),
717                ("rules/saving.md", &constraint("a-save-is-kept")),
718                ("rules/unnamed.md", "---\npage-type: constraint\n---\n# C\n"),
719                ("tests/save.sh", "one() { :; }\n"),
720            ],
721        );
722        assert_eq!(
723            found(&doc),
724            [
725                "rules/saving.md: no test points at this constraint — a test names it a-save-is-kept",
726                "rules/unnamed.md: a constraint has an id — its front matter has no id",
727            ]
728        );
729    }
730
731    #[test]
732    fn a_test_pointing_at_no_constraint_is_a_problem_at_its_line() {
733        let doc = site(
734            "requirements-orphan",
735            &[
736                ("README.md", "# Home\n"),
737                (
738                    "tests/save.sh",
739                    "one() { :; }\n# spec: gone-rule\ntwo() { :; }\n",
740                ),
741            ],
742        );
743        assert_eq!(
744            found(&doc),
745            ["tests/save.sh:2: gone-rule — no constraint has this id"]
746        );
747    }
748
749    #[test]
750    fn two_constraints_with_one_id_are_a_problem_on_the_second() {
751        let doc = site(
752            "requirements-twice",
753            &[
754                ("README.md", "# Home\n"),
755                ("a/one.md", &constraint("kept")),
756                ("b/two.md", &constraint("kept")),
757                ("tests/save.sh", "# spec: kept\none() { :; }\n"),
758            ],
759        );
760        assert_eq!(
761            found(&doc),
762            ["b/two.md: constraint id kept is taken by a/one.md"]
763        );
764    }
765
766    #[test]
767    fn a_site_with_no_requirements_has_none_of_these_problems() {
768        let dir =
769            std::env::temp_dir().join(format!("devpage-requirements-off-{}", std::process::id()));
770        std::fs::create_dir_all(&dir).unwrap();
771        std::fs::write(
772            dir.join("devpage.yml"),
773            "kind: site\ntitle: T\nroot: README.md\n",
774        )
775        .unwrap();
776        std::fs::write(dir.join("README.md"), "# Home\n").unwrap();
777        std::fs::write(dir.join("kept.md"), constraint("kept")).unwrap();
778        let doc = Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap();
779        assert!(doc.requirements.is_none());
780        assert_eq!(found(&doc), Vec::<String>::new());
781    }
782
783    #[test]
784    fn a_junit_report_gives_each_test_and_whether_it_failed() {
785        let cases = junit(
786            "<?xml version=\"1.0\"?>\n<testsuites><testsuite name=\"a\">\
787             <testcase classname=\"save\" name=\"one\"/>\
788             <testcase classname=\"save\" name=\"two\"><failure message=\"x &lt; y\">at line 3</failure></testcase>\
789             <testcase name=\"three\"><error/></testcase>\
790             </testsuite></testsuites>\n\
791             #1 [internal] load <build definition> & more\n\
792             <?xml version=\"1.0\"?>\n<testsuites><testsuite name=\"b\"><testcase name=\"four\"/></testsuite></testsuites>",
793        );
794        let read: Vec<(&str, bool)> = cases.iter().map(|c| (c.name.as_str(), c.failed)).collect();
795        assert_eq!(
796            read,
797            [
798                ("save::one", false),
799                ("save::two", true),
800                ("three", true),
801                ("four", false)
802            ]
803        );
804    }
805
806    #[test]
807    fn a_run_reports_each_failed_test_or_that_nothing_was_printed() {
808        let doc = site("requirements-run", &[("README.md", "# Home\n")]);
809        let suite = &doc.requirements.as_ref().unwrap().suites[0];
810        let report = "<testsuite><testcase name=\"one\"/><testcase name=\"two\"><failure/></testcase></testsuite>";
811        let shown = |printed: &str, exit| -> Vec<String> {
812            run_problems(&doc, suite, printed, exit)
813                .iter()
814                .map(ToString::to_string)
815                .collect()
816        };
817        assert_eq!(
818            shown(report, Some(101)),
819            ["devpage.yml: tests shell: two failed"]
820        );
821        assert_eq!(
822            shown("<testsuite><testcase name=\"one\"/></testsuite>", Some(101)),
823            [
824                "devpage.yml: tests shell: `sh tests/run.sh` failed (exit code 101) and its report names no failed test"
825            ]
826        );
827        assert!(shown("<testsuite><testcase name=\"one\"/></testsuite>", Some(0)).is_empty());
828        assert_eq!(
829            shown("error: could not compile", Some(101)),
830            ["devpage.yml: tests shell: `sh tests/run.sh` printed no JUnit report (exit code 101)"]
831        );
832    }
833
834    #[test]
835    fn a_wrong_configuration_stops_the_site_loading_and_names_the_field() {
836        let dir =
837            std::env::temp_dir().join(format!("devpage-requirements-bad-{}", std::process::id()));
838        std::fs::create_dir_all(&dir).unwrap();
839        std::fs::write(dir.join("README.md"), "# Home\n").unwrap();
840        let load = |tests: &str| {
841            std::fs::write(
842                dir.join("devpage.yml"),
843                format!("kind: site\ntitle: T\nroot: README.md\nextensions:\n  requirements:\n    config:\n      tests:\n{tests}"),
844            )
845            .unwrap();
846            format!(
847                "{:#}",
848                Document::load(&dir, &ServedFolder::new(&dir).unwrap()).unwrap_err()
849            )
850        };
851        assert!(
852            load("        - {name: sh, glob: \"*.sh\", pattern: 'spec', run: \"x\"}\n")
853                .contains("tests sh: pattern spec has no group"),
854        );
855        assert!(
856            load("        - {name: sh, glob: \"*.sh\", pattern: '(', run: \"x\"}\n")
857                .contains("extensions: requirements: tests sh: pattern ("),
858        );
859    }
860
861    #[test]
862    fn a_run_is_kept_and_a_parts_page_lists_its_requirements_with_what_the_run_showed() {
863        let page = |kind: &str, id: &str, title: &str| {
864            let id = if id.is_empty() {
865                String::new()
866            } else {
867                format!("id: {id}\n")
868            };
869            format!("---\npage-type: {kind}\n{id}---\n# {title}\n")
870        };
871        let doc = site(
872            "requirements-kept",
873            &[
874                ("README.md", "# Home\n"),
875                (
876                    "requirements/kept.md",
877                    &page("constraint", "a-save-is-kept", "A save is kept"),
878                ),
879                (
880                    "requirements/lost.md",
881                    &page("constraint", "nothing-is-lost", "Nothing is lost"),
882                ),
883                (
884                    "requirements/rule.md",
885                    &page("review-rule", "", "No rework"),
886                ),
887                (
888                    "requirements/untested.md",
889                    &page("constraint", "it-is-fast", "It is fast"),
890                ),
891                ("requirements/steps.md", &page("process", "", "Steps")),
892                ("part/README.md", "# The part\n"),
893                (
894                    "part/requirements/own.md",
895                    &page("constraint", "the-part-works", "The part works"),
896                ),
897                (
898                    "tests/save.sh",
899                    "# spec: a-save-is-kept\nsaves() { :; }\n# spec: nothing-is-lost\n# spec: a-save-is-kept\nloses() { :; }\n# spec: the-part-works\nnever_ran() { :; }\n",
900                ),
901            ],
902        );
903        let case = |name: &str, failed| Case {
904            name: name.to_string(),
905            failed,
906        };
907        let results = results(&doc, &[case("shell::saves", false), case("loses", true)], 7);
908        let outcomes = |id: &str| -> Vec<(String, Outcome)> {
909            results.tests[id]
910                .iter()
911                .map(|t| (t.test.clone(), t.result))
912                .collect()
913        };
914        assert_eq!(
915            outcomes("a-save-is-kept"),
916            [
917                ("saves".to_string(), Outcome::Passed),
918                ("loses".to_string(), Outcome::Failed)
919            ]
920        );
921        assert_eq!(
922            outcomes("the-part-works"),
923            [("tests/save.sh:6".to_string(), Outcome::NotRun)]
924        );
925        assert!(results.tests["it-is-fast"].is_empty());
926
927        let listing =
928            |page: &str| listing(&doc.served, &doc.base, "devpage.yml", &doc.base.join(page));
929        // Before a run is kept, nothing is known of a constraint.
930        assert_eq!(
931            listing("part/README.md").lines().next(),
932            Some("- [The part works](requirements/own.md) — not checked")
933        );
934        save(&doc, &results).unwrap();
935        assert_eq!(
936            std::fs::read_to_string(doc.base.join(".devpage/.gitignore")).unwrap(),
937            "*\n"
938        );
939        assert_eq!(
940            listing("part/README.md"),
941            "- [The part works](requirements/own.md) — not checked\n\
942             - [Home](../README.md)\n  \
943             - [A save is kept](../requirements/kept.md) — not met\n  \
944             - [Nothing is lost](../requirements/lost.md) — not met\n  \
945             - [No rework](../requirements/rule.md) — review rule\n  \
946             - [It is fast](../requirements/untested.md) — no test\n\
947             \n<span data-checked=\"7\"></span>\n"
948        );
949        assert!(listing("README.md").starts_with("- [A save is kept](requirements/kept.md)"));
950    }
951}