use std::future::{Future, IntoFuture};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::panic::Location;
use std::pin::Pin;
use std::sync::atomic::AtomicBool;
use ::url::Url;
use axum::body::Body;
use bytes::Bytes;
use http::{HeaderMap, HeaderName, HeaderValue, Method, header};
use http_body_util::BodyExt;
use serde::Serialize;
use serde_json::{Map, Value};
use tower::ServiceExt;
use super::TestResponse;
use crate::cookie::PlaintextCookies;
use crate::errors::{Handled, RecordReports};
use crate::foundation::{Application, RecordRoot};
use crate::http::client::Attachment;
use crate::session::{Session, SessionSeed};
use crate::view::RenderedView;
pub trait MakesHttpRequests {
#[track_caller]
fn request(&self, method: Method, uri: impl AsRef<str>) -> TestRequest;
#[track_caller]
fn get(&self, uri: impl AsRef<str>) -> TestRequest {
self.request(Method::GET, uri)
}
#[track_caller]
fn post(&self, uri: impl AsRef<str>) -> TestRequest {
self.request(Method::POST, uri)
}
#[track_caller]
fn put(&self, uri: impl AsRef<str>) -> TestRequest {
self.request(Method::PUT, uri)
}
#[track_caller]
fn patch(&self, uri: impl AsRef<str>) -> TestRequest {
self.request(Method::PATCH, uri)
}
#[track_caller]
fn delete(&self, uri: impl AsRef<str>) -> TestRequest {
self.request(Method::DELETE, uri)
}
}
impl MakesHttpRequests for Application {
#[track_caller]
fn request(&self, method: Method, uri: impl AsRef<str>) -> TestRequest {
TestRequest::new(self.clone(), method, uri.as_ref())
}
}
#[track_caller]
fn parse_uri(uri: &str) -> http::Uri {
let parsed = match uri.parse::<http::Uri>() {
Ok(parsed) if parsed.scheme().is_some() || uri.starts_with('/') => Ok(parsed),
_ => format!("/{uri}").parse::<http::Uri>(),
};
parsed.unwrap_or_else(|error| panic!("the test request URI `{uri}` is invalid: {error}"))
}
fn app_url(application: &Application) -> Option<Url> {
Url::parse(&application.config().app.url)
.ok()
.filter(|url| matches!(url.scheme(), "http" | "https"))
}
fn host(uri: &http::Uri, app_url: Option<&Url>) -> HeaderValue {
let host = match (uri.authority(), app_url) {
(Some(authority), _) => authority.as_str(),
(None, Some(url)) => &url[::url::Position::BeforeHost..::url::Position::AfterPort],
(None, None) => "localhost",
};
HeaderValue::try_from(host).expect("a parsed host is a valid header")
}
#[derive(Debug, Clone)]
#[must_use = "a test request does nothing unless awaited"]
pub struct TestRequest {
application: Application,
method: Method,
uri: http::Uri,
headers: HeaderMap,
cookies: Vec<RequestCookie>,
body: Bytes,
attachments: Vec<(String, Attachment)>,
session: Option<Map<String, Value>>,
extensions: http::Extensions,
ip: IpAddr,
follow_redirects: bool,
location: &'static Location<'static>,
}
impl TestRequest {
#[track_caller]
fn new(application: Application, method: Method, uri: &str) -> Self {
let uri = parse_uri(uri);
let mut headers = HeaderMap::new();
headers.insert(header::HOST, host(&uri, app_url(&application).as_ref()));
headers.insert("sec-fetch-site", HeaderValue::from_static("same-origin"));
Self {
application,
method,
uri,
headers,
cookies: Vec::new(),
body: Bytes::new(),
attachments: Vec::new(),
session: None,
extensions: http::Extensions::new(),
ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
follow_redirects: false,
location: Location::caller(),
}
}
#[track_caller]
pub fn header(mut self, name: &str, value: impl AsRef<str>) -> Self {
let value = value.as_ref();
let name = HeaderName::try_from(name)
.unwrap_or_else(|error| panic!("the test request header name `{name}` is invalid: {error}"));
let value = HeaderValue::try_from(value)
.unwrap_or_else(|error| panic!("the test request header `{name}` value `{value}` is invalid: {error}"));
self.headers.insert(name, value);
self
}
#[track_caller]
pub fn token(self, token: impl AsRef<str>) -> Self {
self.header("authorization", format!("Bearer {}", token.as_ref()))
}
pub fn cookie(mut self, name: &str, value: impl AsRef<str>) -> Self {
self.put_cookie(name, value.as_ref(), true);
self
}
fn put_cookie(&mut self, name: &str, value: &str, plaintext: bool) {
let cookie = RequestCookie {
name: name.to_owned(),
value: value.to_owned(),
plaintext,
};
match self.cookies.iter_mut().find(|existing| existing.name == name) {
Some(existing) => *existing = cookie,
None => self.cookies.push(cookie),
}
}
pub fn with_cookies_from(mut self, response: &TestResponse) -> Self {
for cookie in response.cookies_on_the_way() {
let given = self
.cookies
.iter()
.any(|own| own.plaintext && own.name == cookie.name());
if !given {
self.receive_cookie(response, &cookie);
}
}
self
}
fn receive_cookie(&mut self, response: &TestResponse, cookie: &cookie::Cookie<'_>) {
if response.has_expired(cookie) {
self.cookies.retain(|existing| existing.name != cookie.name());
} else {
self.put_cookie(cookie.name(), cookie.value(), false);
}
}
#[track_caller]
pub fn json(mut self, body: impl Serialize) -> Self {
self.body = serde_json::to_vec(&body)
.expect("the JSON body should serialize")
.into();
self.headers
.insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
self.headers
.insert(header::ACCEPT, HeaderValue::from_static("application/json"));
self
}
#[track_caller]
pub fn form(mut self, body: impl Serialize) -> Self {
self.body = serde_urlencoded::to_string(body)
.expect("the form body should serialize")
.into();
self.headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/x-www-form-urlencoded"),
);
self
}
pub fn body(mut self, content: impl Into<Bytes>) -> Self {
self.body = content.into();
self
}
#[track_caller]
pub fn with_session(mut self, values: impl Serialize) -> Self {
let Value::Object(values) = serde_json::to_value(values).expect("the session values should serialize") else {
panic!("the session values should be a map, such as `json!({{ \"cart\": [1] }})`");
};
self.session.get_or_insert_with(Map::new).extend(values);
self
}
pub fn acting_as<U: crate::auth::Authenticatable>(mut self, user: &U) -> Self {
crate::auth::RequestUser::insert(&mut self.extensions, user.clone());
self
}
#[track_caller]
pub fn from(self, page: &str) -> Self {
let url = match app_url(&self.application) {
Some(app_url) if !page.contains("://") => {
let host = self.headers.get(header::HOST).and_then(|host| host.to_str().ok());
let root = format!("{}://{}", app_url.scheme(), host.unwrap_or("localhost"));
Url::parse(&root)
.and_then(|root| root.join(page))
.map_or_else(|_| page.to_owned(), String::from)
}
_ => page.to_owned(),
};
self.header("referer", url)
}
pub fn with_ip(mut self, ip: impl Into<IpAddr>) -> Self {
self.ip = ip.into();
self
}
pub fn attach(mut self, name: &str, attachment: impl Into<Attachment>) -> Self {
self.attachments.push((name.to_owned(), attachment.into()));
self
}
pub fn follow_redirects(mut self) -> Self {
self.follow_redirects = true;
self
}
async fn multipart(&mut self) {
const BOUNDARY: &str = "laravel-rust-test-boundary";
let is_form = self
.headers
.get(header::CONTENT_TYPE)
.is_some_and(|content_type| content_type == "application/x-www-form-urlencoded");
let fields: Vec<(String, String)> = if is_form {
serde_urlencoded::from_bytes(&self.body).unwrap_or_default()
} else {
assert!(
self.body.is_empty(),
"files can't be attached to a JSON or raw body: give the other fields to `form` instead\n\nat {}",
self.location
);
Vec::new()
};
let mut body = Vec::new();
for (name, value) in fields {
let name = escape_name(&name);
body.extend_from_slice(
format!("--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n")
.as_bytes(),
);
}
for (name, attachment) in std::mem::take(&mut self.attachments) {
let (name, file_name) = (escape_name(&name), escape_name(&attachment.file_name));
let content_type = attachment.content_type();
let contents = attachment
.read(&self.application.config().app.base_path)
.await
.unwrap_or_else(|error| {
let reason = std::error::Error::source(&error)
.map(ToString::to_string)
.unwrap_or_default();
panic!("{error}: {reason}\n\nat {}", self.location)
});
body.extend_from_slice(
format!(
"--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{file_name}\"\r\nContent-Type: {content_type}\r\n\r\n"
)
.as_bytes(),
);
body.extend_from_slice(&contents);
body.extend_from_slice(b"\r\n");
}
body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());
self.body = body.into();
self.headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("multipart/form-data; boundary=laravel-rust-test-boundary"),
);
}
async fn send(mut self) -> TestResponse {
if let Err(error) = self.application.boot().await {
panic!("the application failed to boot: {error}\n\nat {}", self.location);
}
if !self.attachments.is_empty() {
self.multipart().await;
}
let mut response = self.dispatch().await;
let mut redirects = 0;
while self.follow_redirects && self.follow(&response) {
redirects += 1;
if redirects > MAX_REDIRECTS {
panic!(
"followed {MAX_REDIRECTS} redirects without arriving at a page, which is likely a redirect loop\n\n{}\n\nat {}",
response.summary(),
self.location
);
}
let mut next = self.dispatch().await;
let mut reported = std::mem::take(&mut response.reports);
if let Some(handled) = response.handled.take().filter(|handled| handled.reported) {
reported.insert(0, handled.error);
}
next.reports.splice(0..0, reported);
next.earlier_cookies = response.cookies_on_the_way().collect();
response = next;
}
response
}
async fn dispatch(&mut self) -> TestResponse {
let mut headers = self.headers.clone();
if !self.cookies.is_empty() {
headers.insert(header::COOKIE, self.cookie_header());
}
if !self.body.is_empty() && !headers.contains_key(header::CONTENT_LENGTH) {
headers.insert(header::CONTENT_LENGTH, HeaderValue::from(self.body.len()));
}
let mut request = http::Request::builder()
.method(self.method.clone())
.uri(self.url(&headers))
.body(Body::from(self.body.clone()))
.expect("the request URI was parsed when the request was made");
*request.headers_mut() = headers;
let path = request
.uri()
.path_and_query()
.map_or("/", http::uri::PathAndQuery::as_str)
.to_owned();
request
.extensions_mut()
.insert(axum::extract::ConnectInfo(SocketAddr::new(self.ip, 0)));
let reports = RecordReports::default();
request.extensions_mut().insert(reports.clone());
let root = RecordRoot::default();
request.extensions_mut().insert(root.clone());
request.extensions_mut().extend(self.extensions.clone());
if let Some(values) = self.session.take() {
request.extensions_mut().insert(SessionSeed(values));
}
request.extensions_mut().insert(self.plaintext_cookies());
if let Err(problems) = self.application.check_auth_pages() {
panic!("{problems}");
}
let response = self
.application
.router()
.clone()
.oneshot(request)
.await
.unwrap_or_else(|never| match never {});
let (parts, body) = response.into_parts();
let session = parts.extensions.get::<Session>().map(Session::all);
let (body, failed_body) = read_body(body).await;
TestResponse {
referer: self
.headers
.get(header::REFERER)
.and_then(|value| value.to_str().ok())
.map(str::to_owned),
root: root
.0
.get()
.cloned()
.expect("the kernel records each test request's root"),
path,
handled: parts.extensions.get::<Handled>().cloned(),
reports: std::mem::take(&mut *reports.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)),
view: parts.extensions.get::<RenderedView>().cloned(),
session,
status: parts.status,
headers: parts.headers,
body,
failed_body,
asserted_failed_body: AtomicBool::new(false),
earlier_cookies: Vec::new(),
received_at: self.application.clock().now(),
requested_at: self.location,
application: self.application.clone(),
#[cfg(feature = "inertia")]
request: self.clone(),
}
}
#[cfg(feature = "inertia")]
pub(super) fn after(&self, response: &TestResponse) -> Self {
let mut next = self.clone();
for cookie in response.set_cookies() {
next.receive_cookie(response, &cookie);
}
next
}
#[cfg(feature = "inertia")]
pub(super) fn reload(mut self, reload: &::inertia::testing::ReloadRequest) -> Self {
let stale: Vec<HeaderName> = self
.headers
.keys()
.filter(|name| name.as_str().starts_with("x-inertia"))
.cloned()
.collect();
for name in stale.into_iter().chain([header::CONTENT_TYPE, header::CONTENT_LENGTH]) {
self.headers.remove(name);
}
self.headers.extend(reload.headers().clone());
self.method = Method::GET;
self.uri = parse_uri(reload.url());
self.body = Bytes::new();
self.location = reload.location();
self
}
fn url(&self, headers: &HeaderMap) -> http::Uri {
let app_url = app_url(&self.application);
let host = headers.get(header::HOST).and_then(|host| host.to_str().ok());
match (app_url, host) {
(Some(app_url), Some(host)) if self.uri.scheme().is_none() => {
format!("{}://{host}{}", app_url.scheme(), self.uri)
.parse()
.unwrap_or_else(|_| self.uri.clone())
}
_ => self.uri.clone(),
}
}
fn cookie_header(&self) -> HeaderValue {
let own = self.headers.get(header::COOKIE).and_then(|value| value.to_str().ok());
let cookies = self.cookies.iter().map(|cookie| {
cookie::Cookie::new(cookie.name.as_str(), cookie.value.as_str())
.encoded()
.to_string()
});
let header = own.map(str::to_owned).into_iter().chain(cookies).collect::<Vec<_>>();
HeaderValue::try_from(header.join("; ")).expect("encoded cookies are a valid header")
}
fn plaintext_cookies(&self) -> PlaintextCookies {
PlaintextCookies(
self.cookies
.iter()
.filter(|cookie| cookie.plaintext)
.map(|cookie| (cookie.name.clone(), cookie.value.clone()))
.collect(),
)
}
fn follow(&mut self, response: &TestResponse) -> bool {
let status = response.status.as_u16();
let Some(location) = response
.location()
.filter(|_| matches!(status, 301 | 302 | 303 | 307 | 308) && response.failed_body.is_none())
else {
return false;
};
if response
.root_url()
.is_none_or(|root| root.origin() != location.origin())
{
return false;
}
if !matches!(status, 307 | 308) {
if self.method != Method::HEAD {
self.method = Method::GET;
}
self.body = Bytes::new();
self.headers.remove(header::CONTENT_TYPE);
self.headers.remove(header::CONTENT_LENGTH);
}
self.uri = location[..::url::Position::AfterQuery]
.parse()
.expect("a redirect within the application is a valid URI");
for cookie in response.set_cookies() {
self.receive_cookie(response, &cookie);
}
true
}
}
async fn read_body(mut body: Body) -> (Bytes, Option<String>) {
let mut bytes = Vec::new();
let failed = loop {
match body.frame().await {
Some(Ok(frame)) => {
if let Some(data) = frame.data_ref() {
bytes.extend_from_slice(data);
}
}
Some(Err(error)) => break Some(error.to_string()),
None => break None,
}
};
(bytes.into(), failed)
}
#[derive(Debug, Clone)]
struct RequestCookie {
name: String,
value: String,
plaintext: bool,
}
const MAX_REDIRECTS: usize = 10;
fn escape_name(name: &str) -> String {
name.replace('"', "%22").replace('\r', "%0D").replace('\n', "%0A")
}
impl IntoFuture for TestRequest {
type Output = TestResponse;
type IntoFuture = Pin<Box<dyn Future<Output = TestResponse> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.send())
}
}