7 releases (4 breaking)

0.5.0 Oct 10, 2024
0.4.2 Apr 24, 2023
0.3.0 Apr 2, 2023
0.2.0 Mar 31, 2023
0.1.0 Mar 26, 2023

#163 in Testing

Download history 2/week @ 2024-09-23 4/week @ 2024-09-30 152/week @ 2024-10-07 16/week @ 2024-10-14

174 downloads per month
Used in flagger

MIT/Apache

28KB
661 lines

should

crates.io docs msrv

should is a postfix assertion library for Rust, heavily inspired by Shouldly. It aims to make writing assertions feel more natural, while also providing clearer error messages.

use should::*;

fn multiply(x: i32, y: i32) -> i32 {
    x + y // Oh no a bug!
}

#[test]
fn test_multiply() {
    multiply(3, 5).should_be(15);
}
panicked at 'multiply(3, 5) should be 15 but was 8'

Assertions

Implemented for T: PartialEq as well as Ok(T) and Some(T)

  • should_be
  • should_not_be

Implemented for T: PartialOrd as well as Ok(T) and Some(T)

  • should_be_lt
  • should_be_le
  • should_be_gt
  • should_be_ge

Implemented for Option<T>

  • should_be_some
  • should_be_none

Implemented for Result<T, E>

  • should_be_ok
  • should_be_err

Implemented for str

  • should_start_with
  • should_not_start_with
  • should_end_with
  • should_not_end_with

Implemented for T: IntoIterator

  • should_be_empty
  • should_not_be_empty

All asserted types are required to have implemented the Debug trait.

How does it work?

should defines a set of assertion traits, which it implements generically for most types. This is what enables the postfix syntax.

When the assertion fails, should uses a stacktrace to reconstruct the original expression. It finds the file and line where should was called, parses the original expression, and uses that information to generate a nice panic message.

This does however mean that builds without debug symbols (e.g. release build by default) are not able to retrieve the expression. A placeholder will be used for the expression when this is the case, and everything else should still work as expected.

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

Dependencies

~5–11MB
~122K SLoC