7 Testing your Rust integrations

 

This chapter covers

  • Writing automated tests in Rust
  • Testing Rust code from a dynamic language
  • Reusing existing tests using monkey patching
  • Testing new code against old code with randomized inputs

When shipping large refactors, it is important to validate that the code will behave as expected. Some form of automated testing is generally considered best practice across the industry. In this chapter, we will create automated tests for the JSON summing code that we wrote in the last chapter. Let’s get started by adding some unit tests to our Rust code.

7.1 Writing tests with Rust

Rust has a minimal testing system built into the language itself. You may recall a brief mention of it from chapter 3. As we discussed in chapter 2, beginning a new Rust application will automatically create a “Hello world!” program for you. When we create a blank library, we similarly are presented with automated test scaffolding. Let’s create a blank library crate called testing to play around with some tests before we apply what we learn to the JSON library:

$ cargo new --lib testing

Now, open testing/src/lib.rs, and look at the prebuilt test code that we get from Cargo.

Listing 7.1 Contents of a newly initialized Rust library
#[cfg(test)]
mod tests {
  #[test]
  fn it_works() {
    let result = 2 + 2;
    assert_eq!(result, 4);
  }
}

7.1.1 Documentation tests

7.1.2 Adding tests to existing code

7.2 Testing Rust code using Python

7.2.1 Monkey patching

Summary