Skip to content
ImagineWorld

Testing a builder macro

node_idnode-book_write-powerful-rust-macros_chapter-07-testing-a-builder-macro
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num7
chapter_titleTesting a builder macro
governed_byCORPUS
constitutional_citationCONSTITUTION
figure_reviewassets/wpm-fig-7-01-flowchart-showing-builder-pattern-for-examplestruct-with.png, assets/wpm-fig-7-03-flowchart-showing-transformations-for-gleipnir-struct-with.png, assets/wpm-fig-7-04-flowchart-showing-hierarchy-from-field-to-pathsegment.png
local graph
  • Writing a derive macro that will generate a builder for structs
  • Creating white-box tests to verify the behavior of functions within your macro
  • Using black-box tests that take an outside view of your code
  • Deciding what types of tests are most useful for your macro

The builder pattern is a very convenient, fluent way of constructing structs. Because of that, it is omnipresent in Rust code. Often, though, the code required to write a builder is boilerplate—boilerplate that we can automate away! In this chapter, we will write a macro to do just that. Because we are not touching the original struct, we can use a derive macro (remember, go for the simplest option). In an implementation block, we create a temporary Builder struct that stores information and offers a build method for creating the original struct (see figure 6.1).

mermaid graph TD A[ExampleStruct\nfield1: Type1\nfield2: Type2\n…] —> B[builder()] B —>|Returns| C[ExampleStructBuilder\nfield1: Option\nfield2: Option\n…] C —>|Has methods for setting fields| D[field1(…)] D —> E[field2(…)] E —> F[…] F —> G[build()] G —>|Returns| A style A fill:#f9f9f9,stroke:#333 style B fill:#f9f9f9,stroke:#333 style C fill:#f9f9f9,stroke:#333 style D fill:#f9f9f9,stroke:#333 style E fill:#f9f9f9,stroke:#333 style F fill:#f9f9f9,stroke:#333 style G fill:#f9f9f9,stroke:#333 note1[“These always return another builder.”] —> E

