use crate::{
auth::Principal,
http::{RequestContext, RequestId, TraceParent},
};
use super::TestkitError;
#[must_use]
pub fn admin_principal() -> Principal {
Principal::user("test-admin")
.expect("static test principal id is valid")
.with_roles(["admin"])
.expect("static test role is valid")
.with_scopes(["*"])
.expect("static test scope is valid")
}
#[must_use]
pub fn request_context() -> RequestContext {
RequestContext::new(test_request_id("req_test"), None).with_principal(admin_principal())
}
#[must_use]
pub fn traceparent() -> TraceParent {
TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
.expect("static test traceparent is valid")
}
pub struct TestHttpRequestBuilder {
request: axum::http::request::Builder,
body: axum::body::Body,
}
impl TestHttpRequestBuilder {
#[must_use]
pub fn get(uri: impl Into<String>) -> Self {
Self::new(axum::http::Method::GET, uri)
}
#[must_use]
pub fn post(uri: impl Into<String>) -> Self {
Self::new(axum::http::Method::POST, uri)
}
#[must_use]
pub fn new(method: axum::http::Method, uri: impl Into<String>) -> Self {
Self {
request: axum::http::Request::builder()
.method(method)
.uri(uri.into()),
body: axum::body::Body::empty(),
}
}
#[must_use]
pub fn header<K, V>(mut self, name: K, value: V) -> Self
where
axum::http::HeaderName: TryFrom<K>,
<axum::http::HeaderName as TryFrom<K>>::Error: Into<axum::http::Error>,
axum::http::HeaderValue: TryFrom<V>,
<axum::http::HeaderValue as TryFrom<V>>::Error: Into<axum::http::Error>,
{
self.request = self.request.header(name, value);
self
}
#[must_use]
pub fn bearer(self, token: impl AsRef<str>) -> Self {
self.header(
axum::http::header::AUTHORIZATION,
format!("Bearer {}", token.as_ref()),
)
}
#[must_use]
pub fn request_id(self, request_id: impl AsRef<str>) -> Self {
self.header(
axum::http::HeaderName::from_static("x-request-id"),
request_id.as_ref(),
)
}
#[must_use]
pub fn traceparent(self, traceparent: impl AsRef<str>) -> Self {
self.header(
axum::http::HeaderName::from_static("traceparent"),
traceparent.as_ref(),
)
}
#[must_use]
pub fn json_body(mut self, value: &serde_json::Value) -> Self {
self.request = self.request.header(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
);
self.body = axum::body::Body::from(value.to_string());
self
}
#[must_use]
pub fn body(mut self, body: impl Into<axum::body::Body>) -> Self {
self.body = body.into();
self
}
pub fn try_build(self) -> Result<axum::http::Request<axum::body::Body>, TestkitError> {
self.request
.body(self.body)
.map_err(TestkitError::RequestBuild)
}
pub fn build(self) -> axum::http::Request<axum::body::Body> {
self.try_build()
.unwrap_or_else(|error| panic!("test request should build: {error}"))
}
}
pub(super) fn test_request_id(value: &str) -> RequestId {
RequestId::new(value)
.unwrap_or_else(|error| panic!("invalid test request id {value:?}: {error}"))
}