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
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Independent temporary file publication and lifecycle evidence.

use qubit_fs::error::FsErrorKind;
use qubit_fs::error::FsOperation;
use qubit_fs::error::OpenFailureStage;
use qubit_fs::metadata::AchievedAtomicity;
use qubit_fs::metadata::AtomicityRequirement;
use qubit_fs::metadata::FileSystemCapability;
use qubit_fs::path::Path;
use qubit_fs::path::PathSemantics;
use qubit_fs::temp::PersistFailureState;
use qubit_fs::temp::PersistOptions;
use qubit_fs::temp::TempOptions;
use qubit_fs::temp::TempResourceState;

use crate::AsyncFileSystemContractSuite;
use crate::ContractCheckId;
use crate::ContractFailure;
use crate::ContractTempFailure;
use crate::FixtureSupport;
use crate::internal::verify_condition;

impl AsyncFileSystemContractSuite<'_> {
    /// Prepares options and validates the independent-parent contract probe.
    ///
    /// Parent setup is performed before resource creation so fixture ownership
    /// is recorded in the same order as the temporary resource lifecycle.
    ///
    /// # Parameters
    ///
    /// * `id` - Temporary-file contract scenario being prepared.
    ///
    /// # Errors
    ///
    /// Returns an error when the invalid-parent probe or independent fixture
    /// preparation does not satisfy its contract.
    async fn temp_file_options(&mut self, id: ContractCheckId) -> Result<TempOptions, ContractFailure> {
        let mut options = TempOptions::default();
        let basic = id == ContractCheckId::TempFile;
        if basic && self.capable(FileSystemCapability::TempFile) {
            self.verify_invalid_temp_parent(id).await?;
            if self.capable(FileSystemCapability::CreateDirectory) {
                let relative = self.context.relative_name("temp-file-parent");
                let parent = self.fixture.seed_empty_directory(&relative).await.map_err(|error| {
                    ContractFailure::with_source("temporary parent preparation failed", error).at(id)
                })?;
                let FixtureSupport::Supported(parent) = parent else {
                    return Err(ContractFailure::message_only(
                        "temporary parent needs independent fixture preparation",
                    )
                    .at(id));
                };
                self.context.record_created(parent.clone());
                options = options.with_parent(Some(parent));
            }
            options = options
                .with_prefix("contract-file-".to_owned())
                .with_suffix(".tmp".to_owned());
        }
        Ok(options)
    }

    /// Confirms that an invalid parent is rejected during preflight.
    ///
    /// # Parameters
    ///
    /// * `id` - Temporary-file contract scenario being checked.
    ///
    /// # Errors
    ///
    /// Returns an error if the provider accepts the path or reports different
    /// preflight failure details.
    async fn verify_invalid_temp_parent(&self, id: ContractCheckId) -> Result<(), ContractFailure> {
        let filesystem = self.fixture.file_system();
        let incompatible = match self.context.properties().info().path_semantics() {
            PathSemantics::Hierarchical => Path::parse_literal("/temp-invalid-parent"),
            _ => Path::parse("/temp-invalid-parent"),
        }
        .expect("invalid-parent probe path is a valid constant");
        let error = match filesystem
            .create_temp_file(TempOptions::default().with_parent(Some(incompatible.clone())))
            .await
        {
            Err(error) => error,
            Ok(resource) => {
                return Err(ContractFailure::with_owned_source(
                    "invalid temporary parent succeeded",
                    ContractTempFailure::new(
                        ContractFailure::message_only("invalid temporary parent was accepted"),
                        resource,
                    ),
                )
                .at(id));
            }
        };
        if error.recovery().is_some()
            || error.stage() != OpenFailureStage::Preflight
            || error.error().kind() != FsErrorKind::InvalidPath
            || error.error().operation() != FsOperation::CreateTemp
            || error.error().path() != Some(&incompatible)
        {
            return Err(ContractFailure::with_owned_source("temporary parent validation differs", error).at(id));
        }
        Ok(())
    }

    /// Executes the selected temporary-file lifecycle contract scenario.
    ///
    /// The scenario creates, publishes, keeps, or cleans up a temporary file
    /// and uses the fixture's out-of-band observation hooks to verify
    /// filesystem state. Provider and fixture failures are returned as
    /// contract failures.
    ///
    /// # Parameters
    ///
    /// * `id` - Temporary-file contract scenario to execute.
    ///
    /// # Errors
    ///
    /// Returns an error when an operation fails or observed behavior differs
    /// from the selected contract.
    pub(super) async fn execute_temp_file(&mut self, id: ContractCheckId) -> Result<Option<String>, ContractFailure> {
        let filesystem = self.fixture.file_system();
        let options = self.temp_file_options(id).await?;
        let basic = id == ContractCheckId::TempFile;
        let requested_parent = options.parent().cloned();
        let mut temporary = match filesystem.create_temp_file(options).await {
            Ok(resource) => resource,
            Err(error) if !self.capable(FileSystemCapability::TempFile) => {
                if error.recovery().is_some()
                    || error.stage() != OpenFailureStage::Preflight
                    || error.error().kind() != FsErrorKind::UnsupportedCapability
                    || error.error().operation() != FsOperation::CreateTemp
                    || error.error().required_capability() != Some(FileSystemCapability::TempFile)
                {
                    return Err(
                        ContractFailure::with_owned_source("temporary creation rejection differs", error).at(id),
                    );
                }
                return Ok(None);
            }
            Err(error) => {
                return Err(ContractFailure::with_owned_source("temporary resource creation failed", error).at(id));
            }
        };
        let source = temporary.path().clone();
        self.context.record_created(source.clone());
        verify_condition(
            self.capable(FileSystemCapability::TempFile),
            id,
            "unavailable temporary creation succeeded",
        )?;
        if basic {
            if let Some(parent) = requested_parent {
                verify_condition(
                    source
                        .as_str()
                        .starts_with(&format!("{}/", parent.as_str().trim_end_matches('/'))),
                    id,
                    "temporary resource ignored requested parent",
                )?;
            }
            verify_condition(
                source
                    .file_name()
                    .is_some_and(|name| name.starts_with("contract-file-") && name.ends_with(".tmp")),
                id,
                "temp/file: requested prefix or suffix was ignored",
            )?;
            if let Err(error) = temporary.cleanup().await {
                return Err(ContractFailure::with_owned_source(
                    "temporary cleanup failed",
                    ContractTempFailure::new(error, temporary),
                )
                .at(id));
            }
            let after =
                self.fixture.exists_out_of_band(&source).await.map_err(|error| {
                    ContractFailure::with_source("temporary cleanup observation failed", error).at(id)
                })?;
            verify_condition(
                matches!(after, FixtureSupport::Supported(false)),
                id,
                "temp/file: cleanup retained source",
            )?;
            temporary = filesystem
                .create_temp_file(TempOptions::default())
                .await
                .map_err(|error| {
                    ContractFailure::with_owned_source("temporary keep preparation failed", error).at(id)
                })?;
            self.context.record_created(temporary.path().clone());
        }
        if id != ContractCheckId::TempAtomic {
            if let Some(reason) = self.prepare_temp_file_content(id, temporary.path()).await? {
                return Ok(Some(reason));
            }
            let kept_source = temporary.path().clone();
            let kept = match temporary.keep().await {
                Ok(outcome) => outcome,
                Err(error) => {
                    return Err(ContractFailure::with_owned_source(
                        "temporary keep failed",
                        ContractTempFailure::new(error, temporary),
                    )
                    .at(id));
                }
            };
            self.context.record_created(kept.target().clone());
            verify_condition(
                temporary.state() == TempResourceState::Kept && kept.target() != &kept_source,
                id,
                "temporary keep state or publication identity differs",
            )?;
            for (path, expected) in [(&kept_source, false), (kept.target(), true)] {
                let observed =
                    self.fixture.exists_out_of_band(path).await.map_err(|error| {
                        ContractFailure::with_source("temporary keep observation failed", error).at(id)
                    })?;
                verify_condition(
                    matches!(observed, FixtureSupport::Supported(actual) if actual == expected),
                    id,
                    "temporary keep publication differs",
                )?;
            }
            if let Some(reason) = self.verify_temp_file_content(id, kept.target()).await? {
                return Ok(Some(reason));
            }
            if id == ContractCheckId::TempRepeatedLifecycle {
                let failure = match temporary.keep().await {
                    Err(failure) => failure,
                    Ok(_) => {
                        return Err(
                            ContractFailure::message_only("temp/repeated-lifecycle: second keep succeeded").at(id),
                        );
                    }
                };
                if failure.error().kind() != FsErrorKind::InvalidState
                    || failure.state() != PersistFailureState::PublishedSourceReleased
                    || failure.publication_target() != Some(kept.target())
                {
                    return Err(ContractFailure::with_owned_source(
                        "temp/repeated-lifecycle: publication facts lost",
                        ContractTempFailure::new(failure, temporary),
                    )
                    .at(id));
                }
                let error = match temporary.cleanup().await {
                    Err(error) => error,
                    Ok(_) => {
                        return Err(
                            ContractFailure::message_only("temp/repeated-lifecycle: kept target reclaimed").at(id),
                        );
                    }
                };
                if error.kind() != FsErrorKind::InvalidState {
                    return Err(ContractFailure::with_owned_source(
                        "repeated cleanup rejection differs",
                        ContractTempFailure::new(error, temporary),
                    )
                    .at(id));
                }
                verify_condition(temporary.state() == TempResourceState::Kept, id, "kept state changed")?;
                let after = self.fixture.exists_out_of_band(kept.target()).await.map_err(|error| {
                    ContractFailure::with_source("repeated keep publication observation failed", error).at(id)
                })?;
                verify_condition(
                    matches!(after, FixtureSupport::Supported(true)),
                    id,
                    "kept publication disappeared",
                )?;
                if let Some(reason) = self.verify_temp_file_content(id, kept.target()).await? {
                    return Ok(Some(reason));
                }
                let mut cleaned = filesystem
                    .create_temp_file(TempOptions::default())
                    .await
                    .map_err(|error| {
                        ContractFailure::with_owned_source("repeated cleanup preparation failed", error).at(id)
                    })?;
                let cleaned_source = cleaned.path().clone();
                self.context.record_created(cleaned_source.clone());
                if let Err(error) = cleaned.cleanup().await {
                    return Err(ContractFailure::with_owned_source(
                        "initial cleanup failed",
                        ContractTempFailure::new(error, cleaned),
                    )
                    .at(id));
                }
                let after = self
                    .fixture
                    .exists_out_of_band(&cleaned_source)
                    .await
                    .map_err(|error| {
                        ContractFailure::with_source("repeated cleanup observation failed", error).at(id)
                    })?;
                verify_condition(
                    matches!(after, FixtureSupport::Supported(false)),
                    id,
                    "cleanup retained temporary source",
                )?;
                let error = match cleaned.cleanup().await {
                    Err(error) => error,
                    Ok(_) => {
                        return Err(
                            ContractFailure::message_only("temp/repeated-lifecycle: cleaned resource reused").at(id),
                        );
                    }
                };
                if error.kind() != FsErrorKind::InvalidState || cleaned.state() != TempResourceState::Cleaned {
                    return Err(ContractFailure::with_owned_source(
                        "repeated cleanup state differs",
                        ContractTempFailure::new(error, cleaned),
                    )
                    .at(id));
                }
                let mut first = filesystem
                    .create_temp_file(TempOptions::default())
                    .await
                    .map_err(|error| {
                        ContractFailure::with_owned_source("interleaved temporary preparation failed", error).at(id)
                    })?;
                self.context.record_created(first.path().clone());
                let mut second = filesystem
                    .create_temp_file(TempOptions::default())
                    .await
                    .map_err(|error| {
                        ContractFailure::with_owned_source("interleaved temporary preparation failed", error).at(id)
                    })?;
                let second_path = second.path().clone();
                self.context.record_created(second_path.clone());
                let content_reason = self.prepare_temp_file_content(id, &second_path).await?;
                if let Err(error) = first.cleanup().await {
                    return Err(ContractFailure::with_owned_source(
                        "interleaved temporary cleanup failed",
                        ContractTempFailure::new(error, first),
                    )
                    .at(id));
                }
                let mut third = filesystem
                    .create_temp_file(TempOptions::default())
                    .await
                    .map_err(|error| {
                        ContractFailure::with_owned_source("interleaved temporary preparation failed", error).at(id)
                    })?;
                self.context.record_created(third.path().clone());
                verify_condition(
                    third.path() != &second_path,
                    id,
                    "temp/repeated-lifecycle: live file path was reused",
                )?;
                if content_reason.is_none()
                    && let Some(reason) = self.verify_temp_file_content(id, &second_path).await?
                {
                    return Ok(Some(reason));
                }
                if let Err(error) = second.cleanup().await {
                    return Err(ContractFailure::with_owned_source(
                        "interleaved temporary cleanup failed",
                        ContractTempFailure::new(error, second),
                    )
                    .at(id));
                }
                if let Err(error) = third.cleanup().await {
                    return Err(ContractFailure::with_owned_source(
                        "interleaved temporary cleanup failed",
                        ContractTempFailure::new(error, third),
                    )
                    .at(id));
                }
                return Ok(content_reason);
            }
            temporary = filesystem
                .create_temp_file(TempOptions::default())
                .await
                .map_err(|error| {
                    ContractFailure::with_owned_source("temporary persistence preparation failed", error).at(id)
                })?;
            self.context.record_created(temporary.path().clone());
        }
        let source = temporary.path().clone();
        if let Some(reason) = self.prepare_temp_file_content(id, &source).await? {
            return Ok(Some(reason));
        }
        let target = self
            .fixture
            .path(&self.context.relative_name("persisted-file"))
            .map_err(|error| {
                ContractFailure::with_source("temporary publication target preparation failed", error).at(id)
            })?;
        self.context.record_created(target.clone());
        let atomic = id == ContractCheckId::TempAtomic;
        let options = PersistOptions::default().with_atomicity(if atomic {
            AtomicityRequirement::Required
        } else {
            AtomicityRequirement::Preferred
        });
        let publication = temporary.persist(&target, options).await;
        if atomic && !self.capable(FileSystemCapability::AtomicTempPersist) {
            let failure = match publication {
                Err(failure) => failure,
                Ok(_) => {
                    return Err(ContractFailure::message_only("unsupported atomic persistence succeeded").at(id));
                }
            };
            let error = failure.error();
            if error.kind() != FsErrorKind::RequirementNotMet
                || error.operation() != FsOperation::PersistTemp
                || error.path() != Some(&source)
                || error.target() != Some(&target)
                || error.required_capability() != Some(FileSystemCapability::AtomicTempPersist)
                || error.provider() != Some(self.context.properties().info().provider_id())
                || failure.state() != PersistFailureState::NotPublished
            {
                return Err(ContractFailure::with_owned_source(
                    "atomic persistence rejection differs",
                    ContractTempFailure::new(failure, temporary),
                )
                .at(id));
            }
            let before = self.fixture.exists_out_of_band(&source).await.map_err(|error| {
                ContractFailure::with_source("atomic rejection source observation failed", error).at(id)
            })?;
            verify_condition(
                matches!(before, FixtureSupport::Supported(true)),
                id,
                "atomic preflight removed source",
            )?;
            verify_condition(
                temporary.state() == TempResourceState::Owned,
                id,
                "atomic preflight changed resource ownership",
            )?;
            let target_after = self.fixture.exists_out_of_band(&target).await.map_err(|error| {
                ContractFailure::with_source("atomic rejection target observation failed", error).at(id)
            })?;
            verify_condition(
                matches!(target_after, FixtureSupport::Supported(false)),
                id,
                "atomic preflight published a target",
            )?;
            if let Err(error) = temporary.cleanup().await {
                return Err(ContractFailure::with_owned_source(
                    "atomic rejection cleanup failed",
                    ContractTempFailure::new(error, temporary),
                )
                .at(id));
            }
            let after = self.fixture.exists_out_of_band(&source).await.map_err(|error| {
                ContractFailure::with_source("atomic rejection cleanup observation failed", error).at(id)
            })?;
            verify_condition(
                matches!(after, FixtureSupport::Supported(false)),
                id,
                "atomic rejection cleanup retained source",
            )?;
            return Ok(None);
        }
        let outcome = match publication {
            Ok(outcome) => outcome,
            Err(error) => {
                return Err(ContractFailure::with_owned_source(
                    "temp/atomic: persistence failed",
                    ContractTempFailure::new(error, temporary),
                )
                .at(id));
            }
        };
        verify_condition(outcome.target() == &target, id, "temporary persist target mismatch")?;
        if atomic {
            verify_condition(
                outcome.atomicity() == AchievedAtomicity::Atomic,
                id,
                "temp/atomic: non-atomic publication",
            )?;
        }
        for (path, expected) in [(&source, false), (&target, true)] {
            let observed =
                self.fixture.exists_out_of_band(path).await.map_err(|error| {
                    ContractFailure::with_source("temporary persist observation failed", error).at(id)
                })?;
            verify_condition(
                matches!(observed, FixtureSupport::Supported(actual) if actual == expected),
                id,
                "temporary persistence source release or target publication differs",
            )?;
        }
        self.verify_temp_file_content(id, outcome.target()).await
    }

    /// Prepares a temporary file with known bytes through the fixture's
    /// independent write hook.
    ///
    /// # Parameters
    ///
    /// - `id`: Check identity associated with preparation failures.
    /// - `source`: Temporary file path to populate.
    ///
    /// # Returns
    ///
    /// Whether the fixture supplied independent content evidence, or a reason
    /// why it could not do so.
    ///
    /// # Errors
    ///
    /// Returns a failure when the fixture write hook fails.
    async fn prepare_temp_file_content(
        &self,
        id: ContractCheckId,
        source: &qubit_fs::path::Path,
    ) -> Result<Option<String>, ContractFailure> {
        const CONTENT: &[u8] = b"temp-data";
        match self
            .fixture
            .write_file_out_of_band(source, CONTENT)
            .await
            .map_err(|error| ContractFailure::with_source("temporary file content setup failed", error).at(id))?
        {
            FixtureSupport::Supported(()) => {}
            FixtureSupport::Unsupported => {
                return Ok(Some(
                    "temporary file content verification needs fixture.write_file_out_of_band".to_owned(),
                ));
            }
        }
        self.verify_temp_file_content(id, source).await
    }

    /// Observes and compares the bytes stored at a temporary file path.
    ///
    /// # Parameters
    ///
    /// - `id`: Check identity associated with observation failures.
    /// - `path`: Temporary file path whose contents are read.
    ///
    /// # Returns
    ///
    /// Whether the fixture supplied matching content evidence, or a reason why
    /// it could not do so.
    ///
    /// # Errors
    ///
    /// Returns a failure when the fixture read hook fails.
    async fn verify_temp_file_content(
        &self,
        id: ContractCheckId,
        path: &qubit_fs::path::Path,
    ) -> Result<Option<String>, ContractFailure> {
        const CONTENT: &[u8] = b"temp-data";
        let observed =
            self.fixture.read_file(path).await.map_err(|error| {
                ContractFailure::with_source("temporary file content observation failed", error).at(id)
            })?;
        match observed {
            FixtureSupport::Supported(actual) => {
                verify_condition(actual == CONTENT, id, "temporary file publication changed content")?;
                Ok(None)
            }
            FixtureSupport::Unsupported => Ok(Some(
                "temporary file content verification needs fixture.read_file".to_owned(),
            )),
        }
    }
}