Pure function unit tests

Learn what a pure function is, why pure functions are the easiest code to test, and how to write unit tests for them in Rust

A pure function is a function that takes its inputs as arguments, returns a result, and does nothing else. It reads no files, writes no database rows, sends no requests, and changes no shared state. The same inputs always produce the same output. A unit test for a pure function is the simplest test in Rust: call the function with a known input, compare the result with the expected output, and let the test pass or fail on that comparison.

Where This Fits

The tests module from the previous page gives tests a home. This page fills that home with the easiest kind of test there is. Pure functions are the natural first target because nothing stands between the test and the function. There is no server to start, no request to build, and no database to set up. The test calls the function directly, in the same process, and checks the answer. Everything harder in testing is a variation on this shape, with setup added around it.

Think of it like checking a recipe by tasting the sauce. You do not need the whole restaurant, the waiters, or the dining room. You need a spoon, a small bowl, and the sauce itself. A pure function is the sauce, and a unit test is the spoon.

The Smallest Working Version

Start with one pure function and two tests, one for the ordinary case and one for the edge case.

src/lib.rs
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn add_two_and_three_is_five() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    fn add_handles_negative_numbers() {
        assert_eq!(add(-4, 6), 2);
        assert_eq!(add(-4, -6), -10);
    }
}

Run cargo test and both pass:

running 2 tests
test tests::add_two_and_three_is_five ... ok
test tests::add_handles_negative_numbers ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.01s

There is no setup in these tests, no cleanup, and no waiting. Each test is three lines: a name that says what it checks, a call with fixed inputs, and an assertion that compares the answer. That shape, call and compare, is the whole technique. The rest of this page is about choosing good inputs and writing the comparison well.

Working Setup:

If both tests print ok and the summary says 2 passed, the pattern works. A test that calls a function and compares the result is a complete unit test, and every test on this page is built from that same shape.

What Makes a Function Pure

A function is pure when it meets two conditions. First, its result depends only on its arguments. Call it twice with the same inputs, and you get the same output both times. Second, it has no side effects. It does not change anything outside itself: no global variable, no file, no database, no network, no printed output that the program depends on.

// Pure - the answer depends only on the arguments
pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

// Pure - the answer depends only on the title
pub fn slugify(title: &str) -> String {
    let mut slug = String::new();
    let mut last_was_hyphen = true;
    for ch in title.trim().to_lowercase().chars() {
        if ch.is_ascii_alphanumeric() {
            slug.push(ch);
            last_was_hyphen = false;
        } else if !last_was_hyphen {
            slug.push('-');
            last_was_hyphen = true;
        }
    }
    while slug.ends_with('-') {
        slug.pop();
    }
    slug
}

// Not pure - the answer depends on something outside the arguments
pub fn greeting() -> String {
    std::env::var("GREETING").unwrap_or_else(|_| "Hello".to_string())
}

add is pure because 2 + 3 is 5 on every machine, at every hour, in every run. slugify is pure because the same title always produces the same slug. The greeting function is not pure, because its answer changes with an environment variable the test does not set. A test that passes when GREETING is unset fails when someone exports GREETING=Hi, and that failure has nothing to do with the code being wrong. The code depends on something the test does not control.

Most of the small helpers in an Axum project are pure: slug builders, price calculators, title cleaners, range checks, and lookups over fixed data. Handlers are not pure, because they read requests and write responses, but the helpers handlers call usually are. Testing the helpers directly is how you test most of the logic without ever starting a server.

Understanding slugify Line by Line

slugify is the richest pure function in this chapter, so it is worth reading carefully. A slug is a web address friendly version of a title: lowercase, words joined by hyphens, no spaces or punctuation. "The Rust Book" becomes "the-rust-book".

Trimming and lowercasing

    for ch in title.trim().to_lowercase().chars() {

trim() cuts spaces from both ends of the title, to_lowercase() turns every letter lowercase, and chars() walks through the result one character at a time. The loop sees a clean version of the title before it does any work, so leading and trailing spaces never reach the slug.

Keeping letters and digits

        if ch.is_ascii_alphanumeric() {
            slug.push(ch);
            last_was_hyphen = false;
        }

is_ascii_alphanumeric() is true for the letters a to z, A to Z, and the digits 0 to 9. Those characters are pushed straight into the slug, and the last_was_hyphen flag is set to false, recording that the slug currently ends with a real character. Non-English letters, like an accented e, are dropped by this check, because the function only keeps plain ASCII letters and digits.

Turning everything else into one hyphen

        } else if !last_was_hyphen {
            slug.push('-');
            last_was_hyphen = true;
        }

Any other character, a space, an &, an exclamation mark, becomes a hyphen, but only if the slug does not already end with one. The flag stops "Rust & Axum" from turning into "rust--axum" with two hyphens in the middle. The first separator writes a hyphen and sets the flag, and the second separator sees the flag and writes nothing.

