CARGO-TEST(1)

๐Ÿฆ‹ NAME ๐Ÿฆ‹

okay so bestie, this is cargo-test from the General Commands Manual โ€” it's the one that runs your unit and integration tests for a package. that's the whole job. iconic, honestly. ๐Ÿ’–


โœจ SYNOPSIS โœจ

cargo test [options] [testname] [-- test-options]

๐ŸŒธ DESCRIPTION ๐ŸŒธ

It compiles and executes your unit tests, your integration tests, and your documentation tests. three-for-one deal, we love to see it. ๐Ÿ’…

The test filtering argument TESTNAME and literally all the arguments sitting after the two dashes (--) get passed straight to the test binaries, which means they get passed to libtest โ€” that's rustc's built-in unit-test and micro-benchmarking framework. ๐Ÿงš

So if you're passing args to both Cargo and the binary, here's the vibe check: everything after -- goes to the binary, everything before it goes to Cargo. That's the rule, no cap.

Want the deets on libtest's arguments? Run cargo test -- --help and read the output, and also go check out the rustc book's chapter on how tests work at <https://doc.rust-lang.org/rustc/tests/index.html>. ๐Ÿ“š

For example โ€” this filters for tests that have foo in their name and runs them on 3 threads in parallel:

cargo test foo -- --test-threads 3

Tests are built with the --test option to rustc, which creates a special executable by linking your code with libtest. That executable automatically runs all the functions annotated with the #[test] attribute in multiple threads. ๐ŸŒˆ And functions annotated with #[bench] also get run with one iteration, just to verify that they're actually functional.

If your package contains multiple test targets, each target compiles into one of those special executables like I just said, and then they get run serially. one at a time. patient queen behavior. ๐Ÿ‘‘

The libtest harness can be disabled by setting harness = false in the target manifest settings โ€” but if you do that, your code has to provide its own main function to handle running the tests. you're on your own for that part, bestie. ๐Ÿซถ

By default, cargo test uses the test profile at <https://doc.rust-lang.org/cargo/reference/profiles.html#test>, which turns on some optimizations and turns off debugging information so you get fast feedback. โšก If you actually need to debug a test, you can use the --profile=debug command-line option to switch over to the debug profile. Then you can run that debug-enabled test inside a debugger. ๐Ÿ”

๐Ÿ“– Documentation tests ๐Ÿ“–

Documentation tests also run by default, and rustdoc is the one handling them. It pulls code samples out of the documentation comments of the library target, and then executes them. yes, your doc comments are load-bearing. ๐Ÿ™ˆ

Here's where it's different from normal test targets: each code block gets compiled into a doctest executable on the fly with rustc. Those executables run in parallel, in separate processes. And the compilation of a code block is actually a part of a test function controlled by libtest, which means some options โ€” like --jobs โ€” might not take effect. ๐Ÿ˜ญ

Heads up: this execution model for doctests is not guaranteed and may change in the future. So beware of depending on it. fr fr.

See the rustdoc book at <https://doc.rust-lang.org/rustdoc/> for more info on writing doc tests. ๐Ÿ’œ

๐Ÿ—‚๏ธ Working directory of tests ๐Ÿ—‚๏ธ

When each unit and integration test runs, its working directory is set to the root directory of the package the test belongs to. Setting the working directory of tests to the package's root directory means tests can reliably access the package's files using relative paths โ€” no matter where you ran cargo test from. slay, consistency. โœจ

For documentation tests, it's a whole different story: the working directory when invoking rustdoc is set to the workspace root directory, and that's also the directory rustdoc uses as the compilation directory of each documentation test. The working directory when running each documentation test is set to the root directory of the package the test belongs to, and that's controlled via rustdoc's --test-run-directory option. ๐ŸŽ€


๐Ÿ’… OPTIONS ๐Ÿ’…

๐Ÿงช Test Options ๐Ÿงช

  • --no-run โ€” compile it, but don't actually run the tests. build-only era.
  • --no-fail-fast โ€” run all the tests regardless of failure. without this flag, Cargo exits after the first executable fails. The Rust test harness will still run all tests within the executable to completion โ€” this flag only applies to the executable as a whole. ๐Ÿƒโ™€๏ธ

๐Ÿ“ฆ Package Selection ๐Ÿ“ฆ

By default, when you don't give any package selection options, which packages get selected depends on the selected manifest file (based on the current working directory, if --manifest-path isn't given). If the manifest is the root of a workspace, then the workspace's default members are selected. Otherwise, only the package defined by the manifest is selected. โœจ

You can set the default members of a workspace explicitly with the workspace.default-members key in the root manifest. If that's not set, then: a virtual workspace includes all workspace members (equivalent to passing --workspace), and a non-virtual workspace includes only the root crate itself. ๐Ÿซถ

  • -p specโ€ฆ, --package specโ€ฆ โ€” test only the specified packages. See cargo-pkgid(1) for the SPEC format. This flag may be specified multiple times and supports common Unix glob patterns like *, ? and []. But โ€” and listen โ€” to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. ๐Ÿ™ˆ
  • --workspace โ€” test all members in the workspace. everyone's invited ๐Ÿ’–
  • --all โ€” deprecated alias for --workspace. it's giving legacy, use the other one.
  • --exclude *SPEC*โ€ฆ โ€” exclude the specified packages. Must be used together with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like *, ? and []. Same deal as before: to avoid your shell expanding glob patterns before Cargo gets to them, you must use single quotes or double quotes around each pattern. ๐Ÿšซ

๐ŸŽฏ Target Selection ๐ŸŽฏ

When you give no target selection options, cargo test will build these targets of the selected packages:

  • lib โ€” used to link with binaries, examples, integration tests, and doc tests
  • bins โ€” only if integration tests are built and required features are available
  • examples โ€” to make sure they compile
  • lib as a unit test
  • bins as unit tests
  • integration tests
  • doc tests for the lib target

You can change that default behavior by setting the test flag for the target in the manifest settings. Setting examples to test = true will build and run the example as a test, replacing the example's main function with the libtest harness. And if you don't want the main function replaced, also include harness = false โ€” in that case the example gets built and executed as-is. โœจ

Setting targets to test = false stops them from being tested by default. But heads up: target selection options that take a target by name (like --example foo) ignore the test flag and will always test the given target. it said what it said. ๐Ÿ’…

Doc tests for libraries may be disabled by setting doctest = false for the library in the manifest.

See Configuring a target at <https://doc.rust-lang.org/cargo/reference/cargo-targets.html#configuring-a-target> for more info on per-target settings. ๐Ÿ“š

Binary targets are automatically built if there's an integration test or benchmark being selected to test. That's so an integration test can execute the binary to exercise and test its behavior. ๐Ÿƒ The CARGO_BIN_EXE_<name> environment variable at <https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates> is set when the integration test is built and run, so it can use the env macro at <https://doc.rust-lang.org/std/macro.env.html> or the var function at <https://doc.rust-lang.org/std/env/fn.var.html> to locate the executable. ๐Ÿ”

Passing target selection flags will test only the specified targets.

Also note: the --bin, --example, --test and --bench flags also support common Unix glob patterns like *, ? and []. But, again, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each glob pattern. ๐ŸŽ€

  • --lib โ€” test the package's library.
  • --bin *name*โ€ฆ โ€” test the specified binary. This flag may be specified multiple times and supports common Unix glob patterns.
  • --bins โ€” test all binary targets.
  • --example *name*โ€ฆ โ€” test the specified example. This flag may be specified multiple times and supports common Unix glob patterns.
  • --examples โ€” test all example targets.
  • --test *name*โ€ฆ โ€” test the specified integration test. This flag may be specified multiple times and supports common Unix glob patterns.
  • --tests โ€” test all targets that have the test = true manifest flag set. By default this includes the library and binaries built as unittests, plus integration tests. Be aware that this will also build any required dependencies, so the lib target may get built twice (once as a unittest, and once as a dependency for binaries, integration tests, etc.). Targets may be enabled or disabled by setting the test flag in the manifest settings for the target. ๐Ÿซ 
  • --bench *name*โ€ฆ โ€” test the specified benchmark. This flag may be specified multiple times and supports common Unix glob patterns.
  • --benches โ€” test all targets that have the bench = true manifest flag set. By default this includes the library and binaries built as benchmarks, plus bench targets. Be aware that this will also build any required dependencies, so the lib target may get built twice (once as a benchmark, and once as a dependency for binaries, benchmarks, etc.). Targets may be enabled or disabled by setting the bench flag in the manifest settings for the target. ๐Ÿ˜ฎโ€๐Ÿ’จ
  • --all-targets โ€” test all targets. This is equivalent to specifying --lib --bins --tests --benches --examples. the "do everything" button. ๐Ÿ‘‘
  • --doc โ€” test only the library's documentation. This cannot be mixed with other target options. pick a lane bestie โœ‹

๐ŸŒˆ Feature Selection ๐ŸŒˆ

The feature flags let you control which features get enabled. When no feature options are given, the default feature is activated for every selected package. โœจ

