Sub topic 16
Running, filtering, and controlling tests
This chapter assumes you can write #[test] functions, know the difference between unit, integration, and doc tests, and can read a Cargo.toml. It covers how cargo test chooses what to run, how to narrow that selection, and how to change how the tests execute.
What `cargo test` builds and runs
cargo test does not run your tests directly. It compiles a separate test executable for each target in the package and runs them one after another. A package with a library, a binary, two files in tests/, and documentation examples produces these runs, in this order:
- Unit tests inside the library (
src/lib.rsand its modules). - Unit tests inside each binary target.
- One run per file in
tests/. - Doc tests, which
rustdoccompiles and runs last.
By default, a failing stage stops the later ones. If the library's unit tests fail, you never see the integration or doc test results. Pass --no-fail-fast to run every stage regardless:
cargo test --no-fail-fastThe process exits with a non-zero status if any test failed, which is what CI systems check.
Two sets of arguments
Arguments to cargo test are split at a -- separator.
- Before
--, the arguments go to Cargo. They choose what to build and run, such as--lib,--test area,--release, or-p core. - After
--, the arguments go to each test executable. They control how tests run, such as--nocapture,--test-threads=1, or--ignored.
Mixing them up is the most common error. cargo test --nocapture fails because Cargo does not know that flag. cargo test -- --lib fails because the test executable does not know it.
A small crate to experiment with
The examples below use this src/lib.rs for a package named my_geometry.
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
println!("checking add(2, 3)");
assert_eq!(add(2, 3), 5);
}
#[test]
fn adds_negative_numbers() {
assert_eq!(add(-2, -3), -5);
}
#[test]
#[ignore = "slow: sums a large range"]
fn adds_many_numbers() {
let total = (1..=1_000_000).fold(0i64, |acc, n| acc + n as i64);
assert_eq!(total, 500_000_500_000);
}
}Selecting which targets run
These flags go before -- and decide which test executables Cargo builds and runs.
| Command | What runs |
|---|---|
| `cargo test --lib` | Unit tests of the library only |
| `cargo test --bins` | Unit tests of all binary targets |
| `cargo test --test area` | Only the integration test file `tests/area.rs` |
| `cargo test --tests` | Unit tests and all integration tests, no doc tests |
| `cargo test --doc` | Only doc tests |
| `cargo test -p core` | Tests of the package `core` in a workspace |
| `cargo test --workspace` | Tests of every workspace member |
In a workspace, running cargo test at the root tests only the default members. If the root is a virtual manifest with no package of its own, that means all members. Use --workspace when you want to be certain.
Filtering by name
A bare word after cargo test is a name filter. A test runs if its full path contains the filter as a substring. The full path includes the module path, such as tests::adds_two_numbers.
cargo test adds_two # matches adds_two_numbers
cargo test adds # matches all three tests (the ignored one is skipped)
cargo test tests:: # matches everything in the tests moduleThe filter applies to every test executable. Executables with no matching tests still run and report 0 passed, so a filtered run can print several empty result blocks. This is normal.
Options after -- refine the match:
cargo test -- --exact tests::adds_two_numbers # full path must match exactly
cargo test -- --skip adds_negative # run everything except matches
cargo test -- adds_two adds_negative # several filters: any match runs--exact needs the complete path. adds_two_numbers alone does not match, because the real name is tests::adds_two_numbers. You can combine --skip with a positive filter, for example cargo test adds -- --skip many.
To see what would run without running it, list the tests:
cargo test -- --listDoc tests are named by file and line, such as src/lib.rs - add (line 3). You can filter them with cargo test --doc add.
Controlling output
The test harness captures anything a test writes with println! or eprintln!. It shows that output only for failing tests. So adds_two_numbers prints nothing when it passes.
cargo test -- --nocapture # print output live, as tests run
cargo test -- --show-output # print captured output of passing tests too
cargo test -- --quiet # one character per test instead of one lineThe difference matters. --nocapture disables capturing, so output from parallel tests can interleave. --show-output keeps capturing and prints each test's output in a block at the end, which stays readable.
Parallelism and shared state
The harness runs tests on multiple threads. By default it uses one thread per available CPU. Each test runs in its own thread, so tests must not depend on execution order.
cargo test -- --test-threads=1 # run tests one at a time
RUST_TEST_THREADS=1 cargo test # same, through an environment variableSetting --test-threads=1 also makes --nocapture output readable, because only one test prints at a time.
Ignoring tests
Mark slow or environment-dependent tests with #[ignore]. An optional string gives the reason, and the harness prints it in the results.
cargo test # ignored tests are listed as "ignored" and not run
cargo test -- --ignored # run only the ignored tests
cargo test -- --include-ignored # run ignored and normal tests togetherA test run result line looks like this:
test result: ok. 2 passed; 0 failed; 1 ignored; 0 measured; 0 filtered outThe filtered out count is the number of tests excluded by a name filter or --skip. It separates "excluded because of my filter" from "ignored by the attribute". If a test you expected never ran, check which of these two counters moved.
Common mistakes
- Putting harness flags before
--. Cargo rejectscargo test --nocapture. Writecargo test -- --nocapture. - Expecting
--libto include integration tests. Files intests/need--test nameor--tests. - Expecting a filter to select a target.
cargo test areafilters test names. It does not picktests/area.rs. Use--test areafor that. - Reading a green run as complete. Ignored tests are not run, and a failure in an early stage hides later stages unless you pass
--no-fail-fast. - Using
--exactwith a short name. It needs the full module path.
Exercise
A package has a library with unit tests, a file tests/api.rs, and doc examples. You want to run only the tests in tests/api.rs whose names contain parse, and you want to see their println! output even when they pass. Which command do you run, and why does each argument sit on its side of --?
Show answer
cargo test --test api -- parse --show-output. --test api is a Cargo flag that selects the tests/api.rs executable, so it goes before --. The parse name filter and --show-output are handled by the test executable, so they go after --. Without --test api, the filter would also run in the library unit tests and the doc tests.
Exercise
You run cargo test and the library's unit tests fail, but you also want to know whether the doc tests pass. What do you add to the command, and what does the exit status look like afterward?
Show answer
Add --no-fail-fast: cargo test --no-fail-fast. Cargo then runs every test executable, including the doc tests, even after an earlier one fails. The exit status is still non-zero, because at least one test failed.