footing 0.1.3

Feature-gated foundations for Rust backend services
Documentation
use axum::{
    Json, Router,
    http::StatusCode,
    routing::{get, post},
};
use serde_json::json;

use super::*;
use crate::{
    http::ApiProblem,
    observability::{MetricLabels, MetricRecorder},
    result::{Diagnostic, DiagnosticKind, ErrorDescriptor, ErrorKind},
};

#[test]
fn test_metrics_records_samples() {
    let metrics = TestMetrics::new();
    metrics
        .increment_counter("jobs_total", 1, MetricLabels::default())
        .expect("metric should record");

    let snapshot = metrics.snapshot().expect("snapshot should build");
    assert_eq!(snapshot.samples().len(), 1);
    assert_eq!(snapshot.samples()[0].name(), "jobs_total");
    metrics.assert_counter("jobs_total", MetricLabels::default(), 1);
    metrics.assert_counter_at_least("jobs_total", MetricLabels::default(), 1);
    metrics.assert_no_metric("missing_total", MetricLabels::default());
}

#[tokio::test]
async fn test_http_app_runs_requests() {
    let app = TestHttpApp::new(Router::new().route("/health", get(|| async { "ok" })));

    let response = app.get("/health").await;

    assert_eq!(response.status(), StatusCode::OK);
}

#[test]
fn test_http_request_builder_sets_standard_headers() {
    let request = TestHttpRequestBuilder::get("/secure")
        .bearer("token")
        .request_id("req_test")
        .traceparent(traceparent().into_string())
        .build();

    assert_eq!(
        request
            .headers()
            .get(axum::http::header::AUTHORIZATION)
            .and_then(|value| value.to_str().ok()),
        Some("Bearer token")
    );
    assert_eq!(
        request
            .headers()
            .get("x-request-id")
            .and_then(|value| value.to_str().ok()),
        Some("req_test")
    );
    assert!(request.headers().get("traceparent").is_some());
}

#[tokio::test]
async fn test_http_app_decodes_json_responses() {
    let app = TestHttpApp::new(Router::new().route(
        "/echo",
        post(|Json(value): Json<serde_json::Value>| async move { Json(value) }),
    ));

    let response = app.post_json("/echo", &json!({ "ok": true })).await;
    let body: serde_json::Value = assert_response_json(response, StatusCode::OK).await;

    assert_eq!(body, json!({ "ok": true }));
}

#[test]
fn problem_assertion_is_chainable() {
    let code = crate::http::ProblemCode::try_new("invalid_input")
        .expect("test problem code should be valid");
    let problem = ApiProblem::bad_request(code, "bad input")
        .with_request_id(&test_request_id("req_test"))
        .into_body();

    let _problem = ProblemAssert::new(problem)
        .status(StatusCode::BAD_REQUEST)
        .code("invalid_input")
        .detail("bad input")
        .request_id("req_test")
        .into_inner();
}

#[test]
fn diagnostic_and_error_assertions_are_chainable() {
    let diagnostic = Diagnostic::dependency(
        "postgres",
        "connect",
        DiagnosticKind::Unavailable,
        "connection refused",
    )
    .with_resource("postgres://localhost/app")
    .with_remediation("start PostgreSQL")
    .with_retryable(true);

    let _diagnostic = assert_diagnostic(&diagnostic)
        .component("postgres")
        .operation("connect")
        .resource(Some("postgres://localhost/app"))
        .kind(DiagnosticKind::Unavailable)
        .message_contains("refused")
        .remediation_contains("PostgreSQL")
        .retryable(true)
        .into_inner();

    let descriptor = ErrorDescriptor::new(
        ErrorKind::Validation,
        crate::result::ErrorCode::try_new("invalid_test_input")
            .expect("static error code should be valid"),
        "test input is invalid",
    );
    let _descriptor = assert_error_descriptor(descriptor)
        .kind(ErrorKind::Validation)
        .code("invalid_test_input")
        .message_contains("invalid")
        .retryable(false)
        .public_message("test input is invalid")
        .into_inner();
}

#[cfg(feature = "settings")]
#[test]
fn settings_validation_assertion_checks_issue_paths() {
    let error = crate::settings::SettingsValidationError::single(
        "server.http.timeout",
        "must be greater than zero",
    );

    let _error = assert_settings_error(&error)
        .issue_count(1)
        .has_path("server.http.timeout")
        .path_message_contains("server.http.timeout", "greater")
        .into_inner();
}

#[cfg(feature = "settings")]
#[test]
fn http_foundation_test_harness_validates_and_adapts_settings() {
    let harness = TestHttpFoundation::default().assert_valid();

    assert!(harness.config().request_context_enabled());
    assert!(harness.invalid_paths("server.http").is_empty());
}

#[cfg(feature = "worker")]
#[tokio::test]
async fn testkit_outbox_records_dead_letters() {
    use crate::worker::BatchWorkerJob;

    let store = worker::TestOutboxStore::with_items([worker::TestOutboxItem::failed(
        "one",
        "terminal failure",
    )
    .with_attempts(100)]);
    let job = crate::worker::OutboxJob::new(
        "test outbox",
        store.clone(),
        worker::TestOutboxHandler,
        crate::worker::OutboxWorkerSettings::default()
            .with_batch_size(10)
            .build()
            .expect("test outbox settings should be valid"),
    );

    let summary = job.run_batch().await.expect("outbox should run");

    assert_eq!(summary.failed(), 1);
    assert_eq!(summary.dead_lettered(), 1);
    assert_eq!(
        store.dead_letters(),
        vec![("one".to_owned(), "terminal failure".to_owned())]
    );
}