qubit-fs-testkit 0.9.2

Reusable provider contract checks for qubit-fs implementations
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Independent basic, missing-target and conditional deletion evidence.

use qubit_fs::directory::DeleteOptions;
use qubit_fs::error::FsErrorKind;
use qubit_fs::error::FsOperation;
use qubit_fs::metadata::FileSystemCapability;
use qubit_fs::metadata::ResourceVersion;

use crate::AsyncFileSystemContractSuite;
use crate::ContractCheckId;
use crate::ContractCheckOutcome;
use crate::ContractFailure;
use crate::DeleteScenario;
use crate::FixturePreparation;
use crate::FixtureSupport;
use crate::internal::verify_condition;
use crate::internal::verify_fs_error;

impl AsyncFileSystemContractSuite<'_> {
    /// Runs the basic, missing-target, and conditional file-deletion checks.
    ///
    /// Each scenario is prepared and recorded independently so one failure is
    /// attributed to its own contract check.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` after all deletion checks pass.
    ///
    /// # Errors
    ///
    /// Returns the first preparation, filesystem, or contract-verification
    /// failure, tagged with the check that produced it.
    pub(super) async fn check_delete(&mut self) -> Result<(), ContractFailure> {
        for id in [
            ContractCheckId::DeleteBasic,
            ContractCheckId::DeleteMissingOk,
            ContractCheckId::DeleteIfMatch,
        ] {
            self.check_delete_item(id).await?;
        }
        Ok(())
    }

    /// Records exactly one deletion check and preserves its original failure.
    ///
    /// A tree-deletion identifier is delegated to the tree contract; other
    /// identifiers execute a file-deletion scenario and record its capability
    /// and outcome.
    ///
    /// # Parameters
    ///
    /// * `id` — identifies the deletion contract scenario to execute.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` after recording the check, or delegates tree deletion
    /// to its contract check.
    ///
    /// # Errors
    ///
    /// Returns a preparation, filesystem, or verification failure with `id`
    /// attached to its diagnostic context.
    pub(super) async fn check_delete_item(&mut self, id: ContractCheckId) -> Result<(), ContractFailure> {
        self.context.begin_check(id);
        if id == ContractCheckId::DeleteTree {
            return self.check_delete_tree().await;
        }
        let capability = if id == ContractCheckId::DeleteIfMatch {
            FileSystemCapability::ConditionalDelete
        } else {
            FileSystemCapability::Delete
        };
        let outcome = self.execute_delete(id).await?;
        self.context.record_check(id, Some(capability), outcome);
        Ok(())
    }

    /// Selects the file-deletion scenario handler and returns its outcome.
    ///
    /// Capability rejection, missing-target behavior, and seeded file
    /// deletion are handled separately so each helper owns one contract path.
    ///
    /// # Parameters
    ///
    /// * `id` — identifies the file-deletion contract scenario.
    ///
    /// # Returns
    ///
    /// The recorded outcome, or an unverified/not-applicable outcome when the
    /// fixture or required capability cannot support the scenario.
    ///
    /// # Errors
    ///
    /// Returns preparation, filesystem, or contract-verification failures
    /// tagged with `id`.
    async fn execute_delete(&mut self, id: ContractCheckId) -> Result<ContractCheckOutcome, ContractFailure> {
        let relative = self.context.relative_name("delete-target");
        if !self.capable(FileSystemCapability::Delete) {
            return self.execute_unavailable_delete(id, &relative).await;
        }
        if id == ContractCheckId::DeleteMissingOk {
            return self.execute_missing_delete(id, &relative).await;
        }
        if id == ContractCheckId::DeleteIfMatch && !self.capable(FileSystemCapability::ConditionalDelete) {
            let path = self.fixture.path(&relative).map_err(|error| {
                ContractFailure::with_source("conditional delete path preparation failed", error).at(id)
            })?;
            let options = DeleteOptions::default().with_if_match(Some(ResourceVersion::new("contract-version")));
            let error = match self.fixture.file_system().delete_file(&path, options).await {
                Err(error) => error,
                Ok(_) => {
                    return Err(ContractFailure::message_only("unavailable conditional deletion succeeded").at(id));
                }
            };
            verify_fs_error(
                error,
                FsErrorKind::RequirementNotMet,
                FsOperation::Delete,
                &path,
                self.context.properties().info().provider_id(),
                Some(FileSystemCapability::ConditionalDelete),
                id,
            )?;
            return Ok(ContractCheckOutcome::RejectedAsExpected);
        }
        self.execute_seeded_delete(id, &relative).await
    }

    /// Verifies that a filesystem without delete support rejects a basic
    /// delete.
    ///
    /// Other deletion checks require that capability and are reported as not
    /// applicable without attempting an operation.
    ///
    /// # Parameters
    ///
    /// * `id` — identifies the check whose capability is unavailable.
    /// * `relative` — fixture-relative name used to resolve the target path.
    ///
    /// # Returns
    ///
    /// The expected rejection outcome, or not-applicable for non-basic checks.
    ///
    /// # Errors
    ///
    /// Returns path preparation or filesystem-contract verification failures.
    async fn execute_unavailable_delete(
        &mut self,
        id: ContractCheckId,
        relative: &str,
    ) -> Result<ContractCheckOutcome, ContractFailure> {
        if id != ContractCheckId::DeleteBasic {
            return Ok(ContractCheckOutcome::NotApplicable {
                reason: "Delete capability is unavailable".to_owned(),
            });
        }
        let path = self
            .fixture
            .path(relative)
            .map_err(|error| ContractFailure::with_source("delete path preparation failed", error).at(id))?;
        let error = match self
            .fixture
            .file_system()
            .delete_file(&path, DeleteOptions::default())
            .await
        {
            Err(error) => error,
            Ok(_) => {
                return Err(ContractFailure::message_only("unavailable deletion succeeded").at(id));
            }
        };
        verify_fs_error(
            error,
            FsErrorKind::UnsupportedCapability,
            FsOperation::Delete,
            &path,
            self.context.properties().info().provider_id(),
            Some(FileSystemCapability::Delete),
            id,
        )?;
        Ok(ContractCheckOutcome::RejectedAsExpected)
    }

    /// Confirms that deleting an absent target with `missing_ok` leaves it
    /// absent.
    ///
    /// The target is independently checked before and after the operation so
    /// the reported outcome reflects the filesystem state.
    ///
    /// # Parameters
    ///
    /// * `id` — identifies the missing-target contract check.
    /// * `relative` — fixture-relative name used to resolve the absent target.
    ///
    /// # Returns
    ///
    /// `Passed` after the operation reports the target missing and the target
    /// remains absent.
    ///
    /// # Errors
    ///
    /// Returns path preparation, filesystem, observation, or verification
    /// failures tagged with `id`.
    async fn execute_missing_delete(
        &mut self,
        id: ContractCheckId,
        relative: &str,
    ) -> Result<ContractCheckOutcome, ContractFailure> {
        let path = self
            .fixture
            .path(relative)
            .map_err(|error| ContractFailure::with_source("missing-delete path preparation failed", error).at(id))?;
        let before =
            self.fixture.exists_out_of_band(&path).await.map_err(|error| {
                ContractFailure::with_source("missing-delete initial observation failed", error).at(id)
            })?;
        if matches!(before, FixtureSupport::Unsupported) {
            return Ok(ContractCheckOutcome::Unverified {
                reason: "fixture.exists_out_of_band cannot confirm the missing-delete premise".to_owned(),
            });
        }
        verify_condition(
            matches!(before, FixtureSupport::Supported(false)),
            id,
            "missing-delete fixture target must be absent",
        )?;
        self.context.record_created(path.clone());
        let outcome = self
            .fixture
            .file_system()
            .delete_file(&path, DeleteOptions::default().with_missing_ok(true))
            .await
            .map_err(|error| ContractFailure::with_source("missing-ok deletion failed", error).at(id))?;
        verify_condition(
            outcome.already_missing(),
            id,
            "missing-ok outcome did not report absence",
        )?;
        let after =
            self.fixture.exists_out_of_band(&path).await.map_err(|error| {
                ContractFailure::with_source("missing-delete final observation failed", error).at(id)
            })?;
        if matches!(after, FixtureSupport::Unsupported) {
            return Ok(ContractCheckOutcome::Unverified {
                reason: "fixture.exists_out_of_band cannot confirm missing-delete result".to_owned(),
            });
        }
        verify_condition(
            matches!(after, FixtureSupport::Supported(false)),
            id,
            "missing-ok deletion created a resource",
        )?;
        Ok(ContractCheckOutcome::Passed)
    }

    /// Deletes a prepared file and verifies conditional-delete semantics.
    ///
    /// For conditional checks this first proves a stale version is rejected
    /// without changing the seeded file, then deletes with the current version.
    /// Basic checks use the same independently observed seed and final absence.
    ///
    /// # Parameters
    ///
    /// * `id` — identifies either the basic or conditional deletion check.
    /// * `relative` — fixture-relative name supplied to scenario preparation.
    ///
    /// # Returns
    ///
    /// The deletion outcome, or `Unverified` when fixture preparation or
    /// version observations cannot support the requested contract.
    ///
    /// # Errors
    ///
    /// Returns preparation, filesystem, or contract-verification failures
    /// tagged with `id`.
    async fn execute_seeded_delete(
        &mut self,
        id: ContractCheckId,
        relative: &str,
    ) -> Result<ContractCheckOutcome, ContractFailure> {
        let scenario = match id {
            ContractCheckId::DeleteBasic => DeleteScenario::Basic,
            ContractCheckId::DeleteIfMatch => DeleteScenario::IfMatch,
            _ => {
                return Err(ContractFailure::message_only("selected check is not file deletion").at(id));
            }
        };
        let bytes = b"delete evidence";
        let prepared = self
            .fixture
            .prepare_delete(scenario, relative, bytes)
            .await
            .map_err(|error| ContractFailure::with_source("delete scenario preparation failed", error).at(id))?;
        let path = match prepared {
            FixturePreparation::Ready(path) => path,
            FixturePreparation::Unavailable { reason } | FixturePreparation::NotApplicable { reason } => {
                return Ok(ContractCheckOutcome::Unverified { reason });
            }
        };
        self.context.record_created(path.clone());
        let initial = self
            .fixture
            .read_file(&path)
            .await
            .map_err(|error| ContractFailure::with_source("delete initial observation failed", error).at(id))?;
        verify_condition(
            matches!(initial, FixtureSupport::Supported(actual) if actual == bytes),
            id,
            "delete seed lacks independently confirmed contents",
        )?;
        let mut options = DeleteOptions::default();
        if id == ContractCheckId::DeleteIfMatch {
            let current = self.fixture.resource_version(&path).await.map_err(|error| {
                ContractFailure::with_source("delete current version observation failed", error).at(id)
            })?;
            let stale = self.fixture.stale_resource_version(&path).await.map_err(|error| {
                ContractFailure::with_source("delete stale version observation failed", error).at(id)
            })?;
            let (FixtureSupport::Supported(current), FixtureSupport::Supported(stale)) = (current, stale) else {
                return Ok(ContractCheckOutcome::Unverified {
                    reason: "conditional delete needs current and stale versions".to_owned(),
                });
            };
            verify_condition(current != stale, id, "stale delete version equals the current version")?;
            let error = match self
                .fixture
                .file_system()
                .delete_file(&path, DeleteOptions::default().with_if_match(Some(stale)))
                .await
            {
                Err(error) => error,
                Ok(_) => {
                    return Err(ContractFailure::message_only("delete/if-match: stale version was accepted").at(id));
                }
            };
            verify_fs_error(
                error,
                FsErrorKind::PreconditionFailed,
                FsOperation::Delete,
                &path,
                self.context.properties().info().provider_id(),
                None,
                id,
            )?;
            let retained = self.fixture.read_file(&path).await.map_err(|error| {
                ContractFailure::with_source("stale delete content observation failed", error).at(id)
            })?;
            verify_condition(
                matches!(retained, FixtureSupport::Supported(actual) if actual == bytes),
                id,
                "stale delete changed target contents",
            )?;
            options = options.with_if_match(Some(current));
        }
        let outcome = self
            .fixture
            .file_system()
            .delete_file(&path, options)
            .await
            .map_err(|error| ContractFailure::with_source("delete/basic: deletion failed", error).at(id))?;
        verify_condition(
            !outcome.already_missing(),
            id,
            "delete/basic: existing file was reported missing",
        )?;
        verify_condition(
            outcome.deleted_entries().is_none_or(|count| count > 0),
            id,
            "delete/basic: deleted count is zero",
        )?;
        let after = self
            .fixture
            .exists_out_of_band(&path)
            .await
            .map_err(|error| ContractFailure::with_source("delete publication observation failed", error).at(id))?;
        verify_condition(
            matches!(after, FixtureSupport::Supported(false)),
            id,
            "delete/basic: deleted file remained",
        )?;
        Ok(ContractCheckOutcome::Passed)
    }
}

#[cfg(all(test, feature = "async"))]
mod tests {
    use super::super::AsyncFileSystemContractSuite;
    use crate::ContractCheckId;
    use crate::tests::common::AsyncMemoryFixture;
    use crate::tests::common::async_memory_file_system::run_controlled;

    #[test]
    fn test_delete_without_conditional_capability_is_rejected_as_expected() {
        let fixture = AsyncMemoryFixture::without_optional_capabilities();
        run_controlled(async {
            let mut suite = AsyncFileSystemContractSuite::new(&fixture);
            suite.run_check(ContractCheckId::DeleteIfMatch).await.assert_satisfied();
        });
        assert!(fixture.is_empty(), "conditional-delete rejection must clean up");
    }

    #[test]
    fn test_basic_delete_without_delete_capability_is_rejected_as_expected() {
        let fixture = AsyncMemoryFixture::read_only();
        run_controlled(async {
            let mut suite = AsyncFileSystemContractSuite::new(&fixture);
            suite.run_check(ContractCheckId::DeleteBasic).await.assert_satisfied();
        });
    }
}