use std::{error::Error as StdError, fmt, sync::Arc};
use serde::de::DeserializeOwned;
use crate::{
auth::{Principal, PrincipalKind},
clock::ManualClock,
http::{ApiProblem, ProblemDetails, RequestContext, RequestId, TraceParent},
observability::{MetricLabels, MetricRecorder, MetricRegistry, MetricsError, MetricsSnapshot},
result::{ClassifyError, Diagnostic, DiagnosticKind, ErrorDescriptor, ErrorKind},
};
#[derive(Debug)]
#[non_exhaustive]
pub enum TestkitError {
RequestBuild(axum::http::Error),
ResponseBody(axum::Error),
ResponseUtf8(std::string::FromUtf8Error),
ResponseJson(serde_json::Error),
}
impl fmt::Display for TestkitError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::RequestBuild(source) => write!(formatter, "test request build failed: {source}"),
Self::ResponseBody(source) => write!(formatter, "response body read failed: {source}"),
Self::ResponseUtf8(source) => write!(formatter, "response body is not UTF-8: {source}"),
Self::ResponseJson(source) => write!(formatter, "response body is not JSON: {source}"),
}
}
}
impl StdError for TestkitError {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
match self {
Self::RequestBuild(source) => Some(source),
Self::ResponseBody(source) => Some(source),
Self::ResponseUtf8(source) => Some(source),
Self::ResponseJson(source) => Some(source),
}
}
}
#[must_use]
pub fn manual_clock() -> ManualClock {
ManualClock::new()
}
#[must_use]
pub fn admin_principal() -> Principal {
Principal::user("test-admin")
.expect("static test principal id is valid")
.with_roles(["admin"])
.expect("static test role is valid")
.with_scopes(["*"])
.expect("static test scope is valid")
}
#[must_use]
pub fn request_context() -> RequestContext {
RequestContext::new(test_request_id("req_test"), None).with_principal(admin_principal())
}
#[must_use]
pub fn traceparent() -> TraceParent {
TraceParent::new("00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
.expect("static test traceparent is valid")
}
#[derive(Debug, Clone)]
pub struct TestPrincipalBuilder {
principal: Principal,
}
impl TestPrincipalBuilder {
#[must_use]
pub fn user(id: impl Into<String>) -> Self {
Self {
principal: Principal::new(id, PrincipalKind::User)
.expect("test principal id must be valid"),
}
}
#[must_use]
pub fn client(id: impl Into<String>) -> Self {
Self {
principal: Principal::new(id, PrincipalKind::Client)
.expect("test principal id must be valid"),
}
}
#[must_use]
pub fn service_account(id: impl Into<String>) -> Self {
Self {
principal: Principal::new(id, PrincipalKind::ServiceAccount)
.expect("test principal id must be valid"),
}
}
#[must_use]
pub fn tenant(mut self, tenant_id: impl Into<String>) -> Self {
self.principal = self
.principal
.with_tenant_id(tenant_id)
.expect("test tenant id must be valid");
self
}
#[must_use]
pub fn role(mut self, role: impl Into<String>) -> Self {
self.principal
.add_role(role)
.expect("test role must be valid");
self
}
#[must_use]
pub fn scope(mut self, scope: impl Into<String>) -> Self {
self.principal
.add_scope(scope)
.expect("test scope must be valid");
self
}
#[must_use]
pub fn build(self) -> Principal {
self.principal
}
}
#[derive(Debug, Clone)]
pub struct TestRequestContextBuilder {
request_id: RequestId,
traceparent: Option<String>,
principal: Option<Principal>,
}
impl TestRequestContextBuilder {
#[must_use]
pub fn new() -> Self {
Self {
request_id: test_request_id("req_test"),
traceparent: None,
principal: None,
}
}
#[must_use]
pub fn request_id(mut self, request_id: impl Into<String>) -> Self {
self.request_id = test_request_id(&request_id.into());
self
}
#[must_use]
pub fn traceparent(mut self, traceparent: impl Into<String>) -> Self {
self.traceparent = Some(traceparent.into());
self
}
#[must_use]
pub fn standard_traceparent(mut self) -> Self {
self.traceparent = Some(traceparent().into_string());
self
}
#[must_use]
pub fn principal(mut self, principal: Principal) -> Self {
self.principal = Some(principal);
self
}
#[must_use]
pub fn build(self) -> RequestContext {
let context = RequestContext::new(self.request_id, self.traceparent);
if let Some(principal) = self.principal {
context.with_principal(principal)
} else {
context
}
}
}
impl Default for TestRequestContextBuilder {
fn default() -> Self {
Self::new()
}
}
pub struct TestHttpRequestBuilder {
method: axum::http::Method,
uri: String,
headers: Vec<(axum::http::HeaderName, axum::http::HeaderValue)>,
body: axum::body::Body,
}
impl TestHttpRequestBuilder {
#[must_use]
pub fn get(uri: impl Into<String>) -> Self {
Self::new(axum::http::Method::GET, uri)
}
#[must_use]
pub fn post(uri: impl Into<String>) -> Self {
Self::new(axum::http::Method::POST, uri)
}
#[must_use]
pub fn new(method: axum::http::Method, uri: impl Into<String>) -> Self {
Self {
method,
uri: uri.into(),
headers: Vec::new(),
body: axum::body::Body::empty(),
}
}
#[must_use]
pub fn header(mut self, name: axum::http::HeaderName, value: axum::http::HeaderValue) -> Self {
self.headers.push((name, value));
self
}
#[must_use]
pub fn header_str(mut self, name: axum::http::HeaderName, value: impl AsRef<str>) -> Self {
if let Ok(value) = axum::http::HeaderValue::from_str(value.as_ref()) {
self.headers.push((name, value));
}
self
}
#[must_use]
pub fn bearer(self, token: impl AsRef<str>) -> Self {
self.header_str(
axum::http::header::AUTHORIZATION,
format!("Bearer {}", token.as_ref()),
)
}
#[must_use]
pub fn request_id(self, request_id: impl AsRef<str>) -> Self {
self.header_str(
axum::http::HeaderName::from_static("x-request-id"),
request_id,
)
}
#[must_use]
pub fn traceparent(self, traceparent: impl AsRef<str>) -> Self {
self.header_str(
axum::http::HeaderName::from_static("traceparent"),
traceparent,
)
}
#[must_use]
pub fn json_body(mut self, value: &serde_json::Value) -> Self {
self.headers.push((
axum::http::header::CONTENT_TYPE,
axum::http::HeaderValue::from_static("application/json"),
));
self.body = axum::body::Body::from(value.to_string());
self
}
#[must_use]
pub fn body(mut self, body: impl Into<axum::body::Body>) -> Self {
self.body = body.into();
self
}
pub fn try_build(self) -> Result<axum::http::Request<axum::body::Body>, TestkitError> {
let mut builder = axum::http::Request::builder()
.method(self.method)
.uri(self.uri);
for (name, value) in self.headers {
builder = builder.header(name, value);
}
builder.body(self.body).map_err(TestkitError::RequestBuild)
}
pub fn build(self) -> axum::http::Request<axum::body::Body> {
self.try_build()
.unwrap_or_else(|error| panic!("test request should build: {error}"))
}
}
pub fn assert_response_status(
response: &axum::response::Response,
expected: axum::http::StatusCode,
) {
assert_eq!(response.status(), expected);
}
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.to_vec()).map_err(TestkitError::ResponseUtf8)
}
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}"))
}
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)
}
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}"))
}
pub async fn assert_response_json<T>(
response: axum::response::Response,
expected_status: axum::http::StatusCode,
) -> T
where
T: DeserializeOwned,
{
assert_response_status(&response, expected_status);
response_json(response).await
}
pub async fn try_response_problem(
response: axum::response::Response,
) -> Result<ProblemDetails, TestkitError> {
let status = response.status();
let body = try_response_body_text(response).await?;
let problem: ProblemDetails =
serde_json::from_str(&body).map_err(TestkitError::ResponseJson)?;
assert_eq!(
problem.status,
status.as_u16(),
"problem status should match HTTP status"
);
Ok(problem)
}
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}"))
}
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
}
pub async fn assert_problem(
response: axum::response::Response,
expected_status: axum::http::StatusCode,
expected_code: &str,
) -> ProblemAssert {
ProblemAssert::new(assert_response_problem(response, expected_status, expected_code).await)
}
#[derive(Debug, Clone)]
pub struct ProblemAssert {
problem: ProblemDetails,
}
impl ProblemAssert {
#[must_use]
pub const fn new(problem: ProblemDetails) -> Self {
Self { problem }
}
#[must_use]
pub fn code(self, expected: &str) -> Self {
assert_eq!(self.problem.code, expected);
self
}
#[must_use]
pub fn status(self, expected: axum::http::StatusCode) -> Self {
assert_eq!(self.problem.status, expected.as_u16());
self
}
#[must_use]
pub fn detail(self, expected: &str) -> Self {
assert_eq!(self.problem.detail, expected);
self
}
#[must_use]
pub fn request_id(self, expected: &str) -> Self {
assert_eq!(self.problem.request_id.as_deref(), Some(expected));
self
}
#[must_use]
pub fn into_inner(self) -> ProblemDetails {
self.problem
}
}
#[derive(Debug, Clone)]
pub struct ErrorDescriptorAssert {
descriptor: ErrorDescriptor,
}
impl ErrorDescriptorAssert {
#[must_use]
pub const fn new(descriptor: ErrorDescriptor) -> Self {
Self { descriptor }
}
#[must_use]
pub fn kind(self, expected: ErrorKind) -> Self {
assert_eq!(self.descriptor.kind(), expected);
self
}
#[must_use]
pub fn code(self, expected: &str) -> Self {
assert_eq!(self.descriptor.code().as_str(), expected);
self
}
#[must_use]
pub fn message_contains(self, expected: &str) -> Self {
assert!(
self.descriptor.message().contains(expected),
"expected error message {:?} to contain {expected:?}",
self.descriptor.message()
);
self
}
#[must_use]
pub fn retryable(self, expected: bool) -> Self {
assert_eq!(self.descriptor.retryable(), expected);
self
}
#[must_use]
pub fn public_message(self, expected: &str) -> Self {
assert_eq!(self.descriptor.public_message(), expected);
self
}
#[must_use]
pub fn into_inner(self) -> ErrorDescriptor {
self.descriptor
}
}
#[must_use]
pub fn assert_error<E>(error: &E) -> ErrorDescriptorAssert
where
E: ClassifyError + ?Sized,
{
ErrorDescriptorAssert::new(error.error_descriptor())
}
#[must_use]
pub fn assert_error_descriptor(descriptor: ErrorDescriptor) -> ErrorDescriptorAssert {
ErrorDescriptorAssert::new(descriptor)
}
#[derive(Debug, Clone, Copy)]
pub struct DiagnosticAssert<'a> {
diagnostic: &'a Diagnostic,
}
impl<'a> DiagnosticAssert<'a> {
#[must_use]
pub const fn new(diagnostic: &'a Diagnostic) -> Self {
Self { diagnostic }
}
#[must_use]
pub fn component(self, expected: &str) -> Self {
assert_eq!(self.diagnostic.component(), expected);
self
}
#[must_use]
pub fn operation(self, expected: &str) -> Self {
assert_eq!(self.diagnostic.operation(), expected);
self
}
#[must_use]
pub fn resource(self, expected: Option<&str>) -> Self {
assert_eq!(self.diagnostic.resource(), expected);
self
}
#[must_use]
pub fn kind(self, expected: DiagnosticKind) -> Self {
assert_eq!(self.diagnostic.kind(), expected);
self
}
#[must_use]
pub fn message_contains(self, expected: &str) -> Self {
assert!(
self.diagnostic.message().contains(expected),
"expected diagnostic message {:?} to contain {expected:?}",
self.diagnostic.message()
);
self
}
#[must_use]
pub fn remediation_contains(self, expected: &str) -> Self {
let remediation = self
.diagnostic
.remediation()
.expect("expected diagnostic remediation");
assert!(
remediation.summary().contains(expected),
"expected diagnostic remediation {:?} to contain {expected:?}",
remediation.summary()
);
self
}
#[must_use]
pub fn retryable(self, expected: bool) -> Self {
assert_eq!(self.diagnostic.retryable(), expected);
self
}
#[must_use]
pub const fn into_inner(self) -> &'a Diagnostic {
self.diagnostic
}
}
#[must_use]
pub const fn assert_diagnostic(diagnostic: &Diagnostic) -> DiagnosticAssert<'_> {
DiagnosticAssert::new(diagnostic)
}
#[cfg(feature = "config")]
#[derive(Debug, Clone, Copy)]
pub struct ConfigValidationAssert<'a> {
error: &'a crate::config::ConfigValidationError,
}
#[cfg(feature = "config")]
impl<'a> ConfigValidationAssert<'a> {
#[must_use]
pub const fn new(error: &'a crate::config::ConfigValidationError) -> Self {
Self { error }
}
#[must_use]
pub fn issue_count(self, expected: usize) -> Self {
assert_eq!(self.error.issues().len(), expected);
self
}
#[must_use]
pub fn has_path(self, expected_path: &str) -> Self {
assert!(
self.error
.issues()
.iter()
.any(|issue| issue.path() == expected_path),
"expected config validation error to include path {expected_path:?}; got {:?}",
self.error.issues()
);
self
}
#[must_use]
pub fn path_message_contains(self, expected_path: &str, expected_message: &str) -> Self {
let issue = self
.error
.issues()
.iter()
.find(|issue| issue.path() == expected_path)
.unwrap_or_else(|| {
panic!(
"expected config validation error to include path {expected_path:?}; got {:?}",
self.error.issues()
)
});
assert!(
issue.message().contains(expected_message),
"expected config issue message {:?} to contain {expected_message:?}",
issue.message()
);
self
}
#[must_use]
pub const fn into_inner(self) -> &'a crate::config::ConfigValidationError {
self.error
}
}
#[cfg(feature = "config")]
#[must_use]
pub const fn assert_config_error(
error: &crate::config::ConfigValidationError,
) -> ConfigValidationAssert<'_> {
ConfigValidationAssert::new(error)
}
#[derive(Debug, Clone, Default)]
pub struct TestMetrics {
registry: Arc<MetricRegistry>,
}
impl TestMetrics {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn recorder(self: &Arc<Self>) -> Arc<dyn MetricRecorder> {
Arc::clone(self) as Arc<dyn MetricRecorder>
}
#[must_use]
pub fn registry(&self) -> &Arc<MetricRegistry> {
&self.registry
}
pub fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
self.registry.snapshot()
}
pub fn assert_counter(&self, name: &str, labels: MetricLabels, expected: u64) {
let snapshot = self.snapshot().expect("metrics snapshot should build");
assert_metric_value(&snapshot, name, labels, expected as f64);
}
pub fn assert_counter_at_least(&self, name: &str, labels: MetricLabels, expected: u64) {
let snapshot = self.snapshot().expect("metrics snapshot should build");
assert_metric_value_at_least(&snapshot, name, labels, expected as f64);
}
pub fn assert_no_metric(&self, name: &str, labels: MetricLabels) {
let snapshot = self.snapshot().expect("metrics snapshot should build");
assert_no_metric(&snapshot, name, labels);
}
}
impl MetricRecorder for TestMetrics {
fn increment_counter(
&self,
name: &str,
value: u64,
labels: MetricLabels,
) -> Result<(), MetricsError> {
self.registry.increment_counter(name, value, labels)
}
fn set_gauge(&self, name: &str, value: f64, labels: MetricLabels) -> Result<(), MetricsError> {
self.registry.set_gauge(name, value, labels)
}
fn observe_histogram(
&self,
name: &str,
value: f64,
labels: MetricLabels,
) -> Result<(), MetricsError> {
self.registry.observe_histogram(name, value, labels)
}
fn snapshot(&self) -> Result<MetricsSnapshot, MetricsError> {
self.registry.snapshot()
}
}
#[derive(Clone)]
pub struct TestHttpApp {
router: axum::Router,
}
impl TestHttpApp {
#[must_use]
pub fn new(router: axum::Router) -> Self {
Self { router }
}
pub async fn request(
&self,
request: axum::http::Request<axum::body::Body>,
) -> axum::response::Response {
use tower::ServiceExt;
self.router
.clone()
.oneshot(request)
.await
.expect("test HTTP request should complete")
}
pub async fn get(&self, uri: impl Into<String>) -> axum::response::Response {
self.request(TestHttpRequestBuilder::get(uri).build()).await
}
pub async fn post_json(
&self,
uri: impl Into<String>,
value: &serde_json::Value,
) -> axum::response::Response {
self.request(TestHttpRequestBuilder::post(uri).json_body(value).build())
.await
}
}
#[cfg(feature = "config")]
#[derive(Debug, Clone)]
pub struct TestHttpFoundation {
settings: crate::http::HttpFoundationSettings,
}
#[cfg(feature = "config")]
impl Default for TestHttpFoundation {
fn default() -> Self {
Self::new()
}
}
#[cfg(feature = "config")]
impl TestHttpFoundation {
#[must_use]
pub fn new() -> Self {
Self {
settings: crate::http::HttpFoundationSettings::new(),
}
}
#[must_use]
pub fn from_settings(settings: crate::http::HttpFoundationSettings) -> Self {
Self { settings }
}
#[must_use]
pub fn with_settings(
mut self,
update: impl FnOnce(crate::http::HttpFoundationSettings) -> crate::http::HttpFoundationSettings,
) -> Self {
self.settings = update(self.settings);
self
}
#[must_use]
pub const fn settings(&self) -> &crate::http::HttpFoundationSettings {
&self.settings
}
pub fn validate(&self) -> Result<(), crate::config::ConfigValidationError> {
use crate::config::ValidateSettings;
self.settings.validate_settings()
}
#[must_use]
pub fn assert_valid(self) -> Self {
self.validate()
.expect("test HTTP foundation settings should be valid");
self
}
#[must_use]
pub fn config(&self) -> crate::http::HttpLayerConfig {
self.settings
.clone()
.into_config()
.expect("test HTTP foundation settings should adapt")
}
#[must_use]
pub fn invalid_paths(&self, path: &str) -> Vec<String> {
self.settings
.validate_at(path)
.map(|()| Vec::new())
.unwrap_or_else(|error| {
error
.issues()
.iter()
.map(|issue| issue.path().to_owned())
.collect()
})
}
}
#[cfg(feature = "postgres")]
pub mod postgres {
use uuid::Uuid;
#[must_use]
pub fn database_url_from_env() -> Option<String> {
std::env::var("DATABASE_URL")
.ok()
.map(|value| value.trim().to_owned())
.filter(|value| !value.is_empty())
}
#[must_use]
pub fn unique_database_name(prefix: &str) -> String {
let prefix = prefix.trim().trim_matches('_');
let prefix = if prefix.is_empty() { "test" } else { prefix };
format!("{prefix}_{}", Uuid::now_v7().simple())
}
#[must_use]
pub fn database_url_with_name(base_url: &str, database_name: &str) -> String {
match base_url.rsplit_once('/') {
Some((prefix, _)) => format!("{prefix}/{database_name}"),
None => base_url.to_owned(),
}
}
}
pub fn assert_problem_code(problem: &ApiProblem, expected_code: &str) {
assert_eq!(problem.body().code, expected_code);
}
pub fn assert_problem_detail(problem: &ApiProblem, expected_detail: &str) {
assert_eq!(problem.body().detail, expected_detail);
}
pub fn assert_problem_status(problem: &ApiProblem, expected_status: axum::http::StatusCode) {
assert_eq!(problem.status(), expected_status);
}
pub fn assert_problem_request_id(problem: &ApiProblem, expected_request_id: &str) {
assert_eq!(
problem.body().request_id.as_deref(),
Some(expected_request_id)
);
}
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);
}
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()
);
}
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"
);
}
pub fn assert_principal_has_role(principal: &Principal, expected_role: &str) {
assert!(
principal.has_role(expected_role),
"expected principal {} to have role {expected_role}",
principal.id()
);
}
pub fn assert_principal_has_scope(principal: &Principal, expected_scope: &str) {
assert!(
principal.has_scope(expected_scope),
"expected principal {} to have scope {expected_scope}",
principal.id()
);
}
fn test_request_id(value: &str) -> RequestId {
RequestId::new(value)
.unwrap_or_else(|error| panic!("invalid test request id {value:?}: {error}"))
}
#[cfg(feature = "worker")]
pub mod worker {
use std::{
collections::VecDeque,
sync::{
Arc, Mutex, MutexGuard,
atomic::{AtomicU64, Ordering},
},
time::Duration,
};
use async_trait::async_trait;
use tokio::time;
use crate::worker::{
BoxWorkerError, OutboxClaim, OutboxHandler, OutboxItem, OutboxItemState, OutboxStore,
Worker, WorkerTick,
};
#[derive(Debug, Clone)]
pub struct CountingWorker {
name: &'static str,
calls: Arc<AtomicU64>,
processed_per_tick: u64,
}
impl CountingWorker {
#[must_use]
pub fn new(name: &'static str) -> Self {
Self {
name,
calls: Arc::new(AtomicU64::new(0)),
processed_per_tick: 1,
}
}
#[must_use]
pub fn calls(&self) -> u64 {
self.calls.load(Ordering::SeqCst)
}
#[must_use]
pub const fn with_processed_per_tick(mut self, processed_per_tick: u64) -> Self {
self.processed_per_tick = processed_per_tick;
self
}
}
#[async_trait]
impl Worker for CountingWorker {
fn name(&self) -> &str {
self.name
}
async fn run_once(&self) -> Result<WorkerTick, BoxWorkerError> {
self.calls.fetch_add(1, Ordering::SeqCst);
Ok(WorkerTick::new(self.processed_per_tick))
}
}
pub async fn run_once<W>(worker: &W) -> Result<WorkerTick, BoxWorkerError>
where
W: Worker,
{
worker.run_once().await
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct TestOutboxItem {
id: String,
attempts: u32,
action: TestOutboxAction,
}
impl TestOutboxItem {
#[must_use]
pub fn succeeded(id: impl Into<String>) -> Self {
Self::new(id, TestOutboxAction::Succeeded)
}
#[must_use]
pub fn retry(id: impl Into<String>, reason: impl Into<String>, delay: Duration) -> Self {
Self::new(
id,
TestOutboxAction::Retry {
reason: reason.into(),
delay,
},
)
}
#[must_use]
pub fn skipped(id: impl Into<String>, reason: impl Into<String>) -> Self {
Self::new(
id,
TestOutboxAction::Skipped {
reason: reason.into(),
},
)
}
#[must_use]
pub fn failed(id: impl Into<String>, reason: impl Into<String>) -> Self {
Self::new(
id,
TestOutboxAction::Failed {
reason: reason.into(),
},
)
}
#[must_use]
pub fn handler_error(id: impl Into<String>, reason: impl Into<String>) -> Self {
Self::new(
id,
TestOutboxAction::HandlerError {
reason: reason.into(),
},
)
}
#[must_use]
pub fn slow(id: impl Into<String>, delay: Duration) -> Self {
Self::new(id, TestOutboxAction::Slow { delay })
}
#[must_use]
pub fn new(id: impl Into<String>, action: TestOutboxAction) -> Self {
Self {
id: id.into(),
attempts: 0,
action,
}
}
#[must_use]
pub const fn with_attempts(mut self, attempts: u32) -> Self {
self.attempts = attempts;
self
}
#[must_use]
pub fn action(&self) -> &TestOutboxAction {
&self.action
}
}
impl OutboxItem for TestOutboxItem {
fn outbox_id(&self) -> String {
self.id.clone()
}
fn outbox_attempts(&self) -> u32 {
self.attempts
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum TestOutboxAction {
Succeeded,
Skipped {
#[doc = "The reason for this outcome."]
reason: String,
},
Retry {
#[doc = "The reason for this outcome."]
reason: String,
#[doc = "The delay before the next action."]
delay: Duration,
},
Failed {
#[doc = "The reason for this outcome."]
reason: String,
},
HandlerError {
#[doc = "The reason for this outcome."]
reason: String,
},
Slow {
#[doc = "The delay before the next action."]
delay: Duration,
},
}
#[derive(Debug, Clone, Default)]
pub struct TestOutboxStore {
items: Arc<Mutex<VecDeque<TestOutboxItem>>>,
states: Arc<Mutex<Vec<(String, OutboxItemState)>>>,
dead_letters: Arc<Mutex<Vec<(String, String)>>>,
}
impl TestOutboxStore {
#[must_use]
pub fn with_items(items: impl IntoIterator<Item = TestOutboxItem>) -> Self {
let store = Self::default();
store.push_items(items);
store
}
pub fn try_push_items(
&self,
items: impl IntoIterator<Item = TestOutboxItem>,
) -> Result<(), BoxWorkerError> {
lock_test_outbox(&self.items, "items")?.extend(items);
Ok(())
}
pub fn push_items(&self, items: impl IntoIterator<Item = TestOutboxItem>) {
self.try_push_items(items)
.unwrap_or_else(|error| panic!("test outbox items should be writable: {error}"));
}
pub fn try_states(&self) -> Result<Vec<(String, OutboxItemState)>, BoxWorkerError> {
Ok(lock_test_outbox(&self.states, "states")?.clone())
}
#[must_use]
pub fn states(&self) -> Vec<(String, OutboxItemState)> {
self.try_states()
.unwrap_or_else(|error| panic!("test outbox states should be readable: {error}"))
}
pub fn try_dead_letters(&self) -> Result<Vec<(String, String)>, BoxWorkerError> {
Ok(lock_test_outbox(&self.dead_letters, "dead_letters")?.clone())
}
#[must_use]
pub fn dead_letters(&self) -> Vec<(String, String)> {
self.try_dead_letters().unwrap_or_else(|error| {
panic!("test outbox dead letters should be readable: {error}")
})
}
}
#[async_trait]
impl OutboxStore<TestOutboxItem> for TestOutboxStore {
async fn claim_due(
&self,
claim: OutboxClaim,
) -> Result<Vec<TestOutboxItem>, BoxWorkerError> {
let mut items = lock_test_outbox(&self.items, "items")?;
Ok((0..claim.limit())
.filter_map(|_| items.pop_front())
.collect())
}
async fn record_state(
&self,
item: &TestOutboxItem,
state: OutboxItemState,
) -> Result<(), BoxWorkerError> {
lock_test_outbox(&self.states, "states")?.push((item.outbox_id(), state));
Ok(())
}
async fn record_dead_letter(
&self,
item: &TestOutboxItem,
reason: &str,
) -> Result<(), BoxWorkerError> {
lock_test_outbox(&self.dead_letters, "dead_letters")?
.push((item.outbox_id(), reason.to_owned()));
Ok(())
}
}
fn lock_test_outbox<'a, T>(
mutex: &'a Mutex<T>,
name: &'static str,
) -> Result<MutexGuard<'a, T>, BoxWorkerError> {
mutex
.lock()
.map_err(|_| std::io::Error::other(format!("test outbox {name} lock poisoned")).into())
}
#[derive(Debug, Clone, Copy, Default)]
pub struct TestOutboxHandler;
#[async_trait]
impl OutboxHandler<TestOutboxItem> for TestOutboxHandler {
async fn handle(&self, item: &TestOutboxItem) -> Result<OutboxItemState, BoxWorkerError> {
match item.action() {
TestOutboxAction::Succeeded => Ok(OutboxItemState::Succeeded),
TestOutboxAction::Skipped { reason } => Ok(OutboxItemState::skipped(reason)),
TestOutboxAction::Retry { reason, delay } => {
Ok(OutboxItemState::retry(reason, *delay))
}
TestOutboxAction::Failed { reason } => Ok(OutboxItemState::failed(reason)),
TestOutboxAction::HandlerError { reason } => Err(reason.clone().into()),
TestOutboxAction::Slow { delay } => {
time::sleep(*delay).await;
Ok(OutboxItemState::Succeeded)
}
}
}
}
}
#[cfg(test)]
mod tests {
use axum::{
Json, Router,
http::StatusCode,
routing::{get, post},
};
use serde_json::json;
use super::*;
#[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 problem = ApiProblem::bad_request(
crate::http::ProblemCode::from_static("invalid_input"),
"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::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 = "config")]
#[test]
fn config_validation_assertion_checks_issue_paths() {
let error = crate::config::ConfigValidationError::single(
"server.http.timeout",
"must be greater than zero",
);
let _error = assert_config_error(&error)
.issue_count(1)
.has_path("server.http.timeout")
.path_message_contains("server.http.timeout", "greater")
.into_inner();
}
#[cfg(feature = "config")]
#[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::OutboxWorkerConfig::default().with_batch_size(10),
);
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())]
);
}
}