Skip to main content

qubit_fs_testkit/async_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::resume_unwind;
12
13use super::AsyncFileSystemContractSuite;
14use super::FileSystemCapability;
15use super::Path;
16use crate::ContractCheckId;
17use crate::ContractCheckOutcome;
18use crate::FixtureError;
19use crate::FixtureSupport;
20
21impl<'a> AsyncFileSystemContractSuite<'a> {
22    /// Cleans resources created by individually executed asynchronous phases.
23    ///
24    /// The first cleanup attempt closes resource preparation and all run
25    /// entry points, even when cleanup fails or this future is cancelled. Call
26    /// `finish` again to retry cleanup; create a fresh fixture and suite for
27    /// another run.
28    ///
29    /// # Panics
30    ///
31    /// Panics when a recorded resource cannot be inspected or deleted.
32    pub async fn finish(&mut self) {
33        if let Err(payload) = self.finish_capture().await {
34            resume_unwind(payload);
35        }
36    }
37
38    /// Resolves a fixture path or identifies setup failure at the contract
39    /// boundary.
40    ///
41    /// # Parameters
42    ///
43    /// * `relative` - Resource name relative to the current contract phase.
44    ///
45    /// # Returns
46    ///
47    /// The provider path mapped by the fixture.
48    ///
49    /// # Panics
50    ///
51    /// Panics when the fixture cannot map the generated relative name.
52    #[must_use]
53    #[inline]
54    pub fn path(&self, relative: &str) -> Path {
55        let relative = self.context.relative_name(relative);
56        self.fixture
57            .path(&relative)
58            .expect("async contract: fixture path failed")
59    }
60
61    /// Returns whether the cached property snapshot advertises a capability.
62    ///
63    /// # Parameters
64    ///
65    /// * `capability` - Capability to query in the captured snapshot.
66    ///
67    /// # Returns
68    ///
69    /// `true` when the provider advertises the capability.
70    #[must_use]
71    #[inline]
72    pub fn capable(&self, capability: FileSystemCapability) -> bool {
73        self.context.properties().capabilities().supports(capability)
74    }
75
76    /// Seeds a resource and makes fixture support mandatory for the contract.
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 cancelled cleanup attempt does
92    /// not reopen resource preparation.
93    #[must_use]
94    pub async fn required_seed(&mut self, relative: &str, bytes: &[u8], contract: &str) -> Path {
95        assert!(
96            self.context.run.cleanup.attempts == 0,
97            "session cleanup already started; create a fresh fixture for resource preparation"
98        );
99        let relative = self.context.relative_name(relative);
100        match self
101            .fixture
102            .seed_file(&relative, bytes)
103            .await
104            .expect("async contract: fixture seed failed")
105        {
106            FixtureSupport::Supported(path) => {
107                self.context.record_created(path.clone());
108                path
109            }
110            FixtureSupport::Unsupported => {
111                panic!("{contract} contract: advertised capability requires fixture.seed_file support")
112            }
113        }
114    }
115
116    /// Runs asynchronous cleanup and fixture teardown while preserving
117    /// failures.
118    ///
119    /// # Errors
120    ///
121    /// Returns the accumulated cleanup and teardown failures.
122    pub(super) async fn finish_capture(&mut self) -> Result<(), Box<dyn Any + Send>> {
123        self.context.run.cleanup.attempts += 1;
124        self.context.run.cleanup.completed = false;
125        let failure_start = self.context.run.cleanup.failures.len();
126        self.context.cleanup_async(self.fixture.file_system()).await;
127        let mut teardown_failure = None;
128        if !self.teardown_completed {
129            let teardown = crate::internal::catch_unwind_future(self.fixture.teardown()).await;
130            match teardown {
131                Ok(Ok(())) => {
132                    self.teardown_completed = true;
133                }
134                Ok(Err(error)) => {
135                    teardown_failure = Some(format!("[fs-testkit:cleanup/teardown] {error}"));
136                    self.context
137                        .run
138                        .cleanup
139                        .failures
140                        .push(crate::ContractFailure::with_source("fixture teardown failed", error));
141                }
142                Err(payload) => {
143                    self.context
144                        .run
145                        .cleanup
146                        .failures
147                        .push(crate::ContractFailure::panicked("fixture teardown panicked", payload));
148                    teardown_failure = Some("[fs-testkit:cleanup/teardown] fixture teardown panicked".to_owned());
149                }
150            }
151        }
152        if self.context.run.cleanup.failures.len() == failure_start && teardown_failure.is_none() {
153            self.context.run.cleanup.completed = true;
154            return Ok(());
155        }
156        let mut summary = self.context.run.cleanup.failures[failure_start..]
157            .iter()
158            .map(ToString::to_string)
159            .collect::<Vec<_>>();
160        if let Some(failure) = teardown_failure {
161            summary.push(failure);
162        }
163        Err(Box::new(FixtureError::new(summary.join("; "))))
164    }
165
166    /// Returns an ordinary structured failure for fixture or contract errors.
167    ///
168    /// # Errors
169    ///
170    /// Returns a contract failure when path preparation fails or the
171    /// filesystem does not report the generated path as missing.
172    pub(super) async fn check_error_context(&mut self) -> Result<(), crate::ContractFailure> {
173        let id = ContractCheckId::ErrorContext;
174        self.context.begin_check(crate::ContractCheckId::ErrorContext);
175        let relative = self.context.relative_name("missing");
176        let path = self.fixture.path(&relative).map_err(|error| {
177            crate::ContractFailure::with_source("error/context: path preparation failed", error).at(id)
178        })?;
179        let error = match self.fixture.file_system().stat(&path).await {
180            Ok(_) => {
181                return Err(
182                    crate::ContractFailure::message_only("error/context: missing path unexpectedly exists").at(id),
183                );
184            }
185            Err(error) => error,
186        };
187        crate::internal::verify_missing_error(error, &path, self.context.properties().info().provider_id(), id)?;
188        self.context.record_check(id, None, ContractCheckOutcome::Passed);
189        Ok(())
190    }
191}