ifc_lite_testkit/fixtures.rs
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Catalogued-fixture resolution (`tests/models/**`).
6//!
7//! Catalogued fixtures are not committed (`tests/models/manifest.json`), so a
8//! test that needs one skips when it is absent. A skip is invisible in
9//! `cargo test` output, which is issue #2802: a passing skip-shaped test looks
10//! the same as one that asserted something. `IFC_LITE_REQUIRE_FIXTURES=1`
11//! (set by CI after `pnpm fixtures`) turns every skip into a panic.
12//!
13//! [`fixture_bytes`] and [`fixture_text`] are the one decision point:
14//!
15//! | outcome | gate off | gate on (`=1`) |
16//! |--------------------------------|---------------|----------------|
17//! | file present | `Some` | `Some` |
18//! | `NotFound` | `None` (skip) | panic |
19//! | Git LFS pointer (not fetched) | `None` (skip) | panic |
20//! | any other I/O error / bad UTF-8 | panic | panic |
21//!
22//! The gate value is parsed strictly: only unset, `""`, `"0"` (off) and `"1"`
23//! (on) are accepted; anything else (`true`, `yes`, a typo) panics, because
24//! guessing "off" would recreate the silent-pass failure.
25
26use std::env::VarError;
27use std::path::PathBuf;
28
29/// Why a fixture could not be returned (the pure decision, see [`classify`]).
30#[derive(Debug, PartialEq, Eq)]
31pub enum FixtureError {
32 /// The file does not exist (fixture not fetched).
33 NotFound,
34 /// The file is a Git LFS pointer, not the real bytes.
35 LfsPointer,
36}
37
38/// The repository root, derived from this crate's location (`rust/testkit`).
39pub fn repo_root() -> PathBuf {
40 PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("../..")
41}
42
43/// Absolute path of the catalogued fixture `rel` (relative to `tests/models/`).
44pub fn fixture_path(rel: &str) -> PathBuf {
45 repo_root().join("tests/models").join(rel)
46}
47
48/// Parse `IFC_LITE_REQUIRE_FIXTURES`, failing closed on the config itself.
49pub fn require_fixtures() -> bool {
50 require_fixtures_from(std::env::var("IFC_LITE_REQUIRE_FIXTURES"))
51}
52
53/// The pure decision behind [`require_fixtures`]; a parameter so tests need
54/// not mutate the process environment (tests run on shared threads).
55pub fn require_fixtures_from(var: Result<String, VarError>) -> bool {
56 match var {
57 Err(VarError::NotPresent) => false,
58 Ok(v) if v.is_empty() || v == "0" => false,
59 Ok(v) if v == "1" => true,
60 other => panic!(
61 "IFC_LITE_REQUIRE_FIXTURES={other:?} is not recognised (use \"1\" or \"0\") -- \
62 refusing to guess, because guessing \"off\" would silently disable the gate"
63 ),
64 }
65}
66
67/// True when `bytes` is a Git LFS pointer file. Built at runtime so this
68/// source never contains the literal marker line itself.
69fn is_lfs_pointer(bytes: &[u8]) -> bool {
70 let marker = format!("version {}{}", "https://git-lfs.github.com/", "spec/");
71 bytes.starts_with(marker.as_bytes())
72}
73
74/// Classify a read result. `Ok(Ok(bytes))` is a usable fixture, `Ok(Err(_))`
75/// a skippable absence, and a hard I/O error panics.
76pub fn classify(
77 rel: &str,
78 read: std::io::Result<Vec<u8>>,
79) -> Result<Vec<u8>, FixtureError> {
80 match read {
81 Ok(bytes) if is_lfs_pointer(&bytes) => Err(FixtureError::LfsPointer),
82 Ok(bytes) => Ok(bytes),
83 Err(e) if e.kind() == std::io::ErrorKind::NotFound => Err(FixtureError::NotFound),
84 Err(e) => panic!("fixture {rel} exists but could not be read: {e}"),
85 }
86}
87
88/// Apply the gate to an absence: panic when it is on, otherwise report the
89/// skip on stderr and return `None`.
90fn skip_or_panic<T>(rel: &str, why: &FixtureError, gate: bool) -> Option<T> {
91 let what = match why {
92 FixtureError::NotFound => "not present",
93 FixtureError::LfsPointer => "is a Git LFS pointer, not the real bytes",
94 };
95 if gate {
96 panic!(
97 "fixture {rel} {what} and IFC_LITE_REQUIRE_FIXTURES=1 -- run `pnpm fixtures` \
98 to download (sha256 in tests/models/manifest.json)"
99 );
100 }
101 eprintln!(
102 "skipping: fixture {rel} {what} -- run `pnpm fixtures` to download \
103 (sha256 in tests/models/manifest.json)"
104 );
105 None
106}
107
108/// Decide the outcome for `rel` given an explicit gate value (testable core).
109pub fn resolve_bytes(
110 rel: &str,
111 read: std::io::Result<Vec<u8>>,
112 gate: bool,
113) -> Option<Vec<u8>> {
114 match classify(rel, read) {
115 Ok(bytes) => Some(bytes),
116 Err(why) => skip_or_panic(rel, &why, gate),
117 }
118}
119
120/// Bytes of the catalogued fixture `rel` (relative to `tests/models/`), or
121/// `None` to skip. See the module table for the gate semantics.
122pub fn fixture_bytes(rel: &str) -> Option<Vec<u8>> {
123 resolve_bytes(rel, std::fs::read(fixture_path(rel)), require_fixtures())
124}
125
126/// Whether the catalogued fixture `rel` is present, with the same gate
127/// semantics as [`fixture_bytes`] (absent or an LFS pointer: `false`, or a
128/// panic under the gate). Reads only the first bytes, so it is cheap for large
129/// models that the caller then loads itself.
130pub fn fixture_present(rel: &str) -> bool {
131 use std::io::Read;
132 let head = std::fs::File::open(fixture_path(rel)).and_then(|mut f| {
133 let mut buf = vec![0u8; 64];
134 let n = f.read(&mut buf)?;
135 buf.truncate(n);
136 Ok(buf)
137 });
138 resolve_bytes(rel, head, require_fixtures()).is_some()
139}
140
141/// [`fixture_bytes`] decoded as UTF-8 (invalid UTF-8 panics: a corrupt
142/// fixture is a setup error, not an absence).
143pub fn fixture_text(rel: &str) -> Option<String> {
144 fixture_bytes(rel).map(|b| {
145 String::from_utf8(b).unwrap_or_else(|e| panic!("fixture {rel} is not valid UTF-8: {e}"))
146 })
147}
148
149/// Text of a PRIVATE, un-manifested local model under `tests/models/` (one
150/// `pnpm fixtures` can never supply). Absent or an LFS pointer is always `None`
151/// -- the gate deliberately does not apply, or the suite would fail CI
152/// unconditionally -- while any other I/O error or bad UTF-8 still panics.
153/// Catalogued fixtures must use [`fixture_text`] instead.
154pub fn local_fixture_text(rel: &str) -> Option<String> {
155 match classify(rel, std::fs::read(fixture_path(rel))) {
156 Ok(bytes) => Some(
157 String::from_utf8(bytes)
158 .unwrap_or_else(|e| panic!("fixture {rel} is not valid UTF-8: {e}")),
159 ),
160 Err(_) => None,
161 }
162}
163
164/// Bind the fixture text of `$rel` or return from the enclosing test (the
165/// skip). Under `IFC_LITE_REQUIRE_FIXTURES=1` a missing fixture panics.
166#[macro_export]
167macro_rules! fixture_text_or_skip {
168 ($rel:expr) => {
169 match $crate::fixture_text($rel) {
170 Some(text) => text,
171 None => return,
172 }
173 };
174}
175
176/// Bind the fixture bytes of `$rel` or return from the enclosing test.
177#[macro_export]
178macro_rules! fixture_bytes_or_skip {
179 ($rel:expr) => {
180 match $crate::fixture_bytes($rel) {
181 Some(bytes) => bytes,
182 None => return,
183 }
184 };
185}