Testing and shipping
Unit tests beside the code, integration tests that run the binary against fixtures, clippy and rustfmt, and a release build with measurements.
- lesson
- 08 of 08
- read
- 18 min
tally has been checked by eye against one sample file. This lesson pins its behavior down with tests at two levels and runs the standard linter and formatter over the code. It ends with the optimized build, which makes it possible to measure the performance claims of lessons 5 and 7.
Unit tests
Unit tests live in the file they test, in a module that is compiled only for cargo test. Add this at the end of entry.rs:
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_a_combined_log_line() {
let line = r#"203.0.113.7 - - [28/Nov/2026:09:14:30 +0000] "GET /about HTTP/1.1" 200 3310 "-" "curl/8.7.1""#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.addr, "203.0.113.7");
assert_eq!(entry.path, "/about");
assert_eq!(entry.status, 200);
assert_eq!(entry.bytes, Some(3310));
}
#[test]
fn dash_size_means_no_body() {
let line = r#"203.0.113.7 - - [28/Nov/2026:09:15:03 +0000] "GET / HTTP/1.1" 304 -"#;
let entry = parse_line(line).unwrap();
assert_eq!(entry.bytes, None);
}
#[test]
fn says_what_is_wrong_with_a_line() {
let err = parse_line("198.51.100.23 - - [28/Nov/2026:09:14:").unwrap_err();
assert_eq!(err, ParseError::Missing("request"));
let line = r#"203.0.113.7 - - [28/Nov/2026:09:15:03 +0000] "GET / HTTP/1.1" abc 12"#;
let err = parse_line(line).unwrap_err();
assert_eq!(err, ParseError::BadStatus("abc".to_string()));
assert_eq!(err.to_string(), r#"invalid status "abc""#);
}
#[test]
fn classifies_status_codes() {
assert_eq!(StatusClass::from_code(204), StatusClass::Success);
assert_eq!(StatusClass::from_code(404), StatusClass::ClientError);
assert_eq!(StatusClass::from_code(99), StatusClass::Other);
assert_eq!(StatusClass::from_code(600), StatusClass::Other);
}
}#[cfg(test)] removes the module from normal builds. use super::* imports everything from the parent module, private items included, which is why unit tests can reach internals. A #[test] function passes if it returns and fails if it panics, so unwrap() is appropriate here: a parse failure should fail the test. r#"..."# is a raw string, in which quotes and backslashes need no escaping.
cargo testerror[E0369]: binary operation `==` cannot be applied to type `entry::ParseError`
--> src/entry.rs:140:9
|
140 | assert_eq!(err, ParseError::Missing("request"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
| |
| entry::ParseError
| entry::ParseError
|
note: an implementation of `PartialEq` might be missing for `entry::ParseError`
--> src/entry.rs:61:1
|
61 | pub enum ParseError {
| ^^^^^^^^^^^^^^^^^^^ must implement `PartialEq`
help: consider annotating `entry::ParseError` with `#[derive(PartialEq)]`
|
61 + #[derive(PartialEq)]
62 | pub enum ParseError {
|
...assert_eq! compares its arguments with == and prints both with Debug when they differ, so the compared type needs PartialEq. Add it to the derives of ParseError:
#[derive(Debug, PartialEq)]
pub enum ParseError {The summary gets tests as well. Its entries are built directly, without going through the parser:
#[cfg(test)]
mod tests {
use super::*;
fn hit(addr: &'static str, path: &'static str, status: u16) -> Entry<'static> {
Entry {
addr,
path,
status,
bytes: Some(100),
}
}
#[test]
fn ranks_by_count_then_by_name() {
let mut summary = Summary::new();
for path in ["/b", "/c", "/a", "/b", "/a"] {
summary.record(&hit("192.0.2.1", path, 200));
}
let report = summary.report(2);
let names: Vec<&str> = report.top_paths.iter().map(|item| item.name).collect();
assert_eq!(names, ["/a", "/b"]);
assert_eq!(report.top_paths[0].count, 2);
}
#[test]
fn totals_requests_bytes_and_status_classes() {
let mut summary = Summary::new();
summary.record(&hit("192.0.2.1", "/", 200));
summary.record(&hit("192.0.2.2", "/", 503));
summary.record(&Entry {
addr: "192.0.2.2",
path: "/",
status: 304,
bytes: None,
});
assert_eq!(summary.requests, 3);
assert_eq!(summary.bytes, 200);
assert_eq!(summary.status[&StatusClass::ServerError], 1);
assert_eq!(summary.status.get(&StatusClass::ClientError), None);
}
}The return type Entry<'static> says that the entry borrows only from string literals. The first test fixes the tie-breaking order from lesson 5. To see what a failure looks like, swap the two expected names and run cargo test:
...
---- summary::tests::ranks_by_count_then_by_name stdout ----
thread 'summary::tests::ranks_by_count_then_by_name' (1408504) panicked at src/summary.rs:108:9:
assertion `left == right` failed
left: ["/a", "/b"]
right: ["/b", "/a"]
...Integration tests
Files in a top-level tests/ directory are integration tests. Cargo compiles each one as a separate crate that sees the package from outside. For a binary, outside means running it: Cargo builds the executable first and hands its path to the test at compile time, in the environment variable CARGO_BIN_EXE_tally.
The tests need input and an expected report:
mkdir -p tests/fixtures
cp access.log tests/fixtures/access.log
cargo run -q -- tests/fixtures/access.log > tests/fixtures/access.txt 2>/dev/nullaccess.txt is a golden file: output that a person captured and checked once, and that every later run is compared with, byte for byte. Such a test notices every change to the report, intended or not. When the format changes on purpose, regenerate the file and review the diff before committing it.
use std::io::Write;
use std::process::{Command, Stdio};
const LOG: &str = "tests/fixtures/access.log";
fn tally() -> Command {
Command::new(env!("CARGO_BIN_EXE_tally"))
}
#[test]
fn text_report_matches_the_fixture() {
let output = tally().arg(LOG).output().unwrap();
assert!(output.status.success());
let stdout = String::from_utf8(output.stdout).unwrap();
assert_eq!(stdout, include_str!("fixtures/access.txt"));
}
#[test]
fn malformed_lines_are_reported_on_stderr() {
let output = tally().arg(LOG).output().unwrap();
let stderr = String::from_utf8(output.stderr).unwrap();
assert_eq!(
stderr,
"tests/fixtures/access.log:8: missing request\n\
tests/fixtures/access.log:15: missing path\n"
);
}
#[test]
fn json_report_carries_the_same_numbers() {
let output = tally()
.args(&["--format", "json", "--top", "1", LOG])
.output()
.unwrap();
let report: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(report["requests"], 16);
assert_eq!(report["malformed"], 2);
assert_eq!(report["status"]["5xx"], 2);
assert_eq!(report["top_paths"][0]["name"], "/");
assert_eq!(report["top_paths"].as_array().unwrap().len(), 1);
}
#[test]
fn strict_mode_stops_at_the_first_bad_line() {
let output = tally().args(&["--strict", LOG]).output().unwrap();
assert_eq!(output.status.code(), Some(1));
assert!(output.stdout.is_empty());
let stderr = String::from_utf8(output.stderr).unwrap();
assert_eq!(
stderr,
"tally: tests/fixtures/access.log:8: missing request\n"
);
}
#[test]
fn missing_file_exits_with_one() {
let output = tally().arg("tests/fixtures/nope.log").output().unwrap();
assert_eq!(output.status.code(), Some(1));
let stderr = String::from_utf8(output.stderr).unwrap();
assert!(stderr.starts_with("tally: tests/fixtures/nope.log: "));
}
#[test]
fn reads_standard_input_when_no_file_is_given() {
let mut child = tally()
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.unwrap();
let mut stdin = child.stdin.take().unwrap();
stdin
.write_all(include_bytes!("fixtures/access.log"))
.unwrap();
drop(stdin);
let output = child.wait_with_output().unwrap();
let stdout = String::from_utf8(output.stdout).unwrap();
assert_eq!(stdout, include_str!("fixtures/access.txt"));
}Cargo runs tests with the package root as the working directory, which is why the relative fixture path works. include_str! embeds a file in the test binary at compile time, with a path relative to the source file. Command::output runs the program to completion and captures both streams and the exit status, so each row of the status table from lesson 7 has an assertion. The JSON test parses the output into a serde_json::Value and checks a few fields, which keeps it independent of whitespace.
cargo test Compiling tally v0.1.0 (/home/you/tally)
Finished `test` profile [unoptimized + debuginfo] target(s) in 0.38s
Running unittests src/main.rs (target/debug/deps/tally-6078d5719b8547a3)
running 6 tests
test entry::tests::classifies_status_codes ... ok
test entry::tests::dash_size_means_no_body ... ok
test entry::tests::says_what_is_wrong_with_a_line ... ok
test entry::tests::parses_a_combined_log_line ... ok
test summary::tests::totals_requests_bytes_and_status_classes ... ok
test summary::tests::ranks_by_count_then_by_name ... ok
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.00s
Running tests/cli.rs (target/debug/deps/cli-9f07d5f51e1b3844)
running 6 tests
test missing_file_exits_with_one ... ok
test strict_mode_stops_at_the_first_bad_line ... ok
test reads_standard_input_when_no_file_is_given ... ok
test json_report_carries_the_same_numbers ... ok
test text_report_matches_the_fixture ... ok
test malformed_lines_are_reported_on_stderr ... ok
test result: ok. 6 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in 0.27sClippy and rustfmt
Clippy is the linter that ships with the toolchain. A plain cargo clippy checks the program only, and for tally it has nothing to report. Including the tests gives it something to say:
cargo clippy --all-targetswarning: the borrowed expression implements the required traits
--> tests/cli.rs:34:15
|
34 | .args(&["--format", "json", "--top", "1", LOG])
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ help: change this to: `["--format", "json", "--top", "1", LOG]`
|
= help: for further information visit https://rust-lang.github.io/rust-clippy/rust-1.99.0/index.html#needless_borrows_for_generic_args
= note: `#[warn(clippy::needless_borrows_for_generic_args)]` on by default
...args accepts an array directly, so the & is noise. Remove it in both tests. Every lint links to a page that explains its reasoning, and when a lint does not fit, #[allow(clippy::lint_name)] on the item turns it off there. On a CI server, cargo clippy --all-targets -- -D warnings makes any warning fail the build.
cargo fmt rewrites every source file in the standard style. cargo fmt --check changes nothing: it prints a diff for each file that is not formatted and exits with status 1, which also suits CI. This is its output for two lines typed carelessly:
Diff in /home/you/tally/src/output.rs:36:
impl Render for Json {
fn render(&self, report: &Report, out: &mut dyn Write) -> io::Result<()> {
- let text=serde_json::to_string_pretty( report )?;
- writeln!(out,"{text}")
+ let text = serde_json::to_string_pretty(report)?;
+ writeln!(out, "{text}")
}
}All code in this course was formatted that way, with default settings.
Release builds
Everything so far used the dev profile, which does not optimize and keeps full debug information. cargo build --release uses the release profile and writes target/release/tally. To compare the two, build a larger input from the 16 valid lines of the sample:
grep 'HTTP/' access.log > clean.log
yes "$(cat clean.log)" | head -n 1600000 > big.log
cargo build --release
time target/debug/tally big.log > /dev/null
time target/release/tally big.log > /dev/nullbig.log has 1.6 million lines and is 173 MB. These are wall-clock times on an Apple M4, taking the best of several runs:
| Build | Time |
|---|---|
| dev | 2.79 s |
| release | 0.18 s |
release, with reader.lines() in place of the reused buffer |
0.21 s |
release, with entry(key.to_string()) in place of bump |
0.21 s |
A performance number taken from a dev build says little about the program. The last two rows test the claims from lessons 7 and 5. Avoiding the allocations is worth about 0.03 s each on this input: measurable, and small next to the gap between the profiles.
The profiles also differ in one behavior. Integer overflow panics in a dev build and wraps around silently in a release build, unless overflow-checks is enabled for it. With the u8 counter from the third exercise of lesson 1, the release build reports 44 requests for the 300-line file. When a value can overflow, pick a wider type or use checked_add.
The release binary is 1.0 MB on this machine. Profile settings in Cargo.toml trade build time for size:
[profile.release]
strip = true
lto = true
codegen-units = 1strip = true alone brought the binary down to 0.8 MB. All three together gave 0.63 MB and took a clean release build from about 4 seconds to about 7, with no difference in run time beyond measurement noise.
To put the program on your PATH, cargo install --path . --locked builds it in release mode and copies the binary to Cargo’s bin directory, ~/.cargo/bin by default. Without --locked, cargo install ignores Cargo.lock and resolves the newest compatible version of every dependency.
Where to go next
This course left out two large parts of the language. The book The Rust Programming Language covers both: smart pointers such as Rc and RefCell, for data with more than one owner, and concurrency, where the ownership rules of lesson 2 turn out to prevent data races as well. For the program itself, Command Line Applications in Rust goes further into signal handling, configuration files and packaging.
Exercises
- Test the text renderer without starting a process. In a test module in
output.rs, build a smallSummary, render its report into aVec<u8>withText.render, and compare the result with an expected string.cargo testshould then report seven unit tests. - Add two integration tests for the command line:
--format yamlmust exit with status 2 and leave standard output empty, and-n 0must print the headingstop pathsandtop clientswith no entries under them. - Split the package into a library and a binary: move the four
modlines into a newsrc/lib.rsaspub mod, and import fromtally::inmain.rs. Add an integration test that callstally::entry::parse_linedirectly.cargo testshould now show a section forsrc/lib.rs, andcargo clippyshould start suggesting aDefaultimplementation forSummary, since the type has become part of a public interface.