Skip to main content

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