Testing Strategy
Use different types of tests to find regressions, panics, and changes in behavior before a release. Line coverage shows which code the tests execute.
Test commands
For each test binary, cargo test uses one process for all tests. Changes to
global state or environment variables can affect other tests in that process.
Use cargo-nextest for the main test suite. If the crate
has a library target, use cargo test --doc for doctests.
cargo nextest run --locked# If the package has a library target (src/lib.rs), start the doctests.# If the package has only a binary target, omit this command.cargo test --doc --lockedWhy cargo-nextest?
cargo-nextestuses one operating system process for each test. A panic, abort, working directory change, or thread leak stays in that process.cargo-nextestcan complete tests up to three times faster on multi-core runners. It also gives slow-test warnings, detects leaks, and writes JUnit XML.cargo test --doc --lockedcompiles and executes the applicable examples in the API documentation of a library target.
Unit tests
Put unit tests in a mod tests block next to the code.
#[cfg(test)]mod tests { use super::*;
#[test] fn name_defaults_when_missing() { let cfg: Config = serde_json::from_str("{}").unwrap(); assert_eq!(cfg.display_name(), "default"); }
#[test] fn name_uses_configured_value_when_present() { let cfg: Config = serde_json::from_str(r#"{"name":"alpha"}"#).unwrap(); assert_eq!(cfg.display_name(), "alpha"); }}Rules for unit tests
- Write assertions for inputs and outputs. A test in
mod testscan call private functions in the parent module. - If possible, use one test for each behavior. For example,
name_defaults_when_missingchecks the default for a missing name. - Add tests for empty strings, zero, limit values, incorrect UTF-8, incorrect types, and missing fields.
- Add a test for each fallback branch.
- If an assertion compares exact floating-point values, add
#[expect(clippy::float_cmp, reason = "...")]. Inreason, record why the test uses exact equality.
Integration and CLI tests
Put integration tests in tests/. These tests use the public API or start the
compiled binary.
use std::io::Write;use std::process::{Command, Stdio};
#[test]fn valid_input_prints_configured_name() { let mut cmd = Command::new(env!("CARGO_BIN_EXE_my-crate")); cmd.env_clear() .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::piped());
let mut child = cmd.spawn().expect("failed to spawn binary"); child .stdin .take() .expect("child stdin handle") .write_all(br#"{"name":"alpha"}"#) .expect("failed to write to child stdin");
let output = child.wait_with_output().expect("failed to wait on child"); assert!(output.status.success()); assert_eq!(String::from_utf8_lossy(&output.stdout), "alpha\n");}Integration test methods
- Use
env!("CARGO_BIN_EXE_<name>"),assert_cmd, orsnapboxto start the test binary that Cargo compiled. - Use
instato save snapshots for large JSON, diagnostic messages, or CLI output. Review snapshots withcargo insta review. - Set the environment on the child
Command. Use.env(),.env_remove(), or.env_clear()forHOME,XDG_CONFIG_HOME,APPDATA, and application variables. - Do not call
std::env::set_varorstd::env::remove_varin multithreaded tests. In Edition 2024, these functions areunsafe. Changes to process-wide environment variables can cause a race condition. - Use
tempfile::tempdir()in filesystem tests. It removes a temporary directory when its handle goes out of scope.
Property-based testing
Use proptest for parsers, state machines, and
calculations at limits. It generates many inputs and reduces a failure to a
small example. For example, any::<f64>() can generate NaN and ±Infinity.
use proptest::prelude::*;
proptest! { #[test] fn percent_stays_within_0_to_100(used in any::<f64>(), total in any::<f64>()) { let pct = compute_percent(used, total); prop_assert!((0..=100).contains(&pct)); }}Mutation testing, coverage, and unsafe verification
cargo-mutantschanges the code and checks if the test suite detects the change. For example, it can change<to<=, remove a branch, or make a function return early. Use it at intervals or for a change withcargo mutants --in-diff git.diff. This can identify defects in a test suite with high line coverage.cargo-llvm-covmeasures code coverage. Usecargo llvm-cov nextestto find error paths and edge cases that the tests do not execute.- If the crate contains
unsafeblocks, usecargo +nightly miri testin CI. Miri can identify aliasing violations, uninitialized reads, and incorrect pointer provenance. For critical invariants, you can use bounded model checking with Kani.
Regression tests
- Write a regression test that detects the defect.
- Make sure that the test fails before the code correction.
- Correct the code.
- Make sure that the test gives a satisfactory result.
Include the test and the code change in the same pull request.
Never panic on untrusted input
A panic on malformed external input can cause a denial of service.
unwrap, expect, and a slice index outside its limits can cause panics.
Add tests for hostile, truncated, empty, and incorrectly typed inputs. Make sure that each test gives the expected exit code. Make sure that the output contains no Rust panic backtrace.
#[test]fn invalid_json_returns_usage_error_without_panicking() { let out = run_with_stdin("not json"); assert_eq!(out.status.code(), Some(2)); let stderr = String::from_utf8_lossy(&out.stderr); assert!(stderr.contains("invalid configuration")); assert!(!stderr.contains("panicked at"));}Configuration priority
Use this order of priority for configuration.
- Command-line flags
- Environment variables
- Configuration file
- Default values
Add a test for each pair of sources to make sure that the higher-priority source takes effect.