use std::collections::BTreeMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use std::time::Duration;
use axum::Json;
use axum::body::Bytes;
use axum::http::{HeaderMap, Method, StatusCode, Uri};
use axum::routing::{any, get};
use laravel::Application;
use laravel::config::Env;
use laravel::http::client::{self, Backoff, Client, Error, Request};
use laravel::http::sse::EventStream;
use laravel::stream::StreamExt;
use laravel::testing::MakesHttpRequests;
use laravel::time::ToSpan;
use serde_json::{Value, json};
pub(crate) async fn serve(router: axum::Router) -> String {
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let address = listener.local_addr().unwrap();
tokio::spawn(async move { axum::serve(listener, router).await.unwrap() });
format!("http://{address}")
}
async fn server() -> (String, Arc<AtomicUsize>) {
let hits = Arc::new(AtomicUsize::new(0));
let flaky = Arc::clone(&hits);
let router = axum::Router::new()
.route(
"/slow",
get(|| async { tokio::time::sleep(Duration::from_secs(5)).await }),
)
.route("/not-modified", get(|| async { StatusCode::NOT_MODIFIED }))
.route(
"/trickle",
get(|| async { body_of(&["one\n", "two\n", "three\n", "four\n"], 100) }),
)
.route("/stalls", get(|| async { body_of(&["first\n", "never\n"], 2_000) }))
.route(
"/completions",
any(|| async {
(
[("content-type", "text/event-stream")],
body_of(
&[
"data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n",
": keep-alive\n\ndata: {\"choices\":[{\"delta\":",
"{\"content\":\"lo!\"}}]}\n\n",
"data: [DONE]\n\n",
],
50,
),
)
}),
)
.route(
"/sleepy",
get(|| async { tokio::time::sleep(Duration::from_millis(300)).await }),
)
.route(
"/flaky",
get(move || {
let hits = flaky.fetch_add(1, Ordering::SeqCst) + 1;
async move {
match hits {
1 | 2 => (StatusCode::SERVICE_UNAVAILABLE, "try again"),
_ => (StatusCode::OK, "finally"),
}
}
}),
)
.route(
"/missing",
get(|| async { (StatusCode::NOT_FOUND, Json(json!({ "message": "Not found" }))) }),
)
.route("/{*path}", any(echo));
(serve(router).await, hits)
}
fn body_of(chunks: &'static [&'static str], delay_ms: u64) -> axum::body::Body {
let state = (chunks.iter().copied(), true);
let stream = futures_util::stream::unfold(state, move |(mut chunks, first)| async move {
let chunk = chunks.next()?;
if !first {
tokio::time::sleep(Duration::from_millis(delay_ms)).await;
}
Some((
Ok::<_, std::convert::Infallible>(Bytes::from_static(chunk.as_bytes())),
(chunks, false),
))
});
axum::body::Body::from_stream(stream)
}
async fn echo(method: Method, uri: Uri, headers: HeaderMap, body: Bytes) -> Json<Value> {
let header = |name: &str| headers.get(name).map(|value| value.to_str().unwrap().to_owned());
Json(json!({
"method": method.as_str(),
"path": uri.path(),
"query": uri.query(),
"content_type": header("content-type"),
"content_length": header("content-length"),
"accept": header("accept"),
"authorization": header("authorization"),
"user_agent": header("user-agent"),
"tenant": header("x-tenant"),
"body": String::from_utf8_lossy(&body),
}))
}
fn application() -> Application {
Application::configure().replace_env(Env::default()).create()
}
#[tokio::test]
async fn requests_send_their_json_bodies_query_and_headers() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let response = client::base_url(format!("{url}/api/"))
.token("secret")
.accept_json()
.post("/users?source=test")
.query([("page", "2"), ("name", "Taylor Otwell")])
.json(json!({ "name": "Taylor" }))
.await
.unwrap();
assert!(response.successful());
assert_eq!(response.header("content-type"), Some("application/json"));
let echoed: Value = response.json().unwrap();
assert_eq!(echoed["method"], "POST");
assert_eq!(echoed["path"], "/api/users");
assert_eq!(echoed["query"], "source=test&page=2&name=Taylor+Otwell");
assert_eq!(echoed["content_type"], "application/json");
assert_eq!(echoed["accept"], "application/json");
assert_eq!(echoed["authorization"], "Bearer secret");
assert_eq!(echoed["user_agent"], format!("Laravel-Rust/{}", laravel::VERSION));
assert_eq!(echoed["body"], r#"{"name":"Taylor"}"#);
})
.await;
}
#[tokio::test]
async fn requests_send_forms_raw_bodies_and_basic_credentials() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let form: Value = client::put(format!("{url}/form"))
.basic_auth("taylor@laravel.com", "secret")
.user_agent("Acme/1.0")
.form([("name", "Sara"), ("role", "Privacy Consultant")])
.await
.unwrap()
.json()
.unwrap();
assert_eq!(form["method"], "PUT");
assert_eq!(form["content_type"], "application/x-www-form-urlencoded");
assert_eq!(form["body"], "name=Sara&role=Privacy+Consultant");
assert_eq!(form["authorization"], "Basic dGF5bG9yQGxhcmF2ZWwuY29tOnNlY3JldA==");
assert_eq!(form["user_agent"], "Acme/1.0");
let raw: Value = client::patch(format!("{url}/photo"))
.body("raw bytes", "image/jpeg")
.await
.unwrap()
.json()
.unwrap();
assert_eq!(raw["content_type"], "image/jpeg");
assert_eq!(raw["body"], "raw bytes");
})
.await;
}
#[tokio::test]
async fn requests_without_a_body_send_a_zero_length_when_their_method_expects_one() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
for method in [Method::POST, Method::PUT, Method::PATCH, Method::GET, Method::DELETE] {
let echoed: Value = client::request(method.clone(), format!("{url}/action"))
.await
.unwrap()
.json()
.unwrap();
let expected = matches!(method, Method::POST | Method::PUT | Method::PATCH).then_some("0");
assert_eq!(echoed["content_length"].as_str(), expected, "{method}");
}
})
.await;
}
#[derive(serde::Serialize)]
struct Search {
q: String,
page: u32,
active: bool,
sort: Option<String>,
score: serde_json::Value,
}
#[tokio::test]
async fn queries_and_forms_encode_pairs_structs_and_maps() {
let app = application();
app.scope(async || {
let http = client::fake();
let url = "https://example.com/search?existing=1";
let search = || Search {
q: "rust lang".into(),
page: 2,
active: true,
sort: None,
score: json!(1.5),
};
client::get(url).query([("page", 2), ("per_page", 50)]).await.unwrap();
client::get(url).query([("tag", "a"), ("tag", "b")]).await.unwrap();
client::get(url).query(search()).await.unwrap();
client::get(url)
.query(BTreeMap::from([("b", "2"), ("a", "1")]))
.await
.unwrap();
client::get(url).query(json!({ "q": "rust", "page": 2 })).await.unwrap();
client::post(url).form(search()).await.unwrap();
let sent = http.sent();
let urls: Vec<&str> = sent.iter().map(|request| request.url()).collect();
assert_eq!(
urls[..5],
[
"https://example.com/search?existing=1&page=2&per_page=50",
"https://example.com/search?existing=1&tag=a&tag=b",
"https://example.com/search?existing=1&q=rust+lang&page=2&active=true&score=1.5",
"https://example.com/search?existing=1&a=1&b=2",
"https://example.com/search?existing=1&q=rust&page=2",
]
);
assert_eq!(sent[5].body(), b"q=rust+lang&page=2&active=true&score=1.5");
assert_eq!(sent[5].data()["page"], "2");
let error = client::get(url)
.query(json!({ "filter": { "role": "admin" } }))
.await
.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("`filter` holds a list or an object")),
"{error}"
);
client::get(url)
.query([("name", "Taylor")])
.query([("page", 2)])
.await
.unwrap();
assert_eq!(
http.sent().last().map(|request| request.url().to_owned()).as_deref(),
Some("https://example.com/search?existing=1&name=Taylor&page=2"),
"each call adds to the parameters"
);
})
.await;
}
#[tokio::test]
async fn error_statuses_are_responses_unless_the_request_ensures_success() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let response = client::get(format!("{url}/missing")).await.unwrap();
assert_eq!(response.status(), 404);
assert!(response.failed() && response.client_error() && !response.server_error());
let error = client::get(format!("{url}/missing?token=secret"))
.ensure_successful()
.await
.unwrap_err();
let Error::Status(response) = &error else {
panic!("expected a status error, got {error:?}");
};
assert_eq!(response.status(), StatusCode::NOT_FOUND);
assert_eq!(
error.to_string(),
format!(r#"the HTTP request to {url}/missing returned 404 Not Found: {{"message":"Not found"}}"#)
);
let error = client::get(format!("{url}/missing"))
.await
.unwrap()
.ensure_successful()
.unwrap_err();
assert_eq!(
error.response().map(|response| response.status()),
Some(StatusCode::NOT_FOUND)
);
let not_modified = client::get(format!("{url}/not-modified")).await.unwrap();
assert!(not_modified.redirect() && !not_modified.failed());
let error = not_modified.ensure_successful().unwrap_err();
assert_eq!(
error.response().map(|response| response.status()),
Some(StatusCode::NOT_MODIFIED),
"anything outside 2xx fails"
);
})
.await;
}
#[tokio::test]
async fn decoding_the_wrong_type_names_the_status_and_body() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let response = client::get(format!("{url}/missing")).await.unwrap();
let error = response.json::<Vec<u64>>().unwrap_err();
let Error::Decode(decode) = &error else {
panic!("expected a decode error, got {error:?}");
};
assert_eq!(decode.status(), StatusCode::NOT_FOUND);
assert_eq!(
error.to_string(),
format!(
r#"the response from {url}/missing (404 Not Found) can't be decoded as `alloc::vec::Vec<u64>` (its body starts: {{"message":"Not found"}})"#
)
);
let source = std::error::Error::source(&error).unwrap();
assert!(source.is::<serde_json::Error>(), "{source:?}");
})
.await;
}
#[tokio::test]
async fn timeouts_and_refused_connections_are_connection_errors() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let error = client::get(format!("{url}/slow"))
.timeout(100.milliseconds())
.await
.unwrap_err();
assert!(error.is_timeout(), "{error:?}");
let error = client::get(format!("{url}/trickle"))
.timeout(200.milliseconds())
.await
.unwrap_err();
assert!(error.is_timeout(), "the timeout limits the whole body: {error:?}");
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
let address = listener.local_addr().unwrap();
drop(listener);
let error = client::get(format!("http://{address}/users?token=secret"))
.await
.unwrap_err();
let Error::Connection(connection) = &error else {
panic!("expected a connection error, got {error:?}");
};
assert!(!connection.is_timeout());
assert_eq!(connection.url(), format!("http://{address}/users"));
assert!(!format!("{error} {error:?}").contains("secret"), "{error:?}");
})
.await;
}
#[tokio::test]
async fn https_requests_use_the_installed_crypto_provider() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let error = client::get(url.replace("http://", "https://")).await.unwrap_err();
assert!(matches!(error, Error::Connection(_)), "{error:?}");
})
.await;
}
#[tokio::test]
async fn retries_of_allowed_stray_requests_wait_between_attempts() {
let (url, hits) = server().await;
let app = application();
app.scope(async || {
let _http = client::fake().allow_stray_requests([format!("{url}/*")]);
let started = std::time::Instant::now();
let response = client::get(format!("{url}/flaky"))
.retry(3, 100.milliseconds())
.await
.unwrap();
assert_eq!(response.text(), "finally");
assert_eq!(hits.load(Ordering::SeqCst), 3);
assert!(
started.elapsed() >= Duration::from_millis(200),
"{:?}",
started.elapsed()
);
})
.await;
}
#[tokio::test]
async fn exhausted_retries_return_the_last_error() {
for times in [0, 1, 2] {
let (url, hits) = server().await;
let app = application();
app.scope(async || {
let error = client::get(format!("{url}/flaky"))
.retry(times, Backoff::exponential(1.millisecond()))
.await
.unwrap_err();
assert_eq!(
error.response().map(|response| response.status()),
Some(StatusCode::SERVICE_UNAVAILABLE)
);
assert_eq!(hits.load(Ordering::SeqCst), times.max(1) as usize);
})
.await;
}
}
#[tokio::test]
async fn retry_when_decides_which_failures_are_retried() {
let (url, hits) = server().await;
let app = application();
app.scope(async || {
let attempts = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&attempts);
let error = client::get(format!("{url}/flaky"))
.retry(3, Duration::ZERO)
.retry_when(move |error, attempt| {
counted.fetch_add(1, Ordering::SeqCst);
assert_eq!(attempt, 1);
matches!(error, Error::Connection(_))
})
.await
.unwrap_err();
assert!(matches!(error, Error::Status(_)));
assert_eq!(hits.load(Ordering::SeqCst), 1);
assert_eq!(attempts.load(Ordering::SeqCst), 1);
})
.await;
}
#[tokio::test]
async fn the_applications_client_sets_defaults_and_hooks() {
let (url, _) = server().await;
let responses = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&responses);
let app = Application::configure()
.replace_env(Env::default())
.with_services(move |app| {
app.instance(
Client::new()
.user_agent("Acme/1.0")
.timeout(100.milliseconds())
.before_sending(|request| request.header("x-tenant", "acme"))
.after_response(move |_| {
counted.fetch_add(1, Ordering::SeqCst);
}),
);
})
.create();
app.scope(async || {
let echoed: Value = client::get(format!("{url}/hooks")).await.unwrap().json().unwrap();
assert_eq!(echoed["user_agent"], "Acme/1.0");
assert_eq!(echoed["tenant"], "acme");
let error = client::get(format!("{url}/slow")).await.unwrap_err();
assert!(error.is_timeout(), "the client's timeout applies: {error:?}");
let response = client::get(format!("{url}/sleepy")).timeout(0.seconds()).await;
assert!(response.is_ok(), "a zero timeout means no limit: {response:?}");
client::get(format!("{url}/flaky"))
.retry(3, Duration::ZERO)
.await
.unwrap();
assert_eq!(responses.load(Ordering::SeqCst), 5, "every attempt's response is seen");
})
.await;
}
#[tokio::test]
async fn transport_configuration_controls_redirects_without_bypassing_fakes() {
let url = serve(
axum::Router::new()
.route(
"/redirect",
get(|| async { axum::response::Redirect::temporary("/destination") }),
)
.route("/destination", get(|| async { "arrived" })),
)
.await;
let app = Application::configure()
.replace_env(Env::default())
.with_services(|app| {
app.instance(
Client::new().configure_transport(|transport| transport.redirect(reqwest::redirect::Policy::none())),
);
})
.create();
app.scope(async || {
let response = client::get(format!("{url}/redirect")).await.unwrap();
assert_eq!(response.status(), 307);
assert_eq!(response.header("location"), Some("/destination"));
let response = client::get(format!("{url}/redirect"))
.configure_transport(|transport| transport.redirect(reqwest::redirect::Policy::limited(5)))
.await
.unwrap();
assert_eq!(response.text(), "arrived");
assert_eq!(client::get(format!("{url}/redirect")).await.unwrap().status(), 307);
let http = client::fake().with("*", "faked");
let response = client::get(format!("{url}/redirect"))
.configure_transport(|_| panic!("a fully faked request must not build its transport"))
.await
.unwrap();
assert_eq!(response.text(), "faked");
http.assert_sent_count(1);
})
.await;
application()
.scope(async || {
let response = client::get(format!("{url}/redirect")).await.unwrap();
assert_eq!(response.status(), 200);
assert_eq!(response.text(), "arrived");
})
.await;
}
#[tokio::test]
async fn a_transport_that_cant_be_built_fails_requests_as_invalid_with_its_cause() {
let app = application();
app.scope(async || {
let request = Client::new()
.configure_transport(|transport| {
transport.add_root_certificate(reqwest::Certificate::from_der(b"not a certificate").unwrap())
})
.get("http://127.0.0.1:9/unreachable")
.retry(3, 10.seconds());
let error = tokio::time::timeout(Duration::from_secs(1), request)
.await
.expect("a transport that can't be built isn't retried")
.unwrap_err();
let Error::Invalid(error) = error else {
panic!("expected an invalid request, got {error:?}");
};
let mut causes = vec![error.to_string()];
let mut source = std::error::Error::source(&error);
while let Some(cause) = source {
causes.push(cause.to_string());
source = cause.source();
}
assert_eq!(causes[0], "the HTTP client couldn't be created");
assert!(causes.iter().any(|cause| cause.contains("certificate")), "{causes:?}");
})
.await;
}
#[tokio::test]
async fn transport_overrides_keep_request_options_and_the_selected_clients_hooks() {
let (url, _) = server().await;
let app = Application::configure()
.replace_env(Env::default())
.with_services(|app| {
app.instance(Client::new().before_sending(|request| request.header("x-tenant", "application")));
})
.create();
let dedicated = Client::new()
.user_agent("Integration/1.0")
.before_sending(|request| request.header("x-tenant", "integration"));
let template = dedicated
.base_url(&url)
.token("secret")
.url_parameters([("user", "taylor")])
.query([("source", "before")])
.timeout(100.milliseconds())
.retry(2, Duration::ZERO)
.ensure_successful()
.configure_transport(|transport| transport.redirect(reqwest::redirect::Policy::none()));
app.scope(async || {
let response = template
.post("/users/{user}")
.query([("page", 3)])
.json(json!({"name": "Taylor"}))
.await
.unwrap();
let echoed = response.json::<Value>().unwrap();
assert_eq!(echoed["method"], "POST");
assert_eq!(echoed["path"], "/users/taylor");
assert_eq!(echoed["query"], "source=before&page=3");
assert_eq!(echoed["body"], r#"{"name":"Taylor"}"#);
assert_eq!(echoed["authorization"], "Bearer secret");
assert_eq!(echoed["tenant"], "integration");
assert_eq!(echoed["user_agent"], "Integration/1.0");
assert!(template.get("/slow").await.unwrap_err().is_timeout());
let application: Value = client::get(format!("{url}/normal")).await.unwrap().json().unwrap();
assert_eq!(application["tenant"], "application");
let http = client::fake().with("*", client::sequence().push(503).push("one\ntwo\n"));
let response = template
.patch("/users/{user}")
.form([("name", "Taylor")])
.stream()
.await
.unwrap()
.into_response()
.await
.unwrap();
assert_eq!(response.text(), "one\ntwo\n");
http.assert_sent_count(2).assert_sent(|request| {
request.method() == Method::PATCH
&& request.url() == format!("{url}/users/taylor?source=before")
&& request.has_header("x-tenant", "integration")
&& request.has_header("authorization", "Bearer secret")
&& request.data()["name"] == "Taylor"
});
})
.await;
}
#[tokio::test]
async fn explicit_clients_share_connections_and_detach_changed_transport_settings() {
use axum::extract::ConnectInfo;
use std::net::SocketAddr;
let peers = Arc::new(std::sync::Mutex::new(Vec::new()));
let recorded = Arc::clone(&peers);
let router = axum::Router::new()
.route(
"/connection",
get(|ConnectInfo(peer): ConnectInfo<SocketAddr>| async move { peer.port().to_string() }),
)
.route(
"/redirect",
get(|| async { axum::response::Redirect::temporary("/connection") }),
)
.route(
"/flaky",
get(move |ConnectInfo(peer): ConnectInfo<SocketAddr>| {
let mut peers = recorded.lock().unwrap();
peers.push(peer.port());
let status = if peers.len() == 1 {
StatusCode::SERVICE_UNAVAILABLE
} else {
StatusCode::OK
};
let peers = peers.clone();
async move { (status, Json(peers)) }
}),
);
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let url = format!("http://{}", listener.local_addr().unwrap());
let server = tokio::spawn(async move {
axum::serve(listener, router.into_make_service_with_connect_info::<SocketAddr>())
.await
.unwrap();
});
let client = Client::new();
let cloned = client.clone();
let app = application();
app.scope(async || {
let first = cloned.get(format!("{url}/connection")).await.unwrap();
let second = client.get(format!("{url}/connection")).await.unwrap();
assert_eq!(
first.text(),
second.text(),
"cold clones share their eventual connection pool"
);
let renamed = client.clone().user_agent("Other/1.0");
assert_eq!(
renamed.get(format!("{url}/connection")).await.unwrap().text(),
first.text()
);
let changed = client
.clone()
.configure_transport(|transport| transport.redirect(reqwest::redirect::Policy::none()));
assert_eq!(changed.get(format!("{url}/redirect")).await.unwrap().status(), 307);
assert_eq!(
client.get(format!("{url}/redirect")).await.unwrap().text(),
first.text()
);
let reconnected = client.clone().connect_timeout(2.seconds());
assert_ne!(
reconnected.get(format!("{url}/connection")).await.unwrap().text(),
first.text()
);
let overridden = client
.get(format!("{url}/connection"))
.configure_transport(|transport| transport)
.await
.unwrap();
assert_ne!(overridden.text(), first.text());
assert_eq!(
client.get(format!("{url}/connection")).await.unwrap().text(),
first.text()
);
let retried: Vec<u16> = client
.get(format!("{url}/flaky"))
.configure_transport(|transport| transport)
.retry(2, Duration::ZERO)
.await
.unwrap()
.json()
.unwrap();
assert_eq!(retried.len(), 2);
assert_eq!(
retried[0], retried[1],
"retries reuse the request-specific connection pool"
);
let temporary = Client::new().get(format!("{url}/connection"));
assert!(
temporary
.stream()
.await
.unwrap()
.into_response()
.await
.unwrap()
.successful()
);
})
.await;
server.abort();
}
#[tokio::test]
async fn explicit_clients_use_the_current_applications_fakes() {
let client = Client::new().configure_transport(|_| panic!("fakes don't build a transport"));
let pending = client.get("https://example.com");
for body in ["first application", "second application"] {
let app = application();
app.scope(async || {
let http = client::fake().with("*", body);
assert_eq!(pending.clone().await.unwrap().text(), body);
assert_eq!(
client
.get("https://example.com")
.stream()
.await
.unwrap()
.into_response()
.await
.unwrap()
.text(),
body
);
http.assert_sent_count(2);
})
.await;
}
}
#[tokio::test]
async fn hooks_can_scope_credentials_and_sign_the_buffered_request() {
let app = Application::configure()
.replace_env(Env::default())
.with_services(|app| {
app.instance(Client::new().before_sending(|request| {
if request.url().is_ok_and(|url| url.host_str() == Some("api.example.com")) {
let signature = format!(
"{}:{}:{}",
request.method(),
request.header_value("x-version").unwrap(),
String::from_utf8_lossy(&request.body_bytes().unwrap()),
);
request.token("secret").header("x-signature", signature)
} else {
request
}
}));
})
.create();
app.scope(async || {
let http = client::fake();
let request = client::base_url("https://{host}/v1")
.url_parameters([("host", "api.example.com"), ("user", "Taylor Otwell")])
.post("/users/{user}?source=app")
.query([("page", 2)])
.header("x-version", "v2")
.form([("name", "Taylor Otwell")]);
assert_eq!(request.header_map()["x-version"], "v2");
request.await.unwrap();
client::get("https://other.example.com").await.unwrap();
http.assert_sent(|request| {
request.url() == "https://api.example.com/v1/users/Taylor%20Otwell?source=app&page=2"
&& request.has_header("authorization", "Bearer secret")
&& request.has_header("x-signature", "POST:v2:name=Taylor+Otwell")
&& request.body() == b"name=Taylor+Otwell"
});
http.assert_sent(|request| {
request.url() == "https://other.example.com/" && request.header("authorization").is_none()
});
})
.await;
assert_eq!(
client::post("https://example.com")
.json(json!({"a": 3}))
.body_bytes()
.unwrap(),
r#"{"a":3}"#
);
assert_eq!(
client::put("https://example.com")
.body("raw", "text/plain")
.body_bytes()
.unwrap(),
"raw"
);
assert_eq!(client::get("https://example.com").body_bytes().unwrap(), Bytes::new());
assert!(
client::post("https://example.com")
.body_file("not-read", "text/plain")
.body_bytes()
.is_none()
);
assert!(
client::post("https://example.com")
.attach("file", client::Attachment::from_path("not-read"))
.body_bytes()
.is_none()
);
}
#[tokio::test]
async fn invalid_requests_fail_when_sent_without_panicking() {
let app = application();
app.scope(async || {
let error = client::get("https://example.com")
.header("bad header", "value")
.await
.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("`bad header` isn't a valid header name"))
);
let error = client::get("/users").await.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("no base URL")),
"{error}"
);
for url in [
"/v1/users?api_key=secret",
"https://user:secret@example.com:99999/users?api_key=secret#secret",
] {
let error = client::get(url).await.unwrap_err();
assert!(matches!(error, Error::Invalid(_)), "{error}");
assert!(!error.to_string().contains("secret"), "{error}");
}
let error = client::base_url("https://example.com").await.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("has no URL")),
"{error}"
);
let error = Client::new()
.user_agent("Acme\n1.0")
.get("https://example.com")
.await
.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("the client's user agent isn't a valid header value")),
"{error}"
);
})
.await;
}
#[tokio::test]
async fn urls_without_an_http_scheme_are_invalid_even_when_faked() {
let app = application();
app.scope(async || {
for request in [
client::get("localhost:8000/health"),
client::get("ftp://example.com/file"),
client::base_url("api.example.com").get("/users"),
] {
let error = request.clone().retry(3, 5.seconds()).await.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("must start with `http://` or `https://`")),
"{error}"
);
let http = client::fake();
let error = request.await.unwrap_err();
assert!(matches!(error, Error::Invalid(_)), "{error}");
http.assert_nothing_sent();
}
})
.await;
}
#[test]
fn debug_output_hides_credentials() {
let request = client::get("https://example.com")
.token("bearer-secret")
.basic_auth("user", "basic-secret");
let debug = format!("{request:?}");
assert!(!debug.contains("secret"), "{debug}");
let request = client::get("https://example.com").headers([
("Authorization", "Token header-secret"),
("Proxy-Authorization", "Basic proxy-secret"),
("Cookie", "session=cookie-secret"),
]);
let debug = format!("{request:?}");
assert!(!debug.contains("secret"), "{debug}");
let request = client::base_url("https://user:base-secret@example.com/v1")
.get("https://user:url-secret@example.com/teams/{team}?api_key=inline-secret")
.query([("token", "query-secret")])
.url_parameters([("team", "parameter-secret")]);
let debug = format!("{request:?}");
assert!(!debug.contains("secret"), "{debug}");
}
#[tokio::test]
#[should_panic(
expected = "`laravel::http::client` can only be used inside the application: while it handles a request or \
runs a command, in `Application::scope`, or in a task spawned with `laravel::task::spawn` (called at \
tests/http_client.rs:"
)]
async fn sending_outside_the_application_panics() {
let _ = client::get("https://example.com").await;
}
#[tokio::test]
async fn factories_and_boot_hooks_send_requests() {
struct Settings(Value);
let (url, _) = server().await;
let booted = Arc::new(AtomicUsize::new(0));
let counted = Arc::clone(&booted);
let settings_url = format!("{url}/settings");
let hook_url = format!("{url}/warm");
let app = Application::configure()
.replace_env(Env::default())
.with_services(move |services| {
services.singleton(move |_| {
let url = settings_url.clone();
async move { Ok(Settings(client::get(url).ensure_successful().await?.json()?)) }
});
})
.booted(move |_| {
let (url, counted) = (hook_url.clone(), Arc::clone(&counted));
async move {
client::get(url).ensure_successful().await?;
counted.fetch_add(1, Ordering::SeqCst);
laravel::Result::Ok(())
}
})
.create();
app.boot().await.unwrap();
assert_eq!(booted.load(Ordering::SeqCst), 1);
let settings = app.scope(async || laravel::resolve::<Settings>().await).await.unwrap();
assert_eq!(settings.0["path"], "/settings");
}
#[tokio::test]
async fn a_swapped_client_sends_from_then_on_and_fakes_survive_it() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let http = client::fake().with("*/faked", "faked");
app.swap(Client::new().user_agent("Swapped/1.0"));
assert_eq!(client::get(format!("{url}/faked")).await.unwrap().text(), "faked");
http.assert_sent(|request| request.has_header("user-agent", "Swapped/1.0"));
drop(http);
let echoed: Value = client::get(format!("{url}/swapped")).await.unwrap().json().unwrap();
assert_eq!(echoed["user_agent"], "Swapped/1.0");
})
.await;
}
#[tokio::test]
#[should_panic(
expected = "`laravel::http::client` needs `laravel::http::client::Client` registered with \
`app.instance(..)`"
)]
async fn a_client_built_by_a_factory_names_the_registration_to_use() {
let app = Application::configure()
.replace_env(Env::default())
.with_services(|services| {
services.singleton(|_| async { Ok(Client::new()) });
})
.create();
app.scope(async || {
let _http = client::fake();
let _ = client::get("https://example.com").await;
})
.await;
}
async fn profile() -> laravel::Result<String> {
let user: Value = client::base_url("https://api.github.com")
.token("github-token")
.ensure_successful()
.get("/users/taylor")
.await?
.json()?;
Ok(format!(
"{} ({})",
user["name"].as_str().unwrap_or_default(),
user["login"]
))
}
fn github_application() -> Application {
Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.routes(|routes| {
routes.get("/profile", profile);
});
})
.create()
}
#[tokio::test]
async fn fakes_answer_the_applications_requests_and_record_them() {
let app = github_application();
app.scope(async || {
let http = client::fake().with(
"api.github.com/users/*",
json!({ "login": "taylor", "name": "Taylor Otwell" }),
);
app.get("/profile").await.assert_ok().assert_see("Taylor Otwell");
http.assert_sent_count(1)
.assert_sent(|request| {
request.method() == Method::GET
&& request.url() == "https://api.github.com/users/taylor"
&& request.has_header("authorization", "Bearer github-token")
})
.assert_not_sent(|request| request.method() == Method::DELETE);
let recorded = http.recorded();
assert_eq!(recorded.len(), 1);
assert_eq!(recorded[0].1.header("content-type"), Some("application/json"));
})
.await;
}
#[tokio::test]
async fn failures_from_fakes_reach_the_error_handler() {
let app = github_application();
app.scope(async || {
let _http = client::fake().with("api.github.com/*", client::response().status(500).body("down"));
app.get("/profile")
.await
.assert_internal_server_error()
.assert_reported::<Error>();
})
.await;
}
#[tokio::test]
async fn unmatched_requests_get_an_empty_ok_by_default() {
let app = application();
app.scope(async || {
let http = client::fake().with("github.com/*", "ok");
http.assert_nothing_sent();
assert_eq!(client::get("https://github.com/laravel").await.unwrap().text(), "ok");
let unmatched = client::get("https://laravel.com/docs").await.unwrap();
assert_eq!(unmatched.status(), 200);
assert!(unmatched.bytes().is_empty());
http.assert_sent_count(2);
})
.await;
}
#[tokio::test]
async fn prevented_stray_requests_are_refused_unless_allowed() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let http = client::fake()
.with("github.com/*", "ok")
.prevent_stray_requests()
.allow_stray_requests([format!("{url}/*")]);
assert_eq!(client::get("https://github.com/laravel").await.unwrap().text(), "ok");
let error = client::get("https://laravel.com/docs").await.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.is_stray() && invalid.to_string().contains("no fake matches the request GET https://laravel.com/docs")),
"{error}"
);
let echoed: Value = client::get(format!("{url}/allowed")).await.unwrap().json().unwrap();
assert_eq!(echoed["path"], "/allowed");
assert_eq!(http.sent().len(), 2, "stray requests aren't sent");
assert_eq!(http.recorded()[1].1.status(), 200);
})
.await;
}
#[tokio::test]
async fn fakes_give_sequences_callbacks_and_failed_connections() {
let app = application();
app.scope(async || {
let http = client::fake()
.with(
"example.com/sequence",
client::sequence().push("first").push(json!({ "n": 2 })).push(404),
)
.with("example.com/fallback", client::sequence().push(201).when_empty(204))
.with("example.com/down", client::failed_connection())
.with("example.com/echo", |request: &Request| {
request.data()["reply"].as_str().unwrap_or("none").to_owned()
});
let sequence = || client::get("https://example.com/sequence");
assert_eq!(sequence().await.unwrap().text(), "first");
assert_eq!(sequence().await.unwrap().json::<Value>().unwrap()["n"], 2);
assert_eq!(sequence().await.unwrap().status(), 404);
let error = sequence().await.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if !invalid.is_stray() && invalid.to_string().contains("no responses left")),
"{error}"
);
for expected in [201, 204, 204] {
assert_eq!(
client::get("https://example.com/fallback").await.unwrap().status(),
expected
);
}
let error = client::get("https://example.com/down").await.unwrap_err();
assert!(
matches!(&error, Error::Connection(connection) if !connection.is_timeout()),
"{error}"
);
let reply = client::post("https://example.com/echo")
.json(json!({ "reply": "pong" }))
.await
.unwrap();
assert_eq!(reply.text(), "pong");
http.assert_sent_count(9);
assert_eq!(http.recorded().len(), 7, "failed connections are sent, not recorded");
})
.await;
}
#[tokio::test]
async fn faked_retries_run_without_waiting() {
let app = application();
app.scope(async || {
let http = client::fake().with(
"example.com/*",
client::sequence()
.push(client::failed_connection())
.push(503)
.push("done"),
);
let response = tokio::time::timeout(
Duration::from_secs(5),
client::get("https://example.com/flaky").retry(3, Duration::from_secs(60)),
)
.await
.expect("faked retries shouldn't wait")
.unwrap();
assert_eq!(response.text(), "done");
http.assert_sent_count(3);
})
.await;
}
#[tokio::test]
async fn nested_fakes_restore_the_enclosing_one_and_dropping_restores_the_network() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let outer = client::fake().with("*", "outer");
{
let inner = client::fake().with("*", "inner");
assert_eq!(client::get(format!("{url}/a")).await.unwrap().text(), "inner");
inner.assert_sent_count(1);
}
assert_eq!(client::get(format!("{url}/b")).await.unwrap().text(), "outer");
outer.assert_sent_count(1);
drop(outer);
let echoed: Value = client::get(format!("{url}/c")).await.unwrap().json().unwrap();
assert_eq!(echoed["path"], "/c");
})
.await;
}
#[tokio::test]
async fn fakes_belong_to_one_application() {
let (url, _) = server().await;
let faked = application();
let other = application();
faked
.scope(async || {
let http = client::fake().with("*", "faked");
let echoed: Value = other
.scope(async || client::get(format!("{url}/other")).send().await)
.await
.unwrap()
.json()
.unwrap();
assert_eq!(echoed["path"], "/other");
assert_eq!(client::get(format!("{url}/mine")).await.unwrap().text(), "faked");
http.assert_sent_count(1);
})
.await;
}
#[tokio::test]
async fn url_parameters_fill_placeholders_with_encoded_segments() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let echoed: Value = client::get(format!("{url}/users/{{login}}/posts"))
.url_parameters([("login", "../admin?x=1#top")])
.await
.unwrap()
.json()
.unwrap();
assert_eq!(
echoed["path"], "/users/..%2Fadmin%3Fx%3D1%23top/posts",
"the value stays one segment"
);
let http = client::fake();
let github = client::base_url("https://api.github.com").url_parameters([("owner", "laravel")]);
github
.get("/repos/{owner}/{repo}/issues/{number}")
.url_parameters((("repo", "laravel framework"), ("number", 52)))
.await
.unwrap();
client::get("{+endpoint}/docs/{version}")
.url_parameters([("endpoint", "https://laravel.com"), ("version", "13.x")])
.await
.unwrap();
let urls: Vec<String> = http.sent().iter().map(|request| request.url().to_owned()).collect();
assert_eq!(
urls,
[
"https://api.github.com/repos/laravel/laravel%20framework/issues/52",
"https://laravel.com/docs/13.x",
]
);
let error = github.get("/repos/{owner}/{repo}").await.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("`{repo}` placeholder")),
"{error}"
);
let error = client::get("https://example.com/users/{login}")
.url_parameters([("login", "..")])
.await
.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("`login` can't be `..`")),
"{error}"
);
let error = client::get("https://example.com/users/{login}")
.url_parameters([("login", None::<&str>)])
.await
.unwrap_err();
assert!(
matches!(&error, Error::Invalid(invalid) if invalid.to_string().contains("`{login}` placeholder")),
"{error}"
);
})
.await;
}
#[tokio::test]
async fn streamed_bodies_arrive_in_chunks_with_a_timeout_for_each_wait() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let started = std::time::Instant::now();
let response = client::get(format!("{url}/trickle"))
.timeout(250.milliseconds())
.stream()
.await
.unwrap();
assert!(response.successful());
let mut chunks = response.chunks();
let first = chunks.next().await.unwrap().unwrap();
assert_eq!(first, "one\n");
assert!(
started.elapsed() < Duration::from_millis(250),
"the first chunk arrives before the rest"
);
let mut rest = String::new();
while let Some(chunk) = chunks.next().await {
rest.push_str(std::str::from_utf8(&chunk.unwrap()).unwrap());
}
assert_eq!(rest, "two\nthree\nfour\n");
assert!(
started.elapsed() > Duration::from_millis(250),
"the whole stream outlasts the timeout"
);
let mut chunks = client::get(format!("{url}/stalls"))
.timeout(200.milliseconds())
.stream()
.await
.unwrap()
.chunks();
assert_eq!(chunks.next().await.unwrap().unwrap(), "first\n");
let error = chunks.next().await.unwrap().unwrap_err();
assert!(error.is_timeout(), "{error:?}");
assert!(chunks.next().await.is_none(), "the stream ends after an error");
})
.await;
}
#[tokio::test]
async fn server_sent_events_are_parsed_as_they_arrive() {
let (url, _) = server().await;
let app = application();
app.scope(async || {
let mut events = client::post(format!("{url}/completions"))
.json(json!({ "stream": true }))
.ensure_successful()
.stream()
.await
.unwrap()
.events();
let mut reply = String::new();
while let Some(event) = events.next().await {
let event = event.unwrap();
if event.data() == "[DONE]" {
break;
}
let delta: Value = event.json().unwrap();
reply.push_str(delta["choices"][0]["delta"]["content"].as_str().unwrap());
}
assert_eq!(reply, "Hello!");
})
.await;
}
#[tokio::test]
async fn streamed_error_statuses_survive_stalled_broken_and_large_bodies() {
let url = serve(
axum::Router::new()
.route(
"/stalls",
get(|| async {
(
StatusCode::TOO_MANY_REQUESTS,
[("retry-after", "10")],
body_of(&["first\n", "never\n"], 2_000),
)
}),
)
.route(
"/large",
get(|| async { (StatusCode::BAD_GATEWAY, "x".repeat(16 * 1024)) }),
)
.route(
"/breaks",
get(|| async {
let chunks = futures_util::stream::unfold(0, |index| async move {
match index {
0 => Some((Ok(Bytes::from_static(b"first\n")), 1)),
1 => {
tokio::time::sleep(Duration::from_millis(20)).await;
Some((Err(std::io::Error::other("broken body")), 2))
}
_ => None,
}
});
(StatusCode::BAD_GATEWAY, axum::body::Body::from_stream(chunks))
}),
),
)
.await;
let app = application();
app.scope(async || {
let response = client::get(format!("{url}/stalls"))
.timeout(100.milliseconds())
.stream()
.await
.unwrap();
assert_eq!(response.status(), 429);
assert_eq!(response.header("retry-after"), Some("10"));
let mut chunks = response.chunks();
assert_eq!(chunks.next().await.unwrap().unwrap(), "first\n");
assert!(chunks.next().await.unwrap().unwrap_err().is_timeout());
for path in ["stalls", "breaks"] {
let error = client::get(format!("{url}/{path}"))
.ensure_successful()
.timeout(100.milliseconds())
.stream()
.await
.unwrap_err();
let response = error.response().expect("the status survives a body failure");
assert_eq!(response.status(), if path == "stalls" { 429 } else { 502 });
assert_eq!(response.text(), "first\n");
}
let error = client::get(format!("{url}/large"))
.ensure_successful()
.stream()
.await
.unwrap_err();
assert_eq!(error.response().unwrap().bytes().len(), 8 * 1024);
assert!(error.response().unwrap().bytes().iter().all(|byte| *byte == b'x'));
let error = client::get(format!("{url}/stalls"))
.retry(1, Duration::ZERO)
.timeout(100.milliseconds())
.stream()
.await
.unwrap_err();
assert_eq!(error.response().unwrap().status(), 429);
assert_eq!(error.response().unwrap().header("retry-after"), Some("10"));
let http = client::fake().with("*", client::response().status(502).body("x".repeat(16 * 1024)));
let error = client::get("https://example.com")
.retry(1, Duration::ZERO)
.stream()
.await
.unwrap_err();
assert_eq!(error.response().unwrap().bytes().len(), 8 * 1024);
assert_eq!(error.response().unwrap().status(), 502);
let response = client::get("https://example.com")
.stream()
.await
.unwrap()
.into_response()
.await
.unwrap();
assert_eq!(response.bytes().len(), 16 * 1024);
let response = client::get("https://example.com").await.unwrap();
assert_eq!(response.bytes().len(), 16 * 1024);
http.assert_sent_count(3);
})
.await;
}
async fn relay() -> laravel::Result<EventStream> {
let events = client::post("https://api.openai.com/v1/chat/completions")
.token("test-key")
.json(json!({ "stream": true, "messages": [] }))
.ensure_successful()
.stream()
.await?
.events();
let deltas = events
.take_while(|event| std::future::ready(!matches!(event, Ok(event) if event.data() == "[DONE]")))
.filter_map(|event| async move {
let delta: Value = event.ok()?.json().ok()?;
delta["choices"][0]["delta"]["content"].as_str().map(str::to_owned)
});
Ok(EventStream::new(deltas))
}
#[tokio::test]
async fn faked_streams_relay_through_the_application() {
let app = Application::configure()
.replace_env(Env::default())
.with_routing(|routing, _| {
routing.routes(|routes| {
routes.get("/chat", relay);
});
})
.create();
app.scope(async || {
let http = client::fake().with(
"api.openai.com/*",
client::sequence()
.push(503)
.push(client::response().header("content-type", "text/event-stream").body(
"data: {\"choices\":[{\"delta\":{\"content\":\"Hel\"}}]}\n\n\
data: {\"choices\":[{\"delta\":{\"content\":\"lo!\"}}]}\n\n\
data: [DONE]\n\n",
)),
);
app.get("/chat").await.assert_internal_server_error();
app.get("/chat")
.await
.assert_ok()
.assert_see("data: Hel")
.assert_see("data: lo!");
http.assert_sent_count(2);
assert_eq!(http.recorded()[1].1.status(), 200);
})
.await;
}
#[tokio::test]
async fn streams_retry_before_their_body() {
let app = application();
app.scope(async || {
let http = client::fake().with(
"example.com/*",
client::sequence()
.push(client::failed_connection())
.push(503)
.push("one\ntwo\n"),
);
let chunks: Vec<_> = client::get("https://example.com/feed")
.retry(3, 1.second())
.stream()
.await
.unwrap()
.chunks()
.collect()
.await;
let chunks: Vec<Bytes> = chunks.into_iter().map(Result::unwrap).collect();
assert_eq!(chunks, ["one\n", "two\n"], "faked bodies arrive a line at a time");
http.assert_sent_count(3);
})
.await;
}