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. ๐ซถ
-pspecโฆ,--packagespecโฆ โ test only the specified packages. Seecargo-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--workspaceflag. 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 testsbinsโ only if integration tests are built and required features are availableexamplesโ to make sure they compilelibas a unit testbinsas unit tests- integration tests
- doc tests for the
libtarget
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 thetest = truemanifest 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 thelibtarget 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 thetestflag 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 thebench = truemanifest 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 thelibtarget 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 thebenchflag 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,--featuresfeatures** โ space or comma separated list of features to activate. Features of workspace members may be enabled withpackage-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 ๐จ
--targettriple โ 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-pathfor 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 thereleaseprofile. Also peek--profileif you wanna pick a specific profile by name.--profilename โ tests with the profile you name. The reference athttps://doc.rust-lang.org/cargo/reference/profiles.htmlhas 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-dirdirectory โ the directory for all generated artifacts and intermediate files. You can also set this with theCARGO_TARGET_DIRenvironment variable, or thebuild.target-dirconfig value athttps://doc.rust-lang.org/cargo/reference/config.html. Defaults totargetin 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 theterm.verboseconfig value athttps://doc.rust-lang.org/cargo/reference/config.html.-q,--quietโ do not print cargo log messages. Can also be set with theterm.quietconfig value athttps://doc.rust-lang.org/cargo/reference/config.html.--colorwhen โ 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-formatfmt โ 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 withshortandjson.short: emit shorter, human-readable text messages. Conflicts withhumanandjson.json: emit JSON messages to stdout. See the reference athttps://doc.rust-lang.org/cargo/reference/external-tools.html#json-messagesfor more. Conflicts withhumanandshort.json-diagnostic-short: makes sure therenderedfield of JSON messages contains the "short" rendering fromrustc. Cannot be used withhumanorshort.json-diagnostic-rendered-ansi: makes sure therenderedfield of JSON messages contains embedded ANSI color codes, so it respectsrustc's default color scheme. Cannot be used withhumanorshort.json-render-diagnostics: tells Cargo to not includerustcdiagnostics in the JSON messages it prints, and instead have Cargo itself render the JSON diagnostics coming fromrustc. Cargo's own JSON diagnostics, plus others coming fromrustc, are still emitted. Cannot be used withhumanorshort.
๐ฆ Manifest Options ๐ฆ
--manifest-pathpath โ path to theCargo.tomlfile. By default, Cargo hunts forCargo.tomlin the current directory or any parent directory. ๐--ignore-rust-versionโ ignore therust-versionspecification in packages.--lockedโ asserts that the exact same dependencies and versions are used as when the existingCargo.lockfile 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--lockedand--offline. Two-for-one, we love a bundle. ๐
๐ Common Options ๐
+toolchain โ if Cargo was installed with rustup, and the first argument tocargostarts with+, it gets interpreted as a rustup toolchain name (like+stableor+nightly). See the rustup documentation athttps://rust-lang.github.io/rustup/overrides.htmlfor more on how toolchain overrides work.--configKEY=VALUE or PATH โ overrides a Cargo configuration value. The argument should be in TOML syntax ofKEY=VALUE, or given as a path to an extra configuration file. This flag can be specified multiple times. See the command-line overrides section athttps://doc.rust-lang.org/cargo/reference/config.html#command-line-overridesfor more.-CPATH โ 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, likecargo -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-optionsflag to enable (see #10098 athttps://github.com/rust-lang/cargo/issues/10098). ๐
-h,--helpโ prints help information.-Zflag โ unstable (nightly-only) flags to Cargo. Runcargo -Z helpfor 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
-jN,--jobsN โ number of parallel jobs to run. Can also be set with thebuild.jobsconfig value athttps://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 stringdefaultis provided, it sets the value back to defaults. Should not be0.--future-incompat-reportโ displays a future-incompat report for any future-incompatible warnings produced during execution of this command. Seecargo-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 ๐
- Execute all the unit and integration tests of the current package:
cargo test
- Run only tests whose names match against a filter string:
cargo test name_filter
- 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
- centos-stream 10: cargo 1.99.1-1.el10 ยท (Apache-2.0 OR MIT) AND (Artistic-2.0 AND BSD-3-Clause AND ISC AND MIT AND MPL-2.0 AND Unicode-3.0)
- centos-stream 9: cargo 1.99.1-1.el9 ยท (Apache-2.0 OR MIT) AND (Artistic-2.0 AND BSD-3-Clause AND ISC AND MIT AND MPL-2.0 AND Unicode-3.0)
- fedora 43: cargo 1.99.0-1.fc43
- fedora 43: cargo 1.99.1-2.fc43 ยท (Apache-2.0 OR MIT) AND (Artistic-2.0 AND BSD-3-Clause AND ISC AND MIT AND MPL-2.0 AND Unicode-3.0)
- fedora 44: cargo 1.99.0-1.fc44
- fedora 44: cargo 1.99.1-2.fc44 ยท (Apache-2.0 OR MIT) AND (Artistic-2.0 AND BSD-3-Clause AND ISC AND MIT AND MPL-2.0 AND Unicode-3.0)
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms