Why can't tests/cli.rs import functions from a Rust package that has only src/main.rs, and how do you make the tool testable?
answer
- binaries export nothing
- unresolved import
- thin main over a library
- CARGO_BIN_EXE for end-to-end
basics
~20 sA binary crate exposes no items to other crates, so use logfilter::parse; in tests/cli.rs fails with E0432. Move the logic into src/lib.rs, keep src/main.rs a thin caller, and test the library; tests can still run the binary via CARGO_BIN_EXE_<name>.
solid answer
~40 sOnly a library crate offers items for other crates to `use`, and a file in `tests/` is another crate. With just `src/main.rs`, `use logfilter::parse;` fails with E0432, however many items are `pub`. The fix is the library-plus-binary split: `src/lib.rs` holds `pub fn parse` and `pub fn keep`, and `src/main.rs` only reads arguments and stdin, calls `logfilter::parse`, and maps errors to an exit code. Integration tests then import the library. For end-to-end checks Cargo builds the package's binaries before its integration tests and sets `CARGO_BIN_EXE_logfilter`, which `env!` reads and `std::process::Command` runs. The split also matters for doctests: rustdoc tests the library target only, so examples in `main.rs` never run.
code
rust · 21 lines// src/main.rs: a thin shell over the logfilter library in src/lib.rs
use std::io::{self, BufRead, Write};
use std::process::ExitCode;
fn main() -> ExitCode {
let arg = std::env::args().nth(1).unwrap_or_else(|| "info".into());
let min = match logfilter::parse(&arg) {
Ok(l) => l,
Err(e) => {
eprintln!("{e}");
return ExitCode::from(2);
}
};
let lines: Vec<String> = io::stdin().lock().lines().map_while(Result::ok).collect();
let refs: Vec<&str> = lines.iter().map(String::as_str).collect();
let mut out = io::stdout().lock();
for l in logfilter::keep(&refs, min) {
writeln!(out, "{l}").unwrap();
}
ExitCode::SUCCESS
}go deeper
Recall that tests/ can only import a library, so a command-line tool keeps its logic in src/lib.rs and a short main.rs.
Explain why E0432 is about crate kinds rather than visibility, and how CARGO_BIN_EXE_<name> lets a test run the real executable.
Decide what to test through the library and what only through the process, such as exit codes and output, and keep main thin enough to trust.
Treat the library-plus-binary layout as the default for tools, since it shapes testability, reuse and what the package publishes.
## Why a binary crate cannot be imported A Cargo package can contain one **library crate** (`src/lib.rs`) and any number of **binary crates** (`src/main.rs`, `src/bin/*.rs`). They differ in what other crates can do with them: - A **library** is compiled into something other crates link against, so its `pub` items are reachable by path. - A **binary** is compiled into an executable. Nothing else links against it, so it offers no items to anyone. An integration test in `tests/` is a separate crate. In a package with only `src/main.rs`, the line `use logfilter::parse;` has nothing to resolve to, and rustc stops with `error[E0432]: unresolved import `logfilter``. Marking functions `pub` in `main.rs` does not help: the problem is that no library crate named `logfilter` exists. That does **not** make a binary-only package untestable: 1. Unit tests in a `#[cfg(test)]` module inside `main.rs` still run (`Running unittests src/main.rs`); that side belongs to the material on in-module unit tests. 2. Integration tests can still **run the executable** and check its output and exit status. What is lost is the ability to call its functions from `tests/`. ## The library-plus-binary split The usual structure moves the logic into a library and leaves `main` as a thin shell: - `src/lib.rs` holds `pub enum Level`, `pub fn parse` and `pub fn keep`, the parts worth testing. - `src/main.rs` reads the level argument and stdin, calls `logfilter::parse` and `logfilter::keep`, prints the kept lines and returns `ExitCode::from(2)` on a bad level. - Both crates take the package name by default, so `main.rs` refers to the library as `logfilter::...` without any manifest change. Integration tests now `use logfilter::{keep, parse, Level};` and exercise the real logic. If the library works, the few lines in `main` that glue it to the process have little left to go wrong. ## Testing the executable end to end Some behaviour lives only in the binary: argument handling, exit codes, what goes to stdout and stderr. For that, Cargo helps integration tests find the executable: - Binary targets are **built automatically** when an integration test is built, unless a binary has `required-features` that are not enabled. - Cargo sets **`CARGO_BIN_EXE_<name>`** to the absolute path of each binary, where `<name>` is the binary target's name as written, for example `CARGO_BIN_EXE_logfilter`. - The variable is set only for integration tests and benchmarks; `env!("CARGO_BIN_EXE_logfilter")` bakes the path in at compile time. `tests/cli.rs` spawns that path with `std::process::Command`, writes sample lines to its stdin, and asserts on stdout and on the exit code for an unknown level. | Goal | Where the test lives | What it calls | |---|---|---| | Logic through the public API | `tests/*.rs` | `logfilter::parse`, `logfilter::keep` | | The process: args, stdout, exit code | `tests/*.rs` | the executable via `CARGO_BIN_EXE_logfilter` | | Private helpers | `#[cfg(test)]` module in `src/` | anything in scope | ## Doctests follow the library rustdoc extracts doc examples from the **library target** only. In a binary-only package, a code block in a doc comment in `main.rs` is never compiled or run by `cargo test`; there is no `Doc-tests` section at all. After the split, the examples on `pub fn parse` in `lib.rs` run as doctests, which is one more reason the logic belongs there. ## Pitfalls when running the binary from a test - **Close stdin.** `wait_with_output` closes a stdin handle still held by the `Child`, but once the test has taken the `ChildStdin` out to write to it, a filter that reads until end of input keeps waiting until that handle is dropped; drop it before waiting. - **Assert on the exit code, not only on output.** `status.code()` is how a test sees `ExitCode::from(2)`. - **Keep end-to-end tests few.** Each spawns a process, so most cases belong in library tests; a handful of process-level checks cover argument parsing and exit codes. ## What to say in an interview - The error is about **crate kinds**, not visibility: there is no library to import. - The fix is a **thin `main` over a library**, the layout the Rust book describes for projects that provide a binary. - **`CARGO_BIN_EXE_<name>`** covers the behaviour that only the process has. - Doc examples only run from the library.
- When does Cargo set CARGO_BIN_EXE_<name>, and what goes in <name>?Only for integration tests and benchmarks, so `env!` can read it when the test compiles. `<name>` is the binary target's name exactly as written, dashes included, for example `CARGO_BIN_EXE_my-program`. Cargo builds the binaries before the test unless a binary's `required-features` are not enabled.
- Does a Rust package with only src/main.rs run any tests at all?Yes. A `#[cfg(test)]` module inside `main.rs` compiles into the binary's unit-test executable and runs as `unittests src/main.rs`. Integration tests can also run the executable through `CARGO_BIN_EXE_<name>`. What such a package cannot have is integration tests that import its functions, or doctests.
- After the split, why do the doc examples on parse start running?rustdoc extracts doc examples only from the library target. While `parse` lived in `main.rs`, its examples were never compiled; in `lib.rs` they become doctests that `cargo test` runs in its `Doc-tests logfilter` section.
- Marking the functions in main.rs pub lets tests/ import them.
- A binary-only Rust package cannot be tested in any way.
- Integration tests must shell out to cargo run to exercise the binary.
- Doc examples in src/main.rs run as doctests under cargo test.
- The library and the binary need different names before they can live in one package.