Rust for Pythonistas

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 tests module 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.

Python · pytest
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) == -5
Rust · cargo test
pub 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.

pytest output (shortened)
$ 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 output
$ 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.00s

Integration 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.

Python files
# 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
Rust files
// 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.

Terminal · Python
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.whl
Terminal · Rust
cargo run
cargo build --release
ls target/release/
# shop  (the whole program in one file)
./target/release/shop

Publishing 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.

Terminal · Python
uv build
uv publish

uv tool install ruff
Terminal · Rust
cargo package
cargo publish

cargo install ripgrep

Rust 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.

Python · using it
# pip install shop-fast   (a wheel built by maturin)
import shop_fast

print(shop_fast.add(2, 3))
Rust · src/lib.rs
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

Cheat card

PythonRust
pytestcargo test
pytest -k negativecargo test negative
pytest -scargo test -- --nocapture
def test_add():#[test] fn add_works() { }
assert a == bassert_eq!(a, b);
assert okassert!(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 checkcargo fmt / cargo clippy
uv buildcargo build --release
uv publishcargo publish
uv tool install ruffcargo install ripgrep
# C extension modulepyo3 + maturin // Rust inside a wheel

← Cargo in depth: dependencies and workspaces Reading real code →