1use regex::Regex;
51use std::path::{Path, PathBuf};
52use std::process::Command;
53use std::time::{Duration, Instant};
54
55pub const DEFAULT_TIMEOUT_SECS: u64 = 90;
57
58const DIRECTIVE_KEYS: &[&str] = &[
60 "run",
61 "expect",
62 "expect-fail",
63 "expect_fail",
64 "requires",
65 "timeout",
66 "case",
67];
68
69pub struct VerifyCase {
71 pub name: String,
72 pub run_args: Vec<String>,
73 pub again: Vec<Vec<String>>,
81 pub session_cwd: bool,
88 pub expects: Vec<Regex>,
89 pub expect_fails: Vec<Regex>,
90 pub timeout: u64,
91}
92
93impl VerifyCase {
94 fn new(name: impl Into<String>) -> Self {
95 VerifyCase {
96 name: name.into(),
97 run_args: Vec::new(),
98 again: Vec::new(),
99 session_cwd: false,
100 expects: Vec::new(),
101 expect_fails: Vec::new(),
102 timeout: DEFAULT_TIMEOUT_SECS,
103 }
104 }
105}
106
107pub struct VerifyPlan {
109 pub requires: Option<String>,
111 pub cases: Vec<VerifyCase>,
112}
113
114impl VerifyPlan {
115 pub fn parse(src: &str) -> Result<VerifyPlan, String> {
117 let mut plan = parse_directives(src)?;
118 merge_verify_block(src, &mut plan)?;
119 Ok(plan)
120 }
121
122 pub fn is_empty(&self) -> bool {
124 self.requires.is_none() && self.cases.is_empty()
125 }
126}
127
128fn compile(v: &str) -> Result<Regex, String> {
129 Regex::new(v).map_err(|e| format!("bad regex {v:?}: {e}"))
130}
131
132fn parse_directives(src: &str) -> Result<VerifyPlan, String> {
135 let mut requires: Option<String> = None;
136 let mut cases: Vec<VerifyCase> = Vec::new();
137 let mut cur: Option<VerifyCase> = None;
138
139 for raw in src.lines() {
140 let line = raw.trim_start();
141 let Some(rest) = line.strip_prefix("#@") else {
142 continue;
143 };
144 let rest = rest.trim();
145 let (kw, val) = match rest.split_once(char::is_whitespace) {
146 Some((k, v)) => (k.trim_end_matches(':'), v.trim()),
147 None => (rest.trim_end_matches(':'), ""),
148 };
149 macro_rules! case {
150 () => {
151 cur.get_or_insert_with(|| VerifyCase::new("default"))
152 };
153 }
154 match kw {
155 "requires" => requires = Some(val.to_string()),
156 "case" => {
157 if let Some(c) = cur.take() {
158 cases.push(c);
159 }
160 cur = Some(VerifyCase::new(val));
161 }
162 "run" => case!().run_args = val.split_whitespace().map(String::from).collect(),
163 "again" => case!()
164 .again
165 .push(val.split_whitespace().map(String::from).collect()),
166 "session" => match val {
167 "cwd" => case!().session_cwd = true,
168 other => return Err(format!("unknown `#@ session {other}` (only `cwd`)")),
169 },
170 "expect" => case!().expects.push(compile(val)?),
171 "expect-fail" | "expect_fail" => case!().expect_fails.push(compile(val)?),
172 "timeout" => {
173 case!().timeout = val.parse().map_err(|_| format!("bad timeout {val:?}"))?
174 }
175 other => return Err(format!("unknown `#@ {other}` directive")),
176 }
177 }
178 if let Some(c) = cur.take() {
179 cases.push(c);
180 }
181 Ok(VerifyPlan { requires, cases })
182}
183
184fn merge_verify_block(src: &str, plan: &mut VerifyPlan) -> Result<(), String> {
187 let Ok(doc) = serde_yaml::from_str::<serde_yaml::Value>(src) else {
190 return Ok(());
191 };
192 let Some(block) = doc.get("verify") else {
193 return Ok(());
194 };
195 match block {
196 serde_yaml::Value::Sequence(items) => {
197 for (i, item) in items.iter().enumerate() {
198 plan.cases.push(case_from_map(item, None, i)?);
199 }
200 }
201 serde_yaml::Value::Mapping(m) => {
202 let all_directives = m
203 .keys()
204 .all(|k| k.as_str().is_some_and(|s| DIRECTIVE_KEYS.contains(&s)));
205 if all_directives {
206 if let Some(req) = m.get("requires").and_then(|v| v.as_str()) {
209 plan.requires = Some(req.to_string());
210 } else {
211 plan.cases.push(case_from_map(block, None, 0)?);
212 }
213 } else {
214 for (k, v) in m {
216 let name = k.as_str().ok_or("verify: case name must be a string")?;
217 plan.cases.push(case_from_map(v, Some(name), 0)?);
218 }
219 }
220 }
221 _ => return Err("verify: must be a map or a list of cases".to_string()),
222 }
223 Ok(())
224}
225
226fn case_from_map(
229 v: &serde_yaml::Value,
230 name_override: Option<&str>,
231 idx: usize,
232) -> Result<VerifyCase, String> {
233 let m = v.as_mapping().ok_or("verify: each case must be a map")?;
234 let get = |k: &str| m.get(serde_yaml::Value::from(k));
235 let name = name_override
236 .map(String::from)
237 .or_else(|| get("case").and_then(|x| x.as_str()).map(String::from))
238 .unwrap_or_else(|| format!("case-{idx}"));
239 let mut case = VerifyCase::new(name);
240 if let Some(run) = get("run").and_then(|x| x.as_str()) {
241 case.run_args = run.split_whitespace().map(String::from).collect();
242 }
243 for s in strings_of(get("expect")) {
244 case.expects.push(compile(&s)?);
245 }
246 for s in strings_of(get("expect-fail").or_else(|| get("expect_fail"))) {
247 case.expect_fails.push(compile(&s)?);
248 }
249 if let Some(t) = get("timeout").and_then(|x| x.as_u64()) {
250 case.timeout = t;
251 }
252 Ok(case)
253}
254
255fn strings_of(v: Option<&serde_yaml::Value>) -> Vec<String> {
257 match v {
258 Some(serde_yaml::Value::String(s)) => vec![s.clone()],
259 Some(serde_yaml::Value::Sequence(items)) => items
260 .iter()
261 .filter_map(|x| x.as_str().map(String::from))
262 .collect(),
263 _ => Vec::new(),
264 }
265}
266
267pub enum Outcome {
271 Pass,
272 Skip(String),
273 Fail(String),
274}
275
276pub fn run_case(
283 binary: &Path,
284 workload_ref: &str,
285 sandbox: &Path,
286 label: &str,
287 case: &VerifyCase,
288) -> Result<(), String> {
289 let safe_label = label.replace(['/', ' ', ':'], "_");
290 let session = sandbox.join(format!("session-{safe_label}"));
291 let case_cwd;
298 let workdir: &Path = if case.session_cwd {
299 case_cwd = sandbox.join(format!("cwd-{safe_label}"));
300 let _ = std::fs::remove_dir_all(&case_cwd);
301 std::fs::create_dir_all(&case_cwd).map_err(|e| format!("create case cwd: {e}"))?;
302 &case_cwd
303 } else {
304 let _ = std::fs::remove_dir_all(&session);
305 sandbox
306 };
307
308 let invoke = |args: &[String]| -> Result<(String, bool, bool), String> {
313 use std::io::Read as _;
314 use std::process::Stdio;
315 let mut cmd = Command::new(binary);
316 cmd.arg("run")
317 .arg(format!("workload={workload_ref}"))
318 .args(args);
319 if !case.session_cwd {
320 cmd.arg("--session-path").arg(&session);
321 }
322 let mut child = cmd
323 .current_dir(workdir)
324 .stdin(Stdio::null())
325 .stdout(Stdio::piped())
326 .stderr(Stdio::piped())
327 .spawn()
328 .map_err(|e| format!("spawn failed: {e}"))?;
329 let mut out_pipe = child.stdout.take().expect("stdout piped");
332 let mut err_pipe = child.stderr.take().expect("stderr piped");
333 let out_h = std::thread::spawn(move || {
334 let mut buf = Vec::new();
335 let _ = out_pipe.read_to_end(&mut buf);
336 buf
337 });
338 let err_h = std::thread::spawn(move || {
339 let mut buf = Vec::new();
340 let _ = err_pipe.read_to_end(&mut buf);
341 buf
342 });
343 let deadline = std::time::Instant::now() + std::time::Duration::from_secs(case.timeout);
344 let (status, timed_out) = loop {
345 if let Some(st) = child.try_wait().map_err(|e| format!("wait failed: {e}"))? {
346 break (st, false);
347 }
348 if std::time::Instant::now() >= deadline {
349 let _ = child.kill();
350 let st = child.wait().map_err(|e| format!("wait failed: {e}"))?;
351 break (st, true);
352 }
353 std::thread::sleep(std::time::Duration::from_millis(25));
354 };
355 let stdout = out_h.join().unwrap_or_default();
356 let stderr = err_h.join().unwrap_or_default();
357 let mut combined = format!(
358 "{}{}",
359 String::from_utf8_lossy(&stdout),
360 String::from_utf8_lossy(&stderr)
361 );
362 if !status.success() {
363 combined.push_str(&format!("\nnmbrs run ended with {status}\n"));
366 }
367 Ok((combined, status.success(), timed_out))
368 };
369
370 let (mut combined, mut succeeded, mut timed_out) = invoke(&case.run_args)?;
371 for (i, extra) in case.again.iter().enumerate() {
372 if !succeeded || timed_out {
373 return Err(format!(
374 "invocation {} of {} failed before the `again` steps completed:
375{combined}",
376 i + 1,
377 case.again.len() + 1
378 ));
379 }
380 let (c, s, to) = invoke(extra)?;
381 combined.push_str(&c);
382 succeeded = s;
383 timed_out = to;
384 }
385 check_case_output(case, &combined, succeeded, timed_out)
386}
387
388const FAILURE_TAIL_LINES: usize = 15;
391
392pub fn check_case_output(
400 case: &VerifyCase,
401 combined: &str,
402 succeeded: bool,
403 timed_out: bool,
404) -> Result<(), String> {
405 if timed_out {
406 return Err(format!("timed out after {}s", case.timeout));
407 }
408 if case.expect_fails.is_empty() {
409 if !succeeded {
410 let err = match combined
413 .lines()
414 .find(|l| l.contains("error:") || l.contains("panic"))
415 {
416 Some(line) => line.to_string(),
417 None => {
418 let lines: Vec<&str> = combined.lines().collect();
419 let tail = &lines[lines.len().saturating_sub(FAILURE_TAIL_LINES)..];
420 format!("no error line; the output ended:\n{}", tail.join("\n"))
421 }
422 };
423 return Err(format!("run failed (expected success): {err}"));
424 }
425 } else {
426 if succeeded {
427 return Err("expected a failure (`expect-fail`) but the run succeeded".to_string());
428 }
429 for re in &case.expect_fails {
430 if !re.is_match(combined) {
431 return Err(format!(
432 "expect-fail /{re}/ did not match the failure output"
433 ));
434 }
435 }
436 }
437 for re in &case.expects {
438 if !re.is_match(combined) {
439 return Err(format!("expect /{re}/ did not match the output"));
440 }
441 }
442 Ok(())
443}
444
445pub fn requires_verification_rules(run_ref: &str) -> bool {
456 std::path::Path::new(run_ref)
457 .components()
458 .any(|c| c.as_os_str() == "examples")
459}
460
461pub fn verify_source(
466 binary: &Path,
467 label_root: &str,
468 run_ref: &str,
469 rule_text: &str,
470 sandbox: &Path,
471) -> Vec<(String, Outcome)> {
472 let plan = match VerifyPlan::parse(rule_text) {
473 Ok(p) => p,
474 Err(e) => return vec![(label_root.to_string(), Outcome::Fail(e))],
475 };
476 if let Some(reason) = plan.requires {
477 return vec![(label_root.to_string(), Outcome::Skip(reason))];
478 }
479 if plan.cases.is_empty() {
480 return vec![(
492 label_root.to_string(),
493 if requires_verification_rules(run_ref) {
494 Outcome::Fail(
495 "no verification rules — every workload under `examples/` must \
496 declare them (add `#@ expect …` comments or a `verify:` block)"
497 .into(),
498 )
499 } else {
500 Outcome::Skip("no verification rules — nothing to check".into())
501 },
502 )];
503 }
504 plan.cases
505 .iter()
506 .map(|c| {
507 let label = format!("{label_root}::{}", c.name);
508 let outcome = match run_case(binary, run_ref, sandbox, &label, c) {
509 Ok(()) => Outcome::Pass,
510 Err(e) => Outcome::Fail(format!("{label}: {e}")),
511 };
512 (label, outcome)
513 })
514 .collect()
515}
516
517pub fn verify_file(
521 binary: &Path,
522 label_root: &str,
523 workload: &Path,
524 sandbox: &Path,
525) -> Vec<(String, Outcome)> {
526 let src = match std::fs::read_to_string(workload) {
527 Ok(s) => s,
528 Err(e) => {
529 return vec![(
530 label_root.to_string(),
531 Outcome::Fail(format!("read error: {e}")),
532 )];
533 }
534 };
535 let abs = workload
536 .canonicalize()
537 .unwrap_or_else(|_| workload.to_path_buf());
538 verify_source(binary, label_root, &abs.to_string_lossy(), &src, sandbox)
539}
540
541pub enum WorkloadSource {
544 File(PathBuf),
546 Catalog { name: String, source: String },
548}
549
550pub fn resolve_ref(reference: &str) -> Option<WorkloadSource> {
555 let p = Path::new(reference);
556 if p.is_file() {
557 return Some(WorkloadSource::File(
559 p.canonicalize().unwrap_or_else(|_| p.to_path_buf()),
560 ));
561 }
562 crate::catalog::lookup(reference).map(|w| WorkloadSource::Catalog {
563 name: w.name.to_string(),
564 source: w.source.to_string(),
565 })
566}
567
568pub fn declared_params(reference: &str) -> Option<std::collections::HashMap<String, String>> {
582 let merged = match resolve_ref(reference)? {
583 WorkloadSource::File(path) => crate::extends::load_and_merge(&path).ok()?.0,
587 WorkloadSource::Catalog { name, .. } => {
588 crate::extends::load_and_merge_bundled(crate::catalog::lookup(&name)?)
589 .ok()?
590 .0
591 }
592 };
593 let doc: serde_yaml::Value = serde_yaml::from_str(&merged).ok()?;
594 let params = doc.get("params")?.as_mapping()?;
595 let mut out = std::collections::HashMap::new();
596 for (k, v) in params {
597 let Some(key) = k.as_str() else { continue };
598 let val = match v {
601 serde_yaml::Value::String(s) => s.clone(),
602 serde_yaml::Value::Number(n) => n.to_string(),
603 serde_yaml::Value::Bool(b) => b.to_string(),
604 _ => continue,
605 };
606 out.insert(key.to_string(), val);
607 }
608 Some(out)
609}
610
611#[derive(Default)]
613pub struct VerifySummary {
614 pub passed: usize,
615 pub skipped: Vec<String>,
616 pub failures: Vec<String>,
617 pub timings: Vec<WorkloadTiming>,
620}
621
622#[derive(Debug, Clone, Copy, PartialEq, Eq)]
628pub enum CheckStatus {
629 Pass,
630 Skip,
631 Fail,
632}
633
634#[derive(Debug, Clone)]
636pub struct WorkloadTiming {
637 pub label: String,
638 pub elapsed: Duration,
639 pub status: CheckStatus,
640}
641
642#[derive(Debug, Clone)]
646pub enum CheckProgress {
647 Begin { total: usize },
649 Started { label: String },
651 Finished {
653 label: String,
654 elapsed: Duration,
655 status: CheckStatus,
656 },
657}
658
659pub type ProgressFn<'a> = dyn Fn(CheckProgress) + Sync + 'a;
661
662pub fn no_progress(_: CheckProgress) {}
664
665fn aggregate_status(outcomes: &[(String, Outcome)]) -> CheckStatus {
667 let mut saw_pass = false;
668 let mut saw_skip = false;
669 for (_, o) in outcomes {
670 match o {
671 Outcome::Fail(_) => return CheckStatus::Fail,
672 Outcome::Pass => saw_pass = true,
673 Outcome::Skip(_) => saw_skip = true,
674 }
675 }
676 if saw_skip && !saw_pass {
677 CheckStatus::Skip
678 } else {
679 CheckStatus::Pass
680 }
681}
682
683pub fn verify_path(
688 binary: &Path,
689 path: &Path,
690 sandbox: &Path,
691 progress: &ProgressFn,
692) -> VerifySummary {
693 let _ = std::fs::create_dir_all(sandbox);
694 let mut files: Vec<PathBuf> = Vec::new();
695 if path.is_dir() {
696 collect_yaml(path, &mut files);
697 files.sort();
698 } else {
699 files.push(path.to_path_buf());
700 }
701 progress(CheckProgress::Begin { total: files.len() });
702
703 let acc: std::sync::Mutex<VerifySummary> = std::sync::Mutex::new(VerifySummary::default());
704 let next = std::sync::atomic::AtomicUsize::new(0);
712 let workers = files.len().min(
713 std::thread::available_parallelism()
714 .map(|n| n.get())
715 .unwrap_or(4)
716 .saturating_mul(2)
717 .clamp(1, 16),
718 );
719 std::thread::scope(|s| {
720 for _ in 0..workers {
721 s.spawn(|| {
722 loop {
723 let i = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
724 let Some(f) = files.get(i) else { break };
725 let label = f
726 .file_name()
727 .and_then(|n| n.to_str())
728 .unwrap_or("?")
729 .to_string();
730 progress(CheckProgress::Started {
733 label: label.clone(),
734 });
735 let start = Instant::now();
736 let outcomes = verify_file(binary, &label, f, sandbox);
737 let elapsed = start.elapsed();
738 let status = aggregate_status(&outcomes);
739 let mut g = acc.lock().unwrap();
740 for (lbl, outcome) in outcomes {
741 match outcome {
742 Outcome::Pass => g.passed += 1,
743 Outcome::Skip(r) => g.skipped.push(format!("{lbl}: {r}")),
744 Outcome::Fail(m) => g.failures.push(m),
745 }
746 }
747 g.timings.push(WorkloadTiming {
748 label: label.clone(),
749 elapsed,
750 status,
751 });
752 drop(g);
753 progress(CheckProgress::Finished {
754 label,
755 elapsed,
756 status,
757 });
758 }
759 });
760 }
761 });
762 let mut sum = acc.into_inner().unwrap();
763 sum.skipped.sort();
764 sum.failures.sort();
765 sum
766}
767
768pub fn verify_target(
773 binary: &Path,
774 target: &str,
775 sandbox: &Path,
776 progress: &ProgressFn,
777) -> VerifySummary {
778 let p = Path::new(target);
779 if p.is_dir() {
780 return verify_path(binary, p, sandbox, progress);
781 }
782 let _ = std::fs::create_dir_all(sandbox);
783 progress(CheckProgress::Begin { total: 1 });
787 let label = match &resolve_ref(target) {
788 Some(WorkloadSource::File(path)) => path
789 .file_name()
790 .and_then(|n| n.to_str())
791 .unwrap_or(target)
792 .to_string(),
793 _ => target.to_string(),
794 };
795 progress(CheckProgress::Started {
796 label: label.clone(),
797 });
798 let start = Instant::now();
799 let cases: Vec<(String, Outcome)> = match resolve_ref(target) {
800 Some(WorkloadSource::File(path)) => verify_file(binary, &label, &path, sandbox),
801 Some(WorkloadSource::Catalog { name, source }) => {
802 verify_source(binary, &name, &name, &source, sandbox)
803 }
804 None => vec![(
805 target.to_string(),
806 Outcome::Fail(format!(
807 "no such workload '{target}': not a local file, not a directory, and \
808 no bundled workload by that name (try `nmbrs describe workloads --all`).{}",
809 crate::suggest::did_you_mean(&crate::suggest::suggest_workloads(target))
810 )),
811 )],
812 };
813 let elapsed = start.elapsed();
814 let status = aggregate_status(&cases);
815 let mut sum = VerifySummary::default();
816 for (lbl, outcome) in cases {
817 match outcome {
818 Outcome::Pass => sum.passed += 1,
819 Outcome::Skip(r) => sum.skipped.push(format!("{lbl}: {r}")),
820 Outcome::Fail(m) => sum.failures.push(m),
821 }
822 }
823 sum.timings.push(WorkloadTiming {
824 label: label.clone(),
825 elapsed,
826 status,
827 });
828 progress(CheckProgress::Finished {
829 label,
830 elapsed,
831 status,
832 });
833 sum
834}
835
836pub fn collect_workload_files(dir: &Path) -> Vec<PathBuf> {
841 let mut files = Vec::new();
842 collect_yaml(dir, &mut files);
843 files.sort();
844 files
845}
846
847fn collect_yaml(dir: &Path, out: &mut Vec<PathBuf>) {
848 let Ok(entries) = std::fs::read_dir(dir) else {
849 return;
850 };
851 for e in entries.flatten() {
852 let p = e.path();
853 if p.is_dir() {
854 collect_yaml(&p, out);
855 } else if p.extension().is_some_and(|x| x == "yaml" || x == "yml") {
856 out.push(p);
857 }
858 }
859}
860
861#[cfg(test)]
862mod rules_required_tests {
863 use super::requires_verification_rules;
864
865 #[test]
868 fn examples_require_rules() {
869 assert!(requires_verification_rules(
870 "/repo/examples/optimizer/control.yaml"
871 ));
872 assert!(requires_verification_rules("examples/w.yaml"));
873 assert!(requires_verification_rules(
874 "/repo/nmbrs/examples/modules/module_test.yaml"
875 ));
876 }
877
878 #[test]
881 fn other_locations_do_not_require_rules() {
882 assert!(!requires_verification_rules(
883 "/repo/nmbrs/workloads/cql/incremental_sweep.yaml"
884 ));
885 assert!(!requires_verification_rules("/tmp/scratch.yaml"));
886 assert!(!requires_verification_rules("some_catalog_name"));
887 }
888
889 #[test]
892 fn matches_path_components_not_substrings() {
893 assert!(!requires_verification_rules(
894 "/home/me/examples-scratch/w.yaml"
895 ));
896 assert!(!requires_verification_rules("/home/me/myexamples/w.yaml"));
897 assert!(requires_verification_rules(
898 "/home/me/examples/scratch/w.yaml"
899 ));
900 }
901}
902
903#[cfg(test)]
904mod tests {
905 use super::*;
906
907 #[test]
908 fn comment_and_yaml_forms_are_equivalent() {
909 let comment = "ops: { a: { raw: x } }\n#@ run cycles=3\n#@ expect 0 failed\n";
910 let single = "ops: { a: { raw: x } }\nverify: { run: cycles=3, expect: \"0 failed\" }\n";
911 let listed =
912 "ops: { a: { raw: x } }\nverify:\n - { run: cycles=3, expect: \"0 failed\" }\n";
913 let named =
914 "ops: { a: { raw: x } }\nverify:\n smoke: { run: cycles=3, expect: \"0 failed\" }\n";
915 for src in [comment, single, listed, named] {
916 let p = VerifyPlan::parse(src).expect("parse");
917 assert_eq!(p.cases.len(), 1, "one case for: {src}");
918 assert_eq!(p.cases[0].run_args, vec!["cycles=3"], "run for: {src}");
919 assert_eq!(p.cases[0].expects.len(), 1, "expect for: {src}");
920 }
921 }
922
923 #[test]
924 fn name_keyed_map_yields_named_cases() {
925 let src = "verify:\n alpha: { run: scenario=a, expect: \"x\" }\n beta: { expect: [\"y\", \"z\"] }\n";
926 let p = VerifyPlan::parse(src).unwrap();
927 let names: Vec<&str> = p.cases.iter().map(|c| c.name.as_str()).collect();
928 assert!(
929 names.contains(&"alpha") && names.contains(&"beta"),
930 "names: {names:?}"
931 );
932 let beta = p.cases.iter().find(|c| c.name == "beta").unwrap();
933 assert_eq!(beta.expects.len(), 2);
934 }
935
936 #[test]
937 fn requires_block_skips_the_file() {
938 let p = VerifyPlan::parse("verify: { requires: needs a backend }\n").unwrap();
939 assert_eq!(p.requires.as_deref(), Some("needs a backend"));
940 assert!(p.cases.is_empty());
941 }
942
943 #[test]
944 fn comment_and_block_cases_combine() {
945 let src = "#@ case fromcomment\n#@ expect a\nverify:\n fromblock: { expect: b }\n";
946 let p = VerifyPlan::parse(src).unwrap();
947 let names: Vec<&str> = p.cases.iter().map(|c| c.name.as_str()).collect();
948 assert!(
949 names.contains(&"fromcomment") && names.contains(&"fromblock"),
950 "{names:?}"
951 );
952 }
953
954 #[test]
955 fn resolve_ref_finds_files_and_rejects_unknown_names() {
956 let dir = std::env::temp_dir().join(format!("nmbrs-verify-resolve-{}", std::process::id()));
958 let _ = std::fs::create_dir_all(&dir);
959 let file = dir.join("w.yaml");
960 std::fs::write(&file, "ops: { a: { raw: x } }\n").unwrap();
961 match resolve_ref(file.to_str().unwrap()) {
962 Some(WorkloadSource::File(p)) => assert!(p.is_absolute(), "absolute: {p:?}"),
963 other => panic!(
964 "expected File, got {}",
965 matches!(other, Some(WorkloadSource::Catalog { .. })) as i32
966 ),
967 }
968 assert!(resolve_ref("definitely/not/a/workload").is_none());
971 let _ = std::fs::remove_dir_all(&dir);
972 }
973}