Skip to main content

flm_core/dump/
golden.rs

1//! Golden files: compare a test's output with the expected output kept in a
2//! file, and rewrite that file on request.
3//!
4//! A *golden file* holds the output a test expects, and is kept in version
5//! control beside the test. The test compares its actual output with the file.
6//! When the output changes because the code was meant to change it, run the
7//! test with the environment variable [`UPDATE_GOLDEN`] set to exactly `1`: the
8//! file is then rewritten with the actual output, and the change is reviewed as
9//! an ordinary diff. A golden file that does not exist yet fails the
10//! comparison, and the failure message shows the actual output and how to
11//! create the file. The caller passes the file's path; by convention a test
12//! suite keeps its golden files under `tests/goldens/<suite>/`.
13//!
14//! There are two kinds of golden file:
15//!
16//! - **Text** ([`check_text_golden`], [`assert_text_golden`]): compared byte
17//!   for byte.
18//! - **JSON** ([`check_json_golden`], [`assert_json_golden`]): the expected
19//!   value is a techy serialized value, such as a
20//!   [projection](crate::dump::project). The file is parsed back into a
21//!   serialized value and compared with the actual value, so a file a person
22//!   reindented by hand still matches. Two serialized values are equal exactly
23//!   when [`to_json`](crate::dump::json::to_json) writes the same text for
24//!   them, so the comparison ignores only spacing and indentation.
25//!
26//! Each kind comes in two forms. The `check_` functions take the
27//! [`GoldenMode`] as an argument and return a [`GoldenError`] on failure, so
28//! their behavior can be tested without touching the process environment. The
29//! `assert_` functions read the mode from [`UPDATE_GOLDEN`] and panic with the
30//! error's message; use them in tests.
31//!
32//! This module is the only part of `flm-core` that reads or writes files;
33//! nothing in the processing of a document touches the file system.
34
35use std::fmt;
36use std::path::{Path, PathBuf};
37
38use techy::serialize::SerialValue;
39
40use crate::dump::json::{from_json, to_json_pretty};
41
42/// The name of the environment variable that switches the `assert_` functions
43/// to update mode: `UPDATE_GOLDEN`.
44///
45/// Set to exactly `1`, it selects [`GoldenMode::Update`]; any other value, and
46/// the variable being unset, select [`GoldenMode::Compare`]
47/// ([`GoldenMode::from_env`]).
48pub const UPDATE_GOLDEN: &str = "UPDATE_GOLDEN";
49
50/// What a golden check does: compare the actual output with the golden file,
51/// or rewrite the file with the actual output.
52///
53/// The `check_` functions take the mode as an argument; the `assert_` functions
54/// read it from the environment ([`GoldenMode::from_env`]).
55#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
56pub enum GoldenMode {
57    /// Compare the actual output with the golden file (the default).
58    #[default]
59    Compare,
60    /// Write the actual output to the golden file, creating the directories
61    /// above it; the check then succeeds unless the write fails or, for a JSON
62    /// golden file, the actual value has no JSON form.
63    Update,
64}
65
66impl GoldenMode {
67    /// Returns the mode the [`UPDATE_GOLDEN`] environment variable of the
68    /// process selects: [`Update`](GoldenMode::Update) when it is set to exactly
69    /// `1`, [`Compare`](GoldenMode::Compare) for anything else, including unset,
70    /// empty and `true`.
71    pub fn from_env() -> GoldenMode {
72        GoldenMode::from_setting(std::env::var(UPDATE_GOLDEN).ok().as_deref())
73    }
74
75    /// Returns the mode a given value of [`UPDATE_GOLDEN`] selects; `None`
76    /// means the variable is unset. [`from_env`](GoldenMode::from_env) is this
77    /// function applied to the process environment.
78    ///
79    /// # Examples
80    ///
81    /// ```
82    /// use flm_core::dump::GoldenMode;
83    ///
84    /// assert_eq!(GoldenMode::from_setting(Some("1")), GoldenMode::Update);
85    /// assert_eq!(GoldenMode::from_setting(Some("true")), GoldenMode::Compare);
86    /// assert_eq!(GoldenMode::from_setting(None), GoldenMode::Compare);
87    /// ```
88    pub fn from_setting(value: Option<&str>) -> GoldenMode {
89        match value {
90            Some("1") => GoldenMode::Update,
91            _ => GoldenMode::Compare,
92        }
93    }
94}
95
96/// The reason a golden check failed, returned by [`check_text_golden`] and
97/// [`check_json_golden`].
98///
99/// Its `Display` text is the message [`assert_text_golden`] and
100/// [`assert_json_golden`] panic with. The message of a missing or mismatching
101/// file includes the actual output (and the expected output), and says how to
102/// rewrite the file.
103#[derive(Debug, Clone, PartialEq, Eq)]
104pub enum GoldenError {
105    /// The golden file does not exist. `actual` is the output that update mode
106    /// would write to it.
107    Missing {
108        /// The path of the golden file.
109        path: PathBuf,
110        /// The actual output.
111        actual: String,
112    },
113    /// The actual output differs from the golden file.
114    Mismatch {
115        /// The path of the golden file.
116        path: PathBuf,
117        /// The expected output: the file's text, or for a JSON golden file the
118        /// file's value written again as indented JSON.
119        expected: String,
120        /// The actual output.
121        actual: String,
122    },
123    /// The golden file exists but cannot be read, or a JSON golden file's text
124    /// is not the JSON form of a serialized value. [`from_json`] lists every
125    /// such case; one of them is valid JSON that nests deeper than
126    /// [`SerialValue::MAX_NESTING_DEPTH`].
127    Unreadable {
128        /// The path of the golden file.
129        path: PathBuf,
130        /// The underlying error, as text.
131        detail: String,
132    },
133    /// The golden file cannot be written in update mode.
134    Unwritable {
135        /// The path of the golden file.
136        path: PathBuf,
137        /// The underlying error, as text.
138        detail: String,
139    },
140    /// The actual value of a JSON comparison has no JSON form: it holds a map
141    /// key beginning with `$`, a prefix techy reserves.
142    Unrenderable {
143        /// The path of the golden file.
144        path: PathBuf,
145        /// The underlying error, as text.
146        detail: String,
147    },
148}
149
150impl fmt::Display for GoldenError {
151    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
152        match self {
153            GoldenError::Missing { path, actual } => write!(
154                f,
155                "the golden file {} does not exist\n\
156                 (run the test with {UPDATE_GOLDEN}=1 to create it)\n\
157                 --- actual ---\n{actual}",
158                path.display()
159            ),
160            GoldenError::Mismatch { path, expected, actual } => write!(
161                f,
162                "the actual output differs from the golden file {}\n\
163                 (run the test with {UPDATE_GOLDEN}=1 to rewrite the file)\n\
164                 --- expected ---\n{expected}\n--- actual ---\n{actual}",
165                path.display()
166            ),
167            GoldenError::Unreadable { path, detail } => {
168                write!(f, "the golden file {} cannot be read: {detail}", path.display())
169            }
170            GoldenError::Unwritable { path, detail } => {
171                write!(f, "the golden file {} cannot be written: {detail}", path.display())
172            }
173            GoldenError::Unrenderable { path, detail } => {
174                write!(
175                    f,
176                    "the actual value compared with the golden file {} cannot be written \
177                     as JSON: {detail}",
178                    path.display()
179                )
180            }
181        }
182    }
183}
184
185impl std::error::Error for GoldenError {}
186
187/// Writes `content` to `path`, creating the directories above it.
188fn write_golden(path: &Path, content: &str) -> Result<(), GoldenError> {
189    let unwritable = |error: std::io::Error| GoldenError::Unwritable {
190        path: path.to_path_buf(),
191        detail: error.to_string(),
192    };
193    if let Some(parent) = path.parent() {
194        std::fs::create_dir_all(parent).map_err(unwritable)?;
195    }
196    std::fs::write(path, content).map_err(unwritable)
197}
198
199/// Reads the golden at `path`: `Ok(None)` when it does not exist.
200fn read_golden(path: &Path) -> Result<Option<String>, GoldenError> {
201    match std::fs::read_to_string(path) {
202        Ok(content) => Ok(Some(content)),
203        Err(error) if error.kind() == std::io::ErrorKind::NotFound => Ok(None),
204        Err(error) => {
205            Err(GoldenError::Unreadable { path: path.to_path_buf(), detail: error.to_string() })
206        }
207    }
208}
209
210/// Compares the text `actual` with the golden file at `path`, byte for byte.
211///
212/// In [`GoldenMode::Update`] the file is rewritten with `actual` instead,
213/// creating the directories above it, and the check succeeds.
214///
215/// # Errors
216///
217/// [`GoldenError::Missing`] when the file does not exist;
218/// [`GoldenError::Mismatch`] when it differs from `actual`;
219/// [`GoldenError::Unreadable`] when it cannot be read;
220/// [`GoldenError::Unwritable`] when update mode cannot write it.
221///
222/// See also [`assert_text_golden`], which reads the mode from the environment.
223pub fn check_text_golden(path: &Path, actual: &str, mode: GoldenMode) -> Result<(), GoldenError> {
224    if mode == GoldenMode::Update {
225        return write_golden(path, actual);
226    }
227    match read_golden(path)? {
228        None => {
229            Err(GoldenError::Missing { path: path.to_path_buf(), actual: String::from(actual) })
230        }
231        Some(expected) if expected == actual => Ok(()),
232        Some(expected) => Err(GoldenError::Mismatch {
233            path: path.to_path_buf(),
234            expected,
235            actual: String::from(actual),
236        }),
237    }
238}
239
240/// Compares the serialized value `value` with the JSON golden file at `path`.
241///
242/// The file is parsed back into a serialized value and the two values are
243/// compared, so differences of layout in the file do not matter. In
244/// [`GoldenMode::Update`] the file is rewritten instead with `value` as written
245/// by [`to_json_pretty`] followed by a newline, creating the directories above
246/// it, and the check succeeds.
247///
248/// # Errors
249///
250/// [`GoldenError::Missing`] when the file does not exist;
251/// [`GoldenError::Mismatch`] when its value differs from `value`;
252/// [`GoldenError::Unreadable`] when it cannot be read or its text is not the
253/// JSON form of a serialized value (the cases [`from_json`] refuses, among them
254/// nesting deeper than [`SerialValue::MAX_NESTING_DEPTH`]);
255/// [`GoldenError::Unwritable`] when update mode cannot write it;
256/// [`GoldenError::Unrenderable`] when `value` holds a map key beginning with
257/// `$`, which has no JSON form.
258///
259/// See also [`assert_json_golden`], which reads the mode from the environment.
260pub fn check_json_golden(
261    path: &Path,
262    value: &SerialValue,
263    mode: GoldenMode,
264) -> Result<(), GoldenError> {
265    let render = |value: &SerialValue| {
266        to_json_pretty(value).map(|text| text + "\n").map_err(|error| GoldenError::Unrenderable {
267            path: path.to_path_buf(),
268            detail: error.to_string(),
269        })
270    };
271    let actual = render(value)?;
272    if mode == GoldenMode::Update {
273        return write_golden(path, &actual);
274    }
275    let Some(text) = read_golden(path)? else {
276        return Err(GoldenError::Missing { path: path.to_path_buf(), actual });
277    };
278    let expected = from_json(&text).map_err(|error| GoldenError::Unreadable {
279        path: path.to_path_buf(),
280        detail: format!("its content is not the JSON form of a serialized value: {error}"),
281    })?;
282    if &expected == value {
283        return Ok(());
284    }
285    Err(GoldenError::Mismatch { path: path.to_path_buf(), expected: render(&expected)?, actual })
286}
287
288/// Asserts that the text `actual` equals the golden file at `path`, or rewrites
289/// the file when the environment variable [`UPDATE_GOLDEN`] is `1`.
290///
291/// This is [`check_text_golden`] with the mode read from the environment
292/// ([`GoldenMode::from_env`]).
293///
294/// # Panics
295///
296/// Panics with the [`GoldenError`]'s message whenever
297/// [`check_text_golden`] returns one: the golden file is missing, differs
298/// from `actual`, or cannot be read or written.
299pub fn assert_text_golden(path: impl AsRef<Path>, actual: &str) {
300    if let Err(error) = check_text_golden(path.as_ref(), actual, GoldenMode::from_env()) {
301        panic!("{error}");
302    }
303}
304
305/// Asserts that the serialized value `value` equals the JSON golden file at
306/// `path`, or rewrites the file when the environment variable [`UPDATE_GOLDEN`]
307/// is `1`.
308///
309/// This is [`check_json_golden`] with the mode read from the environment
310/// ([`GoldenMode::from_env`]). A projection is usually what is compared:
311/// `assert_json_golden(path, &project_tree(tree, &ProjectOptions::new()))`
312/// ([`project_tree`](crate::dump::project::project_tree)).
313///
314/// # Panics
315///
316/// Panics with the [`GoldenError`]'s message whenever
317/// [`check_json_golden`] returns one: the golden file is missing, differs in
318/// value from `value`, cannot be read or written, or holds text that is not the
319/// JSON form of a serialized value (the cases [`from_json`] refuses); or `value`
320/// has no JSON form.
321pub fn assert_json_golden(path: impl AsRef<Path>, value: &SerialValue) {
322    if let Err(error) = check_json_golden(path.as_ref(), value, GoldenMode::from_env()) {
323        panic!("{error}");
324    }
325}