• Stars
    star
    618
  • Rank 72,605 (Top 2 %)
  • Language
    Rust
  • License
    Apache License 2.0
  • Created over 4 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

HTTP mocking to test Rust applications.

wiremock

HTTP mocking to test Rust applications.


wiremock provides HTTP mocking to perform black-box testing of Rust applications that interact with third-party APIs.

It provides mocking of HTTP responses using request matching and response templating.

The name wiremock is a reference to WireMock.Net, a .NET port of the original Wiremock from Java.

Table of Contents

  1. How to install
  2. Getting started
  3. Matchers
  4. Spying
  5. Responses
  6. Test isolation
  7. Runtime compatibility
  8. Efficiency
  9. Prior art
  10. Future evolution
  11. Related projects
  12. License

How to install

Add wiremock to your development dependencies by editing the Cargo.toml file:

[dev-dependencies]
# ...
wiremock = "0.5"

Or by running:

cargo add wiremock --dev

Getting started

use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::{method, path};

#[async_std::main]
async fn main() {
    // Start a background HTTP server on a random local port
    let mock_server = MockServer::start().await;

    // Arrange the behaviour of the MockServer adding a Mock:
    // when it receives a GET request on '/hello' it will respond with a 200.
    Mock::given(method("GET"))
        .and(path("/hello"))
        .respond_with(ResponseTemplate::new(200))
        // Mounting the mock on the mock server - it's now effective!
        .mount(&mock_server)
        .await;

    // If we probe the MockServer using any HTTP client it behaves as expected.
    let status = surf::get(format!("{}/hello", &mock_server.uri()))
        .await
        .unwrap()
        .status();
    assert_eq!(status.as_u16(), 200);

    // If the request doesn't match any `Mock` mounted on our `MockServer` a 404 is returned.
    let status = surf::get(format!("{}/missing", &mock_server.uri()))
        .await
        .unwrap()
        .status();
    assert_eq!(status.as_u16(), 404);
}

Matchers

wiremock provides a set of matching strategies out of the box - check the matchers module for a complete list.

You can define your own matchers using the Match trait, as well as using Fn closures. Check Match's documentation for more details and examples.

Spying

wiremock empowers you to set expectations on the number of invocations to your Mocks - check the expect method for more details.

Expectations can be used to verify that a side-effect has (or has not) taken place!

Expectations are automatically verified during the shutdown of each MockServer instance, at the end of your test. A failed verification will trigger a panic. By default, no expectations are set on your Mocks.

Responses

wiremock lets you specify pre-determined responses using ResponseTemplate and respond_with.

You are also given the option to have Mocks return different responses based on the matched Request using the Respond trait. Check Respond's documentation for more details and examples.

Test isolation

Each instance of MockServer is fully isolated: start takes care of finding a random port available on your local machine which is assigned to the new MockServer.

To ensure full isolation and no cross-test interference, MockServers shouldn't be shared between tests. Instead, MockServers should be created in the test where they are used.

When a MockServer instance goes out of scope (e.g. the test finishes), the corresponding HTTP server running in the background is shut down to free up the port it was using.

Runtime compatibility

wiremock can be used (and it is tested to work) with both async_std and tokio as futures runtimes. If you encounter any compatibility bug, please open an issue on our GitHub repository.

Efficiency

wiremock maintains a pool of mock servers in the background to minimise the number of connections and the time spent starting up a new MockServer. Pooling reduces the likelihood of you having to tune your OS configurations (e.g. ulimit).

The pool is designed to be invisible: it makes your life easier and your tests faster. If you end up having to worry about it, it's a bug: open an issue!

Prior art

mockito and httpmock provide HTTP mocking for Rust.

Check the table below to see how wiremock compares to them across the following dimensions:

  • Test execution strategy (do tests have to be executed sequentially or can they be executed in parallel?);
  • How many APIs can I mock in a test?
  • Out-of-the-box request matchers;
  • Extensible request matching (i.e. you can define your own matchers);
  • Sync/Async API;
  • Spying (e.g. verify that a mock has/hasn't been called in a test);
  • Standalone mode (i.e. can I launch an HTTP mock server outside of a test suite?).
Test execution strategy How many APIs can I mock? Out-of-the-box request matchers Extensible request matching API Spying Standalone mode
mockito ✔ Parallel ✔ Unbounded Async/Sync
httpmock ✔ Parallel ✔ Unbounded Async/Sync
wiremock ✔ Parallel ️ ✔ Unbounded Async

Future evolution

More request matchers can be added to those provided out-of-the-box to handle common usecases.

Related projects

License

Licensed under either of Apache License, Version 2.0 or MIT license at your option. Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

More Repositories

1

zero-to-production

Code for "Zero To Production In Rust", a book on API development using Rust.
Rust
5,631
star
2

pavex

An easy-to-use Rust framework for building robust and performant APIs
Rust
1,707
star
3

cargo-chef

A cargo-subcommand to speed up Rust Docker builds using Docker layer caching.
Rust
1,706
star
4

build-your-own-jira-with-rust

A test-driven workshop to learn Rust building your own JIRA clone!
Rust
937
star
5

tracing-actix-web

Structured logging for actix-web applications.
Rust
229
star
6

ndarray-koans

Material for "ML Introduction to ndarray" workshop at RustFest 2019.
Jupyter Notebook
110
star
7

biscotti

A Rust library for managing HTTP cookies.
Rust
109
star
8

bunyan

A CLI to pretty print logs in bunyan format. A Rust port of the original JavaScript bunyan CLI.
Rust
92
star
9

tracing-bunyan-formatter

A Layer implementation for tokio-rs/tracing providing Bunyan formatting for events and spans.
Rust
82
star
10

cargo-px

A cargo subcommand that extends cargo's capabilities when it comes to code generation.
Rust
50
star
11

actix-web-flash-messages

A (flash) message framework for actix-web. A port to Rust of Django's message framework.
Rust
46
star
12

multipeek

An iterator adapter to peek at future elements without advancing the cursor of the underlying iterator.
Rust
26
star
13

clustering-benchmarks

Benchmarks `linfa` against `scikit-learn` on a clustering task.
Jupyter Notebook
25
star
14

tracing-panic

A custom panic hook to capture panic info in your telemetry pipeline
Rust
18
star
15

cargo-manifest

Fork to fix some serialization issues.
Rust
12
star
16

jlox-rs

A Rust version of the jlox interpreter from the "Crafting Interpreters" book.
Rust
9
star
17

cargo-like-utils

A collection of utils (shell, styling, locking) to write CLIs that behave similarly to `cargo`
Rust
5
star
18

pavex-project-template

A starter template for a new Pavex project
Rust
3
star
19

LukeMathWalker

2
star
20

reqwest-timeout-minimum-reproducible-example

Minimal reproducible example for a timeout issue with reqwest.
Rust
2
star
21

lukemathwalker.github.io

Personal website.
HTML
1
star
22

iaml-iwildcam2019

Python
1
star
23

tracing-min

Minimum example to reproduce core dump.
Rust
1
star
24

actix-web-minimal-error-example

A minimal reproducible example of issues with actix-web's error handling logic.
Rust
1
star