Lesson 18 of 26
Tests, builds and shipping
cargo test is Rust's pytest, and it is built in. It runs three kinds of tests:
- Unit tests: in a
testsmodule inside the same file as the code. They can test private functions. - Integration tests: files in the
tests/folder. They use your crate from the outside, like a user would. - Doc tests: code examples inside
///doc comments, like Python doctests. Examples in the docs are always run, so they can't go out of date.
Shipping is also different from Python. A Python program needs Python and its packages on the target machine. A Rust program is compiled into one executable file that already contains all its dependencies.
A unit test is a function with #[test]
pytest finds functions named test_*. Cargo finds functions marked #[test]. By
convention they live at the bottom of the same file, in a module called tests. A test fails when it
panics, and a failing assert_eq! panics.
def add(a: int, b: int) -> int:
return a + b
def test_add():
assert add(2, 3) == 5
def test_negative():
assert add(-2, -3) == -5pub fn add(a: i32, b: i32) -> i32 {
a + b
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds() {
assert_eq!(add(2, 3), 5);
}
#[test]
fn negative() {
assert_eq!(add(-2, -3), -5);
}
}Reading cargo test output
Here is the output when the second test expects -6 instead of -5. Both tools show the same
things, in a different layout: what ran, what failed, where, and the two values that differ.
$ uv run pytest
================ test session starts ================
collected 2 items
tests/test_math.py .F [100%]
===================== FAILURES ======================
___________________ test_negative ___________________
def test_negative():
> assert add(-2, -3) == -6
E assert -5 == -6
tests/test_math.py:10: AssertionError
============ 1 failed, 1 passed in 0.01s ============$ cargo test
Compiling shop v0.1.0 (/home/me/shop)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.20s
Running unittests src/lib.rs (target/debug/deps/shop-cc2afb116b8768ed)
running 2 tests
test tests::adds ... ok
test tests::negative ... FAILED
failures:
---- tests::negative stdout ----
thread 'tests::negative' panicked at src/lib.rs:16:9:
assertion `left == right` failed
left: -5
right: -6
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
failures:
tests::negative
test result: FAILED. 1 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00sIntegration tests and doc tests
A file in tests/ is compiled as a separate crate. It can only use what your library makes
pub, exactly like a user who installed it. Doc tests are code blocks inside /// comments.
cargo test compiles and runs them, and docs.rs shows them as examples.
# tests/test_shop.py
from shop import add
def test_add_from_outside():
assert add(1, 1) == 2
# src/shop/__init__.py
def add(a, b):
"""Add two numbers.
>>> add(2, 2)
4
"""
return a + b// tests/shop.rs
use shop::add;
#[test]
fn add_from_outside() {
assert_eq!(add(1, 1), 2);
}
// src/lib.rs
/// Add two numbers.
///
/// ```
/// assert_eq!(shop::add(2, 2), 4);
/// ```
pub fn add(a: i32, b: i32) -> i32 {
a + b
}Debug vs release builds
cargo build and cargo run make a debug build. It compiles fast, runs slowly, and
checks for number overflow. --release turns on optimizations. Compiling takes longer, but the program
often runs many times faster. Always measure speed with --release. A slow debug build doesn't tell you anything.
The result is one file that contains your code and every dependency. Copy it to another machine with the
same OS and CPU type and run it: no Python, no virtual environment, and no Rust needed there. To build for another
platform, use --target, for example --target x86_64-unknown-linux-musl for a fully
static Linux binary that fits in a tiny Docker image.
uv run shop
uv build
ls dist/
# shop-0.1.0-py3-none-any.whl (needs Python + deps)
uv pip install dist/shop-0.1.0-py3-none-any.whlcargo run
cargo build --release
ls target/release/
# shop (the whole program in one file)
./target/release/shopPublishing and installing
crates.io is Rust's PyPI. One difference: it stores source code, not built files like wheels. Whoever
depends on your crate compiles it on their own machine. That's why the first build of a project takes a while.
Command-line tools are installed with cargo install, which compiles them into
~/.cargo/bin.
uv build
uv publish
uv tool install ruffcargo package
cargo publish
cargo install ripgrepRust inside a Python package
Rust code can be shipped as a normal Python package. PyO3 connects Rust to Python, and
maturin builds the wheel: maturin develop installs it into your current virtual environment,
and maturin build --release makes wheels to publish. pydantic-core, polars and orjson are built this way.
ruff and uv are Rust programs that maturin wraps in wheels, which is why pip install ruff works.
# pip install shop-fast (a wheel built by maturin)
import shop_fast
print(shop_fast.add(2, 3))use pyo3::prelude::*;
#[pyfunction]
fn add(a: i64, b: i64) -> i64 {
a + b
}
#[pymodule]
fn shop_fast(m: &Bound<'_, PyModule>) -> PyResult<()> {
m.add_function(wrap_pyfunction!(add, m)?)?;
Ok(())
}Where the Python analogy breaks
- Unit tests live next to the code, in a
#[cfg(test)] mod testsblock in the same file, and they can test private functions. Python usually keeps tests in a separatetests/folder. - No fixtures and no
parametrizebuilt in. A test is a plain function. For a table of cases, loop over an array inside one test. cargo testruns tests in parallel, on several threads, by default. Tests that share a file or a global setting can get in each other's way.- A release build runs on one platform. A pure-Python wheel runs anywhere Python does. A Rust binary is built for one OS and CPU type, so you build one for Linux, one for macOS, and so on.
Cheat card
| Python | Rust |
|---|---|
pytest | cargo test |
pytest -k negative | cargo test negative |
pytest -s | cargo test -- --nocapture |
def test_add(): | #[test]
fn add_works() { } |
assert a == b | assert_eq!(a, b); |
assert ok | assert!(ok); |
with pytest.raises(ValueError): ... | #[should_panic] // or assert!(r.is_err()); |
"""Docstring. >>> add(2, 2)""" | /// Doc comment with a ``` code block |
sphinx-build docs/ html/ | cargo doc --open |
ruff format / ruff check | cargo fmt / cargo clippy |
uv build | cargo build --release |
uv publish | cargo publish |
uv tool install ruff | cargo install ripgrep |
# C extension module | pyo3 + maturin // Rust inside a wheel |
← Cargo in depth: dependencies and workspaces Reading real code →