CARGO-TEST(1)

πŸ“¦ version 1.82.0, in ubuntu jammy, ubuntu noble

🌸 NAME 🌸

cargo-test(1) β€” Execute unit and integration tests of a package

✨ SYNOPSIS ✨

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

πŸ¦‹ DESCRIPTION πŸ¦‹

Okay so bestie, cargo test compiles and runs your unit tests, integration tests, and documentation tests. It's literally the main character of testing in Rust. πŸ’…

The test filtering argument TESTNAME and all the arguments after the two dashes (--) get passed straight to the test binaries, which means they go to libtest (that's rustc’s built in unit-test and micro-benchmarking framework, iykyk). If you’re passing stuff to both Cargo and the binary, the ones after -- go to the binary, the ones before go to Cargo. For the tea on libtest’s arguments, see the output of cargo test -- --help and check out the rustc book’s chapter on how tests work at https://doc.rust-lang.org/rustc/tests/index.html.

As an example, this will filter for tests with foo in their name and run 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 functions annotated with the #[test] attribute in multiple threads. #[bench] annotated functions will also be run with one iteration to verify that they are functional.

If the package contains multiple test targets, each target compiles to a special executable as aforementioned, and then is run serially.

The libtest harness may be disabled by setting harness = false in the target manifest settings, in which case your code will need to provide its own main function to handle running tests. No cap.

πŸ“š Documentation tests πŸ“š

Documentation tests are also run by default, which is handled by rustdoc. It extracts code samples from documentation comments of the library target, and then executes them.

Different from normal test targets, each code block compiles to a doctest executable on the fly with rustc. These executables run in parallel in separate processes. The compilation of a code block is in fact a part of test function controlled by libtest, so some options such as --jobs might not take effect. Note that this execution model of doctests is not guaranteed and may change in the future; beware of depending on it. ⚠️

See the rustdoc book https://doc.rust-lang.org/rustdoc/ for more information on writing doc tests.

πŸ“‚ Working directory of tests πŸ“‚

The working directory when running each unit and integration test 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 makes it possible for tests to reliably access the package’s files using relative paths, regardless from where cargo test was executed from. Slay.

For documentation tests, the working directory when invoking rustdoc is set to the workspace root directory, and is 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 is controlled via rustdoc’s --test-run-directory option.

πŸ’… OPTIONS πŸ’…

πŸ§ͺ Test Options πŸ§ͺ

  • --no-run β€” Compile, but don’t run tests. Just build them, bestie.
  • --no-fail-fast β€” Run all tests regardless of failure. Without this flag, Cargo will exit after the first executable fails. The Rust test harness will run all tests within the executable to completion; this flag only applies to the executable as a whole.

πŸ“¦ Package Selection πŸ“¦

By default, when no package selection options are given, the packages selected depend on the selected manifest file (based on the current working directory if --manifest-path is not given). If the manifest is the root of a workspace then the workspaces default members are selected, otherwise only the package defined by the manifest will be selected.

The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. If this is not set, a virtual workspace will include all workspace members (equivalent to passing --workspace), and a non-virtual workspace will include 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 []. However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. Periodt.
  • --workspace β€” Test all members in the workspace.
  • --all β€” Deprecated alias for --workspace. (It's giving legacy, but okay.)
  • --exclude SPEC… β€” Exclude the specified packages. Must be used in conjunction with the --workspace flag. This flag may be specified multiple times and supports common Unix glob patterns like *, ? and []. However, to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern.

🎯 Target Selection 🎯

When no target selection options are given, cargo test will build the following 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 ensure they compile
  • lib as a unit test
  • bins as unit tests
  • integration tests
  • doc tests for the lib target

The default behavior can be changed 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. If you don’t want the main function replaced, also include harness = false, in which case the example will be built and executed as-is.

Setting targets to test = false will stop them from being tested by default. Target selection options that take a target by name (such as --example foo) ignore the test flag and will always test the given target.

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

See Configuring a target https://doc.rust-lang.org/cargo/reference/cargo-targets.html#configuring-a-target for more information on per-target settings.

Binary targets are automatically built if there is an integration test or benchmark being selected to test. This allows an integration test to execute the binary to exercise and test its behavior. The CARGO_BIN_EXE_<name> environment variable https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates is set when the integration test is built so that it can use the env macro https://doc.rust-lang.org/std/macro.env.html to locate the executable.

Passing target selection flags will test only the specified targets.

Note that --bin, --example, --test and --bench flags also support common Unix glob patterns like *, ? and []. However, 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 in test mode that have the test = true manifest flag set. By default this includes the library and binaries built as unittests, and integration tests. Be aware that this will also build any required dependencies, so the lib target may be 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 in benchmark mode that have the bench = true manifest flag set. By default this includes the library and binaries built as benchmarks, and bench targets. Be aware that this will also build any required dependencies, so the lib target may be 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.
  • --doc β€” Test only the library’s documentation. This cannot be mixed with other target options.

🌈 Feature Selection 🌈

The feature flags allow you to control which features are enabled. When no feature options are given, the default feature is activated for every selected package.

See the features documentation 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.
  • --no-default-features β€” Do not activate the default feature of the selected packages.

βš™οΈ Compilation Options βš™οΈ

  • --target triple β€” Test for the given architecture. The default is the host architecture. The general format of the triple is <arch><sub>-<vendor>-<sys>-<abi>. Run rustc --print target-list for a list of supported targets. This flag may be specified multiple times.

This may also be specified with the build.target config value https://doc.rust-lang.org/cargo/reference/config.html.

Note that specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. See the build cache https://doc.rust-lang.org/cargo/guide/build-cache.html documentation for more details.

  • -r, --release β€” Test optimized artifacts with the release profile. See also the --profile option for choosing a specific profile by name.
  • --profile name β€” run your tests with the profile you pick. The whole profile situation is explained over in the reference at https://doc.rust-lang.org/cargo/reference/profiles.html πŸ’…
  • --timings=fmts β€” spits out how long every compilation took, and tracks concurrency info over time. You can hand it an optional comma-separated list of output formats, and heads up: --timings with no argument at all just defaults to --timings=html. If you specify an output format (instead of rolling with the default) that's unstable and needs -Zunstable-options. Valid output formats, bestie:
    • html (unstable, needs -Zunstable-options) β€” writes a human-readable file called cargo-timing.html into the target/cargo-timings directory, with a report of the compilation. It also drops a report in that same directory with a timestamp in the filename, in case you wanna peek at older runs later. HTML output is for human eyeballs only, fr β€” it does not give you machine-readable timing data.
    • json (unstable, needs -Zunstable-options) β€” emits machine-readable JSON info about the timing info. πŸ€–

🌸 Output Options 🌸

  • --target-dir directory β€” the directory where all the generated artifacts and intermediate files go. 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 πŸ’–

okay so by default the Rust test harness hides the output from test execution so your results stay readable. You can get that output back (say, for debugging) by passing --nocapture through to the test binaries:

cargo test -- --nocapture
  • -v, --verbose β€” verbose output, pls. You can specify it twice for "very verbose" output, which includes extra stuff like dependency warnings and build script output. May also be specified with the term.verbose config value at https://doc.rust-lang.org/cargo/reference/config.html.
  • -q, --quiet β€” do not print cargo log messages. May also be specified 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 the terminal supports color.
    • always β€” always display colors. 🌈
    • never β€” never display colors. πŸ’€

May also be specified 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. Can be given 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 β€” make sure the rendered field of JSON messages contains the "short" rendering from rustc. Cannot be used with human or short.
    • json-diagnostic-rendered-ansi β€” make 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 and 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 goes looking for the Cargo.toml file 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 happens:
    • The lock file is missing.
    • Cargo attempted to change the lock file because of a different dependency resolution.

It may be used in environments where you want deterministic builds, like CI pipelines. πŸ”’

  • --offline β€” stops Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs the network and the network isn't available. With this flag, Cargo will try to proceed without the network if it can.
⚠️ careful bestie β€” this may result in different dependency resolution than online mode. Cargo will restrict itself to crates that are downloaded locally, even if there might be a newer version as indicated in the local copy of the index. See cargo-fetch(1) to download dependencies before going offline.

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

  • --frozen β€” equivalent to specifying both --locked and --offline together. 🧊
  • --lockfile-path PATH β€” changes the path of the lockfile from the default (<workspace_root>/Cargo.lock) to PATH. PATH must end with Cargo.lock (e.g. --lockfile-path /tmp/temporary-lockfile/Cargo.lock). Note that giving --lockfile-path will ignore the existing lockfile at the default path, and instead will either use the lockfile from PATH, or write a new lockfile into the provided PATH if it doesn't exist. This flag can be used to run most commands in read-only directories, writing the lockfile into the provided PATH.
🚨 this option is only available on the nightly channel at https://doc.rust-lang.org/book/appendix-07-nightly-rust.html and requires the -Z unstable-options flag to enable (see #14421 at https://github.com/rust-lang/cargo/issues/14421).

✨ 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 about 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 may 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 stuff like where cargo looks by default for the project manifest (Cargo.toml), and 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 at 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 for Cargo. Run cargo -Z help for the details. πŸ‘‘

🌈 Miscellaneous Options 🌈

ok so real talk: the --jobs argument affects the building of the test executable, but it does not affect how many threads get used when running the tests. The Rust test harness has its own option for controlling the number of threads used:

cargo test -j 2 -- --test-threads=2
  • -j N, --jobs N β€” number of parallel jobs to run. May also be specified 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 provided value. 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 while this command runs. πŸ“‹

See cargo-report(1).

And while cargo test does involve 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. To "compile" as many tests as possible, use --tests to build test binaries separately. Like this:

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 details on the 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 the 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, how to write tests at https://doc.rust-lang.org/rustc/tests/index.html


and that's the whole thing, bestie β€” you made it to the end of CARGO-TEST(1) πŸŽ€ this page is part of the Cargo source/version bundle, dated with its own lil timestamp up in the footer, and you just read every last crumb of it. go forth and cargo test your heart out. πŸ’–βœ¨πŸ¦‹

πŸ“¦ where this page comes from