Skip to main content

OrFailExt

Trait OrFailExt 

Source
pub trait OrFailExt<T> {
    // Required method
    fn or_fail(self) -> TestResult<T>;
}
Expand description

Provides an extension method for converting an arbitrary type into a TestResult.

A type can implement this trait to provide an easy way to return immediately from a test in conjunction with the ? operator. This is useful for Option as well as Result types whose Result::Err variant does not implement std::error::Error.

There is an implementation of this trait for anyhow::Error (which does not implement std::error::Error) when the anyhow feature is enabled. Importing this trait allows one to easily map anyhow::Error to a test failure.

This is also implemented for Option.

See or_fail for usage examples.

Required Methods§

Source

fn or_fail(self) -> TestResult<T>

Converts this instance into a TestResult.

Invoking this method allows direct use of the ? operator in tests. For example, in the case of Option:

use test_that::prelude::*;

#[test]
fn fails_due_to_missing_element() -> TestResult<()> {
    let empty_hash_map = std::collections::HashMap::<u32, u32>::new();
    let value = empty_hash_map.get(&0).or_fail()?;
    Ok(())
}

fails_due_to_missing_element().unwrap_err();

In the case of anyhow::Error:

use test_that::prelude::*;

#[test]
fn fails_due_to_anyhow_error() -> TestResult<()> {
    something_which_can_fail().or_fail()?;
    Ok(())
}

fn something_which_can_fail() -> anyhow::Result<()> {
    anyhow::bail!("An error")
}

fails_due_to_anyhow_error().unwrap_err();

Typically, the Self type is itself a Result or an Option. This method should then map None or the Err variant to a [TestAssertionFailure] and leave the Some or Ok variant unchanged.

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Types§

Source§

impl<OkT, CaseT: Debug> OrFailExt<OkT> for Result<OkT, TestError<CaseT>>

Available on crate feature proptest only.
Source§

fn or_fail(self) -> Result<OkT, TestAssertionFailure>

Source§

impl<T> OrFailExt<T> for Option<T>

Source§

fn or_fail(self) -> Result<T, TestAssertionFailure>

Source§

impl<T> OrFailExt<T> for Result<T, Error>

Available on crate feature anyhow only.
Source§

fn or_fail(self) -> Result<T, TestAssertionFailure>

Implementors§