qubit-fs-testkit 0.9.2

Reusable provider contract checks for qubit-fs implementations
Documentation
// =============================================================================
//    Copyright (c) 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Structured filesystem error assertions.

use qubit_fs::error::FsError;
use qubit_fs::error::FsErrorKind;
use qubit_fs::error::FsOperation;
use qubit_fs::metadata::FileSystemCapability;
use qubit_fs::path::Path;

/// Checks all structured fields required by one filesystem contract.
///
/// # Parameters
///
/// * `error` - Actual provider error.
/// * `kind` - Required error classification.
/// * `operation` - Required public operation.
/// * `path` - Required path when the contract is path-scoped.
/// * `provider` - Expected provider identifier when the error reports provider
///   context.
/// * `capability` - Required capability when the error reports one.
///
/// # Panics
///
/// Panics when any expected field differs from the actual error.
#[track_caller]
#[cfg(test)]
pub(crate) fn assert_error(
    error: &FsError,
    kind: FsErrorKind,
    operation: FsOperation,
    path: Option<&Path>,
    provider: Option<&str>,
    capability: Option<FileSystemCapability>,
) {
    assert_eq!(kind, error.kind(), "filesystem error kind must match");
    assert_eq!(operation, error.operation(), "filesystem error operation must match",);
    assert_eq!(path, error.path(), "filesystem error path must match");
    assert!(
        error.provider().is_none() || error.provider() == provider,
        "filesystem error provider must be absent or match the configured provider",
    );
    assert_eq!(
        capability,
        error.required_capability(),
        "filesystem error required capability must match",
    );
}

/// Checks all structured fields for an error that includes a destination path.
///
/// # Parameters
///
/// * `error` - Actual provider error.
/// * `kind` - Required error classification.
/// * `operation` - Required public operation.
/// * `path` - Required source path.
/// * `target` - Required destination path.
/// * `provider` - Required provider identifier.
/// * `capability` - Required capability when the error reports one.
///
/// # Panics
///
/// Panics when any expected field differs from the actual error.
#[track_caller]
#[cfg(test)]
pub(crate) fn assert_error_with_target(
    error: &FsError,
    kind: FsErrorKind,
    operation: FsOperation,
    path: Option<&Path>,
    target: Option<&Path>,
    provider: Option<&str>,
    capability: Option<FileSystemCapability>,
) {
    assert_error(error, kind, operation, path, provider, capability);
    assert_eq!(target, error.target(), "filesystem error target must match");
}

/// Checks a two-path operation error whose primary path is the concrete
/// failure location.
///
/// Providers may detect a source-side or destination-side conflict first. The
/// public error therefore preserves either request path as its primary path
/// and always retains the destination in `target`.
#[track_caller]
#[cfg(test)]
pub(crate) fn assert_error_with_source_or_target(
    error: &FsError,
    kind: FsErrorKind,
    operation: FsOperation,
    source: &Path,
    target: &Path,
    provider: Option<&str>,
    capability: Option<FileSystemCapability>,
) {
    assert_eq!(kind, error.kind(), "filesystem error kind must match");
    assert_eq!(operation, error.operation(), "filesystem error operation must match");
    assert!(
        matches!(error.path(), Some(path) if path == source || path == target),
        "filesystem error path must identify the source or target failure location",
    );
    assert_eq!(Some(target), error.target(), "filesystem error target must match");
    assert!(
        error.provider().is_none() || error.provider() == provider,
        "filesystem error provider must be absent or match the configured provider",
    );
    assert_eq!(
        capability,
        error.required_capability(),
        "filesystem error required capability must match"
    );
}

/// Checks the required fields of an unsupported-operation error.
///
/// # Parameters
///
/// * `error` - Actual provider error.
/// * `kind` - Required error classification.
/// * `operation` - Required public operation.
/// * `path` - Required source path.
/// * `provider` - Configured provider identifier, when one is available.
/// * `capability` - Required unsupported capability.
///
/// # Panics
///
/// Panics when a required field differs, or when a reported provider does not
/// match the configured provider. Missing provider context remains valid for
/// trait-default errors.
#[track_caller]
#[cfg(test)]
pub(crate) fn assert_unsupported_error(
    error: &FsError,
    kind: FsErrorKind,
    operation: FsOperation,
    path: Option<&Path>,
    provider: Option<&str>,
    capability: Option<FileSystemCapability>,
) {
    assert_eq!(kind, error.kind(), "filesystem error kind must match");
    assert_eq!(operation, error.operation(), "filesystem error operation must match",);
    assert_eq!(path, error.path(), "filesystem error path must match");
    assert_eq!(
        capability,
        error.required_capability(),
        "filesystem error required capability must match",
    );
    assert!(
        error.provider().is_none() || error.provider() == provider,
        "filesystem error provider must be absent or match the configured provider",
    );
}

/// Validates that a missing-resource error matches the stat contract while
/// preserving the original error as the failure source.
///
/// # Parameters
///
/// * `error` - Owned filesystem error to validate and retain on failure.
/// * `path` - Requested path that the error must identify.
/// * `provider` - Provider identifier that reported the operation; an absent
///   provider in the error is accepted.
/// * `check` - Contract check identifier attached to any failure.
///
/// # Returns
///
/// Returns `Ok(())` when the error is a path-matching `NotFound` result from a
/// `Stat` operation with no target or required capability. Otherwise returns
/// an attributed contract failure containing the original filesystem error.
///
/// # Errors
///
/// Returns `ContractFailure` when the kind, operation, path, target,
/// capability, or reported provider differs from the required contract.
pub(crate) fn verify_missing_error(
    error: FsError,
    path: &Path,
    provider: &str,
    check: crate::ContractCheckId,
) -> Result<(), crate::ContractFailure> {
    let valid = error.kind() == FsErrorKind::NotFound
        && error.operation() == FsOperation::Stat
        && error.path() == Some(path)
        && error.target().is_none()
        && error.required_capability().is_none()
        && error.provider().is_none_or(|actual| actual == provider);
    if valid {
        Ok(())
    } else {
        Err(
            crate::ContractFailure::with_source("missing-resource error context differs from the contract", error)
                .at(check),
        )
    }
}

/// Checks structured filesystem error fields against the expected contract.
///
/// # Parameters
///
/// * `error` - Owned filesystem error to validate and retain on failure.
/// * `kind` - Required error classification.
/// * `operation` - Required filesystem operation.
/// * `path` - Required path associated with the operation.
/// * `provider` - Expected provider identifier; an absent provider in the error
///   is accepted.
/// * `capability` - Required capability context, if any.
/// * `check` - Contract check identifier attached to any failure.
///
/// # Returns
///
/// Returns `Ok(())` when all checked fields match. Otherwise returns an
/// attributed contract failure containing the original filesystem error.
///
/// # Errors
///
/// Returns `ContractFailure` when the error kind, operation, path,
/// capability, or reported provider differs from the expected value.
pub(crate) fn verify_fs_error(
    error: FsError,
    kind: FsErrorKind,
    operation: FsOperation,
    path: &Path,
    provider: &str,
    capability: Option<FileSystemCapability>,
    check: crate::ContractCheckId,
) -> Result<(), crate::ContractFailure> {
    let valid = error.kind() == kind
        && error.operation() == operation
        && error.path() == Some(path)
        && error.required_capability() == capability
        && error.provider().is_none_or(|actual| actual == provider);
    if valid {
        Ok(())
    } else {
        Err(crate::ContractFailure::with_source(format!("{check}: filesystem error context mismatch"), error).at(check))
    }
}

