footing 0.1.9

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]
#[cfg(feature = "postgres")]
fn postgres_database_name_replacement_preserves_dot_names_and_overrides_dbname() {
    for name in [".", "..", "test/db ?#%", "app"] {
        for base in [
            "postgres://user:pass@localhost/base?sslmode=require#fragment",
            "postgres://user:pass@localhost/base?dbname=old&sslmode=require&dbname=older#fragment",
        ] {
            let replaced = postgres::database_url_with_name(base, name);
            assert_eq!(
                crate::db::postgres::database_name(&replaced).as_deref(),
                Some(name)
            );
            let url = url::Url::parse(&replaced).unwrap();
            assert_eq!(url.username(), "user");
            assert_eq!(url.password(), Some("pass"));
            assert_eq!(url.host_str(), Some("localhost"));
            assert_eq!(url.fragment(), Some("fragment"));
            assert!(
                url.query_pairs()
                    .any(|(key, value)| key == "sslmode" && value == "require")
            );
            assert!(url.query_pairs().filter(|(key, _)| key == "dbname").count() <= 1);
        }
    }
}

#[test]
#[cfg(feature = "postgres")]
fn postgres_database_name_replacement_preserves_url_components() {
    for base in [
        "postgres://user:pass@localhost/base?sslmode=verify-full",
        "postgresql://user:pass@[::1]:5432/base?sslrootcert=/etc/ssl/root.crt#fragment",
        "postgres://localhost?application_name=test",
        "postgres://user:p%2Fass@localhost/base",
    ] {
        let original = url::Url::parse(base).unwrap();
        let replaced = postgres::database_url_with_name(base, "test/db ?#%");
        let replaced = url::Url::parse(&replaced).unwrap();
        assert_eq!(replaced.query(), original.query());
        assert_eq!(replaced.fragment(), original.fragment());
        assert_eq!(replaced.username(), original.username());
        assert_eq!(replaced.password(), original.password());
        assert_eq!(replaced.host_str(), original.host_str());
        assert_eq!(replaced.port(), original.port());
        assert_eq!(replaced.path(), "/test%2Fdb%20%3F%23%25");
    }
    assert_eq!(
        postgres::database_url_with_name("not-a-url", "test"),
        "not-a-url"
    );
}

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

#[test]
fn invalid_test_headers_fail_request_building() {
    let result = TestHttpRequestBuilder::get("/")
        .bearer("invalid\r\nheader")
        .request_id("valid")
        .try_build();
    assert!(matches!(result, Err(TestkitError::RequestBuild(_))));
}

#[tokio::test]
async fn try_response_problem_returns_status_mismatch() {
    let response = axum::http::Response::builder()
        .status(StatusCode::OK)
        .body(axum::body::Body::from(
            serde_json::to_string(
                &ApiProblem::bad_request(
                    crate::http::ProblemCode::try_new("invalid_request").unwrap(),
                    "invalid request",
                )
                .into_body(),
            )
            .unwrap(),
        ))
        .unwrap();
    assert!(matches!(
        try_response_problem(response).await,
        Err(TestkitError::ResponseStatusMismatch {
            http_status: 200,
            problem_status: 400,
        })
    ));
}

#[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())]
    );
}