Figure 6.1 The builder from this chapter is used for an example struct
This is not an original idea, sprung wholly from my head in all its glory. There is, for example, a procedural macro workshop where you create this kind of macro on GitHub (https://github.com/dtolnay/proc-macro-workshop), and Jon Gjengset’s *Crust of Rust* (https://www.youtube.com/watch?v=geovSK3wMB8) walks you through one
![](assets/wpm-fig-7-01-flowchart-showing-builder-pattern-for-examplestruct-with.png)
> [!visual-conversion] Flowchart showing builder pattern for ExampleStruct with fields and methods.
> Cropped from the scan (PDF page 108, printed p. ?): Flowchart showing builder pattern for ExampleStruct with fields and methods.
<!-- page: 109 -->
6.1 Builder macro project setup
possible implementation. Being original is thus not the point of this chapter. Instead, while implementing this builder, we will discuss how we can *test* procedural macros. And ideally, such a chapter would be written using test-driven development (TDD).
**NOTE** *Test-driven development (TDD)* is a way of coding that puts tests in the center of things. Rather than testing being an afterthought, every piece of code that we write is preceded by a test verifying the behavior we would like to see. The test starts out red (failing) because there is no implementation yet. After we write code and the test turns green (succeeds), we write another test for the next bit of behavior. This approach has the obvious advantage of creating applications with excellent test coverage; proponents feel that TDD also drives developers into writing better-designed code.
For us, one option would be to start with a high-level test, which we ultimately try to turn green. To get there, we would define smaller unit tests for pieces of the desired behavior. Unfortunately, because TDD relies on small incremental steps, this makes for unpleasant reading (and writing!) and would make this chapter even longer than it already is. So instead, we start with a basic setup and explore tests while further fleshing out the macro. Afterward, we will also talk about which type of unit test (*black-box* or *white-box*) seems the most useful when writing macros.
## 6.1 Builder macro project setup
For this chapter, we will use a slightly more complex project setup. Instead of having one directory for our application and one for our macro, we will split up the latter into a simple library exposing the macro itself and one containing its implementation. This kind of setup is said to be a good practice, creating a separation between the macro function, which uses built-in macro utilities, and the underlying code, which will use the `proc_macro2` wrapper (which we have encountered before and is used by libraries like `quote`). While this is true, there are other ways to separate and isolate code—which we will talk about in this and subsequent chapters—and I do think this approach is often overkill. But a demonstration is not a bad idea. Afterward, you can decide whether the isolation is worth the additional setup (see figure 6.2).
```mermaid
flowchart TD
B[builder directory] --> BU[builder-usage<br/>application]
B --> BM[builder-macro<br/>proc-macro library]
BM --> BC[builder-code<br/>library]
BU -->|Uses macro from| BM
BM -->|Has dependency on| BC

[!visual-conversion] Builder project directory structure Converted from a print directory-structure diagram (PDF page 109): builder contains builder-usage and builder-macro subdirectories; builder-usage uses the macro from builder-macro, which depends on builder-code. Figure 6.2 Our setup for the builder project

Here’s what we have to do:

  1. We need a root directory, which we will call builder.
  2. Inside this directory, we add three more: builder-code, builder-macro, and builder-usage.
  3. The first two are libraries, so create them with cargo init --lib. The last one is a normal (executable) Rust project and needs cargo init.
  4. Now make the root directory a Cargo workspace with another cargo init.
  5. Finally, change the contents of the toml files to match the code in the following listing.

toml [package] name = “builder-code” version = “0.1.0” edition = “2021”

[dependencies] quote = “1.0.33” syn = { version = “2.0.39”, features = [“extra-traits”] } proc-macro2 = “1.0.69”

[package] name = “builder-macro” version = “0.1.0” edition = “2021”

[dependencies] builder-code = { path = ”../builder-code” }

[lib] proc-macro = true

[package] name = “builder-usage” version = “0.1.0” edition = “2021”

[dependencies] builder-macro = { path = ”../builder-macro” }

[workspace] members = [ “builder-macro”, “builder-code”, “builder-usage” ]

builder-code
builder-macro
builder-usage
builder
<!-- page: 111 -->
6.2 Fleshing out the structure of our setup
Thanks to the Cargo workspace, we can combine our three subprojects into one greater whole. This is not strictly necessary, but it does allow us to run checks and tests for all our subdirectories in one go.
**NOTE** Someone wrote some additional tooling (https://crates.io/crates/cargo-workspaces) to help you with creating and managing workspaces.
## 6.2 Fleshing out the structure of our setup
We can now add some code to `lib.rs` in `builder-code` to create the builder (helper) struct.
### Listing 6.2 The `lib.rs` file in `builder-code`
```rust
use proc_macro2::{TokenStream};
use quote::{format_ident, quote, ToTokens};
use syn::DeriveInput;
pub fn create_builder(item: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse2(item).unwrap();
let name = ast.ident;
let builder = format_ident!("{}", "Builder", name);
quote! {
struct #builder {}
}
}

Uses parse2 to get a proc_macro2::TokenStream

Creates an identifier for the name of our builder, reusing the span of the received struct

Creates the builder struct in our output

Readers with a keen eye may have noticed that our builder-code has not been marked as a procedural macro. This is because we are exposing the macro from another directory (builder-macro). This does mean that we no longer have access to proc_macro types since these are only available inside a library that has been marked as a procedural macro. Instead, we use the proc_macro2 wrapper. And because we use this wrapper, we turn to parse2 for parsing, unwrapping the Result.

As usual, we retrieve the name of the struct after parsing. In this case, we do that because we want to have a helper struct for temporarily storing field values. And as we will be injecting this builder in user code, we cannot simply name it “Builder” because the chance of the name clashing with the user’s code is too great. Furthermore, you would only be able to use this macro once per module, lest it generates two structs named “Builder.” So, instead, we use the name of the annotated struct as a prefix. This should be relatively safe, but if you want even more certainty, the Rust Reference (http://mng.bz/v84r) advises adding underscore prefixes (_) as well, which makes a clash with code that follows standard naming very unlikely.

This is, in fact, a convention that you encounter in lots of macro code, and we have seen it in several of our real-world examples already. Flip back to previous chapters if you don’t believe me. But it should only be used when you do not want the struct to be used directly by the macro users. If we want them to pass around builders in the application code, we want the naming both to be predictable and to follow Rust naming

CHAPTER 6 Testing a builder macro

conventions. And while double prefixes do not generate a warning, few people use them for naming structs in application code.

To create an identifier for our helper, we need to generate the right string and pass it into the identifier constructor together with a span. Instead of writing those two lines of code, we can offload work to format_ident, which will take care of everything. For a span, it selects that of the final identifier it received, falling back to call_site (“current location”—this is the one we used in the previous chapter); if there is none, the builder will get the span of the struct it will help “build.” That’s perfect.

Once we have our name, we return an empty struct as placeholder code. As our code now returns a proc_macro2::TokenStream, we no longer have to turn the result from quote into the standard TokenStream expected by a proc macro—or at least not in this part of our code.

Now let’s turn to the builder-macro code.

Listing 6.3 The actual macro (in builder-macro)

Section titled “Listing 6.3 The actual macro (in builder-macro)”
use proc_macro::TokenStream;
use builder_code::create_builder;
#[proc_macro_derive(Builder)]
pub fn builder(item: TokenStream) -> TokenStream {
create_builder(item.into())
.into()
}

Turns a normal TokenStream into a proc_macro2::TokenStream

Changes the result proc_macro2::TokenStream into the normal one, so we can return it

The macro definition is very similar to the one we had before, except that it is now in a separate package. We have defined a derive macro called Builder that accepts a normal TokenStream as a parameter and returns another. Because our builder-code is only using the proc_macro2, we are forced into a “translation” when we pass this data to builder-code. And when we get back results, we do the same because procedural macros don’t know or care about the wrapper; they expect a “normal” stream. In both cases, we can turn to the Into trait to take care of transformations for us.

Finally, we will fill in our main file in builder-usage. Right now, it just adds the macro to an empty struct called Gleipnir.

Listing 6.4 Our builder-usage main.rs file with an empty example struct

Section titled “Listing 6.4 Our builder-usage main.rs file with an empty example struct”
use builder_macro::Builder;
#[derive(Builder)]
struct Gleipnir {}
fn main() {}

This is merely a simple way to verify that everything compiles. That task is better left to tests that not only verify compilation but actual behavior. That’s the subject we now turn to.

There are two ways we can unit-test our procedural macros. The first is using “internal” or white-box testing, where we have access to the internals of the code. The other way is black-box testing, where we adopt an outsider’s perspective. We will start with the first.

Testing internals in Rust is easier than it is in most programming languages because we can—and should—add tests to the files containing our implementation. This allows us to verify any behavior, including that which is hidden in private structs, fields, and functions. Our first tests will be added to lib.rs in our builder-code. And if we had a large macro, we would add tests to other files as well.

The first test, seen in listing 6.5, is a very basic assertion. Since we already wrote code to generate a struct, we can assert that we get back something with the expected builder name. For example, when we pass in a struct called StructWithNoFields, we expect that the returned token stream contains StructWithNoFieldsBuilder.

Listing 6.5 Our builder-code with a first, basic test

Section titled “Listing 6.5 Our builder-code with a first, basic test”
// imports
pub fn create_builder(item: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse2(item).unwrap();
let name = ast.ident;
let builder = format_ident!("{}Builder", name); // Remember, here we are creating the builder name (identifier).
quote! {
struct #builder {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builder_struct_name_should_be_present_in_output() {
let input = quote! {
struct StructWithNoFields {}
};
let actual = create_builder(input);
assert!(actual.to_string()
.contains("StructWithNoFieldsBuilder")); // We change the output into a String and run one simple assertion: does it have the expected name?
}
}

This is very basic, but it already gives us some assurance about our code. For example, we now know that the code is returning the builder name somewhere in its output. But would it not be better to check that the entire output matches our expectations?

<!-- page: 114 -->
# CHAPTER 6 Testing a builder macro
We can do that by comparing the output with a TokenStream of our own. That does mean we need to somehow manually build that expected output, and there are several ways to do this. For example, we could create a new TokenStream and use `to_tokens` to add all the expected output to that stream. While that would work, it requires way more effort than the alternative: just use `quote` to generate the expected output.
## Listing 6.6 Adding a second test
rust
#[test]
fn builder_struct_with_expected_methods_should_be_present_in_output() {
let input = quote! {
struct StructWithNoFields {}
};
let expected = quote! {
struct StructWithNoFieldsBuilder {}
};
let actual = create_builder(input);
assert_eq!(
actual.to_string(),
expected.to_string()
);
}

Uses quote to create the input and expected output

Asserts that the expected and actual produce the same string

Since TokenStream does not implement PartialEq, we cannot directly compare both. Changing them to strings and comparing the result is an easy enough workaround.

Instead of making sure our expected value is of the same type as our output, we can also transform our output to make verifying it easier. So a third option is to use parse2. If the parse fails, the test correctly panics thanks to the unwrap call. If it succeeds, we have an AST that we can easily extract information from—and verify that it matches expectations.

#[test]
fn assert_with_parsing() {
let input = quote! {
struct StructWithNoFields {}
};
let actual = create_builder(input);
let derived: DeriveInput = syn::parse2(actual).unwrap();
let name = derived.ident;
assert_eq!(
name.to_string(),
"StructWithNoFieldsBuilder"
);
}

We parse our result into DeriveInput, panicking if this does not work.

When it succeeds, we can retrieve the properties of the parsed result and see if they match our expectation.

This is powerful, but once we start outputting more than one item/struct/function, we have to write custom logic for parsing. And when that becomes too complex, we might have to test our tests. That is why the second variation, which uses quote, is my favorite of the three, for both clarity and—particularly—ease of use. Besides testing token stream output, white-box testing is very useful for verifying the output of helper functions. Since you are expected to be familiar with the basics of testing in Rust, examples of such tests are not shown here.

Still, despite their usefulness in multiple scenarios, white-box tests are by themselves insufficient for fully testing macros. Yes, they can show us that the output of our code is what we think it should be. But what we really want to know is whether the generated code will do what we want it to do. In this case, will it allow us to create our struct? To verify that sort of behavior, we need to adopt an outsider’s perspective.

As we mentioned earlier, black-box tests take an outsider’s view. They only want to know whether the code produces the required result, without knowing how it achieves this. This is often a good idea since the value of code is in what it can produce rather than how. Do we really care that values are temporarily stored somewhere when we build our struct? Is it important to verify that this happens? As a consequence of their approach, black-box tests are less tied to implementation details than white-box tests. This means they change less often when you are only modifying code internals.

We start with some happy path testing, which verifies that the code works when everything goes according to plan. We add the test to builder-usage since this crate is one of the users of our macro. Alternatively, we could add everything to a new tests folder in the root of builder-usage. In normal projects, this is a good place for black-box tests because code in tests does not have privileged access—it can only use the public API of its project. But in our case, the code we are testing is in an entirely different project. So main.rs is fine.

Our first, most basic test verifies compilation of the code and nothing more.

Listing 6.8 A first black-box test (in builder-usage, main.rs)

use builder_macro::Builder;
fn main() {}
#[cfg(test)]
mod tests {
#[test]
fn should_generate_builder_for_struct_with_no_properties() {
#[derive(Builder)]
struct ExampleStructNoFields {}

When we create a struct annotated with #[derive(Builder)] …

let _: ExampleStructNoFields = ExampleStructNoFields::builder()
.build();

… we expect our macro to create a builder function.

Our test defines a struct annotated with our macro, and we are asserting that calling ::builder().build() will return an instance of that struct. By doing this, we are asserting that the code will compile, proving that the functions we are expecting are generated. Even without assertions, the code already complains: function or associated item builder not found for this struct. So let’s turn our test green by adding everything we need for this first use case.

Listing 6.9 Adding enough implementation to turn our test green

Section titled “Listing 6.9 Adding enough implementation to turn our test green”
// earlier imports
pub fn create_builder(item: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse2(item).unwrap();
let name = ast.ident;
let builder = format_ident!("{}", Builder, name);
quote! {
struct #builder {}
impl #builder {
pub fn build(&self) -> #name {
#name {}
}
}
impl #name {
pub fn builder() -> #builder {
#builder {}
}
}
}
}

