Sub topic 12
Library crates and running tests
This chapter assumes that you have Rust and Cargo installed and can run cargo new, cargo build, and cargo run in a terminal. It also assumes you know what Cargo.toml and src/main.rs are. You do not need prior knowledge of Rust's testing features.
Binary crates and library crates
A crate is the unit that rustc compiles. Cargo projects produce two kinds:
- A binary crate compiles to an executable. Its entry point is
fn main(), andcargo runcan start it. - A library crate compiles to a reusable library (an
.rlibfile by default). It has nomainfunction, socargo runhas nothing to run. Other crates, including your own binaries and tests, import its public items.
cargo new creates a binary crate by default. To get a library, pass --lib:
cargo new adder --lib
cd adderThe only difference in the layout is the source file. A binary project has src/main.rs. A library project has src/lib.rs, which is the crate root of the library. Cargo looks for these two file names by convention, so you do not have to list them in Cargo.toml.
The generated src/lib.rs contains a small function and a test module. This is the version used in the rest of the chapter:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 3), 5);
}
}Your Cargo version may generate slightly different starter code, such as u64 instead of i32. The structure is the same.
Running your first test
Run the tests with:
cargo testCargo compiles the crate in test mode, builds a test executable, and runs it. The output looks like this:
running 1 test
test tests::adds_two_numbers ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Doc-tests adder
running 0 tests
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sThere are two blocks because cargo test runs more than one kind of test. The first block is the unit tests inside src/lib.rs. The second block, headed Doc-tests, runs code examples written in documentation comments. There are none yet, so it reports zero tests.
How the test harness works
Three pieces make the example work.
#[test] marks a function as a test. Test functions take no arguments. In a normal build, rustc ignores them. In test mode, rustc generates a main that collects every #[test] function and calls each one.
#[cfg(test)] is a conditional compilation attribute. The tests module is compiled only during cargo test, so test code never ends up in your release library.
A test passes if it returns normally and fails if it panics. The assert!, assert_eq!, and assert_ne! macros panic when their condition is false. assert_eq! prints both values when it fails, so prefer it to assert!(a == b).
The line use super::*; brings everything from the parent module into the tests module. A child module does not automatically see its parent's names, so without this line the test could not call add.
Failing tests and richer test styles
A fuller src/lib.rs shows three common test styles. It adds a function that can panic and a function that can return an error:
pub fn add(a: i32, b: i32) -> i32 {
a + b
}
pub fn divide(a: i32, b: i32) -> i32 {
if b == 0 {
panic!("divide by zero");
}
a / b
}
pub fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
s.trim().parse::<u16>()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_two_numbers() {
assert_eq!(add(2, 3), 5);
}
#[test]
#[should_panic(expected = "divide by zero")]
fn dividing_by_zero_panics() {
divide(1, 0);
}
#[test]
fn parses_a_valid_port() -> Result<(), std::num::ParseIntError> {
assert_eq!(parse_port(" 8080 ")?, 8080);
Ok(())
}
#[test]
fn rejects_an_invalid_port() {
assert!(parse_port("not a port").is_err());
}
}#[should_panic(expected = "...")]passes only if the code panics and the panic message contains the given text. Withoutexpected, any panic passes, which can hide a different bug.- A test can return
Result<(), E>. ReturningErrfails the test, and the?operator works inside it. This avoids a chain of.unwrap()calls. - Use
.is_err()ormatches!to assert on an error value. Do not use#[should_panic]for functions that returnResult.
When a test fails, Cargo prints the panic message, the file and line, and a hint to re-run with RUST_BACKTRACE=1. It then prints a summary and exits with a non-zero status. CI systems rely on that exit code.
Choosing which tests run
By default, the harness runs tests in parallel on several threads and hides the output of passing tests. You control this with two kinds of arguments. Arguments before -- go to Cargo. Arguments after -- go to the test executable.
cargo test add
cargo test --lib
cargo test --doc
cargo test -- --nocapture
cargo test -- --test-threads=1
cargo test -- --ignored| Command | Effect |
|---|---|
| `cargo test add` | Runs only tests whose full name contains `add`. |
| `cargo test --lib` | Runs only the unit tests in the library. |
| `cargo test --doc` | Runs only documentation tests. |
| `cargo test -- --nocapture` | Shows `println!` output from passing tests too. |
| `cargo test -- --test-threads=1` | Runs tests one at a time. |
| `cargo test -- --ignored` | Runs only tests marked `#[ignore]`. |
Mark slow or environment-dependent tests with #[ignore] so a plain cargo test skips them. You can run them on demand with --ignored.
Tests share the process, so parallel tests that touch the same file, environment variable, or port can interfere with each other. If a test passes alone but fails in the full run, try --test-threads=1. If that fixes it, make the tests independent instead of leaving the flag on.
Integration tests
Unit tests live next to the code and can reach private items. Integration tests live in a tests/ directory at the project root, next to src/. Each .rs file there is compiled as a separate crate that depends on your library. It can use only your public API, as an outside user would.
Create tests/add_tests.rs:
use adder::{add, divide};
#[test]
fn add_and_divide_work_together() {
assert_eq!(divide(add(4, 4), 2), 4);
}The name adder is the package name from Cargo.toml. If a package name contains hyphens, such as my-lib, the crate name in use paths uses underscores, as in my_lib. You do not need #[cfg(test)] in tests/, because Cargo compiles those files only for cargo test. Run one integration file with cargo test --test add_tests.
Integration tests need a library crate to import. A package that has only src/main.rs cannot be imported from tests/.
Keeping logic in the library
A package can have both src/lib.rs and src/main.rs. They compile as two crates that share the package name. The binary imports the library the same way an integration test does:
fn main() {
println!("2 + 3 = {}", adder::add(2, 3));
}This layout is common for real projects. Put the logic in lib.rs and keep main.rs thin. The logic is then easy to unit test and integration test, and other crates can reuse it. cargo run runs the binary, and cargo test still tests the library.
Documentation tests
Code examples in /// doc comments are compiled and run by cargo test. In a doc comment, a Markdown fenced code block containing assert_eq!(adder::add(2, 3), 5); becomes a test. Doc tests exercise the public API, so they use the full crate path, such as adder::add. They also keep your documentation honest, because an outdated example fails the build.
Common errors
cargo runsays there is no binary target. You created the project with--lib. Add asrc/main.rsor usecargo testinstead.cannot find functioninside the test module. Theuse super::*;line is missing.unresolved import adderintests/. The package name is different, or the project has nosrc/lib.rs. ChecknameinCargo.toml.- A test passes alone but fails with the others. The tests share state. See the note on parallel tests above.
- No output from
println!. The harness hides output from passing tests. Use--nocapture, or look at the output for a failing test. - A filter runs no tests. The filter matches the full test path, such as
tests::adds_two_numbers. Check the spelling with a plaincargo testfirst.
Exercise
You run cargo test in a package that has only src/main.rs, and you want an integration test in tests/ to call a function from your code. Why does the import fail, and how do you fix it?
Show answer
A binary crate cannot be imported by other crates, so the integration test has nothing to depend on. Move the function into a new src/lib.rs, mark it pub, and import it in the test with use <package_name>::function_name;. Keep src/main.rs as a thin wrapper that calls the library.
Exercise
Write the command that runs only the tests whose names contain port, and shows println! output from them even when they pass.
Show answer
cargo test port -- --nocapture. The filter port goes before -- as a test-name filter. The --nocapture flag goes after -- because it is an option for the test executable.