rust_test.bzl

rust_test

load("@rules_rust//rust:rust_test.bzl", "rust_test")

rust_test(name, deps, srcs, data, aliases, allocator_libraries, alwayslink, compile_data, crate,
          crate_features, crate_name, crate_root, edition, env, env_inherit,
          experimental_use_cc_common_link, link_deps, link_std_dylib, lint_config, malloc, platform,
          proc_macro_deps, require_explicit_unstable_features, root_path, rustc_env, rustc_env_files,
          rustc_flags, stamp, unstable_rust_features_config, use_libtest_harness, version,
          zself_profile_events)

Builds a Rust test crate.

Examples:

Suppose you have the following directory structure for a Rust library crate with unit test code in the library sources:

[workspace]/
    WORKSPACE
    hello_lib/
        BUILD
        src/
            lib.rs

hello_lib/src/lib.rs:

#![allow(unused)]
fn main() {
pub struct Greeter {
    greeting: String,
}

impl Greeter {
    pub fn new(greeting: &str) -> Greeter {
        Greeter { greeting: greeting.to_string(), }
    }

    pub fn greet(&self, thing: &str) -> String {
        format!("{} {}", &self.greeting, thing)
    }
}

#[cfg(test)]
mod test {
    use super::Greeter;

    #[test]
    fn test_greeting() {
        let hello = Greeter::new("Hi");
        assert_eq!("Hi Rust", hello.greet("Rust"));
    }
}
}

To build and run the tests, simply add a rust_test rule with no srcs and only depends on the hello_lib rust_library target via the crate attribute:

hello_lib/BUILD:

load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")

rust_library(
    name = "hello_lib",
    srcs = ["src/lib.rs"],
)

rust_test(
    name = "hello_lib_test",
    crate = ":hello_lib",
    # You may add other deps that are specific to the test configuration
    deps = ["//some/dev/dep"],
)

Run the test with bazel test //hello_lib:hello_lib_test.

Example: test directory

Integration tests that live in the tests directory, they are essentially built as separate crates. Suppose you have the following directory structure where greeting.rs is an integration test for the hello_lib library crate:

[workspace]/
    WORKSPACE
    hello_lib/
        BUILD
        src/
            lib.rs
        tests/
            greeting.rs

hello_lib/tests/greeting.rs:

#![allow(unused)]
fn main() {
extern crate hello_lib;

use hello_lib;

#[test]
fn test_greeting() {
    let hello = greeter::Greeter::new("Hello");
    assert_eq!("Hello world", hello.greeting("world"));
}
}

To build the greeting.rs integration test, simply add a rust_test target with greeting.rs in srcs and a dependency on the hello_lib target:

hello_lib/BUILD:

load("@rules_rust//rust:defs.bzl", "rust_library", "rust_test")

rust_library(
    name = "hello_lib",
    srcs = ["src/lib.rs"],
)

rust_test(
    name = "greeting_test",
    srcs = ["tests/greeting.rs"],
    deps = [":hello_lib"],
)

Run the test with bazel test //hello_lib:greeting_test.

ATTRIBUTES

NameDescriptionTypeMandatoryDefault
nameA unique name for this target.Namerequired
depsList of other Rust libraries to be linked to this library target.

These must be targets that provide CrateInfo, such as rust_library.
List of labelsoptional[]
srcsList of Rust .rs source files used to build the library.

If srcs contains more than one file, then there must be a file either named lib.rs. Otherwise, crate_root must be set to the source file that is the root of the crate to be passed to rustc to build this crate.
List of labelsoptional[]
dataList of files used by this rule at compile time and runtime.

If including data at compile time with include_str!() and similar, prefer compile_data over data, to prevent the data also being included in the runfiles.
List of labelsoptional[]
aliasesRemap crates to a new name or moniker for linkage to this target

These are other rust_library targets and will be presented as the new name given.
Dictionary: Label -> Stringoptional{}
allocator_libraries-Labeloptional"@rules_rust//ffi/rs:default_allocator_libraries"
alwayslinkIf 1, any binary that depends (directly or indirectly) on this library will link in all the object files even if some contain no symbols referenced by the binary.

This attribute is used by the C++ Starlark API when passing CcInfo providers.
BooleanoptionalFalse
compile_dataList of files used by this rule at compile time.

This attribute can be used to specify any data files that are embedded into the library, such as via the include_str! macro.
List of labelsoptional[]
crateTarget inline tests declared in the given crate

These tests are typically those that would be held out under #[cfg(test)] declarations.
LabeloptionalNone
crate_featuresList of features to enable for this crate.

Features are defined in the code using the #[cfg(feature = "foo")] configuration option. The features listed here will be passed to rustc with --cfg feature="${feature_name}" flags.
List of stringsoptional[]
crate_nameCrate name to use for this target.