See the features documentation at <https://doc.rust-lang.org/cargo/reference/features.html#command-line-feature-options> for more details. ๐Ÿ“–

  • *-F *features, --features features** โ€” space or comma separated list of features to activate. Features of workspace members may be enabled with package-name/feature-name` syntax. This flag may be specified multiple times, which enables all specified features. ๐ŸŽ€
  • --all-features โ€” activate all available features of all selected packages. go big or go home ๐Ÿ’–
  • --no-default-features โ€” do not activate the default feature of the selected packages. ๐Ÿ™…โ™€๏ธ

๐Ÿ”จ Compilation Options ๐Ÿ”จ

  • --target triple โ€” test for the specified target architecture. The flag may be specified multiple times. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi>. ๐ŸŒ

Possible values:

  • Any supported target in rustc --print target-list.
  • "host-tuple" โ€” this one gets swapped out internally for your host's target. Super useful when you're cross-compiling some crates and you genuinely do not want to hardcode your host machine as a target โ€” think an xtask in a shared project that a whole bunch of different hosts are working on. iykyk. ๐Ÿซถ
  • A path to a custom target specification. Peep the Custom Target Lookup Path docs at https://doc.rust-lang.org/rustc/targets/custom.html#custom-target-lookup-path for the deets.

This can also be set with the build.target config value, over at https://doc.rust-lang.org/cargo/reference/config.html.

Heads up bestie: setting this flag makes Cargo run in a different mode where the target artifacts get dropped in a separate directory. Go read the build cache docs at https://doc.rust-lang.org/cargo/reference/build-cache.html for the full tea. ๐Ÿ’…
  • -r, --release โ€” tests optimized artifacts with the release profile. Also peek --profile if you wanna pick a specific profile by name.
  • --profile name โ€” tests with the profile you name. The reference at https://doc.rust-lang.org/cargo/reference/profiles.html has all the profile lore.
  • --timings โ€” spits out info on how long every compilation takes, and tracks concurrency info over time. Very "watch me cook" energy. โฑ๏ธ

A file called cargo-timing.html gets written into the target/cargo-timings directory at the end of the build. An extra report with a timestamp in its filename is also written, in case you wanna go back and look at a previous run. These reports are for human consumption only โ€” they do not give you machine-readable timing data. So no piping them into a script, okay? ๐Ÿ™ˆ


๐ŸŽ€ Output Options ๐ŸŽ€

  • --target-dir directory โ€” the directory for all generated artifacts and intermediate files. You can also set this with the CARGO_TARGET_DIR environment variable, or the build.target-dir config value at https://doc.rust-lang.org/cargo/reference/config.html. Defaults to target in the root of the workspace. ๐Ÿ 

โœจ Display Options โœจ

By default, the Rust test harness hides output from test execution so your results stay readable. But you can absolutely recover that output (say, for debugging) by passing --no-capture to the test binaries:

cargo test -- --no-capture
  • -v, --verbose โ€” verbose output. Specify it twice for "very verbose" output, which includes extra stuff like dependency warnings and build script output. Can also be set with the term.verbose config value at https://doc.rust-lang.org/cargo/reference/config.html.
  • -q, --quiet โ€” do not print cargo log messages. Can also be set with the term.quiet config value at https://doc.rust-lang.org/cargo/reference/config.html.
  • --color when โ€” controls when colored output is used. Valid values:
    • auto (default): automatically detect if color support is available on the terminal. ๐ŸŒˆ
    • always: always display colors. periodt.
    • never: never display colors. ๐Ÿ’€

Can also be set with the term.color config value at https://doc.rust-lang.org/cargo/reference/config.html.

  • --message-format fmt โ€” the output format for diagnostic messages. You can specify this multiple times, and it's made of comma-separated values. Valid values:
    • human (default): display in a human-readable text format. Conflicts with short and json.
    • short: emit shorter, human-readable text messages. Conflicts with human and json.
    • json: emit JSON messages to stdout. See the reference at https://doc.rust-lang.org/cargo/reference/external-tools.html#json-messages for more. Conflicts with human and short.
    • json-diagnostic-short: makes sure the rendered field of JSON messages contains the "short" rendering from rustc. Cannot be used with human or short.
    • json-diagnostic-rendered-ansi: makes sure the rendered field of JSON messages contains embedded ANSI color codes, so it respects rustc's default color scheme. Cannot be used with human or short.
    • json-render-diagnostics: tells Cargo to not include rustc diagnostics in the JSON messages it prints, and instead have Cargo itself render the JSON diagnostics coming from rustc. Cargo's own JSON diagnostics, plus others coming from rustc, are still emitted. Cannot be used with human or short.

๐Ÿฆ‹ Manifest Options ๐Ÿฆ‹

  • --manifest-path path โ€” path to the Cargo.toml file. By default, Cargo hunts for Cargo.toml in the current directory or any parent directory. ๐Ÿ”
  • --ignore-rust-version โ€” ignore the rust-version specification in packages.
  • --locked โ€” asserts that the exact same dependencies and versions are used as when the existing Cargo.lock file was originally generated. Cargo will exit with an error when either of these scenarios pops up:
    • The lock file is missing. ๐Ÿ˜ญ
    • Cargo attempted to change the lock file due to a different dependency resolution.

Use it in environments where you want deterministic builds, like in CI pipelines. Very responsible of you ngl.

  • --offline โ€” prevents Cargo from touching the network for any reason. Without this flag, Cargo stops with an error if it needs the network and the network isn't available. With this flag, Cargo will try to keep going without the network if it possibly can.
Beware bestie: this can give you different dependency resolution than online mode. Cargo restricts itself to crates that are downloaded locally, even if there might be a newer version indicated in the local copy of the index. Check out the cargo-fetch(1) command to download dependencies before you go offline. ๐Ÿงš

Can also be set with the net.offline config value at https://doc.rust-lang.org/cargo/reference/config.html.

  • --frozen โ€” equivalent to specifying both --locked and --offline. Two-for-one, we love a bundle. ๐Ÿ’–

๐Ÿ’œ Common Options ๐Ÿ’œ

  • +toolchain โ€” if Cargo was installed with rustup, and the first argument to cargo starts with +, it gets interpreted as a rustup toolchain name (like +stable or +nightly). See the rustup documentation at https://rust-lang.github.io/rustup/overrides.html for more on how toolchain overrides work.
  • --config KEY=VALUE or PATH โ€” overrides a Cargo configuration value. The argument should be in TOML syntax of KEY=VALUE, or given as a path to an extra configuration file. This flag can be specified multiple times. See the command-line overrides section at https://doc.rust-lang.org/cargo/reference/config.html#command-line-overrides for more.
  • -C PATH โ€” changes the current working directory before executing any specified operations. This affects things like where cargo looks by default for the project manifest (Cargo.toml), and also the directories searched for discovering .cargo/config.toml, for example. This option must appear before the command name, like cargo -C path/to/my-project build.
This option is only available on the nightly channel (https://doc.rust-lang.org/book/appendix-07-nightly-rust.html) and requires the -Z unstable-options flag to enable (see #10098 at https://github.com/rust-lang/cargo/issues/10098). ๐Ÿ‘‘
  • -h, --help โ€” prints help information.
  • -Z flag โ€” unstable (nightly-only) flags to Cargo. Run cargo -Z help for details.

๐ŸŒธ Miscellaneous Options ๐ŸŒธ

The --jobs argument affects the building of the test executable, but it does not affect how many threads are used when running the tests. The Rust test harness has its own option to control the number of threads used:

cargo test -j 2 -- --test-threads=2
  • -j N, --jobs N โ€” number of parallel jobs to run. Can also be set with the build.jobs config value at https://doc.rust-lang.org/cargo/reference/config.html. Defaults to the number of logical CPUs. If negative, it sets the maximum number of parallel jobs to the number of logical CPUs plus the value you provided. If a string default is provided, it sets the value back to defaults. Should not be 0.
  • --future-incompat-report โ€” displays a future-incompat report for any future-incompatible warnings produced during execution of this command. See cargo-report(1).

So here's the thing: even though cargo test involves compilation, it does not give you a --keep-going flag. Use --no-fail-fast to run as many tests as possible without stopping at the first failure. And to "compile" as many tests as possible, use --tests to build test binaries separately. Like so:

cargo build --tests --keep-going
cargo test --tests --no-fail-fast

๐ŸŒˆ ENVIRONMENT ๐ŸŒˆ

See the reference at https://doc.rust-lang.org/cargo/reference/environment-variables.html for the details on environment variables that Cargo reads. ๐Ÿ‘€


โญ EXIT STATUS โญ

  • 0: Cargo succeeded. slay. ๐ŸŽ‰
  • 101: Cargo failed to complete. ๐Ÿ’€

๐Ÿ“ EXAMPLES ๐Ÿ“

  1. Execute all the unit and integration tests of the current package:
cargo test
  1. Run only tests whose names match against a filter string:
cargo test name_filter
  1. Run only a specific test within a specific integration test:
cargo test --test int_test_name -- modname::test_name

๐Ÿซถ SEE ALSO ๐Ÿซถ

cargo(1), cargo-bench(1), types of tests at https://doc.rust-lang.org/cargo/reference/cargo-targets.html#tests, and how to write tests at https://doc.rust-lang.org/rustc/tests/index.html


And that's the whole CARGO-TEST(1) page, bestie โ€” you made it to the end, main character behavior fr fr. ๐Ÿ’…โœจ

๐Ÿ“ฆ where this page comes from