use std::net::SocketAddr;
use std::path::{Path, PathBuf};
use std::sync::{Arc, RwLock};
use std::time::Duration;
use http_body_util::{BodyExt as _, Full};
use hyper::body::Bytes;
use hyper::{Method, Request, Uri};
use tokio::sync::Semaphore;
use tracing::Instrument as _;
use crate::handler;
use crate::protect::Protection;
use crate::request::LuaRequest;
use crate::server::current_pool;
use nitr_core::{Error, ErrorInfo, Result, RuntimePool};
mod request;
mod sse;
mod unit;
pub use request::TestRequest;
pub use sse::{SseEvent, parse_sse};
pub use unit::{fake_request, load_app};
const DEFAULT_PEER: ([u8; 4], u16) = ([127, 0, 0, 1], 0);
#[derive(Clone)]
pub struct TestClient {
pool: Arc<RwLock<Arc<RuntimePool>>>,
streams: Arc<Semaphore>,
protection: Arc<Protection>,
tls: bool,
}
#[derive(Debug, Clone)]
pub struct HandlerFailure {
pub info: ErrorInfo,
pub handled: bool,
}
#[derive(Debug)]
pub struct TestResponse {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Bytes,
pub error: Option<HandlerFailure>,
}
impl TestClient {
pub(crate) fn new(
pool: Arc<RwLock<Arc<RuntimePool>>>,
streams: Arc<Semaphore>,
protection: Arc<Protection>,
tls: bool,
) -> Self {
Self {
pool,
streams,
protection,
tls,
}
}
pub async fn request(
&self,
method: &str,
path_and_query: &str,
headers: &[(String, String)],
body: Option<Bytes>,
) -> Result<TestResponse> {
self.send(TestRequest {
method: method.to_string(),
path: path_and_query.to_string(),
headers: headers.to_vec(),
body,
remote_addr: None,
timeout: None,
})
.await
}
pub async fn send(&self, spec: TestRequest) -> Result<TestResponse> {
let method: Method =
spec.method.to_uppercase().parse().map_err(|_| {
Error::Config(format!("invalid test request method `{}`", spec.method))
})?;
let uri: Uri = spec
.path
.parse()
.map_err(|_| Error::Config(format!("invalid test request path `{}`", spec.path)))?;
let mut builder = Request::builder().method(method.clone()).uri(uri.clone());
for (name, value) in &spec.headers {
builder = builder.header(name, value);
}
let req = builder.body(
Full::new(spec.body.unwrap_or_default())
.map_err(|never| match never {})
.boxed(),
)?;
let id = self.protection.request_id_for_parts(req.headers());
let span = tracing::info_span!(
"request",
id = %id,
method = %method,
path = %uri.path(),
status = tracing::field::Empty,
);
let peer = spec.remote_addr.unwrap_or_else(|| DEFAULT_PEER.into());
let mut req = LuaRequest::synthetic(req, peer, id.into());
req.tls = self.tls;
let pool = current_pool(&self.pool);
let streams = self.streams.clone();
let protection = self.protection.clone();
let exchange = async move {
let resp = handler::handle(&pool, req, streams, protection).await?;
collect(resp).await
}
.instrument(span);
match spec.timeout {
None => exchange.await,
Some(limit) => tokio::time::timeout(limit, exchange).await.map_err(|_| {
Error::Script(format!(
"the test request {method} {} did not complete within {} s (its \
`timeout` option); a streaming body that never ends?",
uri.path(),
limit.as_secs_f64()
))
})?,
}
}
}
async fn collect(resp: handler::HttpResponse) -> Result<TestResponse> {
let status = resp.status().as_u16();
let error = resp.extensions().get::<HandlerFailure>().cloned();
let headers = resp
.headers()
.iter()
.map(|(k, v)| {
(
k.as_str().to_string(),
v.to_str().unwrap_or_default().to_string(),
)
})
.collect();
let body = match resp.into_body().collect().await {
Ok(collected) => collected.to_bytes(),
Err(never) => match never {},
};
Ok(TestResponse {
status,
headers,
body,
error,
})
}
impl TestResponse {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case(name))
.map(|(_, v)| v.as_str())
}
}
pub fn fixture_path(root: &Path, rel: &str) -> Result<PathBuf> {
let refuse = |why: &str| {
Error::Script(format!(
"fixture `{rel}` {why}: fixtures are regular files under [testing] dir {}",
root.display()
))
};
let joined =
crate::safe_path::safe_join(root, rel).map_err(|_| refuse("is not a relative path"))?;
let (Ok(canonical), Ok(root_canonical)) = (joined.canonicalize(), root.canonicalize()) else {
return Err(refuse("does not exist"));
};
if !canonical.starts_with(&root_canonical) {
return Err(refuse("resolves outside the tests directory"));
}
if !canonical.is_file() {
return Err(refuse("is not a regular file"));
}
Ok(canonical)
}
pub struct TestWatch {
_guard: crate::watch::WatchGuard,
}
pub fn watch_tests(
cfg: &crate::Config,
extra: &[PathBuf],
changed: tokio::sync::mpsc::Sender<()>,
) -> Option<TestWatch> {
crate::watch::spawn(cfg, extra, changed).map(|guard| TestWatch { _guard: guard })
}
pub(crate) fn parse_peer(text: &str) -> Option<SocketAddr> {
text.parse::<SocketAddr>().ok().or_else(|| {
text.parse::<std::net::IpAddr>()
.ok()
.map(|ip| SocketAddr::new(ip, 0))
})
}
pub(crate) fn seconds(name: &str, secs: f64) -> mlua::Result<Duration> {
Duration::try_from_secs_f64(secs)
.ok()
.filter(|d| !d.is_zero() && *d <= Duration::from_secs(86_400))
.ok_or_else(|| {
mlua::Error::RuntimeError(format!(
"`{name}` must be a number of seconds between 0 and 86400, got {secs}"
))
})
}
#[cfg(test)]
mod tests;