/// Validates a condition and attributes failure to its contract check without
/// formatting observed provider data.
///
/// # Parameters
///
/// * `condition` - Whether the checked contract condition holds.
/// * `check` - Contract check identifier attached to any failure.
/// * `message` - Explanation included in the failure when the condition is
///   false.
///
/// # Returns
///
/// Returns `Ok(())` when `condition` is true; otherwise returns a
/// check-attributed failure containing `message`.
///
/// # Errors
///
/// Returns `ContractFailure` when `condition` is false.
pub(crate) fn verify_condition(
    condition: bool,
    check: crate::ContractCheckId,
    message: &str,
) -> Result<(), crate::ContractFailure> {
    if condition {
        Ok(())
    } else {
        Err(crate::ContractFailure::message_only(format!("{check}: {message}")).at(check))
    }
}

#[cfg(test)]
mod tests {
    use qubit_fs::error::FsError;
    use qubit_fs::error::FsErrorKind;
    use qubit_fs::error::FsOperation;
    use qubit_fs::metadata::FileSystemCapability;
    use qubit_fs::path::Path;

    use super::assert_error;
    use super::assert_error_with_source_or_target;
    use super::assert_error_with_target;
    use super::assert_unsupported_error;
    use super::verify_condition;
    use super::verify_fs_error;
    use super::verify_missing_error;

    #[test]
    fn test_error_assertions_accept_matching_structured_context() {
        let path = Path::parse("/source").unwrap();
        let target = Path::parse("/target").unwrap();
        let capability = FileSystemCapability::Read;
        let error = || {
            FsError::new(FsErrorKind::Io, FsOperation::Read, "read failed")
                .with_path(path.clone())
                .with_provider("memory")
                .with_required_capability(capability)
        };

        assert_error(
            &error(),
            FsErrorKind::Io,
            FsOperation::Read,
            Some(&path),
            Some("memory"),
            Some(capability),
        );
        assert_error_with_target(
            &error().with_target(target.clone()),
            FsErrorKind::Io,
            FsOperation::Read,
            Some(&path),
            Some(&target),
            Some("memory"),
            Some(capability),
        );
        assert_error_with_source_or_target(
            &error().with_path(target.clone()).with_target(target.clone()),
            FsErrorKind::Io,
            FsOperation::Read,
            &path,
            &target,
            Some("memory"),
            Some(capability),
        );
        assert_unsupported_error(
            &FsError::new(FsErrorKind::UnsupportedCapability, FsOperation::Read, "unsupported")
                .with_path(path.clone())
                .with_required_capability(capability),
            FsErrorKind::UnsupportedCapability,
            FsOperation::Read,
            Some(&path),
            Some("memory"),
            Some(capability),
        );
    }

    #[test]
    fn test_error_verifiers_accept_and_reject_structured_context() {
        let path = Path::parse("/missing").unwrap();
        let check = crate::ContractCheckId::ReadBasic;
        let missing = FsError::new(FsErrorKind::NotFound, FsOperation::Stat, "missing").with_path(path.clone());
        assert!(verify_missing_error(missing, &path, "memory", check).is_ok());

        let wrong_missing = FsError::new(FsErrorKind::Io, FsOperation::Stat, "wrong kind").with_path(path.clone());
        assert!(verify_missing_error(wrong_missing, &path, "memory", check).is_err());

        let matching = FsError::new(FsErrorKind::Io, FsOperation::Read, "read failed")
            .with_path(path.clone())
            .with_provider("memory");
        assert!(
            verify_fs_error(
                matching,
                FsErrorKind::Io,
                FsOperation::Read,
                &path,
                "memory",
                None,
                check,
            )
            .is_ok()
        );

        let mismatching = FsError::new(FsErrorKind::Io, FsOperation::Read, "wrong provider")
            .with_path(path.clone())
            .with_provider("other");
        assert!(
            verify_fs_error(
                mismatching,
                FsErrorKind::Io,
                FsOperation::Read,
                &path,
                "memory",
                None,
                check,
            )
            .is_err()
        );

        assert!(verify_condition(true, check, "condition").is_ok());
        assert!(verify_condition(false, check, "condition").is_err());
    }
}