Running Tests

Running Tests in Rust: The full service is one instruction. You say "service it", and the shop works through the whole checklist in whatever order suits the…

The Analogy: The Service Bay

The full service is one instruction. You say "service it", and the shop works through the whole checklist in whatever order suits the bay that morning, and hands you back a single sheet: everything that passed, briefly, and everything that did not, in detail. You did not choose the order and you do not need to.

When you are chasing one specific complaint, you do not order a full service. You ask for the one check -- just look at the offside rear -- and the shop leaves the other forty alone. It is the same check as before, run in isolation, and the entire value of doing it that way is the twenty minutes you did not spend on the thirty-nine checks that were fine yesterday.

The technician talks the whole time. Almost none of that talk reaches the sheet, and that is deliberate: a service sheet carrying a running commentary on twelve passing checks is a sheet nobody reads. The commentary is not lost, though. Ask for it and you get it, and when a check fails you get it whether you asked or not.

And two checks cannot always happen at once. Most can, which is why one person does the lights while another does the tyres. But there is one brake roller in the building and two cars cannot be on it simultaneously. Running everything in parallel is the default because it is faster; when something genuinely is shared, the work has to be put in a queue, and somebody has to say so out loud.


Syntax or Core Structure

Take a small crate with five tests, one of which is marked to be skipped:

pub fn checksum(digits: &str) -> u32 {
    let mut total = 0;

    for c in digits.chars() {
        if let Some(d) = c.to_digit(10) {
            total += d;
        }
    }

    total
}

pub fn valid(digits: &str) -> bool {
    checksum(digits) % 10 == 0
}

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

    #[test]
    fn checksum_of_digits() {
        assert_eq!(checksum("1234"), 10);
    }

    #[test]
    fn checksum_skips_non_digits() {
        assert_eq!(checksum("12-34"), 10);
    }

    #[test]
    fn valid_when_the_total_ends_in_zero() {
        assert!(valid("1234"));
    }

    #[test]
    fn invalid_when_it_does_not() {
        assert!(!valid("1235"));
    }

    #[test]
    #[ignore = "sweeps every three-digit code"]
    fn a_check_digit_can_always_be_appended() {
        for n in 0..1000u32 {
            let body = format!("{n:03}");
            let needed = (10 - checksum(&body) % 10) % 10;
            let full = format!("{body}{needed}");

            assert!(valid(&full), "{full} should be valid");
        }
    }
}
cargo test

Output:

running 5 tests
test tests::checksum_of_digits ... ok
test tests::checksum_skips_non_digits ... ok
test tests::invalid_when_it_does_not ... ok
test tests::valid_when_the_total_ends_in_zero ... ok
test tests::a_check_digit_can_always_be_appended ... ignored, sweeps every three-digit code

test result: ok. 4 passed; 0 failed; 1 ignored; 0 measured; 0 filtered out

A bare word after cargo test is a filter on the test's full name, matched as a substring:

cargo test checksum

Output:

running 2 tests
test tests::checksum_of_digits ... ok
test tests::checksum_skips_non_digits ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out

Substring is the word to hold on to. Filtering on valid does not run the one test whose name starts that way; it runs two, because invalid_when_it_does_not contains valid inside it:

cargo test valid

Output:

running 2 tests
test tests::invalid_when_it_does_not ... ok
test tests::valid_when_the_total_ends_in_zero ... ok

test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 3 filtered out

To run exactly one, name it in full and ask for an exact match:

cargo test -- --exact tests::valid_when_the_total_ends_in_zero

Output:

running 1 test
test tests::valid_when_the_total_ends_in_zero ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 4 filtered out

That -- in the middle is the piece of syntax that causes the most confusion in this whole lesson, and the rule behind it is simple: cargo test builds a test executable and then runs it, so there are two programs to give arguments to. Everything before the -- is for Cargo, which decides what to build. Everything after it is for the test binary, which decides what to run and how to report it.

Written asRead byEffect
cargo test checksumThe harness, as a filterRuns tests whose full name contains checksum
cargo test --libCargoBuilds and runs only the library's own unit tests
cargo test --releaseCargoBuilds with optimisations and without overflow checks
cargo test -- --exact NAMEThe harnessMatches the whole name instead of a substring
cargo test -- --ignoredThe harnessRuns only the tests marked #[ignore]
cargo test -- --nocaptureThe harnessLets passing tests print to the terminal
cargo test -- --test-threads=1The harnessRuns them one at a time, in a stable order
cargo test -- --listThe harnessPrints the names and runs nothing

