qubit_fs_testkit/file_system_contract_suite.rs
1// =============================================================================
2// Copyright (c) 2026 Haixing Hu.
3//
4// SPDX-License-Identifier: Apache-2.0
5//
6// Licensed under the Apache License, Version 2.0.
7// =============================================================================
8//! Stateful synchronous filesystem provider contract suite.
9
10use std::panic::AssertUnwindSafe;
11use std::panic::catch_unwind;
12
13pub(crate) use qubit_fs::error::FsErrorKind;
14pub(crate) use qubit_fs::error::FsOperation;
15pub(crate) use qubit_fs::metadata::FileSystemCapability;
16pub(crate) use qubit_fs::path::Path;
17pub(crate) use qubit_fs::write::WriteDisposition;
18
19use crate::ContractReport;
20use crate::FileSystemContract;
21use crate::FileSystemFixture;
22use crate::contract_context::ContractContext;
23// Implements property snapshots and bounded limit checks.
24mod properties;
25// Implements reader contracts.
26mod read;
27// Implements independently prepared random-access reader contracts.
28mod random_access;
29// Implements writer and publication contracts.
30mod write;
31// Implements independently prepared bounded write evidence.
32mod write_limit;
33// Implements explicit conditional creation evidence.
34mod write_if_absent;
35// Implements explicit version-conditional replacement evidence.
36mod write_if_match;
37// Implements strong write guarantee evidence.
38mod write_guarantee;
39// Implements independent append evidence.
40mod append;
41// Implements independently seeded creation conflicts.
42mod create_conflict;
43// Implements independently prepared replacement and truncation.
44mod replace;
45// Implements independently prepared explicit abort.
46mod abort;
47// Implements independently prepared metadata checks.
48mod stat;
49// Implements independently observed directory creation.
50mod create_directory;
51// Implements independent representation checks.
52mod representations;
53// Implements independent deletion checks.
54mod delete;
55// Implements independently prepared recursive deletion.
56mod delete_tree;
57// Implements independent rename requirements.
58mod rename;
59// Implements independent hierarchy and object listing.
60mod list;
61// Implements independent namespace completeness checks.
62mod namespace;
63// Implements copy contracts.
64mod basic_copy;
65mod copy;
66mod copy_conflict;
67mod native_copy;
68mod server_side_copy;
69// Implements independently observed file-copy guarantees.
70mod strong_file_copy;
71mod strong_tree_copy;
72// Implements temporary resource contracts.
73mod temp;
74mod temp_directory_check;
75// Implements temporary file lifecycle and publication evidence.
76mod temp_file_check;
77// Implements fixture adaptation and suite lifecycle support.
78mod support;
79
80/// Runs synchronous provider contracts against one isolated fixture.
81///
82/// # Type Parameters
83///
84/// * `'a` - Lifetime of the borrowed provider fixture.
85///
86/// # Examples
87///
88/// ```
89/// # mod support { include!(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/common/rustdoc_support.rs")); }
90/// # use support::RustdocSyncFixture;
91/// use qubit_fs_testkit::{FileSystemContract, FileSystemContractSuite};
92///
93/// let fixture = RustdocSyncFixture::new();
94/// let mut suite = FileSystemContractSuite::new(&fixture);
95/// suite.run_contract(FileSystemContract::Properties);
96/// assert!(!suite.run().was_interrupted());
97/// ```
98#[must_use = "the suite must run at least one contract assertion"]
99pub struct FileSystemContractSuite<'a> {
100 /// Provider-owned fixture supplying the facade and observation hooks.
101 fixture: &'a dyn FileSystemFixture,
102 /// Property snapshot and cleanup state for the current suite run.
103 context: ContractContext,
104 /// Whether cleanup has already been attempted for this suite.
105 teardown_completed: bool,
106}
107
108impl<'a> FileSystemContractSuite<'a> {
109 /// Creates a stateful suite borrowing one isolated provider fixture.
110 ///
111 /// # Parameters
112 ///
113 /// * `fixture` - Isolated provider fixture exercised by the suite.
114 ///
115 /// # Returns
116 ///
117 /// A suite with a fresh context and captured property snapshot.
118 #[inline]
119 pub fn new(fixture: &'a dyn FileSystemFixture) -> Self {
120 Self {
121 fixture,
122 context: ContractContext::new(fixture.file_system().properties()),
123 teardown_completed: false,
124 }
125 }
126
127 /// Returns the result retained by this suite, including a failed session.
128 #[must_use = "inspect the retained contract run"]
129 #[inline]
130 pub const fn run(&self) -> &crate::ContractRun {
131 &self.context.run
132 }
133
134 /// Returns the report currently accumulated by this suite.
135 #[must_use = "inspect the accumulated contract report"]
136 #[inline]
137 pub fn report(&self) -> &ContractReport {
138 self.context.report()
139 }
140
141 /// Executes all phases once and retains both execution and cleanup
142 /// failures.
143 ///
144 /// Returns a lifecycle failure without running checks if cleanup has
145 /// already started. Use a fresh fixture and suite for another run.
146 ///
147 /// # Returns
148 /// The retained execution result after the suite finishes.
149 #[must_use = "inspect the retained contract run"]
150 pub fn run_all(&mut self) -> &crate::ContractRun {
151 self.run_selected(&FileSystemContract::ALL, None)
152 }
153
154 /// Executes one phase once and retains its result in the suite.
155 ///
156 /// Returns a lifecycle failure without running checks if cleanup has
157 /// already started. Use a fresh fixture and suite for another run.
158 ///
159 /// # Parameters
160 /// * `contract` - Contract phase to execute.
161 ///
162 /// # Returns
163 /// The retained execution result after the phase finishes.
164 #[must_use = "inspect the retained contract run"]
165 pub fn run_contract(&mut self, contract: FileSystemContract) -> &crate::ContractRun {
166 self.run_selected(&[contract], None)
167 }
168
169 /// Executes one selected check in a fresh session and retains its cleanup
170 /// result.
171 ///
172 /// Returns a lifecycle failure without running checks if cleanup has
173 /// already started. Use a fresh fixture and suite for another run.
174 ///
175 /// # Parameters
176 /// * `id` - Check identity to execute.
177 ///
178 /// # Returns
179 /// The retained execution result after the check finishes.
180 #[must_use = "inspect the retained contract run"]
181 pub fn run_check(&mut self, id: crate::ContractCheckId) -> &crate::ContractRun {
182 self.run_selected(&[id.contract()], Some(id))
183 }
184
185 /// Runs the selected contract phases once and records cleanup evidence.
186 ///
187 /// A focused check is registered before provider I/O begins so interrupted
188 /// execution remains distinguishable from an omitted check.
189 ///
190 /// # Parameters
191 ///
192 /// - `contracts`: Contract phases to execute in this suite session.
193 /// - `selected`: Optional check to execute instead of every check in its
194 /// phase.
195 ///
196 /// # Returns
197 ///
198 /// The retained run report and any execution or cleanup failures.
199 fn run_selected(
200 &mut self,
201 contracts: &[FileSystemContract],
202 selected: Option<crate::ContractCheckId>,
203 ) -> &crate::ContractRun {
204 if self.context.run.started {
205 self.context.run.failures.push(crate::ContractFailure::message_only(
206 "session already started; create a fresh fixture for another run",
207 ));
208 return &self.context.run;
209 }
210 if self.context.run.cleanup.attempts > 0 {
211 self.context.run.failures.push(crate::ContractFailure::message_only(
212 "session cleanup already started; create a fresh fixture for another run",
213 ));
214 return &self.context.run;
215 }
216 self.context.run.started = true;
217 // Register the entire selection before entering provider code.
218 if let Some(id) = selected {
219 let spec = crate::internal::check_catalog::specification(id);
220 self.context.run.report.register(id, spec.capability);
221 self.context.begin_check(id);
222 } else {
223 for contract in contracts {
224 self.context.prepare_phase(*contract, false);
225 }
226 }
227 for contract in contracts {
228 let result = catch_unwind(AssertUnwindSafe(|| match selected {
229 Some(id) => self.dispatch_check(id),
230 None => self.dispatch_contract(*contract),
231 }));
232 match result {
233 Ok(Ok(())) => {}
234 Ok(Err(failure)) => {
235 self.context.fail(failure);
236 break;
237 }
238 Err(payload) => {
239 let mut failure = crate::ContractFailure::panicked("contract execution panicked", payload);
240 if let Some(id) = selected.or(self.context.active_check()) {
241 failure = failure.at(id);
242 }
243 self.context.fail(failure);
244 break;
245 }
246 }
247 }
248 self.context.begin("cleanup");
249 if let Err(payload) = catch_unwind(AssertUnwindSafe(|| self.finish())) {
250 self.context
251 .run
252 .failures
253 .push(crate::ContractFailure::panicked("cleanup failed", payload));
254 }
255 self.context.run.completed = true;
256 &self.context.run
257 }
258
259 /// Resolves focused execution without running sibling checks.
260 ///
261 /// # Parameters
262 ///
263 /// - `id`: Registered check to dispatch.
264 ///
265 /// # Returns
266 ///
267 /// `Ok(())` when the selected synchronous check records its outcome.
268 ///
269 /// # Errors
270 ///
271 /// Returns a failure when the check requires async execution or its
272 /// contract observation fails.
273 fn dispatch_check(&mut self, id: crate::ContractCheckId) -> Result<(), crate::ContractFailure> {
274 if !id.supports_synchronous() {
275 return Err(crate::ContractFailure::message_only("selected check requires asynchronous execution").at(id));
276 }
277 match id.contract() {
278 FileSystemContract::Copy => self.check_copy_item(id),
279 FileSystemContract::TempResources => self.check_temp_item(id),
280 FileSystemContract::List => self.check_list_item(id),
281 FileSystemContract::Rename => self.check_rename_item(id),
282 FileSystemContract::Delete => self.check_delete_item(id),
283 FileSystemContract::Representations => self.check_representation_item(id),
284 FileSystemContract::CreateDirectory => self.check_create_directory_item(id),
285 FileSystemContract::Properties => self.check_properties_item(id),
286 FileSystemContract::Stat => self.check_stat_item(id),
287 FileSystemContract::Read => self.check_read_item(id),
288 FileSystemContract::Write => self.check_write_item(id),
289 FileSystemContract::ErrorContext => self.check_error_context(),
290 }
291 }
292
293 /// Dispatches one complete contract phase to its synchronous checks.
294 ///
295 /// # Parameters
296 ///
297 /// - `contract`: Contract phase whose registered synchronous checks run.
298 ///
299 /// # Returns
300 ///
301 /// `Ok(())` after every check in the phase records an outcome.
302 ///
303 /// # Errors
304 ///
305 /// Returns the first failure from a check in the phase.
306 fn dispatch_contract(&mut self, contract: FileSystemContract) -> Result<(), crate::ContractFailure> {
307 match contract {
308 FileSystemContract::Properties => self.check_properties()?,
309 FileSystemContract::Stat => self.check_stat()?,
310 FileSystemContract::Read => self.check_read()?,
311 FileSystemContract::Write => {
312 self.check_write()?;
313 }
314 FileSystemContract::List => self.check_list()?,
315 FileSystemContract::CreateDirectory => self.check_create_directory()?,
316 FileSystemContract::Representations => self.check_representations()?,
317 FileSystemContract::Delete => {
318 self.check_delete()?;
319 self.check_delete_tree()?;
320 }
321 FileSystemContract::Copy => {
322 self.check_copy()?;
323 }
324 FileSystemContract::Rename => {
325 self.check_rename()?;
326 }
327 FileSystemContract::TempResources => self.check_temp_resources()?,
328 FileSystemContract::ErrorContext => self.check_error_context()?,
329 }
330 Ok(())
331 }
332}