Chapter 11: Testing your Rust application
This introduction explains why and where to test a Rust web service, distinguishes unit and integration tests, and introduces Rust’s basic testing tools.
After this chapter you will be able to
- Testing priorities and compiler limits. Explain why a Rust web service needs tests beyond compiler checks and how to prioritize them.
- Unit and integration scope. Distinguish unit testing an isolated function from integration testing a web-service workflow, using the section’s examples.
- Self-contained business logic tests. Explain the purpose and self-contained nature of the tests introduced in this section.
- Pagination test scenarios. Describe the success and error cases to test for extract_pagination.
- Unit test setup. Describe how the section sets up unit tests for the isolated pagination function, including the missing-offset case.
- Custom error comparison. Explain why the custom errors cannot simply derive PartialEq in this example and how the test compares them instead.
- Configuration Test Cases. Describe how the section tests Config::new both when the API key is missing and when the required environment variables are set.
- Parallel Test Environment Interference. Explain why the separate configuration tests interfere and how combining them addresses the problem.
- Mocking strategy for profanity checks. Explain why the tests use a local mock server instead of replacing Reqwest with dummy logic.
- Oneshot graceful shutdown. Trace how a oneshot channel lets the tests shut down the Warp mock server gracefully.
- Profanity test lifecycle. Trace the test setup, execution, and cleanup, including how the API host is changed.
- Serverless authentication filter testing. Explain how Warp’s test module can exercise the authentication filter without starting a server and why this approach is useful.
- Token timing investigation. Trace how the intermittent authentication test led to changes in the token and Session fields.
- Shared environment test interference. Describe how the config tests interfered with the authentication test and how the section investigated the interference.
- Integration testing scope. Explain what integration testing checks in this book and describe the service environment used for it.
- Library and binary split. Explain why and how the codebase is split into a library and a binary.
- Server startup delegation. Trace how the new server.rs initializes and delegates server startup to the library.
- Oneshot server shutdown. Explain how the integration test can signal the web server to shut down using a oneshot channel.
- Integration crate library access. Describe how to set up the integration-tests crate to access the application’s server functions and modules.
- Registration integration test. Describe how the registration integration test starts the service, sends a dummy user's credentials, and signals success or failure.
- Isolated test database. Describe why the integration tests need a separate database and how the section sets it up for each run.
- Integration Test Failure Cleanup. Explain why the integration-test application must handle failure cleanup itself and what it does when a test fails.
- Catching Unwinding Panics. Describe unwinding and how the integration test uses AssertUnwindSafe and futures_util::catch_unwind to catch a panic while polling its future.
- Route and failure testing. Describe what the tests verify for registration, login, and question creation, and how to check a failure such as creating a question without a token.
What it builds on
- Parsing query parameters (chapter 4) · The application’s pagination query-parameter logic.
- Adding the login endpoint (chapter 9) · The login endpoint used as a workflow example.
- Read and parse environment variables into your web service (chapter 10) · Reading environment variables into the web service
- Refactoring the add_question route handler (chapter 8) · The profanity check used when adding a question.
Section by section
Introduction
This introduction explains why and where to test a Rust web service, distinguishes unit and integration tests, and introduces Rust’s basic testing tools.
- Testing priorities and compiler limits: Explain why a Rust web service needs tests beyond compiler checks and how to prioritize them.
Why it matters: Compiler guarantees do not tell you whether your service behaves correctly for its users. - Unit and integration scope: Distinguish unit testing an isolated function from integration testing a web-service workflow, using the section’s examples.
Why it matters: The two test scopes help you check both individual logic and complete user-facing workflows. - Rust built-in testing tools: Describe the basic Rust tools introduced for running and writing tests, and the section’s advice about extra crates.
Why it matters: These tools let you start testing without immediately adding dependencies.
Key terms: business logic, critical workflow, side effects, codebase coverage, unit testing, integration testing, black box, Pagination, Error, Cargo
11.1 Unit testing our business logic
The section introduces self-contained tests as a way to check that business logic behaves as expected.
- Self-contained business logic tests: Explain the purpose and self-contained nature of the tests introduced in this section.
Why it matters: Self-contained tests help you check whether the application's business logic behaves as intended.
Key terms: self-contained tests, business logic
11.1.1 Testing the pagination logic and dealing with custom errors
This section develops unit tests for pagination behavior and shows how to compare custom errors when deriving PartialEq fails.
- Pagination test scenarios: Describe the success and error cases to test for extract_pagination.
Why it matters: These cases define the behaviors the pagination unit tests need to check. - Unit test setup: Describe how the section sets up unit tests for the isolated pagination function, including the missing-offset case.
Why it matters: A small isolated function makes it straightforward to construct inputs and check expected behavior. - Custom error comparison: Explain why the custom errors cannot simply derive PartialEq in this example and how the test compares them instead.
Why it matters: This provides a way to check the expected error despite the automatic trait derivation failing.
Key terms: extract_pagination, Pagination, MissingParameters, ParseError, limit, offset, unit tests, test module, assert_eq!, PartialEq
11.1.2 Testing the Config module with environment variables
This section tests configuration loading and resolves interference between tests that modify environment variables.
- Configuration Environment Loading: Explain why dotenv loading is moved from Config::new to the server’s main function.
Why it matters: Separating environment loading from configuration creation makes the tests easier to control. - Configuration Test Cases: Describe how the section tests Config::new both when the API key is missing and when the required environment variables are set.
Why it matters: Testing both failure and success shows whether configuration creation responds correctly to its environment. - Parallel Test Environment Interference: Explain why the separate configuration tests interfere and how combining them addresses the problem.
Why it matters: Understanding shared environment state helps explain why tests can fail when run together even if each case appears reasonable.
Key terms: dotenv, Config::new, .env, env::var, catch_unwind, assert!(result.is_err()), API key, parallel tests, environment variables, set_api_key
11.1.3 Testing the profanity module with a newly created mock server
This section tests the profanity checker using a configurable local mock server with predefined responses and a oneshot channel for graceful shutdown.
- Mocking strategy for profanity checks: Explain why the tests use a local mock server instead of replacing Reqwest with dummy logic.
Why it matters: This approach lets you control external responses while still exercising the real client code. - Mock endpoint compatibility: Describe how the mock server imitates the profanity API's request interface and supplies test responses.
Why it matters: Matching the API's request shape lets the real client use the mock without changing its request logic. - Oneshot graceful shutdown: Trace how a oneshot channel lets the tests shut down the Warp mock server gracefully.
Why it matters: A test-controlled shutdown prevents the mock server from being left running after the test. - Profanity test lifecycle: Trace the test setup, execution, and cleanup, including how the API host is changed.
Why it matters: The sequence makes the real checker use controlled responses and cleans up the server afterward.
Key terms: check_profanity, Reqwest, mock server, predefined responses, route, query parameter, raw body, bytes, bind_with_graceful_shutdown, oneshot channel
11.2 Testing our Warp filters
This section tests a Warp authentication filter without a server and traces intermittent failures to token timing and shared environment-variable changes.
- Serverless authentication filter testing: Explain how Warp’s test module can exercise the authentication filter without starting a server and why this approach is useful.
Why it matters: You can test a security-critical filter without running a whole server. - Token timing investigation: Trace how the intermittent authentication test led to changes in the token and Session fields.
Why it matters: The investigation shows how a flaky test can expose a mismatch between token creation and verification. - Shared environment test interference: Describe how the config tests interfered with the authentication test and how the section investigated the interference.
Why it matters: Tests that alter shared configuration can make other tests fail intermittently.
Key terms: authentication filter, Authorization header, warp::test, auth middleware, set_not_before, Utc::now, Session, nbf, Serde, config tests
11.3 Creating an integration testing setup
Defines the book’s integration-testing scope and presents environment options for testing the web service.
- Integration testing scope: Explain what integration testing checks in this book and describe the service environment used for it.
Why it matters: This gives you a concrete target for testing how the application’s pieces work together. - Integration testing environment options: Describe the available environment approaches and the local project arrangement chosen in the book.
Why it matters: The test environment can be organized in different ways depending on the development environment.
Key terms: integration testing, local database, mocking, external API endpoints, Docker environment, local setup, Cargo project, integration tests
11.3.1 Splitting up the codebase into a lib.rs and a binary
This section restructures the application into a reusable library and an executable server, preparing it for integration testing.
- Library and binary split: Explain why and how the codebase is split into a library and a binary.
Why it matters: The split lets tests reuse application code without giving up the runnable server. - Server startup delegation: Trace how the new server.rs initializes and delegates server startup to the library.
Why it matters: This startup sequence shows how the executable uses the reusable library. - Internal library module imports: Describe how imports inside the library change after the rename.
Why it matters: Updating internal imports keeps the reorganized library's modules accessible to one another.
Key terms: lib.rs, binary, public functions, integration-test project, server.rs, dotenv, config, setup_store, run, rust_web_dev
11.3.2 Creating the integration-test crate and the oneshot server implementation
This section prepares a separate integration-test crate and a controllable web server for integration testing.
- Oneshot server shutdown: Explain how the integration test can signal the web server to shut down using a oneshot channel.
Why it matters: Integration tests need a way to control the server they exercise. - Integration crate library access: Describe how to set up the integration-tests crate to access the application’s server functions and modules.
Why it matters: The separate test crate must be able to use application code to create its server. - Integration environment file location: Explain why the project’s .env file is copied into the integration-tests crate.
Why it matters: The test setup needs its environment file where the helper will look for it.
Key terms: oneshot channel, OneshotHandler, sender, integration-tests crate, Cargo.toml, rust-web-dev library, config module, handle_errors module, pub, .env file
11.3.3 Adding the registration test
This section builds a registration integration test and resolves its JSON-response and test-database problems.
- Registration integration test: Describe how the registration integration test starts the service, sends a dummy user's credentials, and signals success or failure.
Why it matters: This test checks account creation through a real HTTP request to the running service. - Registration response JSON: Explain why the registration response could not be parsed as JSON and how the section fixes it.
Why it matters: The integration test needs a response it can parse as JSON. - Isolated test database: Describe why the integration tests need a separate database and how the section sets it up for each run.
Why it matters: A fresh, separate database prevents leftover accounts from interfering with registration tests.
Key terms: oneshot, register_new_user, Reqwest, assert_eq!, warp::reply::json(), JSON, test database, .env, Command builder, cargo run
11.3.4 Unwinding in case of an error
This section explains how the integration-test application catches unwinding panics and cleans up after a test failure.
- Integration Test Failure Cleanup: Explain why the integration-test application must handle failure cleanup itself and what it does when a test fails.
Why it matters: Explicit cleanup prevents a failing integration test from leaving the mock server running. - Catching Unwinding Panics: Describe unwinding and how the integration test uses AssertUnwindSafe and futures_util::catch_unwind to catch a panic while polling its future.
Why it matters: Catching an unwinding panic lets the test application handle the failure and clean up.
Key terms: integration-tests, mock server, register_new_user, unwinding, AssertUnwindSafe, catch_unwind, futures_util, future, panic
11.3.5 Testing the login and posting questions
The section completes the route-testing example, suggests negative tests, and reflects on code improvements made during testing.
- Route and failure testing: Describe what the tests verify for registration, login, and question creation, and how to check a failure such as creating a question without a token.
Why it matters: Testing both successful routes and expected errors helps verify the service's behavior. - Testing driven code improvements: Explain how testing revealed problems and prompted changes to the codebase.
Why it matters: Testing can improve the structure of the code as well as verify its behavior.
Key terms: registration, login, assert macro, error code, store, routes, JSON
11.4 Summary
Concepts explained in this chapter
- integration testIntegration testing evaluates whether interacting parts of a software system work together as expected.
- software testingSoftware testing is the process of evaluating software to find defects and verify expected behavior.
- environment variableAn environment variable is a named value supplied by a process's environment that programs can read to configure behavior.
- mock serverA mock server is a server that simulates an application's behavior for testing.
- assert_eqassert_eq! is a Rust macro that checks whether two expressions are equal and panics if they are not.
- parallel test executionParallel test execution runs multiple software tests concurrently rather than one after another.
- warp::testwarp::test is a Warp module providing utilities for testing filters and requests without starting a server.
- partialeqPartialEq is a Rust trait for types whose values can be compared for equality, without requiring a full equivalence relation.
- library crateA library crate is a Rust crate that provides functionality through a public interface rather than creating an executable.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
