|
| 1 | +// SPDX-License-Identifier: GPL-3.0-or-later |
| 2 | +// Copyright (C) 2026 Mohamed Hammad |
| 3 | + |
| 4 | +//! In-memory [`MockFs`] for unit tests and engine integration tests. |
| 5 | +//! |
| 6 | +//! Compiled both inside `cargo test` (without any feature flag) and when |
| 7 | +//! downstream crates enable the `test-mocks` feature so they can drive |
| 8 | +//! [`StateStore`](crate::StateStore) without touching the real |
| 9 | +//! filesystem. |
| 10 | +
|
| 11 | +#![allow( |
| 12 | + clippy::expect_used, |
| 13 | + reason = "MockFs is a test utility; .expect() on the mutex matches the \ |
| 14 | + standard Mutex<T> idiom and is unreachable in any sane test." |
| 15 | +)] |
| 16 | + |
| 17 | +use crate::io::FileSystem; |
| 18 | +use std::collections::BTreeMap; |
| 19 | +use std::io::{Error, ErrorKind}; |
| 20 | +use std::path::{Path, PathBuf}; |
| 21 | +use std::sync::{Arc, Mutex}; |
| 22 | + |
| 23 | +/// Failure-injection knobs the next operation will honour. |
| 24 | +#[derive(Clone, Copy, Debug, Default)] |
| 25 | +struct Inject { |
| 26 | + /// Make the next `write_temp_then_rename` fail before mutating the |
| 27 | + /// target file. |
| 28 | + fail_next_rename: bool, |
| 29 | + /// Make the next `fsync_dir` fail (the rename has already |
| 30 | + /// committed; this models the "data persisted but parent dir not |
| 31 | + /// yet flushed" window). |
| 32 | + fail_next_fsync_dir: bool, |
| 33 | +} |
| 34 | + |
| 35 | +#[derive(Default)] |
| 36 | +struct Inner { |
| 37 | + files: BTreeMap<PathBuf, Vec<u8>>, |
| 38 | + inject: Inject, |
| 39 | +} |
| 40 | + |
| 41 | +/// Shared, thread-safe in-memory filesystem. |
| 42 | +/// |
| 43 | +/// Cloning gives a second handle to the same backing store — the same |
| 44 | +/// pattern as `Arc<Mutex<...>>`-backed handles in production code. |
| 45 | +#[derive(Clone, Default)] |
| 46 | +pub struct MockFs { |
| 47 | + inner: Arc<Mutex<Inner>>, |
| 48 | +} |
| 49 | + |
| 50 | +impl std::fmt::Debug for MockFs { |
| 51 | + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 52 | + f.debug_struct("MockFs").finish_non_exhaustive() |
| 53 | + } |
| 54 | +} |
| 55 | + |
| 56 | +impl MockFs { |
| 57 | + /// Construct an empty [`MockFs`]. |
| 58 | + #[must_use] |
| 59 | + pub fn new() -> Self { |
| 60 | + Self::default() |
| 61 | + } |
| 62 | + |
| 63 | + /// Pre-seed the in-memory filesystem at `path` with `data`. |
| 64 | + pub fn seed(&self, path: impl Into<PathBuf>, data: impl Into<Vec<u8>>) { |
| 65 | + let mut inner = self |
| 66 | + .inner |
| 67 | + .lock() |
| 68 | + .expect("MockFs mutex must not be poisoned"); |
| 69 | + inner.files.insert(path.into(), data.into()); |
| 70 | + } |
| 71 | + |
| 72 | + /// Read whatever is stored at `path`, if anything. |
| 73 | + #[must_use] |
| 74 | + pub fn snapshot(&self, path: &Path) -> Option<Vec<u8>> { |
| 75 | + self.inner |
| 76 | + .lock() |
| 77 | + .expect("MockFs mutex must not be poisoned") |
| 78 | + .files |
| 79 | + .get(path) |
| 80 | + .cloned() |
| 81 | + } |
| 82 | + |
| 83 | + /// Cause the next `write_temp_then_rename` to fail before the |
| 84 | + /// target file is modified. Self-clearing — a single shot. |
| 85 | + pub fn fail_next_rename(&self) { |
| 86 | + self.inner |
| 87 | + .lock() |
| 88 | + .expect("MockFs mutex must not be poisoned") |
| 89 | + .inject |
| 90 | + .fail_next_rename = true; |
| 91 | + } |
| 92 | + |
| 93 | + /// Cause the next `fsync_dir` to fail. Self-clearing. |
| 94 | + pub fn fail_next_fsync_dir(&self) { |
| 95 | + self.inner |
| 96 | + .lock() |
| 97 | + .expect("MockFs mutex must not be poisoned") |
| 98 | + .inject |
| 99 | + .fail_next_fsync_dir = true; |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +impl FileSystem for MockFs { |
| 104 | + fn read_string(&self, p: &Path) -> std::io::Result<String> { |
| 105 | + let inner = self |
| 106 | + .inner |
| 107 | + .lock() |
| 108 | + .expect("MockFs mutex must not be poisoned"); |
| 109 | + match inner.files.get(p) { |
| 110 | + Some(bytes) => { |
| 111 | + String::from_utf8(bytes.clone()).map_err(|e| Error::new(ErrorKind::InvalidData, e)) |
| 112 | + } |
| 113 | + None => Err(Error::new(ErrorKind::NotFound, "no such mock file")), |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + fn write_temp_then_rename(&self, p: &Path, data: &[u8]) -> std::io::Result<()> { |
| 118 | + let mut inner = self |
| 119 | + .inner |
| 120 | + .lock() |
| 121 | + .expect("MockFs mutex must not be poisoned"); |
| 122 | + if inner.inject.fail_next_rename { |
| 123 | + inner.inject.fail_next_rename = false; |
| 124 | + return Err(Error::new( |
| 125 | + ErrorKind::Other, |
| 126 | + "MockFs: injected rename failure", |
| 127 | + )); |
| 128 | + } |
| 129 | + inner.files.insert(p.to_path_buf(), data.to_vec()); |
| 130 | + Ok(()) |
| 131 | + } |
| 132 | + |
| 133 | + fn fsync_dir(&self, _p: &Path) -> std::io::Result<()> { |
| 134 | + let mut inner = self |
| 135 | + .inner |
| 136 | + .lock() |
| 137 | + .expect("MockFs mutex must not be poisoned"); |
| 138 | + if inner.inject.fail_next_fsync_dir { |
| 139 | + inner.inject.fail_next_fsync_dir = false; |
| 140 | + return Err(Error::new( |
| 141 | + ErrorKind::Other, |
| 142 | + "MockFs: injected fsync_dir failure", |
| 143 | + )); |
| 144 | + } |
| 145 | + Ok(()) |
| 146 | + } |
| 147 | +} |
| 148 | + |
| 149 | +#[cfg(test)] |
| 150 | +#[allow( |
| 151 | + clippy::expect_used, |
| 152 | + clippy::unwrap_used, |
| 153 | + clippy::panic, |
| 154 | + reason = "tests may use expect()/unwrap()/panic!() per Plan §4.2 + CLAUDE.md" |
| 155 | +)] |
| 156 | +mod tests { |
| 157 | + use super::*; |
| 158 | + |
| 159 | + #[test] |
| 160 | + fn seed_then_read_round_trip() { |
| 161 | + let fs = MockFs::new(); |
| 162 | + fs.seed("/state.toml", "hello".as_bytes().to_vec()); |
| 163 | + let read = fs.read_string(Path::new("/state.toml")).expect("read"); |
| 164 | + assert_eq!(read, "hello"); |
| 165 | + } |
| 166 | + |
| 167 | + #[test] |
| 168 | + fn read_missing_yields_not_found() { |
| 169 | + let fs = MockFs::new(); |
| 170 | + let err = fs |
| 171 | + .read_string(Path::new("/nope")) |
| 172 | + .expect_err("missing must fail"); |
| 173 | + assert_eq!(err.kind(), ErrorKind::NotFound); |
| 174 | + } |
| 175 | + |
| 176 | + #[test] |
| 177 | + fn injected_rename_failure_leaves_old_content() { |
| 178 | + let fs = MockFs::new(); |
| 179 | + fs.seed("/state.toml", b"v1".to_vec()); |
| 180 | + |
| 181 | + fs.fail_next_rename(); |
| 182 | + let err = fs |
| 183 | + .write_temp_then_rename(Path::new("/state.toml"), b"v2") |
| 184 | + .expect_err("rename should fail"); |
| 185 | + assert_eq!(err.kind(), ErrorKind::Other); |
| 186 | + |
| 187 | + // Subsequent read still returns v1. |
| 188 | + let read = fs.read_string(Path::new("/state.toml")).expect("read"); |
| 189 | + assert_eq!(read, "v1"); |
| 190 | + } |
| 191 | + |
| 192 | + #[test] |
| 193 | + fn fail_injection_is_single_shot() { |
| 194 | + let fs = MockFs::new(); |
| 195 | + fs.fail_next_rename(); |
| 196 | + assert!( |
| 197 | + fs.write_temp_then_rename(Path::new("/x"), b"a").is_err(), |
| 198 | + "first call should fail" |
| 199 | + ); |
| 200 | + // Second call should succeed. |
| 201 | + fs.write_temp_then_rename(Path::new("/x"), b"b") |
| 202 | + .expect("second call should succeed"); |
| 203 | + assert_eq!(fs.snapshot(Path::new("/x")), Some(b"b".to_vec())); |
| 204 | + } |
| 205 | +} |
0 commit comments