#http #request #client

reqwest_mock

Provides a mockable reqwest-like HTTP client

8 releases (5 breaking)

0.6.0 Jul 15, 2019
0.5.0 Apr 14, 2018
0.4.0 Feb 5, 2018
0.3.2 Nov 25, 2017
0.1.0 Jun 6, 2017

#8 in #request

Download history 35/week @ 2019-07-06 21/week @ 2019-07-13 3/week @ 2019-07-20 12/week @ 2019-07-27 8/week @ 2019-08-03 11/week @ 2019-08-10 4/week @ 2019-08-17 155/week @ 2019-08-24 40/week @ 2019-08-31 35/week @ 2019-09-07 3/week @ 2019-09-14 92/week @ 2019-09-21 11/week @ 2019-09-28 16/week @ 2019-10-05 8/week @ 2019-10-12

95 downloads per month
Used in 1 crate

Apache-2.0

55KB
1K SLoC

reqwest_mock

crates.io Docs Build Status

Provides a mockable reqwest-like HTTP client.

Write your code generic over the Client trait, and in production use DirectClient while in testing you can use ReplayClient, which will record a request the first time and replay it every time the exact same request is made in the future.

Examples

use reqwest_mock::{Client, DirectClient, ReplayClient, Error};
use reqwest_mock::header::UserAgent;

struct MyClient<C: Client> {
    client: C,
}

fn new_client() -> MyClient<DirectClient> {
    MyClient {
        client: DirectClient::new()
    }
}

#[cfg(test)]
fn test_client(path: &str) -> MyClient<ReplayClient> {
    MyClient {
        client: ReplayClient::new(path)
    }
}

impl<C: Client> MyClient<C> {
    /// For simplicity's sake we are not parsing the response but just extracting the
    /// response body.
    /// Also in your own code it might be a good idea to define your own `Error` type.
    pub fn get_time(&self) -> Result<String, Error> {
        let response = self.client
            .get("https://now.httpbin.org/")
            .header(UserAgent("MyClient".to_string()))
            .send()?;

        response.body_to_utf8()
    }
}

Dependencies

~15MB
~378K SLoC