Top 10 Rust Libraries for Working with Testing

Are you a Rust developer looking for the best libraries to help you with testing? Look no further! We've compiled a list of the top 10 Rust libraries for working with testing. These libraries will help you write better tests, automate your testing process, and make your code more reliable.

1. assert_approx_eq!

Have you ever had to compare floating-point numbers in your tests? It can be tricky to get the precision just right. That's where assert_approx_eq! comes in. This macro allows you to compare floating-point numbers with a certain degree of tolerance.

assert_approx_eq!(a, b, epsilon = 0.001);

2. mockito

Testing HTTP clients can be a pain. You need to set up a server, write handlers for each endpoint, and make sure everything is working correctly. mockito simplifies this process by allowing you to mock HTTP requests and responses.

let m = mock("GET", "/hello")
    .with_status(200)
    .with_header("content-type", "text/plain")
    .with_body("hello, world!")
    .create();

let response = reqwest::get(&format!("{}/hello", &m.url()))
    .await
    .unwrap();

assert_eq!(response.status(), 200);
assert_eq!(response.text().await.unwrap(), "hello, world!");

3. proptest

Writing property-based tests can be a powerful way to find edge cases in your code. proptest is a property testing framework for Rust that allows you to generate random inputs for your tests.

use proptest::prelude::*;

proptest! {
    #[test]
    fn test_reverse(s in "\\PC*") {
        let rev: String = s.chars().rev().collect();
        assert_eq!(rev.chars().rev().collect::<String>(), s);
    }
}

4. rustache

Testing templates can be a pain. You need to set up a context, render the template, and compare the output to the expected result. rustache simplifies this process by allowing you to write tests that use templates and context data.

use rustache::{HashBuilder, Render};

#[test]
fn test_template() {
    let template = "Hello, {{name}}!";
    let data = HashBuilder::new().insert("name", "world").build();
    let result = Render::new().render(template, &data).unwrap();
    assert_eq!(result, "Hello, world!");
}

5. serial_test

Do your tests depend on a shared resource, like a database or network connection? serial_test allows you to run tests serially, ensuring that only one test is running at a time.

#[serial]
#[test]
fn test_database() {
    // connect to database
    // run test
}

#[serial]
#[test]
fn test_network() {
    // connect to network
    // run test
}

6. spectral

Do you want to ensure that your API responses conform to a certain schema? spectral is a library for testing JSON and YAML documents against OpenAPI specifications.

use spectral::prelude::*;

#[test]
fn test_response() {
    let response = reqwest::get("https://api.example.com/users").await.unwrap();
    let body = response.text().await.unwrap();
    let schema = include_str!("users.yaml");
    assert_that(&body).is_valid_against_schema_string(schema);
}

7. tempfile

Do your tests need to create temporary files or directories? tempfile allows you to create temporary files and directories that are automatically cleaned up when the test finishes.

use tempfile::tempdir;

#[test]
fn test_file() {
    let dir = tempdir().unwrap();
    let file_path = dir.path().join("test.txt");
    let mut file = File::create(&file_path).unwrap();
    file.write_all(b"hello, world!").unwrap();
    assert_eq!(file_path.exists(), true);
}

8. test-generator

Do you have a lot of similar tests that differ only in their input data? test-generator allows you to generate tests programmatically.

use test_generator::test_resources;

#[test_resources("data/*.json")]
fn test_json(data: &str) {
    let value: serde_json::Value = serde_json::from_str(data).unwrap();
    assert_eq!(value["name"], "John Doe");
}

9. tokio-test

Do your tests use asynchronous code? tokio-test provides utilities for testing asynchronous code with the tokio runtime.

use tokio_test::assert_pending;

#[test]
async fn test_async() {
    let future = async {
        // do some async work
    };
    assert_pending!(future);
}

10. walkdir

Do your tests need to traverse a directory tree? walkdir allows you to recursively traverse a directory tree and perform actions on each file or directory.

use walkdir::WalkDir;

#[test]
fn test_directory() {
    for entry in WalkDir::new("path/to/directory") {
        let entry = entry.unwrap();
        if entry.file_type().is_file() {
            // test file
        }
    }
}

Conclusion

Testing is an important part of software development, and Rust provides a rich ecosystem of libraries to help you write better tests. Whether you need to compare floating-point numbers, mock HTTP requests, or generate random inputs, there's a library out there for you. We hope this list has been helpful in finding the right libraries for your testing needs. Happy testing!

Additional Resources

mlsec.dev - machine learning security
labeleddata.dev - machine learning pre-labeled data sources and sites, about labeling automation and labeling third party services
shareknowledge.app - sharing knowledge related to software engineering and cloud
networksimulation.dev - network optimization graph problems
lakehouse.app - lakehouse the evolution of datalake, where all data is centralized and query-able but with strong governance
dartbook.dev - A site dedicated to learning the dart programming language, digital book, ebook
dsls.dev - domain specific languages, dsl, showcasting different dsls, and offering tutorials
devops.management - devops, and tools to manage devops and devsecops deployment
defimarket.dev - the defi crypto space
rustbook.dev - An online course or book about programming the rust programming language, and everything related to the software development lifecyle in rust
jimmyruska.com - Jimmy Ruska
dataintegration.dev - data integration across various sources, formats, databases, cloud providers and on-prem
changelog.cloud - software and cloud logging, application logging, software logging, cloud logs
mlwriting.com - machine learning writing, copywriting, creative writing
blockchainjobs.page - A jobs board for blockchain jobs
babysit.app - A service and app for finding a babysitter or applying to babysit
mlplatform.dev - machine learning platforms, comparisons and differences, benefits and costs
antipatterns.dev - lessons learned, best practice, common mistakes, and what to avoid in software engineering
knowledgemanagement.community - knowledge management and learning, structured learning, journals, note taking, flashcards and quizzes
learnnlp.dev - learning NLP, natural language processing engineering


Written by AI researcher, Haskell Ruska, PhD (haskellr@mit.edu). Scientific Journal of AI 2023, Peer Reviewed