Package and test a CLI
Quick answer
A CLI release needs tested logic, a reproducible build procedure and documented behavior for arguments, output and exit status.
Test logic and package separately
Place reusable functions in src/lib.rs and the interface in src/main.rs. Unit tests check behavior with controlled inputs; integration tests execute the binary and inspect stdout, stderr and status. Cargo build --release uses the release profile, while --locked refuses a lockfile change. A lockfile alone does not guarantee bit-identical binaries; record toolchain and target too. Use a disposable package for these steps.
pub fn normalize(s: &str) -> &str { s.trim() }#[cfg(test)]mod tests { use super::*; #[test] fn trims_spaces() { assert_eq!(normalize(" hi "), "hi"); } #[test] fn empty_is_empty() { assert_eq!(normalize(" "), ""); }}Manual local Rust/Cargo candidate; not executed. Expected behavior:
cargo test runs two successful tests if the crate is configured.The tests need no terminal or file.
cargo generate-lockfilecargo test --lockedcargo build --release --lockedManual terminal step; not executed. Expected behavior (environment dependent):
Tests and release build succeed if toolchain and dependencies resolve.For a real release, also test the built binary on each supported target.
Common mistake
Do not assume a successful debug build proves release behavior or cross-platform compatibility.
Try it yourself
Create an integration test that checks the missing-argument diagnostic and exit status.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Package and test a CLI — practice quiz
Choose one answer per question. Code examples are predictions; review explanations after attempting them.
A library unit test passes but the CLI exits with the wrong status on failure. What test is missing?
Package and test a CLI — example 1. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```rust pub fn normalize(s: &str) -> &str { s.trim() } #[cfg(test)] mod tests { use super::*; #[test] fn trims_spaces() { assert_eq!(normalize(" hi "), "hi"); } #[test] fn empty_is_empty() { assert_eq!(normalize(" "), ""); } } ``` Which outcome or interpretation best matches this example?
Package and test a CLI — example 2. Read the code; do not execute it for this question. Assume the lesson’s stated setup, compatible dependencies and toolchain, and a fresh disposable directory for file-creating examples. ```bash cargo generate-lockfile cargo test --locked cargo build --release --locked ``` Which outcome or interpretation best matches this example?