Fixture-based test framework for Rust
[![Crate][crate-image]][crate-link] [![Docs][docs-image]][docs-link] [![Status][test-action-image]][test-action-link] [![Apache 2.0 Licensed][license-apache-image]][license-apache-link] [![MIT Licensed][license-mit-image]][license-mit-link]
rstest uses procedural macros to help you on writing
fixtures and table-based tests. To use it, add the
following lines to your Cargo.toml file:
[dev-dependencies]
rstest = "0.27.0"async-timeout: timeout for async tests (Default enabled)crate-name: Import rstest package with different name (Default enabled)The core idea is that you can inject your test dependencies
by passing them as test arguments. In the following example,
a fixture is defined and then used in two tests,
simply providing it as an argument:
use rstest::*;
#[fixture]
pub fn fixture() -> u32 { 42 }
#[rstest]
fn should_success(fixture: u32) {
assert_eq!(fixture, 42);
}
#[rstest]
fn should_fail(fixture: u32) {
assert_ne!(fixture, 42);
}You can also inject values in some other ways. For instance, you can
create a set of tests by simply providing the injected values for each
case: rstest will generate an independent test for each case.
use rstest::rstest;
#[rstest]
#[case(0, 0)]
#[case(1, 1)]
#[case(2, 1)]
#[case(3, 2)]
#[case(4, 3)]
fn fibonacci_test(#[case] input: u32, #[case] expected: u32) {
assert_eq!(expected, fibonacci(input))
}Running cargo test in this case executes five tests:
running 5 tests
test fibonacci_test::case_1 ... ok
test fibonacci_test::case_2 ... ok
test fibonacci_test::case_3 ... ok
test fibonacci_test::case_4 ... ok
test fibonacci_test::case_5 ... ok
test result: ok. 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered outIf you need to just providing a bunch of values for which you
need to run your test, you can use #[values(list, of, values)]
argument attribute:
use rstest::rstest;
#[rstest]
fn should_be_invalid(
#[values(None, Some(""), Some(" "))]
value: Option<&str>
) {
assert!(!valid(value))
}Or create a matrix test by using list of values for some variables that will generate the cartesian product of all the values.
If you need to use a test list for more than one test you can use [rstest_reuse][reuse-crate-link]
crate. With this helper crate you can define a template and use it everywhere.
use rstest::rstest;
use rstest_reuse::{self, *};
#[template]
#[rstest]
#[case(2, 2)]
#[case(4/2, 2)]
fn two_simple_cases(#[case] a: u32, #[case] b: u32) {}
#[apply(two_simple_cases)]
fn it_works(#[case] a: u32, #[case] b: u32) {
assert!(a == b);
}See [rstest_reuse][reuse-crate-link] for more details.
In case you want certain test cases to only be present if a certain feature is
enabled, use #[cfg_attr(feature = …, case(…))]:
use rstest::rstest;
#[rstest]
#[case(2, 2)]
#[cfg_attr(feature = "frac", case(4/2, 2))]
fn it_works(#[case] a: u32, #[case] b: u32) {
assert!(a == b);
}This also works with [rstest_reuse][reuse-crate-link].
If you need a value where its type implement FromStr() trait you can use a literal
string to build it:
# use rstest::rstest;
# use std::net::SocketAddr;
#[rstest]
#[case("1.2.3.4:8080", 8080)]
#[case("127.0.0.1:9000", 9000)]
fn check_port(#[case] addr: SocketAddr, #[case] expected: u16) {
assert_eq!(expected, addr.port());
}You can use this feature also in value list and in fixture default value.
rstest supports async tests, but makes no assumptions about what
async runtime you are using. Async tests require either an
explicit test attribute or an
implicit test attribute.
You are responsible for providing any appropriate peer dependencies to run your async tests.
If your test input is an async value (fixture or test parameter) you can use #[future]
attribute to remove impl Future<Output = T> boilerplate and just use T:
use rstest::*;
#[fixture]
async fn base() -> u32 { 42 }
#[rstest]
#[tokio::test]
#[case(21, async { 2 })]
#[case(6, async { 7 })]
async fn my_async_test(
#[future] base: u32,
#[case] expected: u32,
#[future] #[case] div: u32
) {
assert_eq!(expected, base.await / div.await);
}As you noted you should .await all future values and this sometimes can be really boring.
In this case you can use #[future(awt)] to awaiting an input or annotating your function
with #[awt] attributes to globally .await all your future inputs. Previous code can be
simplified as follows:
use rstest::*;
# #[fixture]
# async fn base() -> u32 { 42 }
#[rstest]
#[tokio::test]
#[case(21, async { 2 })]
#[case(6, async { 7 })]
#[awt]
async fn global(
#[future] base: u32,
#[case] expected: u32,
#[future] #[case] div: u32
) {
assert_eq!(expected, base / div);
}
#[rstest]
#[tokio::test]
#[case(21, async { 2 })]
#[case(6, async { 7 })]
async fn single(
#[future] base: u32,
#[case] expected: u32,
#[future(awt)] #[case] div: u32
) {
assert_eq!(expected, base.await / div);
}If you need to create a test for each file in a given location you can use
#[files("glob path syntax")] attribute to generate a test for each file that
satisfy the given glob path.
#[rstest]
fn for_each_file(
#[files("src/**/*.rs")]
#[exclude("test")] path: PathBuf
) {
assert!(check_file(&path))
}The default behavior is to ignore the files that start with ".", but you can
modify this by use #[include_dot_files] attribute. The files attribute can be
used more than once on the same variable, and you can also create some custom
exclusion rules with the #[exclude("regex")] attributes that filter out all
paths that verify the regular expression.
You can pass in environment variables by using ${ENV_VAR_NAME} in the glob
path, e.g. #[files("${SOME_ENV}/hello")]. To set a default value for the
environment variable, use ${ENV_VAR_NAME:-default_value}.
Files are resolved at compile time against your Cargo project root
(the CARGO_MANIFEST_DIR environment variable). If you need to change this
behavior, you can use the #[base_dir = "..."] attribute to specify a different
base directory. That directory MUST exist, and will be used as the root for
the files, as well as to resolve the relative path when creating the test name.
Similar to the files attribute, you can use ${ENV_VAR_NAME} in the base_dir.
The #[files(...)] attribute ignores matched directory paths by default,
returning only file paths. If you need the test cases to include directories
found by the glob pattern, use the #[dirs] attribute in conjunction with #[files(...)].
#[once] FixtureIf you need to a fixture that should be initialized just once for all tests
you can use #[once] attribute. rstest call your fixture function just once and
return a reference to your function result to all your tests:
#[fixture]
#[once]
fn once_fixture() -> i32 { 42 }
#[rstest]
fn single(once_fixture: &i32) {
// All tests that use once_fixture will share the same reference to once_fixture()
// function result.
assert_eq!(&42, once_fixture)
}#[timeout()]You can define an execution timeout for your tests with #[timeout(<duration>)] attribute. Timeout
works both for sync and async tests and is runtime agnostic. #[timeout(<duration>)] take an
expression that should return a std::time::Duration. Follow a simple async example:
use rstest::*;
use std::time::Duration;
async fn delayed_sum(a: u32, b: u32, delay: Duration) -> u32 {
async_std::task::sleep(delay).await;
a + b
}
#[rstest]
#[async_std::test]
#[timeout(Duration::from_millis(80))]
async fn single_pass() {
assert_eq!(4, delayed_sum(2, 2, ms(10)).await);
}In this case test pass because the delay is just 10 milliseconds and timeout is 80 milliseconds.
You can use timeout attribute like any other attribute in your tests, and you can
override a group timeout with a case specific one. In the follow example we have
3 tests where first and third use 100 milliseconds but the second one use 10 milliseconds.
Another valuable point in this example is to use an expression to compute the
duration.
fn ms(ms: u32) -> Duration {
Duration::from_millis(ms.into())
}
#[rstest]
#[case::pass(ms(1), 4)]
#[timeout(ms(10))]
#[case::fail_timeout(ms(60), 4)]
#[case::fail_value(ms(1), 5)]
#[timeout(ms(100))]
async fn group_one_timeout_override(#[case] delay: Duration, #[case] expected: u32) {
assert_eq!(expected, delayed_sum(2, 2, delay).await);
}If you want to use timeout for async test you need to use async-timeout
feature (enabled by default).
You can set a default timeout for test using the RSTEST_TIMEOUT environment variable.
The value is in seconds and is evaluated on test compile time.
If your test contains an attribute #[test_attr(...)], this is an explicit test attribute declaration.
The contents of the parentheses will be inserted as an attribute of your test. This allows for arbitrary
test attribute syntax.
For instance, if you want to test an async function with smol_macros::test,
you can write
use rstest::*;
use macro_rules_attribute::apply;
use smol_macros::test;
use std::future::Future;
#[rstest]
#[case(2, async { 4 })]
#[case(21, async { 42 })]
#[test_attr(apply(test))]
async fn my_async_test(#[case] a: u32, #[case] #[future] result: u32) {
assert_eq!(2 * a, result.await);
}When using an explicit test attribute, ensure it appears after any #[case()] attributes so that the attribute binds
to the test function and not the case.
If your test contains an attribute whose path ends in test, this is treated
as an implicit test attribute, and replaces the default #[test] attribute.
Simply including the attribute in your test's attribute list is all that is required.
For instance, if you want to test an async function with the actix_rt::test attribute, you can just write:
use rstest::*;
use actix_rt;
use std::future::Future;
#[rstest]
#[case(2, async { 4 })]
#[case(21, async { 42 })]
#[actix_rt::test]
async fn my_async_test(#[case] a: u32, #[case] #[future] result: u32) {
assert_eq!(2 * a, result.await);
}Implicit test attributes have a lower priority than explicit test attributes.
If you have an unrelated attribute whose path ends in test, you should declare an explicit test attribute
for deconfliction.
When using an implicit test attribute, ensure it appears after any #[case()] attributes so that the attribute binds to the
test function and not the case.
Synchronous tests use #[test] as the default test attribute if nothing else is supplied explicitly or implicitly.
Asynchronous tests will fail to compile if no test attribute is specified explicitly or implicitly.
Context objectYou can have a [Context] object for your test just by annotate an argument by #[context] attribute.
This object contains some useful information both to implement simple logics and debugging stuff.
use rstest::{rstest, Context};
#[rstest]
#[case::a_description(42)]
fn my_test(#[context] ctx: Context, #[case] _c: u32) {
assert_eq!("my_test", ctx.name);
assert_eq!(Some("a_description"), ctx.description);
assert_eq!(Some(0), ctx.case);
std::thread::sleep(std::time::Duration::from_millis(100));
assert!(ctx.start.elapsed() >= std::time::Duration::from_milliNo open issues yet, or sync has not completed.