Put a harness flag before the -- and Cargo rejects it as an unrecognised argument, which is the error most people meet on their first attempt at --nocapture.


Technical Depth: The Flags That Change What You See

Finding out what exists

cargo test -- --list

Output:

tests::a_check_digit_can_always_be_appended: test
tests::checksum_of_digits: test
tests::checksum_skips_non_digits: test
tests::invalid_when_it_does_not: test
tests::valid_when_the_total_ends_in_zero: test

5 tests, 0 benchmarks

The list is alphabetical, which is also the order the harness collects them in, and the names printed here are exactly the strings that --exact matches against. When a test name is long or a module path is deep, this beats guessing.

The ignored ones

cargo test -- --ignored

Output:

running 1 test
test tests::a_check_digit_can_always_be_appended ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 4 filtered out

--ignored runs only the ignored tests and skips everything else, which surprises people who expected it to mean "including". The flag for that is --include-ignored, and with it the summary reads 5 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out. A slow sweep marked #[ignore] is a test you intend to run, just not forty times an hour, so a nightly job asking for --include-ignored is the usual arrangement.

Output that is hidden until it is not

Add a print inside the loop in checksum:

        if let Some(d) = c.to_digit(10) {
            total += d;
            println!("{c} -> {total}");
        }

Under a plain cargo test nothing appears. The harness captures each test's standard output and throws it away when the test passes, keeping it only to include in a failure report. That is why a print added for debugging seems to do nothing, and why the fix is to ask:

cargo test checksum_of_digits -- --nocapture

Output:

running 1 test
1 -> 1
2 -> 3
3 -> 6
4 -> 10
test tests::checksum_of_digits ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 4 filtered out

There is a second flag, --show-output, which keeps the capturing but prints what it captured in a grouped section after the run. The exact layout of that section is a harness detail worth reading rather than memorising; the practical difference is that --nocapture shows output as it happens and --show-output shows it afterwards, tidied.

One at a time

Because tests run in parallel by default, two tests printing under --nocapture interleave their lines and neither is readable. The two flags belong together:

cargo test -- --nocapture --test-threads=1

Serial execution also makes the result lines appear in a single repeatable order, which is occasionally worth having on its own -- when comparing two runs, or when a test suite touches something genuinely shared, like a fixed port or a file at a known path. That last case is a smell rather than a solution: a test that needs the world to itself is a test that will fail on somebody else's machine for reasons nobody can reproduce.

What a bare cargo test actually runs

With no target flags, Cargo builds and runs the library's unit tests, the unit tests inside each binary target, every file in tests/ as its own integration test crate, and the examples in your documentation comments.

FlagRuns
--libUnit tests inside the library only
--binsUnit tests inside the binary targets
--test gaugeOnly tests/gauge.rs
--docOnly the examples in doc comments
--all-targetsEvery target except doc tests

The last row is a genuine trap. --all-targets sounds exhaustive and quietly omits documentation tests, so a CI script using it will let a broken example in the public documentation through. Doc tests are ordinary tests: the examples in /// comments are compiled and run, and a failing one is reported with the source file and the line the code block starts on.

cargo test --doc

Output:

running 1 test
test src/lib.rs - checksum (line 3) ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Debug and release are different programs

cargo test builds without optimisations, which means integer overflow panics and debug_assert! runs. cargo test --release turns both off. A suite can therefore be green in one and red in the other:

pub fn total(a: u32, b: u32) -> u32 {
    a + b
}

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

    #[test]
    #[should_panic]
    fn overflow_is_caught() {
        total(u32::MAX, 1);
    }
}

This passes under cargo test and fails under cargo test --release with note: test did not panic as expected, because in a release build the addition wraps to zero instead of panicking. Neither outcome is a bug in the harness; they are two different builds of the same source, and a suite that is only ever run one way is only ever checked one way.


Real World Example: Narrowing A Failing Suite Down To One Command

A crate that validates two kinds of code -- EAN-13 barcodes and Luhn card numbers -- with seven tests over both. One of the two modules has a bug in it.

