footing 0.1.7

Feature-gated foundations for Rust backend services
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
use serde::de::DeserializeOwned;

use crate::{
    auth::Principal,
    http::{ApiProblem, ProblemDetails},
    observability::{MetricLabels, MetricsSnapshot},
    result::{ClassifyError, Diagnostic, DiagnosticKind, ErrorDescriptor, ErrorKind},
};

use super::TestkitError;

/// Asserts response status.
pub fn assert_response_status(
    response: &axum::response::Response,
    expected: axum::http::StatusCode,
) {
    assert_eq!(response.status(), expected);
}

/// Attempts to read a response body as UTF-8 text.
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)
}

/// Reads a response body as UTF-8 text or panics with test context.
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}"))
}

/// Attempts to deserialize a JSON response.
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)
}

/// Deserializes a JSON response or panics with test context.
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}"))
}

/// Asserts response JSON.
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
}

/// Attempts to deserialize an RFC 9457 response.
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)
}

/// Deserializes an RFC 9457 response or panics with test context.
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}"))
}

/// Asserts response problem.
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
}

/// Asserts 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)]
/// Represents problem assert.
pub struct ProblemAssert {
    problem: ProblemDetails,
}

impl ProblemAssert {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(problem: ProblemDetails) -> Self {
        Self { problem }
    }

    #[must_use]
    /// Returns the code.
    pub fn code(self, expected: &str) -> Self {
        assert_eq!(self.problem.code(), expected);
        self
    }

    #[must_use]
    /// Returns the status.
    pub fn status(self, expected: axum::http::StatusCode) -> Self {
        assert_eq!(self.problem.status(), expected.as_u16());
        self
    }

    #[must_use]
    /// Returns the detail.
    pub fn detail(self, expected: &str) -> Self {
        assert_eq!(self.problem.detail(), expected);
        self
    }

    #[must_use]
    /// Returns the request identifier.
    pub fn request_id(self, expected: &str) -> Self {
        assert_eq!(self.problem.request_id(), Some(expected));
        self
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub fn into_inner(self) -> ProblemDetails {
        self.problem
    }
}

#[derive(Debug, Clone)]
/// Represents error descriptor assert.
pub struct ErrorDescriptorAssert {
    descriptor: ErrorDescriptor,
}

impl ErrorDescriptorAssert {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(descriptor: ErrorDescriptor) -> Self {
        Self { descriptor }
    }

    #[must_use]
    /// Returns the kind.
    pub fn kind(self, expected: ErrorKind) -> Self {
        assert_eq!(self.descriptor.kind(), expected);
        self
    }

    #[must_use]
    /// Returns the code.
    pub fn code(self, expected: &str) -> Self {
        assert_eq!(self.descriptor.code().as_str(), expected);
        self
    }

    #[must_use]
    /// Returns the message contains.
    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]
    /// Returns the retryable.
    pub fn retryable(self, expected: bool) -> Self {
        assert_eq!(self.descriptor.retryable(), expected);
        self
    }

    #[must_use]
    /// Returns the public message.
    pub fn public_message(self, expected: &str) -> Self {
        assert_eq!(self.descriptor.public_message(), expected);
        self
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub fn into_inner(self) -> ErrorDescriptor {
        self.descriptor
    }
}

#[must_use]
/// Asserts error.
pub fn assert_error<E>(error: &E) -> ErrorDescriptorAssert
where
    E: ClassifyError + ?Sized,
{
    ErrorDescriptorAssert::new(error.error_descriptor())
}

#[must_use]
/// Asserts error descriptor.
pub fn assert_error_descriptor(descriptor: ErrorDescriptor) -> ErrorDescriptorAssert {
    ErrorDescriptorAssert::new(descriptor)
}

#[derive(Debug, Clone, Copy)]
/// Represents diagnostic assert.
pub struct DiagnosticAssert<'a> {
    diagnostic: &'a Diagnostic,
}

impl<'a> DiagnosticAssert<'a> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(diagnostic: &'a Diagnostic) -> Self {
        Self { diagnostic }
    }

    #[must_use]
    /// Returns the component.
    pub fn component(self, expected: &str) -> Self {
        assert_eq!(self.diagnostic.component(), expected);
        self
    }

    #[must_use]
    /// Returns the operation.
    pub fn operation(self, expected: &str) -> Self {
        assert_eq!(self.diagnostic.operation(), expected);
        self
    }

    #[must_use]
    /// Returns the resource.
    pub fn resource(self, expected: Option<&str>) -> Self {
        assert_eq!(self.diagnostic.resource(), expected);
        self
    }

    #[must_use]
    /// Returns the kind.
    pub fn kind(self, expected: DiagnosticKind) -> Self {
        assert_eq!(self.diagnostic.kind(), expected);
        self
    }

    #[must_use]
    /// Returns the message contains.
    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]
    /// Returns the remediation contains.
    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]
    /// Returns the retryable.
    pub fn retryable(self, expected: bool) -> Self {
        assert_eq!(self.diagnostic.retryable(), expected);
        self
    }

    #[must_use]
    /// Consumes this value and returns inner.
    pub const fn into_inner(self) -> &'a Diagnostic {
        self.diagnostic
    }
}

#[must_use]
/// Asserts diagnostic.
pub const fn assert_diagnostic(diagnostic: &Diagnostic) -> DiagnosticAssert<'_> {
    DiagnosticAssert::new(diagnostic)
}

#[cfg(feature = "settings")]
#[derive(Debug, Clone, Copy)]
/// Fluent assertions for a settings validation error.
pub struct SettingsValidationAssert<'a> {
    error: &'a crate::settings::SettingsValidationError,
}

#[cfg(feature = "settings")]
impl<'a> SettingsValidationAssert<'a> {
    #[must_use]
    /// Creates a new instance.
    pub const fn new(error: &'a crate::settings::SettingsValidationError) -> Self {
        Self { error }
    }

    #[must_use]
    /// Returns the issue count.
    pub fn issue_count(self, expected: usize) -> Self {
        assert_eq!(self.error.issues().len(), expected);
        self
    }

    #[must_use]
    /// Returns whether this value has path.
    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]
    /// Returns the path message contains.
    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]
    /// Consumes this value and returns inner.
    pub const fn into_inner(self) -> &'a crate::settings::SettingsValidationError {
        self.error
    }
}

#[cfg(feature = "settings")]
#[must_use]
/// Starts fluent assertions for a settings validation error.
pub const fn assert_settings_error(
    error: &crate::settings::SettingsValidationError,
) -> SettingsValidationAssert<'_> {
    SettingsValidationAssert::new(error)
}

/// Asserts problem code.
pub fn assert_problem_code(problem: &ApiProblem, expected_code: &str) {
    assert_eq!(problem.body().code(), expected_code);
}

/// Asserts problem detail.
pub fn assert_problem_detail(problem: &ApiProblem, expected_detail: &str) {
    assert_eq!(problem.body().detail(), expected_detail);
}

/// Asserts problem status.
pub fn assert_problem_status(problem: &ApiProblem, expected_status: axum::http::StatusCode) {
    assert_eq!(problem.status(), expected_status);
}

/// Asserts problem request identifier.
pub fn assert_problem_request_id(problem: &ApiProblem, expected_request_id: &str) {
    assert_eq!(problem.body().request_id(), Some(expected_request_id));
}

/// Asserts metric value.
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);
}

/// Asserts metric value at least.
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()
    );
}

/// Asserts no metric.
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"
    );
}

/// Asserts principal has role.
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()
    );
}

/// Asserts principal has scope.
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()
    );
}