#http #request #client

reqwest_mock

Provides a mockable reqwest-like HTTP client

9 releases (breaking)

0.7.0 May 14, 2020
0.6.0 Jul 15, 2019
0.5.0 Apr 14, 2018
0.4.0 Feb 5, 2018
0.1.0 Jun 6, 2017

#156 in Web programming

Download history 34/week @ 2020-03-18 9/week @ 2020-03-25 1/week @ 2020-04-01 36/week @ 2020-04-08 27/week @ 2020-04-15 10/week @ 2020-04-22 22/week @ 2020-04-29 63/week @ 2020-05-13 13/week @ 2020-05-20 38/week @ 2020-05-27 24/week @ 2020-06-03 5/week @ 2020-06-10 11/week @ 2020-06-17 3/week @ 2020-06-24 19/week @ 2020-07-01

67 downloads per month
Used in rs621

Apache-2.0

58KB
1.5K 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.


lib.rs:

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::USER_AGENT;

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(USER_AGENT, "MyClient".parse().unwrap())
            .send()?;

        response.body_to_utf8()
    }
}

Dependencies

~3.5–7MB
~165K SLoC