pub mod ean {
    pub fn check_digit(body: &str) -> u32 {
        let mut sum = 0;
        let mut weight = 3;

        for c in body.chars() {
            if let Some(d) = c.to_digit(10) {
                sum += d * weight;
                weight = if weight == 3 { 1 } else { 3 };
            }
        }

        (10 - sum % 10) % 10
    }

    pub fn valid(code: &str) -> bool {
        if code.len() != 13 {
            return false;
        }

        let body = &code[..12];
        let last = &code[12..];

        match last.parse::<u32>() {
            Ok(d) => d == check_digit(body),
            Err(_) => false,
        }
    }
}

pub mod luhn {
    pub fn valid(number: &str) -> bool {
        let mut sum = 0;
        let mut double = false;

        for c in number.chars().rev() {
            match c.to_digit(10) {
                Some(d) => {
                    let mut v = d;

                    if double {
                        v *= 2;

                        if v > 9 {
                            v -= 9;
                        }
                    }

                    sum += v;
                    double = !double;
                }
                None => return false,
            }
        }

        sum % 10 == 0
    }
}

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

    #[test]
    fn ean_check_digit_of_a_known_code() {
        assert_eq!(ean::check_digit("400638133393"), 1);
    }

    #[test]
    fn ean_accepts_a_known_code() {
        assert!(ean::valid("4006381333931"));
    }

    #[test]
    fn ean_rejects_a_wrong_check_digit() {
        assert!(!ean::valid("4006381333932"));
    }

    #[test]
    fn ean_rejects_a_short_code() {
        assert!(!ean::valid("400638133393"));
    }

    #[test]
    fn luhn_accepts_a_known_number() {
        assert!(luhn::valid("79927398713"));
    }

    #[test]
    fn luhn_rejects_a_changed_digit() {
        assert!(!luhn::valid("79927398710"));
    }

    #[test]
    fn luhn_rejects_anything_with_a_separator() {
        assert!(!luhn::valid("7992-7398713"));
    }
}

Step one is the whole service. Run everything and find out how bad it is:

cargo test

Output:

running 7 tests
test tests::ean_rejects_a_short_code ... ok
test tests::ean_rejects_a_wrong_check_digit ... ok
test tests::luhn_accepts_a_known_number ... ok
test tests::luhn_rejects_a_changed_digit ... ok
test tests::luhn_rejects_anything_with_a_separator ... ok
test tests::ean_accepts_a_known_code ... FAILED
test tests::ean_check_digit_of_a_known_code ... FAILED

failures:

---- tests::ean_check_digit_of_a_known_code stdout ----
thread 'tests::ean_check_digit_of_a_known_code' panicked at src/lib.rs:66:9:
assertion `left == right` failed
  left: 7
 right: 1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- tests::ean_accepts_a_known_code stdout ----
thread 'tests::ean_accepts_a_known_code' panicked at src/lib.rs:71:9:
assertion failed: ean::valid("4006381333931")

failures:
    tests::ean_accepts_a_known_code
    tests::ean_check_digit_of_a_known_code

test result: FAILED. 5 passed; 2 failed; 0 ignored; 0 measured; 0 filtered out

The result lines appear in whatever order the tests finish, because they run in parallel by default, so a second run may list them differently -- there is nothing wrong when that happens. And the real last line ends with a finished in figure that is left out here, since it is a measurement of your machine and not of your code.

Both failures name ean, so step two narrows to that module. The filter is a substring of the test name, and every EAN test was named with that prefix on purpose:

cargo test ean

Output:

running 4 tests
test tests::ean_rejects_a_short_code ... ok
test tests::ean_rejects_a_wrong_check_digit ... ok
test tests::ean_accepts_a_known_code ... FAILED
test tests::ean_check_digit_of_a_known_code ... FAILED

failures:

---- tests::ean_check_digit_of_a_known_code stdout ----
thread 'tests::ean_check_digit_of_a_known_code' panicked at src/lib.rs:66:9:
assertion `left == right` failed
  left: 7
 right: 1
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

---- tests::ean_accepts_a_known_code stdout ----
thread 'tests::ean_accepts_a_known_code' panicked at src/lib.rs:71:9:
assertion failed: ean::valid("4006381333931")