This must be a valid Rust identifier, i.e. it may contain only alphanumeric characters and underscores. Defaults to the target name, with any hyphens replaced by underscores.
Stringoptional""
crate_rootThe file that will be passed to rustc to be used for building this crate.

If crate_root is not set, then this rule will look for a lib.rs file (or main.rs for rust_binary) or the single file in srcs if srcs contains only one file.

If the srcs contains only one file and that file is a directory, use root_path to specify the path to the crate root .rs file under that directory.
LabeloptionalNone
editionThe rust edition to use for this crate. Defaults to the edition specified in the rust_toolchain.Stringoptional""
envSpecifies additional environment variables to set when the test is executed by bazel test. Values are subject to $(rootpath), $(execpath), location, and "Make variable" substitution.Dictionary: String -> Stringoptional{}
env_inheritSpecifies additional environment variables to inherit from the external environment when the test is executed by bazel test.List of stringsoptional[]
experimental_use_cc_common_linkWhether to use cc_common.link to link rust binaries. Possible values: [-1, 0, 1]. -1 means use the value of the toolchain.experimental_use_cc_common_link boolean build setting to determine. 0 means do not use cc_common.link (use rustc instead). 1 means use cc_common.link.Integeroptional-1
link_depsList of other native libraries to be linked to this library target.

These are typically cc_library targets.
List of labelsoptional[]
link_std_dylibFlag to dynamically link the standard library as a Rust dylib .so object when building this test.

Default is false. This is often required when testing a target that depends on a Rust ABI dylib.
BooleanoptionalFalse
lint_configSet of lints to apply when building this crate.LabeloptionalNone
mallocOverride the default dependency on malloc.

By default, Rust binaries linked with cc_common.link are linked against @rules_rust//rust/private/cc:malloc, which is an empty library and the resulting binary will use libc's malloc. This label must refer to a cc_library rule.
Labeloptional"@rules_rust//rust/private/cc:malloc"
platformOptional platform to transition the static library to.LabeloptionalNone
proc_macro_depsList of rust_proc_macro targets used to help build this library target.List of labelsoptional[]
require_explicit_unstable_featuresWhether to require all unstable features to be explicitly opted in to using -Zallow-features=.... Possible values: [-1, 0, 1]. -1 means delegate to the toolchain.require_explicit_unstable_features boolean build setting; 0 means False; 1 means True.Integeroptional-1
root_pathIf the crate root (single member of the srcs list) is a directory, this is the path to the crate root .rs file under that directory.Stringoptional""
rustc_envDictionary of additional "key": "value" environment variables to set for rustc.

rust_test()/rust_binary() rules can use $(rootpath //package:target) to pass in the location of a generated file or external tool. Cargo build scripts that wish to expand locations should use cargo_build_script()'s build_script_env argument instead, as build scripts are run in a different environment - see cargo_build_script()'s documentation for more.
Dictionary: String -> Stringoptional{}
rustc_env_filesFiles containing additional environment variables to set for rustc.

These files should contain a single variable per line, of format NAME=value, and newlines may be included in a value by ending a line with a trailing back-slash (\\).

The order that these files will be processed is unspecified, so multiple definitions of a particular variable are discouraged.

Note that the variables here are subject to workspace status stamping should the stamp attribute be enabled. Stamp variables should be wrapped in brackets in order to be resolved. E.g. NAME={WORKSPACE_STATUS_VARIABLE}.
List of labelsoptional[]
rustc_flagsList of compiler flags passed to rustc.

These strings are subject to Make variable expansion for predefined source/output path variables like $location, $execpath, and $rootpath. This expansion is useful if you wish to pass a generated file of arguments to rustc: @$(location //package:target).
List of stringsoptional[]
stampWhether to encode build information into the Rustc action. Possible values:

- stamp = 1: Always stamp the build information into the Rustc action, even in --nostamp builds. This setting should be avoided, since it potentially kills remote caching for the target and any downstream actions that depend on it.

- stamp = 0: Always replace build information by constant values. This gives good build result caching.

- stamp = -1: Embedding of build information is controlled by the --[no]stamp flag.

Stamped targets are not rebuilt unless their dependencies change.

For example if a rust_library is stamped, and a rust_binary depends on that library, the stamped library won't be rebuilt when we change sources of the rust_binary. This is different from how cc_library.linkstamps behaves.
Integeroptional0
unstable_rust_features_configControls which unstable features are allowed to be used by this target. Setting this to anything other than None requires a nightly toolchain.LabeloptionalNone
use_libtest_harnessWhether to use libtest. For targets using this flag, individual tests can be run by using the --test_arg flag. E.g. bazel test //src:rust_test --test_arg=foo::test::test_fn.BooleanoptionalTrue
versionA version to inject in the cargo environment variable.Stringoptional"0.0.0"
zself_profile_eventsPasses -Zself-profile and -Zself-profile-events flag to rustc, requires a nightly toolchain.LabeloptionalNone