footing 0.3.1

Feature-gated foundations for Rust backend services
Documentation
use serde::de::DeserializeOwned;

use crate::{
    http::ProblemDetails,
    observability::{MetricLabels, MetricsSnapshot},
};

use super::TestkitError;

/// Attempts to read a response body as UTF-8 text.
pub async fn try_response_body_text(
    response: axum::response::Response,
) -> Result<String, TestkitError> {
    let bytes = axum::body::to_bytes(response.into_body(), usize::MAX)
        .await
        .map_err(TestkitError::ResponseBody)?;
    String::from_utf8(bytes.into()).map_err(TestkitError::ResponseUtf8)
}

/// Reads a response body as UTF-8 text or panics with test context.
pub async fn response_body_text(response: axum::response::Response) -> String {
    try_response_body_text(response)
        .await
        .unwrap_or_else(|error| panic!("response body should be text: {error}"))
}

/// Attempts to deserialize a JSON response.
pub async fn try_response_json<T>(response: axum::response::Response) -> Result<T, TestkitError>
where
    T: DeserializeOwned,
{
    let body = try_response_body_text(response).await?;
    serde_json::from_str(&body).map_err(TestkitError::ResponseJson)
}

/// Deserializes a JSON response or panics with test context.
pub async fn response_json<T>(response: axum::response::Response) -> T
where
    T: DeserializeOwned,
{
    try_response_json(response)
        .await
        .unwrap_or_else(|error| panic!("response body should be JSON: {error}"))
}

/// Checks the HTTP status and decodes the JSON response body.
pub async fn assert_response_json<T>(
    response: axum::response::Response,
    expected_status: axum::http::StatusCode,
) -> T
where
    T: DeserializeOwned,
{
    assert_eq!(response.status(), expected_status);
    response_json(response).await
}

/// Attempts to deserialize an RFC 9457 response.
pub async fn try_response_problem(
    response: axum::response::Response,
) -> Result<ProblemDetails, TestkitError> {
    let status = response.status();
    let problem: ProblemDetails = try_response_json(response).await?;
    if problem.status() != status.as_u16() {
        return Err(TestkitError::ResponseStatusMismatch {
            http_status: status.as_u16(),
            problem_status: problem.status(),
        });
    }
    Ok(problem)
}

/// Deserializes an RFC 9457 response or panics with test context.
pub async fn response_problem(response: axum::response::Response) -> ProblemDetails {
    try_response_problem(response)
        .await
        .unwrap_or_else(|error| panic!("response body should be problem+json: {error}"))
}

/// Checks the HTTP status, matching problem status, and application error code.
/// Returns the decoded problem for any additional field assertions.
pub async fn assert_response_problem(
    response: axum::response::Response,
    expected_status: axum::http::StatusCode,
    expected_code: &str,
) -> ProblemDetails {
    assert_eq!(response.status(), expected_status);
    let problem = response_problem(response).await;
    assert_eq!(problem.code(), expected_code);
    problem
}

#[derive(Debug, Clone, Copy)]
/// Fluent assertions for a settings validation error.
pub struct SettingsValidationAssert<'a> {
    error: &'a crate::settings::SettingsValidationError,
}

impl<'a> SettingsValidationAssert<'a> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(error: &'a crate::settings::SettingsValidationError) -> Self {
        Self { error }
    }

    #[must_use]
    /// Returns the issue count.
    pub fn issue_count(self, expected: usize) -> Self {
        assert_eq!(self.error.issues().len(), expected);
        self
    }

    #[must_use]
    /// Returns whether this value has path.
    pub fn has_path(self, expected_path: &str) -> Self {
        assert!(
            self.error
                .issues()
                .iter()
                .any(|issue| issue.path() == expected_path),
            "expected settings validation error to include path {expected_path:?}; got {:?}",
            self.error.issues()
        );
        self
    }

    #[must_use]
    /// Asserts that an issue at this path contains the expected message.
    pub fn path_message_contains(self, expected_path: &str, expected_message: &str) -> Self {
        assert!(
            self.error.issues().iter().any(|issue| {
                issue.path() == expected_path && issue.message().contains(expected_message)
            }),
            "expected settings issue at {expected_path:?} to contain {expected_message:?}; got {:?}",
            self.error.issues()
        );
        self
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub const fn into_inner(self) -> &'a crate::settings::SettingsValidationError {
        self.error
    }
}

#[must_use]
/// Starts fluent assertions for a settings validation error.
pub const fn assert_settings_error(
    error: &crate::settings::SettingsValidationError,
) -> SettingsValidationAssert<'_> {
    SettingsValidationAssert::new(error)
}

/// Asserts metric value.
pub fn assert_metric_value(
    snapshot: &MetricsSnapshot,
    name: &str,
    labels: MetricLabels,
    expected: f64,
) {
    let labels = labels.into_vec();
    let sample = snapshot
        .samples()
        .iter()
        .find(|sample| sample.name() == name && sample.labels() == labels.as_slice())
        .unwrap_or_else(|| panic!("metric sample {name} with expected labels was not found"));
    assert_eq!(sample.value(), expected);
}

/// Asserts metric value at least.
pub fn assert_metric_value_at_least(
    snapshot: &MetricsSnapshot,
    name: &str,
    labels: MetricLabels,
    expected_minimum: f64,
) {
    let labels = labels.into_vec();
    let sample = snapshot
        .samples()
        .iter()
        .find(|sample| sample.name() == name && sample.labels() == labels.as_slice())
        .unwrap_or_else(|| panic!("metric {name} with labels {labels:?} should exist"));
    assert!(
        sample.value() >= expected_minimum,
        "metric {name} with labels {labels:?} value {} should be at least {expected_minimum}",
        sample.value()
    );
}

/// Asserts no metric.
pub fn assert_no_metric(snapshot: &MetricsSnapshot, name: &str, labels: MetricLabels) {
    let labels = labels.into_vec();
    let found = snapshot
        .samples()
        .iter()
        .any(|sample| sample.name() == name && sample.labels() == labels.as_slice());
    assert!(
        !found,
        "metric {name} with labels {labels:?} should not exist"
    );
}