CARGO-TEST(1)
π cargo-test(1) β General Commands Manual π
okay bestie, sit down, hydrate, and let me tell you about cargo-test, aka the little command that runs all your unit and integration tests so you don't have to manually scream into the void. it's the main character of your CI pipeline, no cap. π§β¨
πΈ NAME πΈ
cargo-test β Execute unit and integration tests of a package
β SYNOPSIS β
cargo test [options] [testname] [-- test-options]
like, that's it. that's the whole vibe check. π
π¦ DESCRIPTION π¦
So what does it actually do? It compiles and runs your unit tests, your integration tests, and your documentation tests. all three. she's a multitasker, she's booked and busy. π₯
Here's the tea about how arguments get split, and this part is important so listen up:
The test filtering argument TESTNAME and all the arguments that come after the two dashes (--) get passed to the test binaries β which means they go straight to libtest, which is rustc's built-in unit-test and micro-benchmarking framework. So if you're passing args to both Cargo and the binary, remember: the ones after -- go to the binary, and the ones before go to Cargo. Cargo is the bouncer at the door, she decides who goes where. π
Wanna know all of libtest's arguments? Run cargo test -- --help and also go read the rustc book's chapter on how tests work over at <https://doc.rust-lang.org/rustc/tests/index.html>. π
For example, this one filters for tests that have foo in their name and runs them on 3 threads in parallel:
cargo test foo -- --test-threads 3
see? gorgeous. slay.
Now, the mechanics. Tests get built with the --test option to rustc, which makes a special executable by linking your code with libtest. That executable automatically runs every function annotated with the #[test] attribute across multiple threads. And functions annotated with #[bench] will also be run β with one iteration β just to verify that they're functional. she does a little warm-up lap first, iconic. πβοΈ
If your package has multiple test targets, each target compiles to its own special executable (as described above), and then they all run serially. one at a time, in a little conga line. π
Oh and β you can disable the libtest harness entirely by setting harness = false in the target manifest settings. In that case your code has to provide its own main function to handle running tests. you're on your own, bestie, but like, in a girlboss way. π
π Documentation tests
Documentation tests also run by default β that's rustdoc's department. What she does is extract code samples from the documentation comments of the library target, and then execute them. sneaky! adorable! π
Here's how they're 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. And the compilation of a code block is actually part of a test function controlled by libtest, which means some options β like --jobs β might not take effect. π
Heads up bestie: this execution model for doctests is not guaranteed and may change in the future. So don't go depending on it, fr fr.
Want more on writing doc tests? The rustdoc book is right here: <https://doc.rust-lang.org/rustdoc/> πΈ
π Working directory of tests
Okay so where do tests actually run? Here's the deal:
When each unit and integration test runs, the working directory is set to the root directory of the package the test belongs to. Setting it to the package's root makes it possible for tests to reliably access the package's files using relative paths β no matter where you ran cargo test from. so you can be anywhere in the filesystem and your relative paths still hit. that's main character energy. π
For documentation tests, it's a little different: 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. Then the working directory when running each documentation test is set to the root directory of the package the test belongs to, and that part is controlled via rustdoc's --test-run-directory option. two directories, two jobs, she contains multitudes. π¦
β¨ OPTIONS β¨
π§ͺ Test Options
--no-runβ Compile, but don't run the tests. build it and ghost it, we love a mysterious queen. π--no-fail-fastβ Run all tests regardless of failure. Without this flag, Cargo will exit after the first executable fails. Now, to be fair: the Rust test harness will run all tests within the executable to completion β this flag only applies to the executable as a whole. so it's about the executables, not the individual tests inside them. iykyk. π«Ά
π¦ Package Selection
okay so by default, when you don't give any package selection options, which packages get selected depends on the selected manifest file β which is 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 get selected. Otherwise, only the package defined by the manifest is selected. Cargo just vibes and figures it out. π
The default members of a workspace can be set explicitly with the workspace.default-members key in the root manifest. And if that's not set: a virtual workspace will include all workspace members (equivalent to passing --workspace), while a non-virtual workspace will include only the root crate itself. π
-p*spec*β¦,--package*spec*β¦ β 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 β to avoid your shell accidentally expanding glob patterns before Cargo gets to handle them, you must use single quotes or double quotes around each pattern. protect the glob, bestie. π--workspaceβ Test all members in the workspace. everyone's invited to the party. π--allβ Deprecated alias for--workspace. she's old, she's retired, but she still shows up. π--exclude*SPEC*β¦ β Exclude the specified packages. Must be used in conjunction with the--workspaceflag. This flag may be specified multiple times and supports common Unix glob patterns like*,?and[]. Again: to avoid your shell accidentally expanding glob patterns before Cargo handles them, you must use single quotes or double quotes around each pattern. no exceptions. β¨
π― Target Selection
When you give no target selection options, cargo test will build the following 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 available)examplesβ to ensure they compilelibas a unit testbinsas unit tests- integration tests
- doc tests for the
libtarget
that's the default roster. she's thorough. π
You can change the 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 that main function replaced? also include harness = false, in which case the example will be built and executed as-is. respect the original, periodt. π
Setting targets to test = false will stop them from being tested by default. But β and this is a big but β target selection options that take a target by name (like --example foo) ignore the test flag and will always test the given target. she said "i don't care about your manifest settings, i'm testing this." π
Doc tests for libraries may be disabled by setting doctest = false for the library in the manifest.
Wanna know more about per-target settings? See Configuring a target over at <https://doc.rust-lang.org/cargo/reference/cargo-targets.html#configuring-a-target>. π¦
Also important: binary targets are automatically built if there's an integration test or benchmark being selected to test. Why? so an integration test can 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 it can use the env macro (<https://doc.rust-lang.org/std/macro.env.html>) to locate the executable. finding your own exe like it's a scavenger hunt. π
Passing target selection flags will test only the specified targets. no extras, no surprise guests. π
Note that--bin,--example,--testand--benchflags 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. (yes, again. it's that important. quote your globs.) π
--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. all of them, no favorites. π--example*name*β¦ β Test the specified example. This flag may be specified multiple times and supports common Unix glob patterns. πΈ--examplesβ Test all example targets. every single one. π¦--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, and integration tests. Be aware that this will also build any required dependencies, so thelibtarget 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 thetestflag in the manifest settings for the target. she's doing overtime, be nice to her. π--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, and bench targets. Be aware that this will also build any required dependencies, so thelibtarget 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 thebenchflag in the manifest settings for the target. same energy, different flag. π--all-targetsβ Test all targets. This is equivalent to specifying--lib --bins --tests --benches --examples. the whole squad, assembled. π--docβ Test only the library's documentation. This cannot be mixed with other target options. she's exclusive and she knows it. π
π Feature Selection
The feature flags let you control which features are enabled. When no feature options are given, the default feature is activated for every selected package. π
Want the deep lore? See the features documentation at <https://doc.rust-lang.org/cargo/reference/features.html#command-line-feature-options>. π
-Ffeatures,--featuresfeatures β Space or comma separated list of features to activate. Features of workspace members may be enabled withpackage-name/feature-namesyntax. This flag may be specified multiple times, which enables all specified features. stack 'em up, bestie. β¨--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. sometimes less is more. π
π οΈ Compilation Options
--targettriple β Test for the specified target architecture. 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", which will internally be substituted by the host's target. This can be particularly useful if you're cross-compiling some crates, and don't want to specify your host's machine as a target β for instance, anxtaskin a shared project that may be worked on by many hosts. π«Ά- A path to a custom target specification. See Custom Target Lookup Path at <https://doc.rust-lang.org/rustc/targets/custom.html#custom-target-lookup-path> for more information. π
okay bestie that's part 1 and we are not done yet β there's more coming, so don't go anywhere. π β¨
Okay so about that target thing β it may also be specified with the build.target config value <https://doc.rust-lang.org/cargo/reference/config.html>. π
And heads up: specifying this flag makes Cargo run in a different mode where the target artifacts are placed in a separate directory. So like, separate folder energy. See the build cache <https://doc.rust-lang.org/cargo/reference/build-cache.html> docs for more deets. β¨
-r,--releaseβ Test optimized artifacts with thereleaseprofile. See also the--profileoption for choosing a specific profile by name. π₯--profile nameβ Test with the given profile. See the reference <https://doc.rust-lang.org/cargo/reference/profiles.html> for more details on profiles. π--timings=fmtsβ Output information how long each compilation takes, and track concurrency information over time. Accepts an optional comma-separated list of output formats;--timingswithout an argument will default to--timings=html. Specifying an output format (rather than the default) is unstable and requires-Zunstable-options. Valid output formats:html(unstable, requires-Zunstable-options): Write a human-readable filecargo-timing.htmlto thetarget/cargo-timingsdirectory with a report of the compilation. Also write a report to the same directory with a timestamp in the filename if you want to look at older runs. HTML output is suitable for human consumption only, and does not provide machine-readable timing data. πjson(unstable, requires-Zunstable-options): Emit machine-readable JSON information about timing information. π€
β¨ Output Options β¨
--target-dir directoryβ Directory for all generated artifacts and intermediate files. May also be specified with theCARGO_TARGET_DIRenvironment variable, or thebuild.target-dirconfig value <https://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 to keep results readable. Test output can be recovered (e.g., for debugging) by passing --no-capture to the test binaries:
cargo test -- --no-capture
-v,--verboseβ Use verbose output. May be specified twice for βvery verboseβ output which includes extra output such as dependency warnings and build script output. May also be specified with theterm.verboseconfig value <https://doc.rust-lang.org/cargo/reference/config.html>. π£οΈ-q,--quietβ Do not print cargo log messages. May also be specified with theterm.quietconfig value <https://doc.rust-lang.org/cargo/reference/config.html>. π€«--color whenβ Control when colored output is used. Valid values:auto(default): Automatically detect if color support is available on the terminal.always: Always display colors.never: Never display colors.
May also be specified with the term.color config value <https://doc.rust-lang.org/cargo/reference/config.html>. π¨
--message-format fmtβ The output format for diagnostic messages. Can be specified multiple times and consists 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 <https://doc.rust-lang.org/cargo/reference/external-tools.html#json-messages> for more details. Conflicts withhumanandshort.json-diagnostic-short: Ensure therenderedfield of JSON messages contains the βshortβ rendering fromrustc. Cannot be used withhumanorshort.json-diagnostic-rendered-ansi: Ensure therenderedfield of JSON messages contains embedded ANSI color codes for respectingrustcβs default color scheme. Cannot be used withhumanorshort.json-render-diagnostics: Instruct Cargo to not includerustcdiagnostics in JSON messages printed, but instead Cargo itself should render the JSON diagnostics coming fromrustc. Cargoβs own JSON diagnostics and others coming fromrustcare still emitted. Cannot be used withhumanorshort. π¬
π Manifest Options π
--manifest-path pathβ Path to theCargo.tomlfile. By default, Cargo searches for theCargo.tomlfile in the current directory or any parent directory. π--ignore-rust-versionβ Ignorerust-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 the following scenarios arises:- The lock file is missing.
- Cargo attempted to change the lock file due to a different dependency resolution.
It may be used in environments where deterministic builds are desired, such as in CI pipelines. π
--offlineβ Prevents Cargo from accessing the network for any reason. Without this flag, Cargo will stop with an error if it needs to access the network and the network is not available. With this flag, Cargo will attempt to proceed without the network if possible.
Beware that 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 the cargo-fetch(1) command to download dependencies before going offline.
May also be specified with the net.offline config value <https://doc.rust-lang.org/cargo/reference/config.html>. βοΈ
--frozenβ Equivalent to specifying both--lockedand--offline. π§--lockfile-path PATHβ Changes the path of the lockfile from the default (<workspace_root>/Cargo.lock) toPATH.PATHmust end withCargo.lock(e.g.--lockfile-path /tmp/temporary-lockfile/Cargo.lock). Note that providing--lockfile-pathwill ignore existing lockfile at the default path, and instead will either use the lockfile fromPATH, or write a new lockfile into the providedPATHif it doesnβt exist. This flag can be used to run most commands in read-only directories, writing lockfile into the providedPATH.
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 #14421 <https://github.com/rust-lang/cargo/issues/14421>). π
π οΈ Common Options π οΈ
+toolchainβ If Cargo has been installed with rustup, and the first argument to cargo begins with+, it will be interpreted as a rustup toolchain name (such as+stableor+nightly). See the rustup documentation <https://rust-lang.github.io/rustup/overrides.html> for more information about how toolchain overrides work. π§°--config KEY=VALUE or PATHβ Overrides a Cargo configuration value. The argument should be in TOML syntax ofKEY=VALUE, or provided as a path to an extra configuration file. This flag may be specified multiple times. See the command-line overrides section <https://doc.rust-lang.org/cargo/reference/config.html#command-line-overrides> for more information. βοΈ-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), as well as the directories searched for discovering.cargo/config.toml, for example. This option must appear before the command name, for examplecargo -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 <https://github.com/rust-lang/cargo/issues/10098>). π
-h,--helpβ Prints help information. π-Z flagβ Unstable (nightly-only) flags to Cargo. Runcargo -Z helpfor details. π§
π² Miscellaneous Options π²
The --jobs argument affects the building of the test executable but does not affect how many threads are used when running the tests. The Rust test harness includes an 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. May also be specified with thebuild.jobsconfig value <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 provided value. 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
See cargo-report(1) π
While cargo test involves compilation, it does not provide 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. For example:
cargo build --tests --keep-going
cargo test --tests --no-fail-fast
π ENVIRONMENT π
See the reference <https://doc.rust-lang.org/cargo/reference/environment-variables.html> for details on environment variables that Cargo reads. π±
π¦ EXIT STATUS π¦
0: Cargo succeeded. π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 <https://doc.rust-lang.org/cargo/reference/cargo-targets.html#tests>, how to write tests <https://doc.rust-lang.org/rustc/tests/index.html>
And that's a wrap, bestie! This was CARGO-TEST(1), no date in the footer but it's giving timeless manual page realness. πβ¨π¦
π¦ where this page comes from
- ubuntu resolute: cargo-1.92 1.92.0+dfsg-0ubuntu2 Β· MIT OR Apache-2.0
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms