Crate reqwest_mock

Source
Expand description

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()
    }
}

Re-exports§

pub use self::error::Error;
pub use self::client::*;

Modules§

client
Defines the main types to be used to mock the HTTP client.
config
Some types used to configure a Client instance.
error
Defines the Error type we use in this library (error-chain).
header
HTTP header types

Structs§

Body
A HTTP request body.
Method
The Request Method (VERB)
StatusCode
An HTTP status code (status-code in RFC 7230 et al.).
Url
A parsed URL record.

Enums§

UrlError
Errors that can occur during parsing.

Traits§

IntoUrl
A trait to try to convert some type into a Url.