kicad_monkey_core/testing/synthetics.rs
1//! Find KiCad Monkey's synthetic test cases.
2//!
3//! Synthetic cases are small KiCad projects authored for one feature. They
4//! live in git at `tests/cases/<topic>/<case>/` in the KiCad Monkey source
5//! tree, and each one is a whole project:
6//!
7//! - `input/` holds the `.kicad_pro`, the `.kicad_sch` and the `.kicad_pcb`
8//! (the board may be blank);
9//! - `reference_output/` holds the checked-in kicad-cli references, when the
10//! case has any;
11//! - `output/` is ignored by git and holds results for people to look at;
12//! - `case_metadata.json` describes the case, hashes its files and records
13//! the kicad-cli version that made the references.
14//!
15//! `WN_KICAD_SYNTHETICS` names the folder that holds the topics. When it is
16//! unset or blank, the in-repo `tests/cases` folder is used, so the cases can
17//! move later by changing only the variable. Python has the same resolver,
18//! `kicad_monkey.testing.synthetics`, and the two behave alike.
19//!
20//! Cases are shared test input: a test that runs kicad-cli (which writes a
21//! `.kicad_prl` next to any project it opens) or writes anything else copies
22//! the input to a temporary folder first.
23
24use std::ffi::OsStr;
25use std::io;
26use std::path::{Component, Path, PathBuf};
27
28/// The environment variable that names the synthetic cases folder.
29pub const SYNTHETICS_ENV: &str = "WN_KICAD_SYNTHETICS";
30/// The file that makes a `<topic>/<case>/` folder a case.
31pub const CASE_METADATA_FILE: &str = "case_metadata.json";
32/// Trimmed from both ends of the variable's value.
33const BLANKS: [char; 4] = [' ', '\t', '\r', '\n'];
34
35/// `tests/cases` of the KiCad Monkey source tree this crate was built from.
36#[must_use]
37pub fn default_synthetic_cases_root() -> PathBuf {
38 let mut root = PathBuf::new();
39 for component in Path::new(env!("CARGO_MANIFEST_DIR"))
40 .join("../../../tests/cases")
41 .components()
42 {
43 match component {
44 Component::ParentDir => {
45 root.pop();
46 }
47 Component::CurDir => {}
48 other => root.push(other.as_os_str()),
49 }
50 }
51 root
52}
53
54/// The synthetic cases folder for a `WN_KICAD_SYNTHETICS` value.
55///
56/// `value` is the variable's value, or `None` when it is unset. An unset
57/// value, or one of only spaces, tabs and line breaks, selects
58/// [`default_synthetic_cases_root`]. Any other value, with those characters
59/// trimmed from both ends, must be an absolute path. The folder must exist.
60///
61/// # Errors
62///
63/// `InvalidInput` for a relative or non-Unicode value, `NotFound` when the
64/// folder does not exist.
65pub fn resolve_synthetic_cases_root(value: Option<&OsStr>) -> io::Result<PathBuf> {
66 let text = match value {
67 None => "",
68 Some(value) => value.to_str().ok_or_else(|| {
69 invalid_input(format!(
70 "{SYNTHETICS_ENV} is not valid Unicode: {}",
71 value.to_string_lossy()
72 ))
73 })?,
74 }
75 .trim_matches(BLANKS);
76 let root = if text.is_empty() {
77 default_synthetic_cases_root()
78 } else {
79 let root = Path::new(text);
80 if !root.is_absolute() {
81 return Err(invalid_input(format!(
82 "{SYNTHETICS_ENV} must be an absolute path: {text}"
83 )));
84 }
85 root.components().collect()
86 };
87 if !root.is_dir() {
88 return Err(io::Error::new(
89 io::ErrorKind::NotFound,
90 format!(
91 "KiCad synthetic cases folder not found: {} \
92 (set {SYNTHETICS_ENV} to the folder that holds <topic>/<case>/)",
93 root.display()
94 ),
95 ));
96 }
97 Ok(root)
98}
99
100/// The synthetic cases folder that `WN_KICAD_SYNTHETICS` selects.
101///
102/// # Errors
103///
104/// As [`resolve_synthetic_cases_root`].
105pub fn synthetic_cases_root() -> io::Result<PathBuf> {
106 resolve_synthetic_cases_root(std::env::var_os(SYNTHETICS_ENV).as_deref())
107}
108
109/// The `<topic>/<case>/` folder, which holds `case_metadata.json`.
110///
111/// # Errors
112///
113/// `InvalidInput` when `topic` or `case` is not a plain folder name (ASCII
114/// letters, digits, `_` and `-`), `NotFound` when the folder or its
115/// metadata does not exist, and the errors of [`synthetic_cases_root`].
116pub fn synthetic_case(topic: &str, case: &str) -> io::Result<PathBuf> {
117 check_name(topic, "topic")?;
118 check_name(case, "case")?;
119 let case_dir = synthetic_cases_root()?.join(topic).join(case);
120 if !case_dir.join(CASE_METADATA_FILE).is_file() {
121 return Err(io::Error::new(
122 io::ErrorKind::NotFound,
123 format!("KiCad synthetic case not found: {}", case_dir.display()),
124 ));
125 }
126 Ok(case_dir)
127}
128
129/// Enumerate every `<topic>/<case>/` folder holding `case_metadata.json`,
130/// sorted by `(topic, case)`. When `topic` is `Some`, filters to that topic.
131///
132/// # Errors
133///
134/// `InvalidInput` when `topic` is not a plain folder name, or any I/O error
135/// from [`synthetic_cases_root`] or directory traversal.
136pub fn iter_synthetic_cases(topic: Option<&str>) -> io::Result<Vec<PathBuf>> {
137 let root = synthetic_cases_root()?;
138 let topic_dirs: Vec<PathBuf> = match topic {
139 Some(name) => {
140 check_name(name, "topic")?;
141 let dir = root.join(name);
142 if dir.is_dir() { vec![dir] } else { Vec::new() }
143 }
144 None => {
145 let mut dirs: Vec<PathBuf> = std::fs::read_dir(&root)?
146 .filter_map(Result::ok)
147 .map(|entry| entry.path())
148 .filter(|path| path.is_dir())
149 .collect();
150 dirs.sort();
151 dirs
152 }
153 };
154 let mut out = Vec::new();
155 for topic_dir in topic_dirs {
156 let mut cases: Vec<PathBuf> = std::fs::read_dir(&topic_dir)?
157 .filter_map(Result::ok)
158 .map(|entry| entry.path())
159 .filter(|path| path.is_dir() && path.join(CASE_METADATA_FILE).is_file())
160 .collect();
161 cases.sort();
162 out.extend(cases);
163 }
164 Ok(out)
165}
166
167fn check_name(name: &str, label: &str) -> io::Result<()> {
168 let plain = !name.is_empty()
169 && name
170 .bytes()
171 .all(|byte| byte.is_ascii_alphanumeric() || byte == b'_' || byte == b'-');
172 if plain {
173 Ok(())
174 } else {
175 Err(invalid_input(format!(
176 "synthetic case {label} must be a plain folder name: \"{name}\""
177 )))
178 }
179}
180
181fn invalid_input(message: String) -> io::Error {
182 io::Error::new(io::ErrorKind::InvalidInput, message)
183}