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
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Independently prepared ordinary and recursive directory creation.

use qubit_fs::directory::CreateDirectoryOptions;
use qubit_fs::error::FsErrorKind;
use qubit_fs::error::FsOperation;
use qubit_fs::metadata::FileSystemCapability;
use qubit_fs::path::Path;

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

impl AsyncFileSystemContractSuite<'_> {
    /// Runs ordinary and recursive directory creation contracts independently.
    ///
    /// Each check receives a separately derived target name. The selected
    /// operation is rejected with an unsupported-capability error when the
    /// provider reports that directory creation is unavailable; otherwise,
    /// the check verifies publication and acceptance of an existing directory.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` after both checks have been recorded.
    ///
    /// # Errors
    ///
    /// Returns a contract failure if either target cannot be prepared, an
    /// unsupported operation is accepted, required absence cannot be
    /// confirmed, creation or metadata observation fails, or the provider
    /// reports an incorrect creation result.
    pub(super) async fn check_create_directory(&mut self) -> Result<(), ContractFailure> {
        for id in [ContractCheckId::DirectoryCreate, ContractCheckId::DirectoryRecursive] {
            self.check_create_directory_item(id).await?;
        }
        Ok(())
    }

    /// Checks one ordinary or recursive directory creation request.
    ///
    /// The target and its possible ancestor must be independently confirmed
    /// absent before creation. Recursive creation also requires a positive
    /// created-ancestor count when the provider supplies that count. After
    /// creation, each requested path must be independently visible and
    /// directory-like, and a repeated request with `exists_ok` enabled must
    /// report that the target already existed. If the capability is
    /// unavailable, the request must be rejected with the matching filesystem
    /// error instead.
    ///
    /// # Parameters
    ///
    /// * `id` - Directory creation check to execute.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` after the selected check has been recorded.
    ///
    /// # Errors
    ///
    /// Returns a contract failure if `id` is not a directory creation check,
    /// if an initial absence or later publication cannot be independently
    /// observed, or if the provider's capability, creation, metadata, or
    /// existing-directory result violates the selected contract.
    pub(super) async fn check_create_directory_item(&mut self, id: ContractCheckId) -> Result<(), ContractFailure> {
        let recursive = match id {
            ContractCheckId::DirectoryCreate => false,
            ContractCheckId::DirectoryRecursive => true,
            _ => {
                return Err(ContractFailure::message_only("selected check is not directory creation").at(id));
            }
        };
        self.context.begin_check(id);
        let relative = self.context.relative_name("created-directory");
        let parent = self
            .fixture
            .path(&relative)
            .map_err(|error| ContractFailure::with_source("directory path preparation failed", error).at(id))?;
        let target = if recursive {
            self.fixture.path(&format!("{relative}/child")).map_err(|error| {
                ContractFailure::with_source("recursive directory path preparation failed", error).at(id)
            })?
        } else {
            parent.clone()
        };
        let capability = FileSystemCapability::CreateDirectory;
        let options = CreateDirectoryOptions::default().with_recursive(recursive);
        if !self.capable(capability) {
            return self
                .check_create_directory_rejected(id, capability, &target, options)
                .await;
        }
        if !self
            .verify_create_directory_targets_absent(id, capability, &parent, &target)
            .await?
        {
            return Ok(());
        }
        self.context.record_created(parent.clone());
        self.context.record_created(target.clone());
        let outcome = self
            .fixture
            .file_system()
            .create_directory(&target, options)
            .await
            .map_err(|error| ContractFailure::with_source("directory creation failed", error).at(id))?;
        verify_condition(
            !outcome.already_existed(),
            id,
            "new directory reported as already existing",
        )?;
        if recursive {
            verify_condition(
                outcome.created_ancestors().is_none_or(|count| count > 0),
                id,
                "recursive ancestor count is zero",
            )?;
        }
        if !self
            .verify_create_directory_publication(id, capability, &parent, &target)
            .await?
        {
            return Ok(());
        }
        self.verify_create_directory_exists_ok(id, recursive, &target).await?;
        if !self
            .verify_create_directory_rejection(id, capability, recursive, &parent, &target)
            .await?
        {
            return Ok(());
        }
        self.context
            .record_check(id, Some(capability), ContractCheckOutcome::Passed);
        Ok(())
    }

    /// Requires an existing directory to be rejected when `exists_ok` is off,
    /// then independently confirms the rejection preserved both paths.
    ///
    /// # Parameters
    ///
    /// * `id` - Contract check used to attribute a failure.
    /// * `capability` - Directory-creation capability associated with the
    ///   check.
    /// * `recursive` - Whether parent creation is enabled for the request.
    /// * `parent` - Existing parent directory to preserve.
    /// * `target` - Existing target directory to reject and preserve.
    ///
    /// # Returns
    ///
    /// Returns `true` when independent evidence verifies the rejection, or
    /// `false` when required fixture observation is unsupported.
    ///
    /// # Errors
    ///
    /// Returns an attributed contract failure when the request or its
    /// independent state checks violate the contract.
    async fn verify_create_directory_rejection(
        &mut self,
        id: ContractCheckId,
        capability: FileSystemCapability,
        recursive: bool,
        parent: &Path,
        target: &Path,
    ) -> Result<bool, ContractFailure> {
        let mut observation_unsupported = false;
        for path in [parent, target] {
            let observed = self.fixture.exists_out_of_band(path).await.map_err(|error| {
                ContractFailure::with_source("directory rejection precondition observation failed", error).at(id)
            })?;
            if matches!(observed, FixtureSupport::Unsupported) {
                observation_unsupported = true;
                continue;
            }
            verify_condition(
                matches!(observed, FixtureSupport::Supported(true)),
                id,
                "directory rejection precondition path is missing",
            )?;
            let metadata = self.fixture.file_system().stat(path).await.map_err(|error| {
                ContractFailure::with_source("directory rejection precondition metadata failed", error).at(id)
            })?;
            verify_condition(
                metadata.is_directory_like(),
                id,
                "directory rejection precondition is not directory-like",
            )?;
        }
        let error = match self
            .fixture
            .file_system()
            .create_directory(target, CreateDirectoryOptions::default().with_recursive(recursive))
            .await
        {
            Err(error) => error,
            Ok(_) => {
                return Err(ContractFailure::message_only("existing directory was accepted without exists_ok").at(id));
            }
        };
        let provider_id = self.context.properties().info().provider_id();
        if error.provider() != Some(provider_id) {
            return Err(ContractFailure::with_source(
                "directory rejection error omitted or mismatched provider ID",
                error,
            )
            .at(id));
        }
        verify_fs_error(
            error,
            FsErrorKind::AlreadyExists,
            FsOperation::CreateDir,
            target,
            provider_id,
            None,
            id,
        )?;
        for path in [parent, target] {
            let observed = self.fixture.exists_out_of_band(path).await.map_err(|error| {
                ContractFailure::with_source("directory rejection observation failed", error).at(id)
            })?;
            if matches!(observed, FixtureSupport::Unsupported) {
                observation_unsupported = true;
                continue;
            }
            verify_condition(
                matches!(observed, FixtureSupport::Supported(true)),
                id,
                "directory rejection removed a requested path",
            )?;
            let metadata =
                self.fixture.file_system().stat(path).await.map_err(|error| {
                    ContractFailure::with_source("directory rejection metadata failed", error).at(id)
                })?;
            verify_condition(
                metadata.is_directory_like(),
                id,
                "rejected directory is no longer directory-like",
            )?;
        }
        if observation_unsupported {
            self.context.record_check(
                id,
                Some(capability),
                ContractCheckOutcome::Unverified {
                    reason: "fixture.exists_out_of_band cannot confirm directory rejection preserved the paths"
                        .to_owned(),
                },
            );
            return Ok(false);
        }
        Ok(true)
    }

    /// Verifies that a provider rejects a directory request for an unavailable
    /// capability.
    ///
    /// # Parameters
    ///
    /// * `id` - Contract check used to associate any failure with the request.
    /// * `capability` - Capability expected to be unavailable.
    /// * `target` - Target path supplied to the provider.
    /// * `options` - Ordinary or recursive request options under examination.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` after recording the expected capability rejection.
    ///
    /// # Errors
    ///
    /// Returns a contract failure if the operation succeeds or its error does
    /// not identify the expected unsupported create-directory operation.
    async fn check_create_directory_rejected(
        &mut self,
        id: ContractCheckId,
        capability: FileSystemCapability,
        target: &Path,
        options: CreateDirectoryOptions,
    ) -> Result<(), ContractFailure> {
        let error = match self.fixture.file_system().create_directory(target, options).await {
            Err(error) => error,
            Ok(_) => {
                return Err(ContractFailure::message_only("unavailable directory creation succeeded").at(id));
            }
        };
        verify_fs_error(
            error,
            FsErrorKind::UnsupportedCapability,
            FsOperation::CreateDir,
            target,
            self.context.properties().info().provider_id(),
            Some(capability),
            id,
        )?;
        self.context
            .record_check(id, Some(capability), ContractCheckOutcome::RejectedAsExpected);
        Ok(())
    }

    /// Confirms the recursive ancestor and requested target are initially
    /// absent.
    ///
    /// # Parameters
    ///
    /// * `id` - Contract check used to associate observation failures.
    /// * `parent` - Path that recursive creation may need to create.
    /// * `target` - Requested directory path.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` when both paths are confirmed absent.
    ///
    /// # Errors
    ///
    /// Returns a contract failure if either path cannot be independently
    /// observed as absent.
    async fn verify_create_directory_targets_absent(
        &mut self,
        id: ContractCheckId,
        capability: FileSystemCapability,
        parent: &Path,
        target: &Path,
    ) -> Result<bool, ContractFailure> {
        for path in [parent, target] {
            let before =
                self.fixture.exists_out_of_band(path).await.map_err(|error| {
                    ContractFailure::with_source("directory initial observation failed", error).at(id)
                })?;
            if matches!(before, FixtureSupport::Unsupported) {
                self.context.record_check(
                    id,
                    Some(capability),
                    ContractCheckOutcome::Unverified {
                        reason: "fixture.exists_out_of_band cannot confirm the initial directory premise".to_owned(),
                    },
                );
                return Ok(false);
            }
            verify_condition(
                matches!(before, FixtureSupport::Supported(false)),
                id,
                "directory fixture needs independently confirmed absent paths",
            )?;
        }
        Ok(true)
    }

    /// Checks independent publication and directory metadata for requested
    /// paths.
    ///
    /// # Parameters
    ///
    /// * `id` - Contract check used to associate observation failures.
    /// * `parent` - Possible ancestor whose publication recursive mode
    ///   requires.
    /// * `target` - Requested directory path.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` when both paths are published as directories.
    ///
    /// # Errors
    ///
    /// Returns a contract failure if a path is not observed as present or its
    /// metadata is not directory-like.
    async fn verify_create_directory_publication(
        &mut self,
        id: ContractCheckId,
        capability: FileSystemCapability,
        parent: &Path,
        target: &Path,
    ) -> Result<bool, ContractFailure> {
        for path in [parent, target] {
            let observed = self.fixture.exists_out_of_band(path).await.map_err(|error| {
                ContractFailure::with_source("directory publication observation failed", error).at(id)
            })?;
            if matches!(observed, FixtureSupport::Unsupported) {
                self.context.record_check(
                    id,
                    Some(capability),
                    ContractCheckOutcome::Unverified {
                        reason: "fixture.exists_out_of_band cannot confirm directory publication".to_owned(),
                    },
                );
                return Ok(false);
            }
            verify_condition(
                matches!(observed, FixtureSupport::Supported(true)),
                id,
                "directory creation did not publish every requested ancestor and target",
            )?;
            let metadata = self
                .fixture
                .file_system()
                .stat(path)
                .await
                .map_err(|error| ContractFailure::with_source("created directory metadata failed", error).at(id))?;
            verify_condition(
                metadata.is_directory_like(),
                id,
                "created resource is not directory-like",
            )?;
        }
        Ok(true)
    }

    /// Repeats creation with `exists_ok` and checks the already-existing
    /// result.
    ///
    /// # Parameters
    ///
    /// * `id` - Contract check used to associate the provider response.
    /// * `recursive` - Whether the repeated request includes recursive mode.
    /// * `target` - Directory already created by the preceding contract phase.
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` when the provider reports the target already existed.
    ///
    /// # Errors
    ///
    /// Returns a contract failure if the provider rejects the existing target
    /// or does not report that it already existed.
    async fn verify_create_directory_exists_ok(
        &self,
        id: ContractCheckId,
        recursive: bool,
        target: &Path,
    ) -> Result<(), ContractFailure> {
        let outcome = self
            .fixture
            .file_system()
            .create_directory(
                target,
                CreateDirectoryOptions::default()
                    .with_exists_ok(true)
                    .with_recursive(recursive),
            )
            .await
            .map_err(|error| ContractFailure::with_source("existing directory was not accepted", error).at(id))?;
        verify_condition(
            outcome.already_existed(),
            id,
            "existing directory outcome was not reported",
        )?;
        Ok(())
    }
}