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://[",
"postgres://localhost/production?application_name=test%00database%00production",
"postgres://localhost/production?options[search_path%00database]=public",
"postgres://user%00application_name%00test@localhost/production",
"postgres://localhost/production?application_name=test%0\n0database%0\t0production",
] {
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)
.header(axum::http::header::CONTENT_TYPE, "application/problem+json")
.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 try_response_problem_accepts_media_type_case_and_parameters() {
for value in [
"application/problem+json",
"Application/Problem+JSON",
"application/problem+json; charset=utf-8",
"application/problem+json; charset=\"UTF-8\"; profile=\"test; profile\"",
" \tapplication/problem+json \t",
] {
let mut response = ApiProblem::bad_request(
crate::http::ProblemCode::from_static("invalid_request"),
"invalid request",
)
.into_response();
response
.headers_mut()
.insert(axum::http::header::CONTENT_TYPE, value.parse().unwrap());
let problem = try_response_problem(response).await.unwrap();
assert_eq!(problem.status(), 400);
assert_eq!(problem.code(), "invalid_request");
}
}
#[tokio::test]
async fn try_response_problem_rejects_missing_or_invalid_content_type() {
for value in [
None,
Some("application/json"),
Some("text/problem+json"),
Some("application/problem+xml"),
Some("application/problem+json-extra"),
Some("application/problem+json, application/problem+json"),
Some("application/problem+json; charset=\"unterminated"),
Some("application/problem+json; invalid parameter=value"),
Some(""),
] {
let mut response = ApiProblem::bad_request(
crate::http::ProblemCode::from_static("invalid_request"),
"invalid request",
)
.into_response();
response
.headers_mut()
.remove(axum::http::header::CONTENT_TYPE);
if let Some(value) = value {
response
.headers_mut()
.insert(axum::http::header::CONTENT_TYPE, value.parse().unwrap());
}
assert!(
matches!(
try_response_problem(response).await,
Err(TestkitError::ResponseContentType)
),
"unexpected acceptance of Content-Type {value:?}"
);
}
}
#[tokio::test]
async fn try_response_problem_rejects_non_ascii_and_duplicate_content_types() {
let mut response = ApiProblem::bad_request(
crate::http::ProblemCode::from_static("invalid_request"),
"invalid request",
)
.into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_bytes(b"application/problem+json; charset=\xff").unwrap(),
);
assert!(matches!(
try_response_problem(response).await,
Err(TestkitError::ResponseContentType)
));
for second in ["application/problem+json", "application/json"] {
let mut response = ApiProblem::bad_request(
crate::http::ProblemCode::from_static("invalid_request"),
"invalid request",
)
.into_response();
response
.headers_mut()
.append(axum::http::header::CONTENT_TYPE, second.parse().unwrap());
assert!(matches!(
try_response_problem(response).await,
Err(TestkitError::ResponseContentType)
));
}
}
#[tokio::test]
#[should_panic(
expected = "problem response must have exactly one application/problem+json Content-Type"
)]
async fn assert_response_problem_rejects_wrong_content_type() {
let mut response = ApiProblem::bad_request(
crate::http::ProblemCode::from_static("invalid_request"),
"invalid request",
)
.into_response();
response.headers_mut().insert(
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
);
assert_response_problem(response, StatusCode::BAD_REQUEST, "invalid_request").await;
}
#[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 mut issues = crate::settings::SettingsIssues::new();
issues.push("server.http.timeout", "must be greater than zero");
issues.push("server.http.timeout", "must be below the shutdown timeout");
issues.push("server.http.port", "must fit in u16");
let error = crate::settings::SettingsValidationError::new(issues);
let _error = assert_settings_error(&error)
.issue_count(3)
.has_path("server.http.timeout")
.path_message_contains("server.http.timeout", "greater")
.path_message_contains("server.http.timeout", "below")
.into_inner();
for (path, message) in [
("server.http.timeout", "u16"),
("server.http.timeout", "missing message"),
("server.http.unknown", "greater"),
] {
assert!(
std::panic::catch_unwind(|| {
let _ = assert_settings_error(&error).path_message_contains(path, message);
})
.is_err()
);
}
}
#[tokio::test]
async fn testkit_outbox_persists_fixture_outcomes_and_dead_letters() {
use std::time::Duration;
use crate::worker::{BatchWorkerJob, OutboxItemState};
let retry = OutboxItemState::retry("temporary failure", Duration::from_secs(9));
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),
worker::TestOutboxItem::new("retry", worker::TestOutboxAction::Return(retry.clone())),
worker::TestOutboxItem::handler_error("error", "handler failure"),
worker::TestOutboxItem::slow("slow", Duration::ZERO),
]);
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(), 2);
assert_eq!(summary.skipped(), 1);
assert_eq!(summary.failed(), 2);
assert_eq!(summary.dead_lettered(), 2);
assert_eq!(summary.retrying(), 2);
let states = store.states();
assert_eq!(states.len(), 7);
assert_eq!(states[4], ("retry".to_owned(), retry));
assert!(matches!(
&states[5].1,
OutboxItemState::Retry { reason, .. } if reason == "outbox_handler_failed"
));
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,
);
}
}