Test That!
Test That! is a powerful test assertion library for Rust.
TL;DR
Write test assertions which precisely specify your intent:
let vec = vec!;
assert_that!;
and get informative, meaningful diagnostics when the tests fail:
Value of: vec
Expected: only contains elements that is greater than 0
Actual: [5, 123, -4],
whose element #2 is -4, which is less than or equal to 0
Background
The existing assertions which come with Rust are fairly primitive:
assert!assert_eq!assert_matches!(as of Rust 1.96)
These work fine for simple cases. But suppose you want to express something
like "every element of this Vec is positive". You could assert on the exact
values:
assert_eq!;
But then the test may be brittle. The specific values might change, causing the test to fail. But the intent of the test is just that the values are positive, so nothing is really wrong.
You could also express the intent with a computation:
assert!;
What happens, then, when the test fails?
assertion failed: vec.into_iter().all(|i| i > 0)
There's no context in the assertion failure. You look at the test logs of
your CI system and only see this one message. No indication what the contents
of vec were or which element caused the failure. To get that information, you
already have to rerun the test and investigate. Possibly adding more debugging
information. This costs time and nerves.
Test That! lets you write test assertions which precisely capture your intent while then producing test failure messages which tell you exactly what was wrong.
assert_that!;
Value of: vec
Expected: only contains elements that is greater than 0
Actual: [-1],
whose element #0 is -1, which is less than or equal to 0
Writing test assertions is a finger exercise. You can churn out tests without having to think much about how they show up when they fail.
History of this crate
I started Test That! as a fork of the crate GoogleTest Rust, which I had spearheaded while working at Google. The goal of the fork is to provide a more ergonomic developer experience than GoogleTest Rust does. See my blog post for more information my motivations for this fork.
The GoogleTest Rust was in turn inspired by Google's C++ testing library GoogleTest. Its goal was to bring the powerful assertions and matchers of GoogleTest to the Rust world.
A brief tour of Test That!
The core of Test That! is its matchers. Matchers indicate what aspect of an actual value one is asserting: (in-)equality, containment, regular expression matching, and so on.
To make an assertion using a matcher, Test That! offers three macros:
assert_that!panics if the assertion fails, aborting the test.expect_that!logs an assertion failure, marking the test as having failed, but allows the test to continue running (called a non-fatal assertion). It requires the use of thetest_that::testattribute macro on the test itself.verify_that!has no side effects and evaluates to aResultwhoseErrvariant describes the assertion failure, if there is one (type alias:TestResult). In combination with the?operator, this can be used to abort the test on assertion failure without panicking. (It is also the building block for the other two macros above.)
For example:
use *;
This library includes a rich set of matchers, covering:
- Equality, numeric inequality, and approximate equality;
- Strings and regular expressions;
- Containers and set-theoretic matching.
Matchers are composable:
use *;
They can also be logically combined:
use *;
Pattern-matching
One can use the macro matches_pattern! to create a composite matcher for a
struct or enum that matches fields with other matchers:
use *;
Writing matchers
One can write one's own matchers. To do so, create a struct holding the
matcher's data and have it implement the traits Matcher and
Describable:
One should also expose a function which constructs the matcher:
The new matcher can then be used in the assertion macros:
Non-fatal assertions
Using non-fatal assertions, a single test is able to log multiple assertion failures. Any single assertion failure causes the test to be considered having failed, but execution continues until the test completes or otherwise aborts.
This is analogous to the EXPECT_* family of macros in GoogleTest.
To make a non-fatal assertion, use the macro expect_that!. The test must
also be marked with test_that::test instead of the Rust-standard #[test].
use *;
This can be used in the same tests as verify_that!, in which case the test
function must also return Result:
use *;
use *;
Interoperability
You can use the #[test_that::test] macro together with many other libraries
such as rstest and
tokio. Just apply both attribute macros to the
test:
async
Predicate assertions
The macro verify_pred! provides predicate assertions analogous to
GoogleTest's EXPECT_PRED family of macros. Wrap an invocation of a predicate
in a verify_pred! invocation to turn that into a test assertion which passes
precisely when the predicate returns true:
let x = 3;
let y = 4;
verify_pred!?;
The assertion failure message shows the arguments and the values to which they evaluate:
stuff_is_correct(x, y) was false with
x = 3,
y = 4
The verify_pred! invocation evaluates to a Result just like
verify_that!. There is also a macro expect_pred! to make a non-fatal
predicate assertion.
Unconditionally generating a test failure
The macro fail! unconditionally evaluates to a Result indicating a test
failure. It can be used analogously to verify_that! and verify_pred! to
cause a test to fail, with an optional formatted message:
Configuration
This library is configurable through environment variables. Since the
configuration does not impact whether a test fails or not but how a failure is
displayed, we recommend setting those variables in the personal
~/.cargo/config.toml instead of in the project-scoped Cargo.toml.
The following environment variables are supported:
| Variable name | Description |
|---|---|
| NO_COLOR | Disables colored output. See https://no-color.org/. |
| FORCE_COLOR | Forces colors even when the output is piped to a file. |
Dependencies and nostd
Test That! runs in nostd environments, though it does require an allocator.
It also has no required dependencies. Regular expression matching, floating point matching and non-fatal assertions require features which are enabled by default.
Porting from GoogleTest Rust
GoogleTest Rust made major changes between versions 0.11 and 0.12, so there are separate instructions.
GoogleTest Rust 0.11
Key differences are:
-
Matchernow takes its actual value as a type parameter and not an associated type. -
The
describemethod is now in a separate traitDescribable, which must be implemented to implementMatcher. -
The alias
Resulthas been renamed toTestResult. -
The macro
elements_are!has been renamedcontains_exactly!. -
The macro
unordered_elements_are!has been removed. Instead, a new methodin_order()is available on the matcher produced by the macroscontains_exactly!,contains_each!, andis_contained_in!to provide the same functionality. -
The syntax for matching
HashMapwithcontains_exactly!has changed from pairs tokey => valueexpressions. So what was previously:let map = from; assert_that!;becomes:
let map = from; assert_that!; -
The macro
property!has been removed in favour of a new macroresult_of!.
To facilitate porting existing code, Test That! has two features:
googletest-compat: Reintroduces symbol names used in GoogleTest Rust as much as feasible. This minimizes the actual code changes you must make. In particular, it adds:test_that::Resultas an alias fortest_that::TestResult,elements_are!as an alias forcontains_exactly![...].in_order(),unordered_elements_are!as an alias forcontains_exactly!,into_test_result()as an alias foror_fail(), and- the pair-based syntax for matching against
HashMapinunordered_elements_are!(not, however, forcontains_each!oris_contained_in!).
googletest-migrate: Marks, as much as possible, each of the aliases introduced bygoogletest-compatas deprecated, so you can easily find and update them. This feature impliesgoogletest-compat.
I believe that this covers most cases. You will have to manually port any other changes.
GoogleTest Rust 0.12 and later
The key differences include:
-
In GoogleTest,
Matcher::matchestakes an owned value which must beCopy. In Test That!, it takes a reference, just as in GoogleTest prior to 0.11. This means that nearly all cases where one must add&orrefin GoogleTest are not required (or allowed) in Test That!. For example, in GoogleTest:assert_that!;is in Test That!:
assert_that!; -
The
matches_pattern!matcher in Test That! does not support exhaustive matching. The..syntax used in GoogleTest is neither necessary nor allowed. -
The attribute macro to enable non-fatal assertions in Test That! is
#[test_that::test]rather than#[gtest]. -
Test That! has no
verify_eq!or similar. Useverify_that!(.., eq()). -
Test That! does not support the implicit
eqmatcher:verify_that!(value, 123). One must use theeqmatcher explicitly. -
Test That! also has no matcher
ne. Usenot(eq(..)). -
There is no support for fixtures. Such functionality is available in the crate rstest.
-
As with GoogleTest 0.11, the equivalent alias to
ResultisTestResult. -
As with GoogleTest 0.11, there is no macro
property!. -
The same notes as above apply to
elements_are!andunordered_elements_are!.
Contributing Changes
Please read CONTRIBUTING.md for details on how to contribute to this project.