We already had this builder struct.

But now it has an implementation, containing a build method that will return an instance of the annotated struct.

And the original struct gets a method that returns the builder struct.

All changes are located in the quote macro. Instead of generating an empty struct, we have added an implementation block for both the builder and the original struct. In these blocks, we define the two functions that we are calling in our test.

Some errors you may come across writing this piece of code (or similar) are as follows:

  • expected value, found struct ExampleStructNoFields—This error is caused by forgetting to add {} behind #name inside build. The error message is helpful but—as usual—points to the macro instead of a specific line. One way to track down the error is to search for places where you are using #name since you know its value is the ExampleStructNoFields that appears in the message. You could also use cargo expand to visualize what the generated code looks like. The

6.4 Black-box unit tests

command is a bit different now because it is tests that are being expanded—in this case, cargo expand --tests --bin builder-usage, which you can run inside builder-usage.

  • expected () because of default return type—This error is less clear until you realize that you have functions that should return things. So you probably forgot to specify a return type (e.g. -> #name).

  • expected identifier, found "ExampleStructNoFieldsBuilder"—You will get this error if you forget that you need identifiers instead of strings for the names of structs. You may recall that we encountered similar problems in the previous chapter.

  • cannot find value build in this scope—A typo inside quote means that we have a hashtag in combination with an unknown variable. Rust won’t like that. So check for hashtags that do not match anything. An IDE will probably give you autocomplete for these hashtags, helping you track down or avoid this problem.

We have turned our first type happy path test—call it a “compile test”—green! This is a good first step. Even if the code does not do what we expect, at the very least it verifies that our generated code does not crash and burn. Note that these implementation changes will cause our second white-box test to fail, as we are now producing more output. You can fix it or disable it for now. I would also advise disabling the third (parsing) test because, as predicted, it now requires too much custom parsing effort vis-à-vis its value. Meanwhile, the first white-box test shows that there is value in simplicity: it just keeps on working.

6.4.2 A happy path test with an actual property

Section titled “6.4.2 A happy path test with an actual property”

What would be a useful second test? How about a struct with a single property?

Listing 6.10 A test for keeping Fenrir at bay (still in main.rs, builder-usage)

#[test]
fn should_generate_builder_for_struct_with_one_property() {
#[derive(Builder)]
struct Gleipnir {
roots_of: String,
}
let gleipnir = Gleipnir::builder()
.roots_of("mountains".to_string())
.build();
assert_eq!(gleipnir.roots_of, "mountains".to_string());
}

This will fail with no method named roots_of found for struct Gleipnir. What do we need to do to fix this? Well, our builder has to expose one method for every field in

the struct, which will save the value. Our build method will use that saved information to create the struct (Gleipnir, in our case). The associated builder function will create the initial builder as before, but now we have to make sure the builder defines properties for saving all the required values. It seems safe to conclude that we need to retrieve the struct fields to work our magic. More specifically, we need to know their names and types to generate our functions.

NOTE We are following TDD philosophy, trying to write just enough code to make our tests turn green. So it is okay for now to assume that we only have to deal with a String. We will make the code more generic—and performant—in the next section.

The implementation is shown in the following listing.

Listing 6.11 builder-code implementation (without white-box tests and imports)

Section titled “Listing 6.11 builder-code implementation (without white-box tests and imports)”
pub fn create_builder(item: TokenStream) -> TokenStream {
// AST, retrieving name and creating builder identifier
let fields = match ast.data {
Struct(
DataStruct {
fields: Named(
FieldsNamed {
ref named, ..
}, ..
), ..
}
) => named,
_ => unimplemented!(
"only implemented for structs"
),
};
let builder_fields = fields.iter().map(|f| {
let field_name = &f.ident;
let field_type = &f.ty;
quote! { #field_name: Option<#field_type> }
});
let builder_inits = fields.iter().map(|f| {
let field_name = &f.ident;
quote! { #field_name: None }
});
let builder_methods = fields.iter().map(|f| {
let field_name = &f.ident;
let field_type = &f.ty;
quote! {
pub fn #field_name(&mut self, input: #field_type) -> &mut Self {
self.#field_name = Some(input);
self
}
}
});
}
<!-- page: 119 -->
6.4 Black-box unit tests
rust
let set_fields = fields.iter().map(|f| {
let field_name = &f.ident;
let field_name_as_string = field_name
.as_ref().unwrap().to_string();
quote! {
#field_name: self.#field_name.as_ref()
.expect(
&format!("field {} not set", #field_name_as_string)
)
}
});
quote! {
struct #builder {
#(#builder_fields,)*
}
impl #builder {
#(#builder_methods)*
pub fn build(&self) -> #name {
#name {
#(#set_fields,)*
}
}
}
impl #name {
pub fn builder() -> #builder {
#builder {
#(#builder_inits,)*
}
}
}
}

This is a lot to unwrap. Let’s go over it bit by bit. We start with retrieving the fields of the incoming struct, like we did several times before. Once that is done, we use these fields in four different ways.

First, we make sure our helper struct has the same properties as the original struct. That way, we can temporarily store all field information. But when we first create this helper, when builder() is called, we do not have any values to store. So we will wrap the types in an Option. (And we will ignore complexities such as what to do when a type is already an Option.) That is what is happening in the code fragment in the following listing.

Listing 6.12 Adding fields to the builder struct definition

