#http #test #testing #mock #fake

dev httptest

HTTP testing facilities including a mock server

39 releases

0.15.4 Nov 22, 2021
0.15.2 Mar 21, 2021
0.14.0 Dec 24, 2020
0.13.2 Sep 29, 2020
0.5.3 Dec 19, 2019

#16 in Testing

Download history 4295/week @ 2022-03-10 4403/week @ 2022-03-17 4383/week @ 2022-03-24 4242/week @ 2022-03-31 3909/week @ 2022-04-07 4339/week @ 2022-04-14 4752/week @ 2022-04-21 5530/week @ 2022-04-28 5130/week @ 2022-05-05 6307/week @ 2022-05-12 5531/week @ 2022-05-19 4624/week @ 2022-05-26 7192/week @ 2022-06-02 5356/week @ 2022-06-09 6317/week @ 2022-06-16 5565/week @ 2022-06-23

25,295 downloads per month
Used in fewer than 15 crates

MIT/Apache

84KB
1.5K SLoC

httptest

Provide convenient mechanism for testing http clients against a locally running http server. The typical usage is as follows:

  • Start a server
  • Configure the server by adding expectations
  • Test your http client by making requests to the server
  • On Drop the server verifies all expectations were met.

Example Test

#[tokio::test]
async fn test_readme() {
    use httptest::{mappers::*, responders::*, Expectation, Server};
    use serde_json::json;
    // Starting a logger within the test can make debugging a failed test
    // easier. The mock http server will log::debug every request and response
    // received along with what, if any, matcher was found for the request. When
    // env_logger is initialized running the test with `RUST_LOG=httptest=debug
    // cargo test` can provide that information on stderr.
    let _ = pretty_env_logger::try_init();
    // Start a server running on a local ephemeral port.
    let server = Server::run();
    // Configure the server to expect a single GET /foo request and respond
    // with a 200 status code.
    server.expect(
        Expectation::matching(request::method_path("GET", "/foo")).respond_with(status_code(200)),
    );
    // Configure the server to also receive between 1 and 3 POST /bar requests
    // with a json body matching {'foo': 'bar'}, and respond with a json body
    // {'result': 'success'}
    server.expect(
        Expectation::matching(all_of![
            request::method("POST"),
            request::path("/bar"),
            request::body(json_decoded(eq(json!({"foo": "bar"})))),
        ])
        .times(1..=3)
        .respond_with(json_encoded(json!({"result": "success"}))),
    );

    // The server provides server.addr() that returns the address of the
    // locally running server, or more conveniently provides a server.url()
    // method that gives a fully formed http url to the provided path.
    let url = server.url("/foo");

    // Now test your http client against the server.
    let client = hyper::Client::new();
    // Issue the GET /foo to the server.
    let resp = client.get(url).await.unwrap();
    // Optionally use response matchers to assert the server responded as
    // expected.

    // Assert the response was a 200.
    assert_eq!(200, resp.status().as_u16());

    // Issue a POST /bar with {'foo': 'bar'} json body.
    let post_req = http::Request::post(server.url("/bar"))
        .body(json!({"foo": "bar"}).to_string().into())
        .unwrap();
    // Read the entire response body into a Vec<u8> to allow using the body
    // response matcher.
    let resp = read_response_body(client.request(post_req)).await;
    // Assert the response was a 200 with a json body of {'result': 'success'}
    assert_eq!(200, resp.status().as_u16());
    assert_eq!(
        json!({"result": "success"}),
        serde_json::from_slice::<serde_json::Value>(resp.body()).unwrap()
    );

    // on Drop the server will assert all expectations have been met and will
    // panic if not.
}

Dependencies

~8–15MB
~280K SLoC