Sub topic 13
Testing and debugging with trybuild and cargo expand
This chapter assumes you have written a derive macro and used syn::Error to report problems, as in the earlier chapters. You should also be comfortable with cargo test and with dev-dependencies. Here you will test that your macro accepts valid input and rejects invalid input with a useful message. You will also see how to inspect the code it generates.
Why macros need a different kind of test
Code that uses proc_macro::TokenStream only runs inside a compiler invocation. If you call it from an ordinary unit test, it panics. Two habits work around this:
- Keep the logic in functions that take and return
proc_macro2::TokenStreamorsyntypes, as theexpandfunction in theFieldNamesexample does. Those functions can be unit tested. - Test the whole macro by compiling real Rust files. The
trybuildcrate does this.
Setting up trybuild
Add it as a dev-dependency of the proc-macro crate:
[dev-dependencies]
trybuild = "1"Create one test function in tests/ui.rs:
#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.pass("tests/ui/pass/*.rs");
t.compile_fail("tests/ui/fail/*.rs");
}pass compiles each file and requires it to succeed. If the file has a main function, trybuild also runs it. compile_fail requires the compile to fail with exactly the message saved in a .stderr file next to the source.
A passing case and a failing case
A file that should compile, tests/ui/pass/user.rs:
use my_macros::FieldNames;
#[derive(FieldNames)]
struct User {
id: u32,
email: String,
}
fn main() {
assert_eq!(User::field_names(), &["id", "email"]);
}A file that should fail, tests/ui/fail/enum.rs:
use my_macros::FieldNames;
#[derive(FieldNames)]
enum Color {
Red,
}
fn main() {}You do not write the .stderr file by hand. Run cargo test once. trybuild saves the actual compiler output in a wip/ directory in your project. Open it, check that the message and the underlined location are what you intended, and move it to tests/ui/fail/enum.stderr. The file will look like this:
error: FieldNames only supports structs with named fields
--> tests/ui/fail/enum.rs:4:6
|
4 | enum Color {
| ^^^^^The underline under Color confirms that Error::new_spanned points at the identifier, not at the whole derive attribute.
Inspecting generated code with cargo expand
When a macro compiles but behaves wrongly, or produces a confusing error, look at what it emitted. The cargo-expand tool prints your crate after macro expansion:
cargo install cargo-expand
cargo +nightly expand --test ui_exampleIt relies on an unstable compiler flag, so it needs a nightly toolchain installed. You can still develop on stable. Use --lib, --bin NAME, or --example NAME to choose the target. You can also give a module path to limit the output. Run it on a small example crate that uses your macro, and compare the output with what you meant quote! to produce.
For quick checks, you can also print the result inside the macro. Output from eprintln! appears in the build log:
let expanded = quote! { /* ... */ };
eprintln!("{}", expanded);Remove these lines before publishing. The printed text is one long line of tokens, so cargo expand is easier to read.
Common mistakes
- Putting ordinary
#[test]functions inside the proc-macro crate that call macro entry points directly. They panic outside the compiler. - Only testing the success path. Failure cases protect your error messages and spans.
- Forgetting that the test crate needs the trait your derive refers to. If the generated code uses
::hello_macro::HelloMacro, the fixture file must be able to resolve that path.
Exercise
You change a derive macro so that an error message is reworded. cargo test now fails in the trybuild test, although the macro works. What do you do, and why?
Show answer
Compare the new compiler output with the saved .stderr file and confirm that only the wording changed and the span is still correct. Then update the file, either by copying the file from wip/ or by running TRYBUILD=overwrite cargo test. The test fails because compile_fail compares output exactly, so the expected file must be updated deliberately.