failures:
    tests::ean_accepts_a_known_code
    tests::ean_check_digit_of_a_known_code

test result: FAILED. 2 passed; 2 failed; 0 ignored; 0 measured; 3 filtered out

Three tests filtered out, and the three that vanished were the Luhn ones. Everything from here on is a fraction of a full run.

The failure says the computed digit is 7 where 1 was wanted, which is a statement that the answer is wrong and no help at all with why. So step three adds a trace to the loop:

            if let Some(d) = c.to_digit(10) {
                sum += d * weight;
                println!("{c} x {weight} -> {sum}");
                weight = if weight == 3 { 1 } else { 3 };
            }

A print in a passing test is invisible and a print in a failing one is buried in a report, so pick the test that exercises the arithmetic without dying halfway and ask for its output directly:

cargo test ean_rejects_a_wrong -- --nocapture

Output:

running 1 test
4 x 3 -> 12
0 x 1 -> 12
0 x 3 -> 12
6 x 1 -> 18
3 x 3 -> 27
8 x 1 -> 35
1 x 3 -> 38
3 x 1 -> 41
3 x 3 -> 50
3 x 1 -> 53
9 x 3 -> 80
3 x 1 -> 83
test tests::ean_rejects_a_wrong_check_digit ... ok

test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 6 filtered out

The first line is the answer. The leading 4 was multiplied by 3, and EAN-13 weights the first digit by one, alternating three and one after it. The whole bug is let mut weight = 3. Change it to let mut weight = 1, delete the trace print, and run the service again:

cargo test

Output:

running 7 tests
test tests::ean_accepts_a_known_code ... ok
test tests::ean_check_digit_of_a_known_code ... ok
test tests::ean_rejects_a_short_code ... ok
test tests::ean_rejects_a_wrong_check_digit ... ok
test tests::luhn_accepts_a_known_number ... ok
test tests::luhn_rejects_a_changed_digit ... ok
test tests::luhn_rejects_anything_with_a_separator ... ok

test result: ok. 7 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out

Read that session as a shape rather than as five commands. It runs everything twice -- once at the start to see the damage and once at the end to prove nothing else moved -- and everything in between is deliberately narrow. On a crate with seven tests the saving is nothing. On a crate where the suite takes four minutes, the difference between iterating on cargo test ean_check_digit_of_a_known_code and iterating on cargo test is the difference between fixing the bug this morning and fixing it this afternoon, and the commands are the same length.

The diagnosis came from output that a plain run would have thrown away. The failure report gave two numbers, 7 and 1, and no route between them; the trace gave twelve lines, of which the first was conclusive. That is the usual division of labour: assertions tell you a claim is false, prints tell you what the machine was actually doing, and --nocapture is what connects the second to your terminal. Reaching for it early is cheaper than reasoning about the arithmetic in your head, particularly when the arithmetic is somebody else's standard.

Look at what ean_rejects_a_wrong_check_digit did through all of this: it passed. It passed with the bug in place, because the computed digit was 7, the supplied one was 2, those differ, and rejecting the code is exactly what the test demanded. It also passes with the bug fixed, for a different reason. A test that asserts something is refused is satisfied by a refusal for any reason at all, including a reason that is itself broken, and that makes negative tests systematically weaker than positive ones. The test with teeth here was ean_accepts_a_known_code, because only a correct implementation can accept a genuinely valid code.

The limits are worth naming. The trace println! sat in library code, not in the test module, so #[cfg(test)] offered no protection and nothing but discipline stops it shipping -- a real risk, and the reason a diagnostic print belongs in the test whenever the test can reach the values. --nocapture only stayed readable because exactly one test was running; with four printing at once the lines interleave and you need --test-threads=1 as well. The filter ean is a substring, so a module later renamed european would widen it silently. And the suite itself is thin: nothing covers EAN-8, and valid checks code.len() in bytes then slices at byte 12, so a thirteen-byte string with a multi-byte character in it passes the length check and panics inside the slice instead of returning false.


Common Mistakes

  1. Putting a harness flag before the --. cargo test --nocapture does not work: Cargo reads its own arguments first, does not recognise that one, and stops with an unexpected-argument error (it does at least suggest moving it after a --). The rule to remember is that Cargo decides what gets built and the test binary decides what gets run, so --release and --lib go on the left and --nocapture, --ignored, --exact and --test-threads go on the right.
  1. Expecting a println! to appear in a passing test. It never does. The harness captures each test's output and discards it on success, so a print added to check a value looks like it was never reached. Ask for -- --nocapture before concluding the code is not being executed.
  1. Reading --ignored as "including the ignored ones". It means only the ignored ones, and a run that reports 1 passed where you expected forty-one is that misreading. --include-ignored is the flag that runs both sets.
  1. Trusting a filter to be as narrow as it looks. Filters match a substring of the full test name, so valid also matches invalid_when_it_does_not, and ean would match a future test called clean_input. Use -- --list to see what a filter will hit and -- --exact when you want precisely one.
  1. Using --all-targets in CI and thinking it covers everything. It covers every target except doc tests, so a broken example in your public documentation sails through. If a script needs to be exhaustive it needs cargo test with no target flags, or a separate cargo test --doc.
  1. Writing a test that depends on another test having run first. Tests run in parallel, in an order the harness chooses, and --test-threads=1 makes that order stable rather than making it yours. A test that sets something up for the next one passes on your machine and fails in CI, and the failure looks like a bug in the code.
  1. Assuming a green cargo test means a green cargo test --release. The debug build panics on integer overflow and runs debug_assert!; the release build does neither. A #[should_panic] test for overflow passes in one and fails in the other, and arithmetic that quietly wraps in production was quietly wrapping all along.
  1. Leaving a diagnostic print in the code under test. #[cfg(test)] strips the test module, not a println! you added inside a library function to trace it. Put the print in the test where you can, and when the value only exists inside the function, delete the line as part of the same change that fixes the bug.
  1. Reading only the first counter on the summary line. test result: ok. 2 passed and test result: ok. 200 passed both start with ok. The number that catches a mistake is filtered out: a leftover filter in a CI command runs two tests out of two hundred, reports success, and looks identical to a healthy run unless you check that the count is zero.

Best Practices

  • Filter hard while you are working and run the whole suite before you commit. Narrow runs are for the loop you are in; the full run is what earns the commit.
  • Reach for -- --list when you do not know the exact name, and -- --exact when you do. Guessing at a filter and getting three tests is a slower way to arrive at the same place.
  • Pair --nocapture with --test-threads=1 whenever more than one test can print. Interleaved output from parallel tests is worse than no output, because it looks like data.
  • Write every test so it would pass if it were the only test in the crate, and so it would pass if it ran last. Independence is what makes the parallel default free.
  • Run the suite in both debug and release somewhere automatic. It costs one extra line in CI and it is the only thing that catches an overflow the debug build was politely panicking about.
  • Prefer #[ignore] with a reason plus a nightly -- --include-ignored job over deleting a slow test. The test that is too slow to run every minute is usually the one covering the widest ground.
  • Let the exit code be the judge in scripts -- it is zero only when everything passed -- and let your eyes check the filtered out count when you are the one reading.
  • Keep diagnostic prints on the test side of the boundary. A trace inside a library function is a temporary change to shipped code; a trace inside a test disappears from the release build on its own.

Practice Exercises

  1. Take the checksum crate from the top of this lesson and run it seven ways: bare, with the filter checksum, with the filter valid, with -- --exact on one full name, with -- --ignored, with -- --include-ignored, and with -- --list. Record the five counters from each summary line and write one sentence explaining what the filtered out number was telling you in each case.
  1. Add debug_assert!(digits.len() <= 32, "unexpectedly long input"); to the top of checksum, and a test that calls it with a forty-character string wrapped in #[should_panic]. Show the test passing under cargo test and failing under cargo test --release, and explain in two sentences why that is not a bug in the harness.
  1. Move the checksum tests into tests/codes.rs as an integration test. Prove that the new file cannot see a private helper by adding fn digits_only(s: &str) -> String without pub and trying to call it, then make the file compile again. Run only that target with cargo test --test codes, and confirm with -- --list that the unit tests are not in it.
  1. Add a documentation example to valid showing one accepted and one rejected input. Run it with cargo test --doc and note the line number the harness reports. Then break the example deliberately, run cargo test --all-targets, and confirm that the broken example does not fail the run -- this is mistake five, reproduced on purpose.