let builder_fields = fields.iter().map(|f| {
let field_name = &f.ident;
let field_type = &f.ty;
quote! { #field_name: Option<#field_type> }
});
<!-- page: 120 -->
# CHAPTER 6 Testing a builder macro
**NOTE** You may at some point think that creating these temporary variables (`field_name` and `field_type` in this instance) is a waste. Can’t we just inline this stuff and use `f` directly inside `quote` (e.g., `#f.ident`)? Unfortunately, no. The `quote` macro is great, but, as stated earlier, it won’t retrieve struct fields for you.
Next, when `builder()` is called, we have to *initialize* the fields, setting each one to `None` since we do not have a value yet.
## Listing 6.13 Initial values for the builder fields
rust
let builder_inits = fields.iter().map(|f| {
let field_name = &f.ident;
quote! { #field_name: None }
});

Now we want to generate public methods with a name equal to that of a field, for setting that field to something other than None. They will take a parameter of the same type as the field and save it in an Option. As an example, take the roots_of field of type String: the method name will be roots_of, and the input will be of type String and will be saved as an Option<String> in a builder struct field called roots_of. The method will return the builder (self). That way, we can have a fluent builder that sets value after value: builder().first_field(...).second_field(...).build().

Listing 6.14 Generating methods for setting the value of a property

Section titled “Listing 6.14 Generating methods for setting the value of a property”
let builder_methods = fields.iter().map(|f| {
let field_name = &f.ident;
let field_type = &f.ty;
quote! {
pub fn #field_name(&mut self, input: #field_type) -> &mut Self {
self.#field_name = Some(input);
self
}
}
});

Finally, when we call build, we want to retrieve all the stored values and create the annotated struct. With the code in listing 6.15, we create this initialization for each field. Since we are dealing with optionals, we use expect to get the actual value, and the operation might fail since a user could forget to set a value. So we will return an informative error using field_name_as_string. Once that is done, we have the actual field. But as we can’t just “move” out of the field, we do a to_string to get a copy of the value.

Listing 6.15 Initializing the actual struct

Section titled “Listing 6.15 Initializing the actual struct”
let set_fields = fields.iter().map(|f| {
let field_name = &f.ident;
<!-- page: 121 -->
6.4 Black-box unit tests
rust
let field_name_as_string = field_name
.as_ref().unwrap().to_string();
quote! {
#field_name: self.#field_name.as_ref()
.expect(&format!("field {} not set", #field_name_as_string))
.to_string()
}

These are all loose pieces, which we need to bring together in quote. If you have trouble visualizing this, run cargo expand on the test or consult figure 6.3.

quote! {
struct #builder {
#(#builder_fields,)*
}
impl #builder {
#(#builder_methods)*
pub fn build(&self) -> #name {
#name {
#(#set_fields,)*
}
}
}
impl #name {
pub fn builder() -> #builder {
#builder {
#(#builder_inits,)*
}
}
}
}

The builder has the same fields as the annotated struct, but the type is wrapped in an Option.

It has one setter method for every field.

And its build function can be used to create the struct.

To create a new builder with all fields initialized to None, we add a builder() to the original struct.

When writing this code, I encountered one annoying error:

22 | #[derive(Builder)]
| ^^^^^^^^
|
| item list starts here
| non-item starts here
| item list ends here

Printing information and expanding did not give me any real insights. I suspected that the problems lay in my “builder methods” and confirmed this by temporarily disabling that part of the code. Then it dawned on me that I had written #(#builder_methods,)*—and functions are not separated by commas! Removing the comma did the trick.

Figure 6.3 shows an overview of the output generated by the different parts of our code and how everything fits together. From a simple struct with a single field, we

generate a builder with a property, its initialization, a method to set its one field, and a build method where the original Gleipnir struct is created.

mermaid graph TD A[Gleipnir\nroots_of: String] —> B[Fields (1)\nfield_name: roots_of\nfield_type: String] B —> C[builder_fields\nroots_of: Option] B —> D[builder_inits\nroots_of: None] B —> E[builder_methods\npub fn roots_of(&mut self, input: String) -> &mut Self {\n self.roots_of = Some(input);\n self\n}] B —> F[set_fields\nroots_of: self.roots_of\n.as_ref()\n.expect(&format!(“Field {} not set”, “roots_of”))\n.to_string()] C —> G[struct GleipnirBuilder {\n roots_of: Option\n}\nimpl GleipnirBuilder {\n pub fn roots_of(&mut self, input: String) -> &mut Self {\n self.roots_of = Some(input);\n self\n }\n pub fn build(&self) -> Gleipnir {\n Gleipnir {\n roots_of: self.roots_of\n .as_ref()\n .expect(&format!(“Field {} not set”, “roots_of”))\n .to_string(),\n }\n }\n}\nimpl Gleipnir {\n pub fn builder() -> GleipnirBuilder {\n GleipnirBuilder {\n roots_of: None,\n }\n }\n}”] D —> G E —> G F —> G

Figure 6.3 An overview of transformations for our example struct
## 6.4.3 Testing enables refactoring
The previous code is far from perfect. But the good news is that tests make it easier and safer to refactor. As long as the black-box tests stay green, we know that our behavior is still the same, albeit only for empty structs and those with one field. Let’s make
![](assets/wpm-fig-7-03-flowchart-showing-transformations-for-gleipnir-struct-with.png)
> [!visual-conversion] Flowchart showing transformations for Gleipnir struct with fields, builder methods, …
> Cropped from the scan (PDF page 122, printed p. ?): Flowchart showing transformations for Gleipnir struct with fields, builder methods, and code blocks.
<!-- page: 123 -->
# 6.4 Black-box unit tests
use of that freedom. Until now, we have often placed all our code in one file and one function. While that is good enough for simple examples, this one is now quite big—a single function containing almost 70 lines of code. If we expect the implementation to grow even further, it makes sense to split things up.
Ideally, refactoring happens step by step, and we should verify that our code keeps working after every minor step. We can start by extracting some functions. Each of these does an iteration over the fields to do one thing (field definitions, initializations, etc.). With IDE tooling, this is a piece of cake.
## Listing 6.17 Code fragment from our refactored create_builder function
rust
let builder_fields = builder_field_definitions(fields);
let builder_inits = builder_init_values(fields);
let builder_methods = builder_methods(fields);
let original_struct_set_fields = original_struct_setters(fields);

The tests are still green. Retrieving the field name and type is something we do in both builder_field_definitions and builder_methods, so we can deduplicate. The following listing shows the code for the helper and how it is used in another function.

Listing 6.18 Adding a helper function for getting the field name and type

Section titled “Listing 6.18 Adding a helper function for getting the field name and type”
use syn::{Ident, Type}; // plus other imports
fn builder_field_definitions(fields: &Punctuated<Field, Comma>)
-> impl Iterator<Item = TokenStream2> + '_ {
fields.iter().map(|f| {
let (name, f_type) = get_name_and_type(f);
quote! { pub #name: Option<#f_type> }
})
}
fn get_name_and_type<'a>(f: &'a Field) -> (&'a Option<Ident>, &'a Type) {
let field_name = &f.ident;
let field_type = &f.ty;
(field_name, field_type)
}

In one of the exercises, we had a very concrete return type for a function like builder_field_definitions: Map<Iter<Field>, fn(&Field) -> TokenStream>. That works, but this impl Iterator<Item = TokenStream2> + '_ is more idiomatic when you return iterator types. Instead of specifically telling Rust that the function gives back a Map, we say it is something that iterates over token streams: impl Iterator<Item = TokenStream2>. The '_' is obligatory, as Rust will tell you if you forget to add it. The error it throws is quite clear in its explanation: our parameter fields, a reference, has an anonymous lifetime. This is captured by us but not mentioned as part of the bounds of the return type impl Iterator<Item = TokenStream2>. So we have to make this explicit, which we can do with a placeholder lifetime. That’s possible because there is

<!-- page: 124 -->
# CHAPTER 6 Testing a builder macro
only a single lifetime. If we had multiple reference parameters for this function, things would be more complicated.
We also had to add lifetimes to `get_name_and_type`. This is because the *lifetime elision rules*, which allow Rust to infer the proper lifetime, could not be applied to this function with two outputs. In any case, the tests are still running.
Next, there’s too much code in a single file, so we should split off some functionality. We could do this in two ways. First, we could create a subdirectory (perhaps called “implementation”?—names are hard), and add a file with the code and a `mod.rs` that determines what is exported (and thus usable in our root library file). This has the advantage of a bit more power and flexibility—which we don’t need at the moment—at the cost of a little more effort. Instead, we go with the second option: putting the helpers in a separate file, which is the more “modern” way of doing things in Rust anyway (even though `directory + mod.rs` is still widely used).
That means we have to create a new file, called `fields.rs`, in the `src` directory of our macro code. We can move all the functions except `create_builder` to that file, leaving the tests untouched. When this is done, we need to add `mod fields` to `lib.rs` and import our functions.
## Listing 6.19 Part of the new `fields.rs` file
rust
// imports
pub fn original_struct_setters(fields: &Punctuated<Field, Comma>)
-> impl Iterator<Item = TokenStream2> + '_ {
fields.iter().map(|f| {
let field_name = &f.ident;
let field_name_as_string = field_name.as_ref()
.unwrap().to_string();
quote! {
#field_name: self.#field_name.as_ref()
.expect(
&format!("field {} not set", #field_name_as_string))
.to_string()
}
}))
}

One of the four functions that are now public (pub) so we can use them elsewhere

// three more functions
fn get_name_and_type<'a>(f: &'a Field) -> (&'a Option<Ident>, &'a Type) {
let field_name = &f.ident;
let field_type = &f.ty;
(field_name, field_type)
}

This helper can stay private because it is only used by functions in this file.

Listing 6.20 Using the functions in lib.rs

Section titled “Listing 6.20 Using the functions in lib.rs”
mod fields;
use crate::fields::{
builder_field_definitions,
builder_init_values,
builder_methods,
original_struct_setters
};
// other imports and code

Moving the field-related code has made our library cleaner and has hidden a helper (get_name_and_type) that is only of interest to the field-related functions. This is good: more information hiding and less “surface” area. Having separate functions instead of one big blob also opens the door for additional unit testing. The following listing shows an example of our helper.

Listing 6.21 An example test for get_name_and_type

Section titled “Listing 6.21 An example test for get_name_and_type”
#[test]
fn get_name_and_type_give_back_name() {
let p = PathSegment {
ident: Ident::new("String", Span::call_site()),
arguments: Default::default(),
};
let mut pun = Punctuated::new();
pun.push(p);
let ty = Type::Path(TypePath {
qself: None,
path: Path {
leading_colon: None,
segments: pun,
},
});
let f = Field {
attrs: vec![],
vis: Visibility::Inherited,
mutability: FieldMutability::None,
ident: Some(Ident::new("example", Span::call_site())),
colon_token: None,
ty,
};
let (actual_name, _) = get_name_and_type(&f);
assert_eq!(
actual_name.as_ref().unwrap().to_string(),
"example".to_string()
)
}

As you can see, constructing the parameters for this function requires a lot of boilerplate. And in this case, our trick with quote + parse2 can’t help us since Field does not implement Parse. So perhaps you will decide against white-box testing at this level of detail. But if you need it, it’s available.

With this first bit of refactoring out of the way, we should focus on our implementation, because we are still only able to accept strings. We can verify this behavior with a test, as real, hard-core TDD practitioners should.

Listing 6.22 A test with two properties, including one that is not a String

Section titled “Listing 6.22 A test with two properties, including one that is not a String”
#[test]
fn should_generate_builder_for_struct_with_two_properties() {
#[derive(Builder)]
struct Gleipnir {
roots_of: String,
breath_of_a_fish: u8
}
let gleipnir = Gleipnir::builder()
.roots_of("mountains".to_string())
.breath_of_a_fish(1)
.build();
assert_eq!(gleipnir.roots_of, "mountains".to_string());
assert_eq!(gleipnir.breath_of_a_fish, 1);
}

As expected, this fails at compilation time (expected u8, found struct String) because we are doing a to_string on our values:

