2 releases

Uses new Rust 2024

new 0.1.1 Mar 27, 2025
0.1.0 Mar 27, 2025

#1083 in Rust patterns

32 downloads per month

MIT license

6KB

should_error

NOTE: This crate is deprecated in favor of should_match.

Pass a test if an error is returned.

Setup

This crate is primarily intended for use in tests, so add it to your dev-dependencies instead of dependencies:

cargo add --dev should_error

Recommended to work with macro_rules_attr:

cargo add --dev macro_rules_attr should_error

Usage

With macro_rules_attr

Simply apply the should_error macro (the order does not matter):

use macro_rules_attr::apply;
use should_error::should_error;

// This test will pass
#[apply(should_error)]
#[test]
fn test_apply_first() -> Result<(), &'static str> {
    Err("error")
}

// This test will also pass
#[test]
#[apply(should_error)]
fn test_apply_second() -> Result<(), &'static str> {
    Err("error")
}

To further specify the pattern that's expected to match, use the expected argument:

# use macro_rules_attr::apply;
# use should_error::should_error;
#
#[test]
#[apply(should_error, expected = Err("error"))]
fn test_with_error_expected() -> Result<(), &'static str> {
    Err("error")
}

You can also match anything else other than an Err:

# use macro_rules_attr::apply;
# use should_error::should_error;
#
#[allow(dead_code, reason = "Only used in tests")]
enum MyEnum {
    One,
    Two,
}

#[test]
#[apply(should_error, expected = MyEnum::One)]
fn test_with_arbitrary_expected() -> MyEnum {
    MyEnum::One
}

Directly

Wrap your tests with should_error! (note that the #[test] attribute must be wrapped inside the macro):

use should_error::should_error;

// This test will pass
should_error! {
    #[test]
    fn test() -> Result<(), &'static str> {
        Err("error")
    }
}

// This is not a valid test: the `#[test]` attribute may only be used on a non-associated function
#[test]
should_error! {
    fn test() -> Result<(), &'static str> {
        Ok(())
    }
}

To further specify the pattern that's expected to match, use the expected argument:

# use should_error::should_error;
#
should_error! {
    #[test]
    fn test_with_error_expected() -> Result<(), &'static str> {
        Err("error")
    }, expected = Err("error")
}

You can also match anything else other than an Err:

# use should_error::should_error;
#
# #[allow(dead_code, reason = "Only used in tests")]
enum MyEnum {
    One,
    Two,
}

should_error! {
    #[test]
    fn test_with_arbitrary_expected() -> MyEnum {
        MyEnum::One
    }, expected = MyEnum::One
}

No runtime deps