Skip to main content

shuyi_platform/harness/
kept.rs

1//! A session record kept as a file, as a test.
2#![cfg(feature = "std")]
3
4use std::ffi::OsStr;
5
6use shuyi_ui::GameData;
7
8use super::{bless_session, check_session};
9use crate::app::Start;
10
11/// Whether `SHUYI_BLESS`, set to `value` or not, asks to write the file.
12fn blesses(value: Option<&OsStr>) -> bool {
13    value.is_some_and(|value| value == "1")
14}
15
16/// A test that the session record at `path` plays from `start` with no
17/// difference ([`check_session`]). With the environment variable
18/// `SHUYI_BLESS=1` it writes the file again instead ([`bless_session`]).
19///
20/// # Panics
21///
22/// If the file can't be read or written, or the record doesn't play.
23#[track_caller]
24pub fn assert_session<G: GameData>(start: Start<G>, path: impl AsRef<std::path::Path>) {
25    let path = path.as_ref();
26    let shown = path.display();
27    let text = std::fs::read_to_string(path).unwrap_or_else(|e| panic!("{shown}: {e}"));
28    if blesses(std::env::var_os("SHUYI_BLESS").as_deref()) {
29        let blessed = bless_session(start, &text).unwrap_or_else(|e| panic!("{shown}: {e}"));
30        std::fs::write(path, blessed).unwrap_or_else(|e| panic!("{shown}: {e}"));
31    } else if let Err(e) = check_session(start, &text) {
32        panic!("{shown}: {e}");
33    }
34}
35
36#[cfg(test)]
37mod tests {
38    use super::*;
39
40    #[test]
41    fn only_a_shuyi_bless_of_1_writes_the_file() {
42        assert!(blesses(Some(OsStr::new("1"))));
43        assert!(!blesses(Some(OsStr::new("0"))));
44        assert!(!blesses(None));
45    }
46}