quote! {
#field_name: self.#field_name.as_ref()
.expect(&format!("field {} not set", #field_name_as_string))
.to_string()
}

There are several ways to fix this. One extremely easy solution is to replace to_string with clone, which will make Strings, primitives, and all structs that implement Clone work automatically. And if we get a field that does not implement this trait, we will get an error pointing that out (YourCustomStruct does not implement Clone). Neat. But it does require you to implement Clone for every struct property, which you may not want.

There are two other solutions. One of them requires additional code and has limited capabilities. The other is shorter and more elegant but requires more thinking in advance about our goal and the rules of Rust. (Obviously, the first solution is the one I thought of first before stumbling on the second one, which works by consuming the builder.) But why on earth would we explore the first alternative when it sounds worse

6.4 Black-box unit tests

than what we already have? Well, in a book about macros, this solution has the advantage that it requires us to dive into the AST!

So let’s begin. One problem with our current solution is that to_string only works for one type. Primitive types like u8 don’t require anything like that, since they implement Copy. This means we could check the type we receive and leave out the to_string bit when we have a primitive or when we do not have a String.

To do that, we want a helper that can tell us whether something is a String. But where inside the type can we find that information? Since Type is a large enum, let us print out part of the AST we get in our test:

Path(TypePath {
qself: None,
path: Path {
leading_colon: None,
segments: [
PathSegment {
ident: Ident {
ident: "String",
span: #0 bytes(226..232),
},
arguments: PathArguments::None,
},
],
},
})

So our Type contains a Path and TypePath, with an ident inside path.segments (see figure 6.4). And an identifier can be turned into a string.

Figure 6.4 A simplified drilling down from Field to PathSegment

Field
ty: Type
Type
Path(TypePath)
TypePath
path: Path
Path
segments:
Punctuated
PathSegment
ident: Ident
arguments: PathArguments

[!visual-conversion] Flowchart showing hierarchy from Field to PathSegment with labeled boxes … Cropped from the scan (PDF page 127, printed p. ?): Flowchart showing hierarchy from Field to PathSegment with labeled boxes and arrows.

That means we can write a helper function to retrieve the identifier, turn it into a string, and compare it with a string representation of the type. As you can see, writing this code is a matter of figuring out where to look for useful data.

Listing 6.23 Adding a type helper to fields.rs

Section titled “Listing 6.23 Adding a type helper to fields.rs”
fn matches_type(ty: &Type, type_name: &str) -> bool {
if let Type::Path(ref p) = ty {
let first_match = p.path.segments[0].ident.to_string();
return first_match == *type_name;
}
false
}

Only if we have a Type::Path do we dig deeper and compare the identifier as a string with our type_name.

Compares the identifier as a string with the type_name parameter, a string representation of the type

We will now use this helper inside fields.rs. What we want to do there is to add an as_ref and to_string call to our TokenStream when we have a string, or else we assume we’re dealing with a primitive that implements Copy, which means we don’t have to worry about moving.

Listing 6.24 Producing different output depending on our matches_type result

Section titled “Listing 6.24 Producing different output depending on our matches_type result”
pub fn original_struct_setters(fields: &Punctuated<Field, Comma>)
-> impl Iterator<Item = TokenStream2> + '_ {
fields.iter().map(|f| {
let (field_name, field_type) = get_name_and_type(f);
let field_name_as_string = field_name.as_ref()
.unwrap().to_string();
if matches_type(field_type, "String") {
quote! {
#field_name: self.#field_name.as_ref()
.expect(
&format!(
"field {} not set", #field_name_as_string
)
)
}
} else {
quote! {
#field_name: self.#field_name
.expect(
&format!(
"field {} not set", #field_name_as_string
)
)
}
}
})
}

This is our original quote output, now only used when the helper returns true.

Checks whether the type is a string

In every other case, we do not need the as_ref and to_string calls because the type can be copied.

6.4 Black-box unit tests

If you run our last test again, everything will be green. Huzzah. But the code has a bit of duplication, and if that bothers you, we can get rid of it. The example in listing 6.25 avoids some duplication, though it is also harder to read. It’s a tradeoff.

Listing 6.25 Combining TokenStream pieces with each other to avoid duplication

pub fn original_struct_setters(fields: &Punctuated<Field, Comma>)
-> impl Iterator<Item = TokenStream2> + '_ {
fields.iter().map(|f| {
let (field_name, field_type) = get_name_and_type(f);
let field_name_as_string = field_name.as_ref()
.unwrap().to_string();
let error = quote! {
expect(&format!("Field {} not set", #field_name_as_string))
};
let handle_type = if matches_type(field_type, "String") {
quote! {
as_ref()
.#error
.to_string()
}
} else {
quote! {
#error
}
};
quote! {
#field_name: self.#field_name.#handle_type
}
})
}

This is TokenStream all the way down, baby! We have said it before: quote offers some nice, flexible ways to compose output. So don’t think that individual functions need to return a complete, working piece of generated code. It is perfectly possible to build small pieces of a token stream, which will be stitched together in your final output. Or you can ignore things that are not relevant—but more on that later.

Our work is not done yet, as you would find out if you started experimenting with other nonprimitive properties. Remember, right now, we are checking whether a field is a String and relying on Copy when it’s not. But there are a lot of other types out there that are (perhaps) cloneable but not copyable. So let’s add another test, for Vec<String>.

Listing 6.26 Testing with an additional property that is not Copy

Section titled “Listing 6.26 Testing with an additional property that is not Copy”
#[test]
fn should_generate_builder_for_struct_with_multiple_properties() {
#[derive(Builder)]
struct Gleipnir {
roots_of: String,
breath_of_a_fish: u8,
other_necessities: Vec<String>,
}
let gleipnir = Gleipnir::builder()
.roots_of("mountains".to_string())
.breath_of_a_fish(1)
.other_necessities(vec![
"sound of cat's footsteps".to_string(),
"beard of a woman".to_string(),
"spittle of a bird".to_string()
])
.build();
assert_eq!(gleipnir.roots_of, "mountains".to_string());
assert_eq!(gleipnir.breath_of_a_fish, 1);
assert_eq!(gleipnir.other_necessities.len(), 3)
}

We’re going to find out whether Vec<String> works with our code.

As expected, compilation fails with move occurs because self.vec_value has type Option<Vec<String>> which does not implement the Copy trait, because this is a field that is neither String nor Copy. So maybe we should rewrite our code and clone everything that is not Copy? That is certainly one solution to make our current test green. And at the cost of additional code in our macro, it would produce less (and a bit more performant) output code than our original “clone everything” solution, though it would limit our builder macro to types that are Clone or Copy, and not everything we encounter will be one or the other.

But there is another, less limiting way. Our builder is a temporary struct—something to hold onto our data while the struct we want is incomplete. So moving, which we have been trying to avoid, can actually be a good thing. And the most efficient way to deal with the builder is probably to empty it. How do we go about doing this? The answer is by consuming self instead of borrowing a (mutable) reference to it. (These changes will once again break our white-box tests. You can get them running again with some minor fixes, but we won’t show that here.)

Listing 6.27 Stop borrowing our builder struct (lib.rs)

Section titled “Listing 6.27 Stop borrowing our builder struct (lib.rs)”
pub fn build(self) -> #name {
#name {
#(#set_fields,)*
}
}

&self, a borrow, has been changed into the consumption of the builder by passing on self.

Listing 6.28 Stop borrowing our builder struct (fields.rs)

Section titled “Listing 6.28 Stop borrowing our builder struct (fields.rs)”
pub fn #field_name(mut self, i: #field_type) -> Self {
self.#field_name = Some(i);
self
}

Here the parameter self is no longer a reference, and the return is not a mutable reference anymore

With a couple of minor changes, the code compiles. But we are not done yet: if everything is moved instead of copied, we no longer need to treat strings as something special. And while we are at it, using format for the errors is not ideal, because it does part of its work at run time (expand the code if you do not believe me). In an early chapter, we used the stringify macro to avoid some run-time work. This time, we turn to concat, a macro that concatenates string literals, which should allow us to produce a suitable message.

Listing 6.29 Simplifying original_struct_setters

Section titled “Listing 6.29 Simplifying original_struct_setters”
pub fn original_struct_setters(fields: &Punctuated<Field, Comma>)
-> impl Iterator<Item = TokenStream2> + '_ {
fields.iter().map(|f| {
let field_name = &f.ident;
let field_name_as_string = field_name
.as_ref().unwrap().to_string();
quote! {
#field_name: self.#field_name
.expect(
concat!("field not set: ", #field_name_as_string),
)
}
})
}

matches_type has been removed, the to_string is gone, and we use concat to produce the panic message.

The one downside of this consuming approach is that a builder instance is consumed, meaning you have to clone it if you want to reuse it. Apart from that, our latest solution is shorter and more elegant and should be more performant than what came before. Plus, it doesn’t require clone, since we are moving values instead.

With a disclaimer that this is not my area of expertise: like a copy, a move is actually a memcpy in the background—basically a system function that copies byte buffers, generally a cheap operation. Most of these memcpys will probably be optimized away by your compiler, but that is not guaranteed. If they are not optimized away, these copies are not a problem for small types or those that are only pointers plus “bookkeeping,” with everything else located on the heap. On the other hand, large types that live entirely on the stack will be costly to copy, and this may cause performance

<!-- page: 132 -->
CHAPTER 6 Testing a builder macro
(continued)
problems. There’s a reason it’s important to measure performance, because modern computer architecture laughs at our feeble attempts to simplify things (“move is always the best choice”).
## 4.6 Unhappy path
In unhappy path testing, we want to check failure modes. And for our Rust macros, we are interested in both run-time and compile-time failures. In the first category, our code is expected to panic when a field is missing. We start by verifying that behavior.
### Listing 6.30 Testing panic on a missing field
rust
#[test]
#[should_panic]
fn should_panic_when_field_is_missing() {
#[derive(Builder)]
struct Gleipnir {
_roots_of: String,
}
Gleipnir::builder().build();
}

We are expecting a panic.

Our struct has a property, but we are not setting it before calling build.

#[should_panic] tells Rust that we expect this code to panic because we are calling build without setting a value for our property. This covers the one place where we panic at run time. But we are also panicking at compile time—for example when we receive something that is not a struct. We should verify this behavior as well. To do that, we will add the crate trybuild to our dependencies. Run cargo add --dev trybuild or add trybuild = "1.0.85" to your Cargo.toml dev dependencies (we only need this dependency for testing) in builder-usage. Then add a tests folder in the root of builder-usage, and create a file named compilation_tests.rs with the content in the following listing.

Listing 6.31 Our compilation test runner in the tests folder

