footing 0.1.12

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

use super::TestkitError;

#[must_use]
/// Creates a manual monotonic clock starting at the current instant.
pub fn manual_clock() -> ManualClock {
    ManualClock::new()
}

#[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")
}

#[derive(Debug, Clone)]
/// Builder for constructing test principal.
pub struct TestPrincipalBuilder {
    principal: Principal,
}

impl TestPrincipalBuilder {
    #[must_use]
    /// Creates user.
    pub fn user(id: impl Into<String>) -> Self {
        Self {
            principal: Principal::new(id, PrincipalKind::User)
                .expect("test principal id must be valid"),
        }
    }

    #[must_use]
    /// Creates client.
    pub fn client(id: impl Into<String>) -> Self {
        Self {
            principal: Principal::new(id, PrincipalKind::Client)
                .expect("test principal id must be valid"),
        }
    }

    #[must_use]
    /// Creates service account.
    pub fn service_account(id: impl Into<String>) -> Self {
        Self {
            principal: Principal::new(id, PrincipalKind::ServiceAccount)
                .expect("test principal id must be valid"),
        }
    }

    #[must_use]
    /// Returns the tenant.
    pub fn tenant(mut self, tenant_id: impl Into<String>) -> Self {
        self.principal = self
            .principal
            .with_tenant_id(tenant_id)
            .expect("test tenant id must be valid");
        self
    }

    #[must_use]
    /// Returns the role.
    pub fn role(mut self, role: impl Into<String>) -> Self {
        self.principal
            .add_role(role)
            .expect("test role must be valid");
        self
    }

    #[must_use]
    /// Returns the scope.
    pub fn scope(mut self, scope: impl Into<String>) -> Self {
        self.principal
            .add_scope(scope)
            .expect("test scope must be valid");
        self
    }

    #[must_use]
    /// Builds the configured value.
    pub fn build(self) -> Principal {
        self.principal
    }
}

#[derive(Debug, Clone)]
/// Builder for constructing test request context.
pub struct TestRequestContextBuilder {
    request_id: RequestId,
    traceparent: Option<String>,
    principal: Option<Principal>,
}

impl TestRequestContextBuilder {
    #[must_use]
    /// Creates a new instance.
    pub fn new() -> Self {
        Self {
            request_id: test_request_id("req_test"),
            traceparent: None,
            principal: None,
        }
    }

    #[must_use]
    /// Returns the request identifier.
    pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
        self.request_id = test_request_id(&request_id.into());
        self
    }

    #[must_use]
    /// Returns the traceparent.
    pub fn traceparent(mut self, traceparent: impl Into<String>) -> Self {
        self.traceparent = Some(traceparent.into());
        self
    }

    #[must_use]
    /// Returns the standard traceparent.
    pub fn standard_traceparent(mut self) -> Self {
        self.traceparent = Some(traceparent().into_string());
        self
    }

    #[must_use]
    /// Returns the principal.
    pub fn principal(mut self, principal: Principal) -> Self {
        self.principal = Some(principal);
        self
    }

    #[must_use]
    /// Builds the configured value.
    pub fn build(self) -> RequestContext {
        let context = RequestContext::new(self.request_id, self.traceparent);
        if let Some(principal) = self.principal {
            context.with_principal(principal)
        } else {
            context
        }
    }
}

impl Default for TestRequestContextBuilder {
    fn default() -> Self {
        Self::new()
    }
}

/// 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]
    /// Returns the header.
    pub fn header(mut self, name: axum::http::HeaderName, value: axum::http::HeaderValue) -> Self {
        self.request = self.request.header(name, value);
        self
    }

    #[must_use]
    /// Adds a header, preserving invalid values as an error for `try_build`.
    pub fn header_str(mut self, name: axum::http::HeaderName, value: impl AsRef<str>) -> Self {
        self.request = self.request.header(name, value.as_ref());
        self
    }

    #[must_use]
    /// Returns the bearer.
    pub fn bearer(self, token: impl AsRef<str>) -> Self {
        self.header_str(
            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_str(
            axum::http::HeaderName::from_static("x-request-id"),
            request_id,
        )
    }

    #[must_use]
    /// Returns the traceparent.
    pub fn traceparent(self, traceparent: impl AsRef<str>) -> Self {
        self.header_str(
            axum::http::HeaderName::from_static("traceparent"),
            traceparent,
        )
    }

    #[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}"))
}