footing 0.1.21

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

use super::*;
use crate::{http::ApiProblem, observability::MetricLabels};

#[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).unwrap();
            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 ?#%").unwrap();
        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");
    }
}

#[test]
#[cfg(feature = "postgres")]
fn postgres_database_name_replacement_isolates_opaque_urls() {
    use std::str::FromStr;

    for base in [
        "postgres:production",
        "postgresql:production?application_name=test#fragment",
        "postgres:production?dbname=first&sslmode=require&dbname=second",
    ] {
        crate::db::postgres::PostgresBootstrapSettings::new(base)
            .build()
            .expect("SQLx-supported opaque URLs are valid Footing inputs");
        for name in ["isolated_test", ".", "..", "test/db ?#%", "quoted\"name"] {
            let replaced = postgres::database_url_with_name(base, name).unwrap();
            assert_eq!(
                crate::db::postgres::database_name(&replaced).as_deref(),
                Some(name)
            );
            let options = sqlx::postgres::PgConnectOptions::from_str(&replaced).unwrap();
            assert_eq!(options.get_database(), Some(name));
            let original = url::Url::parse(base).unwrap();
            let rewritten = url::Url::parse(&replaced).unwrap();
            assert_eq!(original.fragment(), rewritten.fragment());
            assert_eq!(
                rewritten
                    .query_pairs()
                    .filter(|(key, _)| key == "dbname")
                    .count(),
                1
            );
            for option in original.query_pairs().filter(|(key, _)| key != "dbname") {
                assert!(rewritten.query_pairs().any(|value| value == option));
            }
        }
    }
}

#[test]
#[cfg(feature = "postgres")]
fn postgres_database_name_replacement_rejects_invalid_inputs() {
    for base in [
        "not-a-url",
        "https://localhost/production",
        "sqlite::memory:",
        "postgres://[",
    ] {
        assert!(matches!(
            postgres::database_url_with_name(base, "isolated_test"),
            Err(TestkitError::InvalidPostgresUrl)
        ));
    }
    for name in [
        "",
        "  ",
        "name\0suffix",
        "name\nsuffix",
        &"a".repeat(64),
        &"库".repeat(22),
    ] {
        assert!(matches!(
            postgres::database_url_with_name("postgres://localhost/production", name),
            Err(TestkitError::InvalidDatabaseName)
        ));
    }
}

#[test]
fn test_metrics_records_samples() {
    let metrics = TestMetrics::new();
    metrics
        .recorder()
        .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")
        .header("x-custom", "custom-value")
        .header(
            axum::http::header::ACCEPT,
            axum::http::HeaderValue::from_static("application/json"),
        )
        .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());
    assert_eq!(request.headers()["x-custom"], "custom-value");
    assert_eq!(
        request.headers()[axum::http::header::ACCEPT],
        "application/json"
    );
}

#[test]
fn invalid_test_headers_fail_request_building() {
    use std::error::Error;

    for request in [
        TestHttpRequestBuilder::get("/")
            .bearer("invalid\r\nheader")
            .request_id("valid"),
        TestHttpRequestBuilder::get("/").header("invalid header name", "value"),
    ] {
        let error = request.try_build().unwrap_err();
        assert!(matches!(error, TestkitError::RequestBuild(_)));
        assert!(error.source().unwrap().is::<axum::http::Error>());
    }
}

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

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

    let problem = assert_response_problem(response, StatusCode::BAD_REQUEST, "invalid_input").await;
    assert_eq!(problem.detail(), "bad input");
    assert_eq!(problem.request_id(), Some("req_test"));
}

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

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

    let store = worker::TestOutboxStore::with_items([
        worker::TestOutboxItem::succeeded("ok"),
        worker::TestOutboxItem::failed("one", "terminal failure").with_attempts(100),
        worker::TestOutboxItem::skipped("skipped", "not needed"),
        worker::TestOutboxItem::failed("two", "other 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(crate::worker::WorkerContext::default())
        .await
        .expect("outbox should run");

    assert_eq!(summary.succeeded(), 1);
    assert_eq!(summary.skipped(), 1);
    assert_eq!(summary.failed(), 2);
    assert_eq!(summary.dead_lettered(), 2);
    assert_eq!(store.states().len(), 4);
    assert_eq!(
        store.dead_letters(),
        vec![
            ("one".to_owned(), "terminal failure".to_owned()),
            ("two".to_owned(), "other failure".to_owned()),
        ]
    );
}

#[tokio::test]
async fn testkit_outbox_claims_only_available_items_up_to_the_limit() {
    use crate::worker::{OutboxClaim, OutboxStore, WorkerContext};
    use std::time::Duration;

    let first = worker::TestOutboxItem::succeeded("first");
    let second = worker::TestOutboxItem::succeeded("second");
    let store = worker::TestOutboxStore::with_items([first.clone(), second.clone()]);
    for (limit, expected) in [
        (0, vec![]),
        (1, vec![first]),
        (u32::MAX, vec![second]),
        (u32::MAX, vec![]),
    ] {
        assert_eq!(
            store
                .claim_due(
                    OutboxClaim::new(limit, Duration::from_secs(1)),
                    WorkerContext::default()
                )
                .await
                .unwrap(),
            expected,
        );
    }
}