Skip to main content

astrs_cli/command/
validate.rs

1//! `astrs validate [--prove]` (blueprint §17).
2//!
3//! Runs the full pipeline a manifest goes through before anything is
4//! spawned — parse, structural validation, module expansion, structural
5//! validation again on the flattened result, graph construction, graph
6//! diagnostics — and reports **every** observation found along the way as
7//! one flat, ordered [`CliDiagnostic`] list, stopping early only when a
8//! later stage would be meaningless (there is nothing to expand from a
9//! manifest that never parsed).
10//!
11//! Exit code convention (blueprint §17): `0` clean, `1` warnings only,
12//! `2` any error — see [`crate::diagnostic::exit_code_for`].
13//!
14//! # `--prove`
15//!
16//! With `--prove`, the graph is additionally handed to `astrs-verify`,
17//! which discharges the obligations of blueprint §15 through an SMT solver
18//! and returns a [`VerificationReport`]. Its results fold into the same
19//! exit-code scale rather than inventing a second one:
20//!
21//! - a **refuted** obligation is an [`Severity::Error`] diagnostic, so the
22//!   command exits `2` — a graph proven to deadlock is not a warning;
23//! - an obligation that reached **no verdict** (a missing service time, an
24//!   undecided solver run) is a [`Severity::Warning`], so the command exits
25//!   `1`. "Nothing failed" and "everything was proved" are different
26//!   claims, and the exit code says which one this run earned;
27//! - a build **without the `verify` feature** still encodes and prints
28//!   every obligation, then returns [`CliError::ProofUnavailable`]
29//!   ([`crate::error::EXIT_UNAVAILABLE`], `69`), so a script can tell a
30//!   missing solver from a failed proof by exit code alone.
31
32use std::io::Write;
33use std::path::{Path, PathBuf};
34
35use astrs_graph::{DataflowGraph, Severity};
36use astrs_manifest::Manifest;
37use astrs_manifest::expand::FsModuleLoader;
38use astrs_verify::{
39    Profile, ProveOptions, RenderOptions, VerificationReport, prove, render_human as render_proof,
40};
41use serde::Serialize;
42
43use crate::diagnostic::{CliDiagnostic, exit_code_for, render_human};
44use crate::error::CliError;
45
46/// Arguments for `astrs validate`.
47#[derive(Debug, Clone)]
48pub struct ValidateArgs {
49    /// The manifest file to validate.
50    pub manifest_path: PathBuf,
51    /// Prove the graph's obligations — deadlock freedom, queue
52    /// boundedness, rate consistency, latency budgets and type-rule
53    /// consistency (blueprint §15) — through the SMT solver.
54    pub prove: bool,
55    /// An optional verification profile supplying per-node service times
56    /// and named end-to-end latency budgets. Only consulted when
57    /// [`Self::prove`] is set.
58    pub profile: Option<PathBuf>,
59    /// Emit the report as JSON instead of human-readable text.
60    pub json: bool,
61    /// Colorize human-readable output with plain ANSI SGR codes.
62    pub color: bool,
63}
64
65/// The result of validating one manifest.
66#[derive(Debug, Clone, Serialize)]
67pub struct ValidateReport {
68    /// The path that was validated, rendered with [`Path::display`].
69    pub manifest_path: String,
70    /// Every observation found, in pipeline order.
71    pub diagnostics: Vec<CliDiagnostic>,
72    /// The full proof report, when `--prove` reached the proving stage.
73    ///
74    /// Nested rather than flattened into [`Self::diagnostics`] on purpose:
75    /// the counterexamples, the per-obligation SMT-LIB2 systems and the
76    /// caveats are the part of a proof worth having, and folding them into
77    /// one-line strings would throw exactly that away.
78    #[serde(skip_serializing_if = "Option::is_none")]
79    pub proof: Option<VerificationReport>,
80}
81
82impl ValidateReport {
83    /// This report's process exit code — see [`exit_code_for`].
84    #[must_use]
85    pub fn exit_code(&self) -> i32 {
86        exit_code_for(&self.diagnostics)
87    }
88}
89
90/// Run `astrs validate`, writing a human or JSON report to `out`.
91///
92/// Every problem with the manifest itself becomes a [`CliDiagnostic`] in
93/// the rendered report rather than an `Err` — see this module's docs for
94/// why a diagnostic tool reports rather than aborts. The proof results
95/// join the same list on the same terms; see this module's header for how
96/// they map onto the exit-code scale.
97///
98/// # Errors
99///
100/// Returns [`CliError::Io`] if writing to `out` fails, or
101/// [`CliError::ProofUnavailable`] if `--prove` reached the proving stage on
102/// a build without the `verify` feature. In the latter case the report —
103/// including every encoded obligation — has already been written to `out`.
104/// A `--prove` run that never got that far (an unparseable manifest, a
105/// profile that does not match) reports *that* instead, on the ordinary
106/// exit-code scale.
107pub fn run(out: &mut dyn Write, args: &ValidateArgs) -> Result<ValidateReport, CliError> {
108    let (mut diagnostics, graph) = collect_diagnostics(args);
109    let proof = if args.prove {
110        run_proof(args, graph.as_ref(), &mut diagnostics)
111    } else {
112        None
113    };
114    let report = ValidateReport {
115        manifest_path: args.manifest_path.display().to_string(),
116        diagnostics,
117        proof,
118    };
119    render(out, args, &report)?;
120    // Only once the obligations were actually *encoded*: if the proof never
121    // got that far — the manifest did not parse, the profile did not match —
122    // the real problem is upstream, and reporting a missing solver instead
123    // would bury it behind exit code 69.
124    if report.proof.is_some() && !astrs_verify::solver_available() {
125        return Err(CliError::ProofUnavailable);
126    }
127    Ok(report)
128}
129
130/// Discharge the graph obligations, folding their results into
131/// `diagnostics` and returning the full report.
132///
133/// Returns `None` when the pipeline never produced a graph (the manifest
134/// did not get that far) or when the proof run could not be set up — both
135/// already recorded as diagnostics by the time this returns.
136fn run_proof(
137    args: &ValidateArgs,
138    graph: Option<&DataflowGraph>,
139    diagnostics: &mut Vec<CliDiagnostic>,
140) -> Option<VerificationReport> {
141    let Some(graph) = graph else {
142        diagnostics.push(CliDiagnostic::prove_error(
143            "--prove needs a graph, and this manifest did not produce one",
144        ));
145        return None;
146    };
147
148    let profile = match &args.profile {
149        Some(path) => match Profile::from_file(path) {
150            Ok(profile) => profile,
151            Err(err) => {
152                diagnostics.push(CliDiagnostic::prove_error(err.to_string()));
153                return None;
154            }
155        },
156        None => Profile::empty(),
157    };
158    // Report *every* mismatch between the profile and the graph, not only
159    // the first one `prove` would stop at: a profile is hand-written
160    // configuration, and fixing it one error per run is a poor trade.
161    let profile_errors = profile.validate_against(graph);
162    if !profile_errors.is_empty() {
163        for error in &profile_errors {
164            diagnostics.push(CliDiagnostic::prove_error(error.to_string()));
165        }
166        return None;
167    }
168
169    let report = match prove(graph, &ProveOptions::with_profile(profile)) {
170        Ok(report) => report,
171        Err(err) => {
172            diagnostics.push(CliDiagnostic::prove_error(err.to_string()));
173            return None;
174        }
175    };
176
177    for outcome in report.violations() {
178        let headline = outcome
179            .discharge
180            .counterexample()
181            .map_or("obligation refuted", |c| c.headline.as_str());
182        diagnostics.push(CliDiagnostic::prove_violation(
183            &outcome.obligation.heading(),
184            headline,
185        ));
186    }
187    if !astrs_verify::solver_available() {
188        diagnostics.push(CliDiagnostic::prove_unavailable());
189    } else if !report.everything_discharged() {
190        let summary = report.summary();
191        diagnostics.push(CliDiagnostic::prove_incomplete(
192            report.gap_count().saturating_sub(summary.inconclusive),
193            summary.inconclusive,
194        ));
195    }
196    Some(report)
197}
198
199/// Run the parse → validate → expand → validate → graph → diagnostics
200/// pipeline, stopping early after any stage that leaves nothing
201/// meaningful for the next one to do.
202fn collect_diagnostics(args: &ValidateArgs) -> (Vec<CliDiagnostic>, Option<DataflowGraph>) {
203    let mut diagnostics = Vec::new();
204
205    let content = match std::fs::read_to_string(&args.manifest_path) {
206        Ok(content) => content,
207        Err(err) => {
208            diagnostics.push(CliDiagnostic::io(format!(
209                "failed to read `{}`: {err}",
210                args.manifest_path.display()
211            )));
212            return (diagnostics, None);
213        }
214    };
215
216    let manifest = match Manifest::from_yaml_str(&content) {
217        Ok(manifest) => manifest,
218        Err(err) => {
219            diagnostics.push(CliDiagnostic::parse(&err));
220            return (diagnostics, None);
221        }
222    };
223
224    if let Err(errors) = manifest.validate() {
225        diagnostics.extend(errors.errors().iter().map(CliDiagnostic::structural));
226        return (diagnostics, None);
227    }
228
229    let base_dir = base_dir_of(&args.manifest_path);
230    let loader = FsModuleLoader;
231    let expanded = match manifest.expand(&base_dir, &loader) {
232        Ok(expanded) => expanded,
233        Err(err) => {
234            diagnostics.push(CliDiagnostic::expand(&err));
235            return (diagnostics, None);
236        }
237    };
238
239    // Module expansion can produce a shape `validate` has not already
240    // checked (the flattened id namespace, boundary types transplanted
241    // onto internal nodes) — see `astrs_manifest::expand`'s own
242    // recommendation to re-validate the flattened result.
243    if let Err(errors) = expanded.validate() {
244        diagnostics.extend(errors.errors().iter().map(CliDiagnostic::structural));
245        return (diagnostics, None);
246    }
247
248    match DataflowGraph::from_manifest(&expanded) {
249        Ok((graph, construction_diagnostics)) => {
250            diagnostics.extend(construction_diagnostics.iter().map(CliDiagnostic::graph));
251            diagnostics.extend(graph.diagnostics().iter().map(CliDiagnostic::graph));
252            (diagnostics, Some(graph))
253        }
254        Err(err) => {
255            diagnostics.push(CliDiagnostic::graph_build_error(&err));
256            (diagnostics, None)
257        }
258    }
259}
260
261/// The directory `manifest_path`'s own `module:` references resolve
262/// against — its parent directory, or `.` when `manifest_path` is a bare
263/// filename with no parent segment at all (never the process's cwd
264/// implicitly; `.` here is that same cwd made an explicit, documented
265/// choice for the common "manifest lives in the invocation directory"
266/// case).
267fn base_dir_of(manifest_path: &Path) -> PathBuf {
268    match manifest_path.parent() {
269        Some(parent) if !parent.as_os_str().is_empty() => parent.to_path_buf(),
270        _ => PathBuf::from("."),
271    }
272}
273
274fn render(
275    out: &mut dyn Write,
276    args: &ValidateArgs,
277    report: &ValidateReport,
278) -> Result<(), CliError> {
279    if args.json {
280        let json = serde_json::to_string_pretty(report).unwrap_or_else(|err| {
281            format!("{{\"error\": \"failed to serialize validate report: {err}\"}}")
282        });
283        writeln!(out, "{json}").map_err(|e| CliError::io("<output>", e))?;
284        return Ok(());
285    }
286
287    if report.diagnostics.is_empty() {
288        writeln!(out, "{}: clean", report.manifest_path)
289            .map_err(|e| CliError::io("<output>", e))?;
290    } else {
291        writeln!(out, "{}", render_human(&report.diagnostics, args.color))
292            .map_err(|e| CliError::io("<output>", e))?;
293        let error_count = report
294            .diagnostics
295            .iter()
296            .filter(|d| d.severity == Severity::Error)
297            .count();
298        let warning_count = report
299            .diagnostics
300            .iter()
301            .filter(|d| d.severity == Severity::Warning)
302            .count();
303        writeln!(out, "{error_count} error(s), {warning_count} warning(s)")
304            .map_err(|e| CliError::io("<output>", e))?;
305    }
306
307    // The proof report comes last and in full: the one-line diagnostics
308    // above say *that* an obligation failed, and this says why, with the
309    // counterexample.
310    if let Some(proof) = &report.proof {
311        writeln!(out).map_err(|e| CliError::io("<output>", e))?;
312        write!(
313            out,
314            "{}",
315            render_proof(
316                proof,
317                &RenderOptions {
318                    color: args.color,
319                    show_systems: false,
320                }
321            )
322        )
323        .map_err(|e| CliError::io("<output>", e))?;
324    }
325    Ok(())
326}
327
328#[cfg(test)]
329mod tests {
330    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
331    use super::*;
332
333    fn write_temp(name: &str, content: &str) -> PathBuf {
334        // A monotonic counter, not just `(pid, name)`, disambiguates the
335        // directory -- see `command::graph`'s own test helper for the
336        // observed race this guards against if a future test ever reuses
337        // an existing `name` under cargo's multi-threaded test runner.
338        static COUNTER: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
339        let n = COUNTER.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
340        let dir = std::env::temp_dir().join(format!(
341            "astrs-cli-validate-test-{}-{name}-{n}",
342            std::process::id()
343        ));
344        std::fs::create_dir_all(&dir).unwrap();
345        let path = dir.join("manifest.yaml");
346        std::fs::write(&path, content).unwrap();
347        path
348    }
349
350    fn args(path: PathBuf) -> ValidateArgs {
351        ValidateArgs {
352            manifest_path: path,
353            prove: false,
354            profile: None,
355            json: false,
356            color: false,
357        }
358    }
359
360    /// The clean two-node pipeline used by the `--prove` tests: a timer
361    /// drives it, so nothing can starve.
362    const LIVE: &str = "\
363nodes:
364  - id: camera
365    path: ./camera
366    inputs:
367      tick:
368        source: astrs/timer/hz/10
369        queue_size: 1
370    outputs: [frames]
371  - id: sink
372    path: ./sink
373    inputs:
374      frames:
375        source: camera/frames
376        queue_size: 1
377";
378
379    /// Two nodes waiting on each other, with nothing to start them.
380    #[cfg(feature = "verify")]
381    const DEADLOCKED: &str = "\
382nodes:
383  - id: a
384    path: ./a
385    inputs: { i: b/out }
386    outputs: [out]
387  - id: b
388    path: ./b
389    inputs: { i: a/out }
390    outputs: [out]
391";
392
393    #[test]
394    fn missing_file_is_an_io_diagnostic_with_exit_code_two() {
395        let mut out = Vec::new();
396        let a = args(std::env::temp_dir().join("astrs-cli-does-not-exist.yaml"));
397        let report = run(&mut out, &a).unwrap();
398        assert_eq!(report.exit_code(), 2);
399        assert_eq!(report.diagnostics.len(), 1);
400        assert_eq!(report.diagnostics[0].source, crate::diagnostic::Source::Io);
401    }
402
403    #[test]
404    fn malformed_yaml_is_a_parse_diagnostic() {
405        let path = write_temp("malformed", "nodes: [");
406        let mut out = Vec::new();
407        let report = run(&mut out, &args(path)).unwrap();
408        assert_eq!(report.exit_code(), 2);
409        assert_eq!(
410            report.diagnostics[0].source,
411            crate::diagnostic::Source::Parse
412        );
413    }
414
415    #[test]
416    fn structural_violation_is_reported() {
417        let path = write_temp(
418            "dup-id",
419            "nodes:\n  - id: x\n    path: ./x\n  - id: x\n    path: ./y\n",
420        );
421        let mut out = Vec::new();
422        let report = run(&mut out, &args(path)).unwrap();
423        assert_eq!(report.exit_code(), 2);
424        assert!(
425            report
426                .diagnostics
427                .iter()
428                .any(|d| d.source == crate::diagnostic::Source::Structural)
429        );
430    }
431
432    #[test]
433    fn clean_manifest_has_no_diagnostics_and_exit_code_zero() {
434        let path = write_temp(
435            "clean",
436            "nodes:\n  - id: camera\n    path: ./camera\n    outputs: [frames]\n  - id: sink\n    path: ./sink\n    inputs:\n      frames: camera/frames\n",
437        );
438        let mut out = Vec::new();
439        let report = run(&mut out, &args(path)).unwrap();
440        assert_eq!(
441            report.diagnostics.len(),
442            0,
443            "diagnostics: {:?}",
444            report.diagnostics
445        );
446        assert_eq!(report.exit_code(), 0);
447        let text = String::from_utf8(out).unwrap();
448        assert!(text.contains("clean"));
449    }
450
451    #[test]
452    fn unconsumed_output_is_an_info_diagnostic_with_exit_code_zero() {
453        // `UnconsumedOutput` is `Severity::Info` (it does not, by itself,
454        // make the graph unsafe to run) -- reported, but does not fail
455        // `validate`.
456        let path = write_temp(
457            "unconsumed",
458            "nodes:\n  - id: camera\n    path: ./camera\n    outputs: [frames]\n",
459        );
460        let mut out = Vec::new();
461        let report = run(&mut out, &args(path)).unwrap();
462        assert_eq!(report.diagnostics.len(), 1);
463        assert_eq!(report.diagnostics[0].severity, astrs_graph::Severity::Info);
464        assert_eq!(report.exit_code(), 0);
465    }
466
467    #[test]
468    fn a_plain_cycle_is_a_warning_with_exit_code_one() {
469        let path = write_temp(
470            "cycle",
471            "nodes:\n  - id: a\n    path: ./a\n    outputs: [out]\n    inputs:\n      i: b/out\n  - id: b\n    path: ./b\n    outputs: [out]\n    inputs:\n      i: a/out\n",
472        );
473        let mut out = Vec::new();
474        let report = run(&mut out, &args(path)).unwrap();
475        assert_eq!(report.exit_code(), 1);
476        assert!(
477            report
478                .diagnostics
479                .iter()
480                .any(|d| d.severity == astrs_graph::Severity::Warning)
481        );
482    }
483
484    #[test]
485    fn collect_diagnostics_hands_the_graph_back_for_proving() {
486        let a = args(write_temp("graph-out", LIVE));
487        let (diagnostics, graph) = collect_diagnostics(&a);
488        assert!(diagnostics.is_empty(), "{diagnostics:?}");
489        assert_eq!(graph.map(|g| g.node_count()), Some(2));
490    }
491
492    #[test]
493    fn a_manifest_that_never_became_a_graph_cannot_be_proved() {
494        let mut a = args(write_temp("no-graph", "nodes: ["));
495        a.prove = true;
496        let mut out = Vec::new();
497        let report = run(&mut out, &a).expect("a parse failure is reported, not raised");
498        assert!(report.proof.is_none());
499        assert!(
500            report
501                .diagnostics
502                .iter()
503                .any(|d| d.source == crate::diagnostic::Source::Prove)
504        );
505    }
506
507    #[test]
508    fn a_profile_that_does_not_match_the_graph_reports_every_mismatch() {
509        let dir = write_temp("bad-profile", LIVE);
510        let profile = dir.with_file_name("verify.yaml");
511        std::fs::write(
512            &profile,
513            "nodes:\n  ghost:\n    wcet: 0.001\n  phantom:\n    wcet: 0.002\n",
514        )
515        .unwrap();
516        let mut a = args(dir);
517        a.prove = true;
518        a.profile = Some(profile);
519        let mut out = Vec::new();
520        let report = run(&mut out, &a).expect("a profile failure is reported, not raised");
521        assert!(report.proof.is_none());
522        let prove_errors = report
523            .diagnostics
524            .iter()
525            .filter(|d| d.source == crate::diagnostic::Source::Prove)
526            .count();
527        assert_eq!(prove_errors, 2, "both mismatches must be reported at once");
528    }
529
530    #[test]
531    fn a_missing_profile_file_is_reported_not_ignored() {
532        let mut a = args(write_temp("missing-profile", LIVE));
533        a.prove = true;
534        a.profile = Some(std::env::temp_dir().join("astrs-cli-no-such-profile.yaml"));
535        let mut out = Vec::new();
536        let report = run(&mut out, &a).expect("a missing profile is reported, not raised");
537        assert!(report.proof.is_none());
538        assert!(
539            report
540                .diagnostics
541                .iter()
542                .any(|d| d.message.contains("verification profile"))
543        );
544    }
545
546    #[test]
547    #[cfg(not(feature = "verify"))]
548    fn without_the_feature_prove_encodes_and_then_reports_no_solver() {
549        let mut a = args(write_temp("prove-nofeature", LIVE));
550        a.prove = true;
551        let mut out = Vec::new();
552        let err = run(&mut out, &a).unwrap_err();
553        assert!(matches!(err, CliError::ProofUnavailable), "{err:?}");
554        assert_eq!(err.exit_code(), crate::error::EXIT_UNAVAILABLE);
555        let printed = String::from_utf8(out).unwrap();
556        assert!(printed.contains("--features verify"), "{printed}");
557        assert!(printed.contains("graph proofs"), "{printed}");
558    }
559
560    #[test]
561    #[cfg(feature = "verify")]
562    fn a_live_graph_without_a_profile_proves_clean_but_exits_one() {
563        let mut a = args(write_temp("prove-clean", LIVE));
564        a.prove = true;
565        let mut out = Vec::new();
566        let report = run(&mut out, &a).unwrap();
567        let proof = report.proof.as_ref().expect("a proof was run");
568        assert!(!proof.has_violations());
569        // Without a profile, queue boundedness has no service time, so the
570        // run is honest rather than clean: exit 1, not 0.
571        assert_eq!(report.exit_code(), 1);
572        let printed = String::from_utf8(out).unwrap();
573        assert!(printed.contains("no obligation was violated"), "{printed}");
574    }
575
576    #[test]
577    #[cfg(feature = "verify")]
578    fn a_deadlocking_graph_is_an_error_with_exit_code_two() {
579        let mut a = args(write_temp("prove-deadlock", DEADLOCKED));
580        a.prove = true;
581        let mut out = Vec::new();
582        let report = run(&mut out, &a).unwrap();
583        assert_eq!(report.exit_code(), 2);
584        let proof = report.proof.as_ref().expect("a proof was run");
585        assert!(proof.has_violations());
586        assert!(
587            report.diagnostics.iter().any(|d| {
588                d.source == crate::diagnostic::Source::Prove
589                    && d.severity == astrs_graph::Severity::Error
590                    && d.message.contains("deadlock freedom")
591            }),
592            "{:?}",
593            report.diagnostics
594        );
595        let printed = String::from_utf8(out).unwrap();
596        assert!(printed.contains("can never fire"), "{printed}");
597        assert!(printed.contains("fix:"), "{printed}");
598    }
599
600    #[test]
601    #[cfg(feature = "verify")]
602    fn a_full_profile_lets_the_run_reach_a_verdict_everywhere() {
603        let manifest = write_temp("prove-profiled", LIVE);
604        let profile = manifest.with_file_name("verify.yaml");
605        std::fs::write(
606            &profile,
607            "nodes:\n  camera:\n    wcet: 0.001\n  sink:\n    wcet: 0.001\n",
608        )
609        .unwrap();
610        let mut a = args(manifest);
611        a.prove = true;
612        a.profile = Some(profile);
613        let mut out = Vec::new();
614        let report = run(&mut out, &a).unwrap();
615        let proof = report.proof.as_ref().expect("a proof was run");
616        assert!(proof.everything_discharged(), "{:?}", proof.summary());
617        assert_eq!(report.exit_code(), 0);
618    }
619
620    #[test]
621    fn prove_output_is_appended_after_the_diagnostics() {
622        let mut a = args(write_temp("prove-order", LIVE));
623        a.prove = true;
624        let mut out = Vec::new();
625        let _ = run(&mut out, &a);
626        let printed = String::from_utf8(out).unwrap();
627        assert!(printed.contains("graph proofs"), "{printed}");
628    }
629
630    #[test]
631    fn prove_json_nests_the_whole_report() {
632        let mut a = args(write_temp("prove-json", LIVE));
633        a.prove = true;
634        a.json = true;
635        let mut out = Vec::new();
636        let _ = run(&mut out, &a);
637        let text = String::from_utf8(out).unwrap();
638        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
639        assert!(value["proof"]["obligations"].is_array(), "{text}");
640        assert!(value["proof"]["window_seconds"].is_number(), "{text}");
641    }
642
643    #[test]
644    fn json_output_is_valid_json_and_contains_the_manifest_path() {
645        let path = write_temp("json", "nodes:\n  - id: solo\n    path: ./solo\n");
646        let mut out = Vec::new();
647        let mut a = args(path.clone());
648        a.json = true;
649        let report = run(&mut out, &a).unwrap();
650        assert_eq!(report.exit_code(), 0);
651        let text = String::from_utf8(out).unwrap();
652        let value: serde_json::Value = serde_json::from_str(&text).unwrap();
653        assert_eq!(
654            value["manifest_path"].as_str(),
655            Some(path.display().to_string().as_str())
656        );
657    }
658
659    #[test]
660    fn module_that_fails_to_expand_is_an_expand_diagnostic() {
661        let path = write_temp(
662            "bad-module",
663            "nodes:\n  - id: m\n    module: ./missing.yaml\n",
664        );
665        let mut out = Vec::new();
666        let report = run(&mut out, &args(path)).unwrap();
667        assert_eq!(report.exit_code(), 2);
668        assert!(
669            report
670                .diagnostics
671                .iter()
672                .any(|d| d.source == crate::diagnostic::Source::Expand)
673        );
674    }
675
676    #[test]
677    fn base_dir_of_bare_filename_is_dot() {
678        assert_eq!(base_dir_of(Path::new("manifest.yaml")), PathBuf::from("."));
679    }
680
681    #[test]
682    fn base_dir_of_nested_path_is_its_parent() {
683        assert_eq!(
684            base_dir_of(Path::new("/graphs/sub/manifest.yaml")),
685            PathBuf::from("/graphs/sub")
686        );
687    }
688}