Skip to main content

qubit_fs_testkit/file_system_contract_suite/
support.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//! Implements fixture adaptation and suite lifecycle support.
9
10use std::any::Any;
11use std::panic::AssertUnwindSafe;
12use std::panic::catch_unwind;
13use std::panic::resume_unwind;
14
15use super::FileSystemCapability;
16use super::FileSystemContractSuite;
17use super::Path;
18use crate::ContractCheckId;
19use crate::ContractCheckOutcome;
20use crate::FixtureError;
21use crate::FixtureSupport;
22
23impl<'a> FileSystemContractSuite<'a> {
24    /// Cleans resources created by individually executed contract phases.
25    ///
26    /// The first cleanup attempt closes resource preparation and all run
27    /// entry points, even when cleanup fails. Call `finish` again to retry
28    /// cleanup; create a fresh fixture and suite for another run.
29    ///
30    /// # Panics
31    ///
32    /// Panics when a recorded resource cannot be inspected or deleted.
33    pub fn finish(&mut self) {
34        if let Err(payload) = self.finish_capture() {
35            resume_unwind(payload);
36        }
37    }
38
39    /// Resolves a fixture path or identifies the contract that could not set
40    /// up.
41    ///
42    /// # Parameters
43    ///
44    /// * `relative` - Resource name relative to the current contract phase.
45    ///
46    /// # Returns
47    ///
48    /// The provider path mapped by the fixture.
49    ///
50    /// # Panics
51    ///
52    /// Panics when the fixture cannot map the generated relative name.
53    #[must_use]
54    #[inline]
55    pub fn path(&self, relative: &str) -> Path {
56        let relative = self.context.relative_name(relative);
57        self.fixture.path(&relative).expect("contract: fixture path failed")
58    }
59
60    /// Returns whether the immutable snapshot declares a capability.
61    ///
62    /// # Parameters
63    ///
64    /// * `capability` - Capability to query in the captured snapshot.
65    ///
66    /// # Returns
67    ///
68    /// `true` when the provider advertises the capability.
69    #[must_use]
70    #[inline]
71    pub fn capable(&self, capability: FileSystemCapability) -> bool {
72        self.context.properties().capabilities().supports(capability)
73    }
74
75    /// Seeds a resource and makes support mandatory for the requested
76    /// capability.
77    ///
78    /// # Parameters
79    ///
80    /// * `relative` - Resource name relative to the current contract phase.
81    /// * `bytes` - Exact content to publish.
82    /// * `contract` - Contract label used in failure diagnostics.
83    ///
84    /// # Returns
85    ///
86    /// The provider path of the seeded file.
87    ///
88    /// # Panics
89    ///
90    /// Panics when cleanup has started, fixture setup fails, or the required
91    /// seed hook is unsupported. A failed or interrupted cleanup attempt does
92    /// not reopen resource preparation.
93    #[must_use]
94    #[inline]
95    pub fn required_seed(&mut self, relative: &str, bytes: &[u8], contract: &str) -> Path {
96        match self.seed(relative, bytes) {
97            FixtureSupport::Supported(path) => path,
98            FixtureSupport::Unsupported => {
99                panic!("{contract} contract: advertised capability requires fixture.seed_file support")
100            }
101        }
102    }
103
104    /// Delegates out-of-band resource preparation to the fixture.
105    ///
106    /// # Parameters
107    ///
108    /// * `relative` - Resource name relative to the current contract phase.
109    /// * `bytes` - Exact content to publish.
110    ///
111    /// # Returns
112    ///
113    /// The fixture's support result and seeded path, when available.
114    ///
115    /// # Panics
116    ///
117    /// Panics when cleanup has started or provider-specific fixture setup
118    /// returns an error. A failed cleanup attempt does not reopen preparation.
119    #[inline]
120    pub fn seed(&mut self, relative: &str, bytes: &[u8]) -> FixtureSupport<Path> {
121        assert!(
122            self.context.run.cleanup.attempts == 0,
123            "session cleanup already started; create a fresh fixture for resource preparation"
124        );
125        let relative = self.context.relative_name(relative);
126        let support = self
127            .fixture
128            .seed_file(&relative, bytes)
129            .expect("contract: fixture seed failed");
130        if let FixtureSupport::Supported(path) = &support {
131            self.context.record_created(path.clone());
132        }
133        support
134    }
135
136    /// Runs facade cleanup and fixture teardown while preserving failures.
137    ///
138    /// # Errors
139    ///
140    /// Returns the cleanup and teardown failures collected during this attempt.
141    /// The error payload is resumed by [`Self::finish`].
142    pub(super) fn finish_capture(&mut self) -> Result<(), Box<dyn Any + Send>> {
143        self.context.run.cleanup.attempts += 1;
144        self.context.run.cleanup.completed = false;
145        let failure_start = self.context.run.cleanup.failures.len();
146        self.context.cleanup(self.fixture.file_system());
147        let mut teardown_failure = None;
148        if !self.teardown_completed {
149            let teardown = catch_unwind(AssertUnwindSafe(|| self.fixture.teardown()));
150            match teardown {
151                Ok(Ok(())) => {
152                    self.teardown_completed = true;
153                }
154                Ok(Err(error)) => {
155                    teardown_failure = Some(format!("[fs-testkit:cleanup/teardown] {error}"));
156                    self.context
157                        .run
158                        .cleanup
159                        .failures
160                        .push(crate::ContractFailure::with_source("fixture teardown failed", error));
161                }
162                Err(payload) => {
163                    self.context
164                        .run
165                        .cleanup
166                        .failures
167                        .push(crate::ContractFailure::panicked("fixture teardown panicked", payload));
168                    teardown_failure = Some("[fs-testkit:cleanup/teardown] fixture teardown panicked".to_owned());
169                }
170            }
171        }
172        if self.context.run.cleanup.failures.len() == failure_start && teardown_failure.is_none() {
173            self.context.run.cleanup.completed = true;
174            return Ok(());
175        }
176        let mut summary = self.context.run.cleanup.failures[failure_start..]
177            .iter()
178            .map(ToString::to_string)
179            .collect::<Vec<_>>();
180        if let Some(failure) = teardown_failure {
181            summary.push(failure);
182        }
183        Err(Box::new(FixtureError::new(summary.join("; "))))
184    }
185
186    /// Returns an ordinary structured failure for fixture or contract errors.
187    ///
188    /// # Errors
189    ///
190    /// Returns a failure when the fixture cannot prepare the missing path, the
191    /// path unexpectedly exists, or the provider reports an invalid
192    /// missing-path error.
193    pub(super) fn check_error_context(&mut self) -> Result<(), crate::ContractFailure> {
194        let id = ContractCheckId::ErrorContext;
195        self.context.begin_check(crate::ContractCheckId::ErrorContext);
196        let relative = self.context.relative_name("missing");
197        let path = self.fixture.path(&relative).map_err(|error| {
198            crate::ContractFailure::with_source("error/context: path preparation failed", error).at(id)
199        })?;
200        let error = match self.fixture.file_system().stat(&path) {
201            Ok(_) => {
202                return Err(
203                    crate::ContractFailure::message_only("error/context: missing path unexpectedly exists").at(id),
204                );
205            }
206            Err(error) => error,
207        };
208        crate::internal::verify_missing_error(error, &path, self.context.properties().info().provider_id(), id)?;
209        self.context.record_check(id, None, ContractCheckOutcome::Passed);
210        Ok(())
211    }
212}