Section titled “Listing 6.31 Our compilation test runner in the tests folder”
#[test]
fn should_not_compile() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/fails/*.rs");
}

trybuild will look inside the given directory (tests/fails) for tests that fail at compile time.

trybuild will verify that everything inside the chosen directory fails to compile. When you run it for the first time for a given test, it will output the error message it received (if any). If the error message matches your expectations, you add the generated output file to the folder your test is in. This approach makes a lot of sense: things can fail

6.5 What kinds of unit tests do I need? 123

to compile for any number of stupid reasons. You want to be sure it fails for the right reason.

Right now, we do not have any failing tests. Add a fails directory, and put build_enum.rs inside with the content in the following listing.

Listing 6.32 Testing whether running our macro with an enum fails

use builder_macro::Builder;
#[derive(Builder)]
pub enum ExampleEnum {}
fn main() {}

Since this is an enum, which we don’t handle, we expect compilation to fail.

A main function is required for trybuild, though it can be empty.

We are annotating an enum with our builder macro, which should fail because we only support named structs. When you run the test, you will get the following error message, as well as a failure file in a wip directory inside your project. Either copy the file or take the error message and add it as a file to fails under the name build_enum.stderr. A newline at the end is important:

error: proc-macro derive panicked
--> tests/fails/build_enum.rs:4:10
|
4 | #[derive(Builder)]
| ^^^^^^^^
|
= help: message: not implemented: Only implemented for structs

This is what we expect to get when applying our macro to an enum: the panic we wrote earlier in this chapter! So that’s working—well, failing—as expected. We could add a function example. But derive macros are only allowed on structs, enums, and unions, so Rust is handling that one for us. This means we have now covered the most important unhappy paths for our macro. If you want, you could now move the happy path tests we placed in main.rs to the tests folder. That way, you have all your tests in one place.

All the unit tests! Ideally. But their importance does vary.

A simple happy path compilation test (a black-box test) seems like the most basic requirement. If your macro won’t even compile when you expect it to, what use does it have? Unhappy path compilation failures can be important if you have a lot of failure modes to test. But for a simple macro, there might be few—or you might find ways to work around them.

With regard to white-box unit testing—well, it depends. I really like that Rust allows you to test private functions. That allows you to hide all the information you want while

CHAPTER 6 Testing a builder macro

(continued)

problems. There’s a reason it’s important to measure performance, because modern computer architecture laughs at our feeble attempts to simplify things (“move is always the best choice”).

In unhappy path testing, we want to check failure modes. And for our Rust macros, we are interested in both run-time and compile-time failures. In the first category, our code is expected to panic when a field is missing. We start by verifying that behavior.

Listing 6.30 Testing panic on a missing field

Section titled “Listing 6.30 Testing panic on a missing field”
#[test]
#[should_panic]
fn should_panic_when_field_is_missing() {
#[derive(Builder)]
struct Gleipnir {
_roots_of: String,
}
Gleipnir::builder().build();
}

We are expecting a panic.

Our struct has a property, but we are not setting it before calling build.

#[should_panic] tells Rust that we expect this code to panic because we are calling build without setting a value for our property. This covers the one place where we panic at run time. But we are also panicking at compile time—for example when we receive something that is not a struct. We should verify this behavior as well. To do that, we will add the crate trybuild to our dependencies. Run cargo add --dev trybuild or add trybuild = "1.0.85" to your Cargo.toml dev dependencies (we only need this dependency for testing) in builder-usage. Then add a tests folder in the root of builder-usage, and create a file named compilation_tests.rs with the content in the following listing.

Listing 6.31 Our compilation test runner in the tests folder

Section titled “Listing 6.31 Our compilation test runner in the tests folder”
#[test]
fn should_not_compile() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/fails/*.rs");
}

trybuild will look inside the given directory (tests/fails) for tests that fail at compile time.

trybuild will verify that everything inside the chosen directory fails to compile. When you run it for the first time for a given test, it will output the error message it received (if any). If the error message matches your expectations, you add the generated output file to the folder your test is in. This approach makes a lot of sense: things can fail

sure it fails for the right

directory, and put build_

n fails

use bui.
#[de
pub enum ExampleEn
fn main() {}

A main function is required for trybuild, though it can be empty.

We are annotating an enum with our builder macro, which should fail because we only support named structs. When you run the test, you will get the following error message, as well as a failure file in a wip directory inside your project. Either copy the file or take the error message and add it as a file to fails under the name build_enum.stderr. A newline at the end is important:

error: proc-macro derive panicked
--> tests/fails/build_enum.rs:4:10
|
4 | #[derive(Builder)]
| ^^^^^^^^
|
= help: message: not implemented: Only implemented for structs

This is what we expect to get when applying our macro to an enum: the panic we wrote earlier in this chapter! So that’s working—well, failing—as expected. We could add a function example. But derive macros are only allowed on structs, enums, and unions, so Rust is handling that one for us. This means we have now covered the most important unhappy paths for our macro. If you want, you could now move the happy path tests we placed in main.rs to the tests folder. That way, you have all your tests in one place.

All the unit tests! Ideally. But their importance does vary.

A simple happy path compilation test (a black-box test) seems like the most basic requirement. If your macro won’t even compile when you expect it to, what use does it have? Unhappy path compilation failures can be important if you have a lot of failure modes to test. But for a simple macro, there might be few—or you might find ways to work around them.

With regard to white-box unit testing—well, it depends. I really like that Rust allows you to test private functions. That allows you to hide all the information you want while

also allowing for easy testing of pure functions. This mixes well with my personal preference: keep your impure functions both small in size and number, moving transformations and business logic where possible to pure functions. In the impure parts, where we communicate with outside parties, databases, etc., we can rely on the type system to guide us in the right direction and keep us from doing silly things. (Throw in a few integration tests if you have any doubts.) And as pure functions are straightforward to test, I can still get good coverage on a large part of my code base without thinking about things like mocking or how to bring in real dependencies.

NOTE Pure functions are functions that have no side effects and whose returns are determined solely by the input parameters. We’ll talk about them again in the next chapter.

That being said, white-box testing for macros is a lot of work. Creating the in- and outputs of helper functions, like the ones in this chapter, is cumbersome. (I am excluding functions that have no macro-specific inputs or outputs from this discussion. For that category, see the brief discussion in the previous paragraph.) In a large project, such tests can help you catch bugs early on. But black-box tests will also detect problems relatively quickly, are easier to set up and reason about, and are less sensitive to minor changes. Even just moving around parts of our output will break white-box tests without changing the workings and meaning of our code. On the other hand, the error you get from a black-box test might be unclear, requiring you to follow a long trail of breadcrumbs (hope you were running your tests after every small addition of code!). So in a larger and more complex application, internal tests at strategic locations can be very worthwhile.

We have spent an entire chapter writing unit tests, but this exploration is only scratching the surface of testing. For example, you have tests that take a broader perspective:

  • Integration tests verify that the integration between parts of your system works as expected. They are generally slower than unit tests because they cover more code and might draw in real dependencies, but they cover more ground and give you more certainty that your code will do what it should do.

  • End-to-end tests verify the workings of your entire system, meaning most or even all dependencies will be real. A test suite like this offers a lot of value during continuous deployment, making sure that your code probably doesn’t break anything—if you can keep it working, because end-to-end tests can be brittle and hard to maintain.

  • Smoke tests are a sort of variant of end-to-end testing. They focus on a limited number of important paths and make sure that what you deploy is not completely broken. (Is there smoke coming from the servers?) If your app is constantly crashing without doing anything, these tests will tell you.

Other tests feature a different approach or focus:

  • Performance testing verifies that the system has certain speed and reliability characteristics under various kinds of load. For Rust, you can use Criterion.rs (https://github.com/bheisler/criterion.rs).

  • Load testing is similar, but its main goal is to verify that your application keeps working without degrading under heavy load.

  • Contract testing checks that a producer is returning data in the agreed-upon format (i.e., is adhering to its existing public API). This avoids accidentally breaking consumers because something happened to the data they were expecting to receive.

  • Mutation testing, a fairly new category, makes minor modifications (mutations) to your code and checks that some unit tests failed because of the change. If changing the implementation did not cause any test to turn red, you may be missing coverage.

  • Fuzz testing tries to make your application crash by injecting all kinds of invalid or unexpected data. Fixing the mistakes found by fuzzing will make your code safer and more stable. For Rust, you can fuzz by combining libFuzzer (https://llvm.org/docs/LibFuzzer.html) with cargo fuzz (https://github.com/rust-fuzz/cargo-fuzz).

  • Property-based testing is popular in the functional programming world and is ideal for testing code that has certain mathematical guarantees in its contract. It generates a whole range (hundreds, thousands) of values, using these to verify that your code always upholds its guarantees. For example, for a function that sums numbers, it would generate two random values (say, xx and yy) and check whether the return value equals x+yx + y.

There are even some Rust-specific testing variants:

  • Doctests, short for documentation tests, are Rust unit tests embedded within documentation.

  • The miri interpreter can be used to check for some types of undefined behavior in your code, making your application even safer.

  • Loom is a tool for verifying the correct behavior of concurrent programs by exploring “all possible valid behaviors.”

Obviously, we cannot explore all these kinds of testing in depth. That would double the size of this book! But what kinds of tests are useful when you’re writing macros? In my opinion, integration tests that check your interaction with other systems, like APIs or databases, can be useful depending on the type of macro you are creating. For our current example (builder), unit tests are all we need. But if you are writing a macro for interacting with a database, surely you would want something beyond unit tests—something that actually puts things in a real database that’s running locally or—ideally—on a server or in the cloud. So, in another chapter, we will come back to

CHAPTER 6 Testing a builder macro

integration testing. At that time, we will also talk about documentation, so doctests will make their appearance as well.

Very few macro crates have no testing at all. Most have a couple of unit tests, and trybuild is often used for failure scenarios (e.g., by Tokio and lazy_static). Here we will discuss just two crates that are worth checking out.

The first, Rocket, is one we have encountered before in the introduction as well as in chapter 3. It is a web framework for Rust that uses macros to generate HTTP endpoints. For example, adding the macro #[get("/hello/<name>")] to a function will make it the entry point to a URL with path /hello and will pass on a path parameter called “name.” Rocket’s unit tests are black-box and located in the tests folder of the project. A large number of happy path unit tests as well as many failure scenarios use trybuild. Apart from that, separate packages even have “benchmark” tests with criterion and a fuzzing setup.

The next crate, serde (https://serde.rs/), needs no introduction. It is an extremely popular tool for serializing and deserializing data (e.g., changing raw JSON into a custom struct). One way you can tell serde to do this is by using its derive macros, one for serializing and one for deserializing. Once you’ve added those, things will “just work.” serde has a wide variety of tests. Some are white-box unit tests for simple, pure functions (the following example has been abbreviated):

#[test]
fn rename_fields() {
for &(original, upper, pascal) in &[
(
"outcome", "OUTCOME", "Outcome"
),
(
"very_tasty",
"VERY_TASTY",
"VeryTasty",
),
] {
assert_eq!(None.apply_to_field(original), original);
assert_eq!(UpperCase.apply_to_field(original), upper);
assert_eq!(PascalCase.apply_to_field(original), pascal);
}
}

But these are the exception. Most are black-box unit tests with the familiar mix of happy path and unhappy path using trybuild.

One detail you may be wondering about is what implementation these tests run against. After all, serde helps you change Rust code into something concrete like JSON. So you need some kind of implementation of serde’s traits to have an output to compare against. But testing against a real implementation is fraught with danger. It is also circular, since that dependency would itself depend on serde. Instead, serde_test contains a simple implementation that can be used to verify behavior.

See the appendix for solutions.

  1. We never did write any white-box tests for structs that actually have fields, so add one that runs against the final version of our code.

  2. We only wrote code for handling structs with named fields, not the unnamed variety, so we should cover that failure case with another trybuild compilation test.

  3. In Rocket, you can add headers to functions that make them into endpoints for calls. If you add #[get("/world")] and #[catch(404)] to a function called world, you get an error that looks like this:

error[E0428]: the name world is defined multiple times —> hello/src/main.rs:23:1 | 22 | #[get(“/world”)] | ------------------ previous definition of the type world here 23 | #[catch(404)] | ^^^^^^^^^^^^^^^ world redefined here | = note: world must be defined only once in the type namespace of this module

What could be causing this? Can you think of a way this problem might be avoided?
# Summary
- The builder pattern allows you to fluently build structs that require multiple parameters.
- By writing a macro to generate a builder, we can avoid a lot of boilerplate code.
- Unit tests are our most important tool for testing macros, and they can be divided into two categories: white-box and black-box.
- White-box unit tests “know” implementation details about the code. This allows for more in-depth testing but can also lead to brittleness and breaking on minor changes.
- Black-box tests only know what they are testing from an outside perspective. Because they are less brittle and verify the desired behavior of a macro, they are an essential check for your macro code.
- In macro code, white-box tests can be useful for tracking down tricky errors or to verify important behavior.
- If your macro communicates with external systems, some integration-level testing is probably a good idea.
- There is a large variety of other testing options available for use in Rust projects.