Cutting a trailing hyphen

    while slug.ends_with('-') {
        slug.pop();
    }

A title that ends with punctuation, like "Rust!", leaves a hyphen at the end of the slug. The loop pops hyphens off the end until the slug ends with a real character. The while is a loop because a title could leave more than one, though the flag above usually leaves at most one.

Testing slugify Case by Case

A function with several behaviours needs several tests, one per behaviour. Each test below checks one rule of slugify, and its name says which rule it checks.

src/lib.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn slugify_lowercases_and_hyphenates() {
        assert_eq!(slugify("The Rust Book"), "the-rust-book");
    }

    #[test]
    fn slugify_trims_edges_and_collapses_separators() {
        assert_eq!(slugify("  Rust  &  Axum!  "), "rust-axum");
        assert_eq!(slugify("Dune"), "dune");
        assert_eq!(slugify(""), "");
    }
}

The first test checks the ordinary case: words lowercased and joined with hyphens. The second test checks three edge cases in one function. The messy input with double spaces, an ampersand, and an exclamation mark must collapse to a single hyphen between words. A single word must come back lowercased with no hyphen. An empty string must come back empty, not crash. The empty case matters because slugify("") walks a loop over zero characters and returns an empty String, and a test pins that behaviour so a later rewrite cannot break it by accident. Run cargo test and both tests pass.

One Table Instead of Many Tests

When a function needs many examples, writing one test function per example gets repetitive. A table-driven test puts the examples in a list and loops over them, running the same assertion for each row.

src/lib.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn slugify_table_of_cases() {
        let cases = [
            ("The Rust Book", "the-rust-book"),
            ("Dune", "dune"),
            ("  Rust  &  Axum!  ", "rust-axum"),
            ("", ""),
        ];
        for (input, expected) in cases {
            assert_eq!(slugify(input), expected, "slugify({input:?})");
        }
    }
}

Each row is a pair, an input and the expected output. The loop calls the function once per row and asserts the result. The third argument to assert_eq!, the message "slugify({input:?})", prints the failing input when a row fails. Without it, a failure only says the two values differed, and with four rows you would not know which input broke. The {:?} format prints the input with quotes, so an empty string shows as "" instead of disappearing.

A table is the right shape when the examples differ only in values. It is the wrong shape when the examples need different setup or different assertions. A test that checks a success case and a test that checks an error case do not belong in one table, because the assertion itself is different. Keep tables for rows that share one assertion.

Run cargo test slugify to run just the three slugify tests:

running 3 tests
test tests::slugify_table_of_cases ... ok
test tests::slugify_trims_edges_and_collapses_separators ... ok
test tests::slugify_lowercases_and_hyphenates ... ok

test result: ok. 3 passed; 0 failed; 0 ignored; 0 measured; 30 filtered out; finished in 0.01s

The filter slugify matched the three test names and skipped the other 30 tests in the crate. That filtered run is the loop to use while working on one function: change the function, run its tests, see the result in under a second.

One Failing Row Fails the Whole Test:

A table-driven test stops at the first failing row, so a failure hides the rows after it. When a table grows past a handful of rows, split it into two tests, or accept that fixing one row at a time is the workflow. The table is a convenience for writing cases, not a way to get several test results from one test function.

Testing a Function That Returns a Result

Pure functions that can fail return a Result, and their tests check both arms. find_book looks a book up by id and returns either the book or AppError::NotFound, and the shared error type is the one from the error handling design, where NotFound becomes a 404 with the body {"error":"resource not found"}.

src/lib.rs
pub fn find_book(id: u32) -> Result<Book, AppError> {
    match id {
        1 => Ok(Book {
            id: 1,
            title: "The Rust Book".to_string(),
        }),
        _ => Err(AppError::NotFound),
    }
}
src/lib.rs
#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn find_book_returns_the_book_for_id_one() {
        assert_eq!(
            find_book(1).unwrap(),
            Book {
                id: 1,
                title: "The Rust Book".to_string()
            }
        );
    }

    #[test]
    fn find_book_returns_not_found_for_unknown_ids() {
        assert_eq!(find_book(99).unwrap_err(), AppError::NotFound);
    }
}

The success test calls unwrap() to pull the Book out of the Ok, then compares the whole struct with assert_eq!. That comparison works because Book derives PartialEq, which is the trait that lets two values be compared for equality. Without the derive, the assertion would not compile.

The failure test calls unwrap_err() to pull the error out of the Err, then compares it with AppError::NotFound. If the function ever returned a book for id 99, unwrap_err() would panic and the test would fail, which is the correct outcome for a test that expects a failure.

When the test only cares about which variant came back and not about the data inside it, the matches! macro is shorter:

#[test]
fn find_book_failure_is_the_not_found_variant() {
    let error = find_book(99).unwrap_err();
    assert!(matches!(error, AppError::NotFound));
}

matches! checks a value against a pattern and returns true or false. It is the right tool when the variant is the whole story. assert_eq! is the right tool when the exact value matters, including the message inside a ValidationError.

Testing Numbers and Boundaries

Numbers deserve tests at the edges, not just in the middle. A price calculator is easy to get right for ordinary numbers and easy to get wrong at zero, at one, and at the largest value. The tests below pin each of those points.

src/lib.rs
pub fn total_price_cents(unit_price_cents: u32, quantity: u32) -> u32 {
    unit_price_cents * quantity
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn total_price_multiplies_unit_price_by_quantity() {
        assert_eq!(total_price_cents(499, 3), 1497);
        assert_eq!(total_price_cents(499, 0), 0);
    }
}

499 * 3 is 1497, the ordinary case. 499 * 0 is 0, the boundary where a quantity of zero must produce a total of zero rather than the unit price. A test for a quantity of one would pin that one item costs exactly the unit price, and a test for a large quantity would pin that the multiplication does not overflow in debug builds. The habit is to ask, for every number the function takes, what happens at zero, at one, and at the biggest value the type allows.

Boundaries matter even more for range checks, where the values just inside and just outside the limit decide whether the function is right. A check that accepts ages 0 to 150 needs tests at 0, 150, minus 1, and 151. The middle of the range tells you almost nothing. The edges tell you whether the comparison uses the right operator, and that is where range bugs live.

Naming Tests So Failures Explain Themselves

A test name is the first thing you read when a test fails, so it should say what the test checks. The names on this page follow one pattern: the function name, then the situation, then the expected outcome.

  • add_two_and_three_is_five says the function, the inputs, and the answer.
  • slugify_trims_edges_and_collapses_separators says the function and the two behaviours it checks.
  • find_book_returns_not_found_for_unknown_ids says the function, the outcome, and the situation that produces it.

A name like test_add says nothing, and a failure under that name sends you into the test body to learn what broke. A name like test1 is worse, because it does not even say which function it covers. Rust test names use snake_case, words in lowercase joined by underscores, and they can be long. Length is free, and clarity is the point.

A Vague Name Hides a Vague Test:

When a test is hard to name, the test is usually checking too much. A test called slugify_works that asserts five different behaviours in one body is five tests hiding in one name. Split it, and the names write themselves. If you cannot say what a test checks in one sentence, the test does not know what it checks either.

Choosing Between assert, assert_eq, and assert_ne

Three assertion macros cover nearly every pure function test, and each one fits a different comparison.

assert! checks a condition is true. It fits boolean results, like a function that answers yes or no.

assert!(check_title("Dune").is_ok());

assert_eq! checks two values are equal. It fits every test where the expected output is known exactly, which is most pure function tests. On failure it prints both values.

assert_eq!(add(2, 3), 5);

assert_ne! checks two values are not equal. It fits tests that prove two inputs produce different outputs, like two different titles producing different slugs.

assert_ne!(slugify("Dune"), slugify("Dune 2"));

The failure message is the reason to prefer assert_eq! over assert! whenever two values are compared. assert!(add(2, 3) == 5) failing prints only that the assertion was false. assert_eq!(add(2, 3), 5) failing prints the value the function returned and the value the test expected, which is usually enough to see the bug without a debugger.

How Pure Tests Fit Into the Whole Suite

The diagram below shows where a pure function test sits in the testing picture. It is the smallest loop, and every larger test adds one layer around it.

Pure function test
        |
        v
Call the function directly, no setup
        |
        v
Compare the returned value with assert_eq!
        |
        v
Pass when equal, panic with both values when not

A test for a validation helper adds a Result to the comparison. A test for a handler adds a request and a response around the same comparison. The core never changes: run something, compare the answer with the expected answer, report the difference. Learning the core on pure functions means the harder tests later are about setup, not about a new idea.

Common Beginner Mistakes

Testing through the handler instead of the helper

// Wrong - slow, indirect, and the failure hides which helper broke
async fn create_book(Json(input): Json<NewBook>) -> Result<Json<Book>, AppError> {
    // ... handler that calls slugify internally
}

When a helper is wrong, a test that goes through the handler fails with a wrong HTTP response, and the failure does not say whether the helper, the handler, or the routing broke. A unit test on the helper fails with the exact input and output, and the fix is obvious. Test helpers directly, and test handlers for the wiring between helpers, not for the helpers themselves.

Only testing the happy path

// Wrong - the empty title and the long title are untested
#[test]
fn check_title_accepts_a_normal_title() {
    assert!(check_title("Dune").is_ok());
}

A function that passes its happy path test and fails on empty input is a function with one test too few. Every function has edge cases: empty strings, zero, negative numbers, the maximum length, the value just past the limit. Write the happy path first, then ask what input would break the function, and write a test for each answer.

Copying the implementation into the test

// Wrong - the test repeats the logic instead of checking the answer
#[test]
fn total_price_matches_manual_multiplication() {
    let expected = 499 * 3;
    assert_eq!(total_price_cents(499, 3), expected);
}

A test that computes the expected value with the same operation it is testing cannot catch a mistake in that operation. The expected value should be a literal number written by hand, 1497, so the test checks the function against an independent answer. When the expected value is not obvious, compute it once by hand, write it down as a literal, and let the test pin it.

Asserting on a value the function does not promise

// Wrong - the order of a HashMap is not promised
let errors = validate_signup(&input);
assert_eq!(errors.keys().next(), Some(&"username".to_string()));

A HashMap does not keep its entries in insertion order, so a test that reads the first key can pass on one run and fail on the next. Assert on lookups by name, errors.get("username"), which is stable, and never on order, which is not. The same rule applies to any function whose output order is unspecified: test the contents, not the sequence.

Final Complete Example

Here is everything from this page in one place: the pure functions, the lookup with its shared error type, and the full tests module.

src/lib.rs
pub mod errors;
pub mod validation;

use errors::AppError;
use serde::Serialize;

#[derive(Debug, PartialEq, Serialize)]
pub struct Book {
    pub id: u32,
    pub title: String,
}

pub fn add(a: i32, b: i32) -> i32 {
    a + b
}

pub fn slugify(title: &str) -> String {
    let mut slug = String::new();
    let mut last_was_hyphen = true;
    for ch in title.trim().to_lowercase().chars() {
        if ch.is_ascii_alphanumeric() {
            slug.push(ch);
            last_was_hyphen = false;
        } else if !last_was_hyphen {
            slug.push('-');
            last_was_hyphen = true;
        }
    }
    while slug.ends_with('-') {
        slug.pop();
    }
    slug
}

pub fn total_price_cents(unit_price_cents: u32, quantity: u32) -> u32 {
    unit_price_cents * quantity
}

pub fn find_book(id: u32) -> Result<Book, AppError> {
    match id {
        1 => Ok(Book {
            id: 1,
            title: "The Rust Book".to_string(),
        }),
        _ => Err(AppError::NotFound),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn add_two_and_three_is_five() {
        assert_eq!(add(2, 3), 5);
    }

    #[test]
    fn add_handles_negative_numbers() {
        assert_eq!(add(-4, 6), 2);
        assert_eq!(add(-4, -6), -10);
    }

    #[test]
    fn slugify_lowercases_and_hyphenates() {
        assert_eq!(slugify("The Rust Book"), "the-rust-book");
    }

    #[test]
    fn slugify_trims_edges_and_collapses_separators() {
        assert_eq!(slugify("  Rust  &  Axum!  "), "rust-axum");
        assert_eq!(slugify("Dune"), "dune");
        assert_eq!(slugify(""), "");
    }

    #[test]
    fn slugify_table_of_cases() {
        let cases = [
            ("The Rust Book", "the-rust-book"),
            ("Dune", "dune"),
            ("  Rust  &  Axum!  ", "rust-axum"),
            ("", ""),
        ];
        for (input, expected) in cases {
            assert_eq!(slugify(input), expected, "slugify({input:?})");
        }
    }

    #[test]
    fn total_price_multiplies_unit_price_by_quantity() {
        assert_eq!(total_price_cents(499, 3), 1497);
        assert_eq!(total_price_cents(499, 0), 0);
    }

    #[test]
    fn find_book_returns_the_book_for_id_one() {
        assert_eq!(
            find_book(1).unwrap(),
            Book {
                id: 1,
                title: "The Rust Book".to_string()
            }
        );
    }

    #[test]
    fn find_book_returns_not_found_for_unknown_ids() {
        assert_eq!(find_book(99).unwrap_err(), AppError::NotFound);
    }

    #[test]
    fn find_book_failure_is_the_not_found_variant() {
        let error = find_book(99).unwrap_err();
        assert!(matches!(error, AppError::NotFound));
    }
}

Run cargo test and expect every test in this module to pass, along with the tests in the other modules of the crate. Run cargo test slugify and expect the three slugify tests to pass with the rest filtered out.

Summary

The test worth writing first is the one with nothing around it. A pure function takes an input and returns an output, and a unit test checks that pair directly, which makes the test fast, stable, and precise about what broke. The working rule is to test the edges before the middle: empty strings, zero, the values just inside and just outside a limit, and the failure arm of every Result. A table holds the rows when the examples share one assertion, a descriptive name tells you what failed before you open the test, and a literal expected value keeps the test honest. The decision that follows from all of this is about where effort goes. When logic can live in a pure helper, put it there, because a helper can be tested in three lines, and a handler that only wires helpers together needs only a wiring test.