use serde::de::DeserializeOwned;
use crate::{
auth::Principal,
http::{ApiProblem, ProblemDetails},
observability::{MetricLabels, MetricsSnapshot},
result::{ClassifyError, Diagnostic, DiagnosticKind, ErrorDescriptor, ErrorKind},
};
use super::TestkitError;
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)?;
if problem.status() != status.as_u16() {
return Err(TestkitError::ResponseStatusMismatch {
http_status: status.as_u16(),
problem_status: problem.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(), 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 = "settings")]
#[derive(Debug, Clone, Copy)]
pub struct SettingsValidationAssert<'a> {
error: &'a crate::settings::SettingsValidationError,
}
#[cfg(feature = "settings")]
impl<'a> SettingsValidationAssert<'a> {
#[must_use]
pub const fn new(error: &'a crate::settings::SettingsValidationError) -> 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 settings 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 settings validation error to include path {expected_path:?}; got {:?}",
self.error.issues()
)
});
assert!(
issue.message().contains(expected_message),
"expected settings issue message {:?} to contain {expected_message:?}",
issue.message()
);
self
}
#[must_use]
pub const fn into_inner(self) -> &'a crate::settings::SettingsValidationError {
self.error
}
}
#[cfg(feature = "settings")]
#[must_use]
pub const fn assert_settings_error(
error: &crate::settings::SettingsValidationError,
) -> SettingsValidationAssert<'_> {
SettingsValidationAssert::new(error)
}
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(), 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()
);
}