ugi 0.2.1

Runtime-agnostic Rust request client with HTTP/1.1, HTTP/2, HTTP/3, H2C, WebSocket, SSE, and gRPC support
Documentation
use futures_lite::future::block_on;
use httpmock::prelude::*;
use serde_json::json;
use ugi::{Client, RedirectPolicy, Version, get};

fn run<T>(value: T) -> T::Output
where
    T: std::future::IntoFuture,
{
    block_on(async move { value.await })
}

#[test]
fn httpmock_json_roundtrip_works() {
    let server = MockServer::start();
    let payload = json!({ "name": "Ada" });
    let reply = json!({ "message": "hello Ada" });

    let mock = server.mock(|when, then| {
        when.method(POST)
            .path("/json")
            .header("content-type", "application/json")
            .body(payload.to_string());
        then.status(200)
            .header("content-type", "application/json")
            .body(reply.to_string());
    });

    let client = Client::builder().build().unwrap();
    let response =
        block_on(async { client.post(server.url("/json")).json(&payload)?.await }).unwrap();

    let body = block_on(response.json::<serde_json::Value>()).unwrap();
    assert_eq!(body, reply);
    mock.assert();
}

#[test]
fn httpmock_redirects_follow_public_api() {
    let server = MockServer::start();

    let start = server.mock(|when, then| {
        when.method(GET).path("/start");
        then.status(302).header("location", "/final");
    });
    let final_mock = server.mock(|when, then| {
        when.method(GET).path("/final");
        then.status(200).body("ok");
    });

    let client = Client::builder()
        .redirect(RedirectPolicy::Limit(5))
        .build()
        .unwrap();
    let response = run(client.get(server.url("/start"))).unwrap();

    assert_eq!(block_on(response.text()).unwrap(), "ok");
    start.assert();
    final_mock.assert();
}

#[test]
fn httpmock_prefer_http3_falls_back_to_http1_for_http_urls() {
    let server = MockServer::start();

    let mock = server.mock(|when, then| {
        when.method(GET).path("/fallback");
        then.status(200).body("fallback-ok");
    });

    let response = run(get(server.url("/fallback")).prefer_http3()).unwrap();

    assert_eq!(response.version(), Version::Http11);
    assert_eq!(block_on(response.text()).unwrap(), "fallback-ok");
    mock.assert();
}