footing 0.1.22

Feature-gated foundations for Rust backend services
Documentation
use crate::{
    auth::Principal,
    http::{RequestContext, RequestId, TraceParent},
};

use super::TestkitError;

#[must_use]
/// Creates a conventional administrator principal for tests.
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]
/// Creates a request context with stable test identifiers.
pub fn request_context() -> RequestContext {
    RequestContext::new(test_request_id("req_test"), None).with_principal(admin_principal())
}

#[must_use]
/// Creates a valid W3C `traceparent` value for tests.
pub fn traceparent() -> TraceParent {
    TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
        .expect("static test traceparent is valid")
}

/// Builder for constructing test HTTP request.
pub struct TestHttpRequestBuilder {
    request: axum::http::request::Builder,
    body: axum::body::Body,
}

impl TestHttpRequestBuilder {
    #[must_use]
    /// Creates get.
    pub fn get(uri: impl Into<String>) -> Self {
        Self::new(axum::http::Method::GET, uri)
    }

    #[must_use]
    /// Creates post.
    pub fn post(uri: impl Into<String>) -> Self {
        Self::new(axum::http::Method::POST, uri)
    }

    #[must_use]
    /// Creates a new instance.
    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]
    /// Adds a typed or string header, preserving invalid input for [`Self::try_build`].
    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]
    /// Returns the bearer.
    pub fn bearer(self, token: impl AsRef<str>) -> Self {
        self.header(
            axum::http::header::AUTHORIZATION,
            format!("Bearer {}", token.as_ref()),
        )
    }

    #[must_use]
    /// Returns the request identifier.
    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]
    /// Returns the traceparent.
    pub fn traceparent(self, traceparent: impl AsRef<str>) -> Self {
        self.header(
            axum::http::HeaderName::from_static("traceparent"),
            traceparent.as_ref(),
        )
    }

    #[must_use]
    /// Returns the JSON body.
    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]
    /// Returns the body.
    pub fn body(mut self, body: impl Into<axum::body::Body>) -> Self {
        self.body = body.into();
        self
    }

    /// Attempts to build the configured HTTP request.
    pub fn try_build(self) -> Result<axum::http::Request<axum::body::Body>, TestkitError> {
        self.request
            .body(self.body)
            .map_err(TestkitError::RequestBuild)
    }

    /// Builds the configured value.
    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}"))
}