tideway 0.7.17

A batteries-included Rust web framework built on Axum for building SaaS applications quickly
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
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
//! Alba-style HTTP testing utilities for Axum applications
//!
//! This module provides a fluent API for testing HTTP endpoints without starting a server,
//! inspired by .NET's Alba testing framework.
//!
//! # Example
//!
//! ```rust,ignore
//! use axum::{Router, routing, Json};
//! use tideway::testing;
//! use serde_json::json;
//!
//! async fn hello() -> Json<serde_json::Value> {
//!     Json(json!({"message": "Hello, World!"}))
//! }
//!
//! #[tokio::test]
//! async fn test_hello_endpoint() {
//!     let app = Router::new().route("/hello", routing::get(hello));
//!
//!     let response = testing::get(app, "/hello")
//!         .execute()
//!         .await
//!         .assert_ok()
//!         .assert_json();
//!
//!     let body: serde_json::Value = response.json().await;
//!     assert_eq!(body["message"], "Hello, World!");
//! }
//! ```

#[cfg(feature = "test-auth-bypass")]
use crate::auth::extractors::{TEST_CLAIMS_HEADER, TEST_USER_ID_HEADER, encode_test_claims_header};
use axum::{
    Router,
    body::{Body, Bytes},
    http::{Method, Request, StatusCode, header},
};
use serde::{Deserialize, Serialize};
use tower::ServiceExt;

/// Alba-style test scenario builder for easy endpoint testing
pub struct Scenario {
    app: Router,
    request: Request<Body>,
}

impl Scenario {
    /// Create a new test scenario with the given app
    pub fn new(app: Router) -> Self {
        Self {
            app,
            request: Request::builder()
                .method(Method::GET)
                .uri("/")
                .body(Body::empty())
                .unwrap(),
        }
    }

    /// Set the HTTP method
    pub fn method(mut self, method: Method) -> Self {
        *self.request.method_mut() = method;
        self
    }

    /// Set the URI/path
    pub fn uri(mut self, uri: &str) -> Self {
        *self.request.uri_mut() = uri.parse().unwrap();
        self
    }

    /// Add a header
    pub fn header(mut self, key: &str, value: &str) -> Self {
        use axum::http::HeaderName;
        self.request.headers_mut().insert(
            HeaderName::from_bytes(key.as_bytes()).unwrap(),
            value.parse().unwrap(),
        );
        self
    }

    /// Convenience alias for `header`.
    pub fn with_header(self, key: &str, value: &str) -> Self {
        self.header(key, value)
    }

    /// Alba-style alias for `header`.
    pub fn with_request_header(self, key: &str, value: &str) -> Self {
        self.header(key, value)
    }

    /// Set the Authorization header with Bearer token
    pub fn bearer_token(self, token: &str) -> Self {
        self.header("Authorization", &format!("Bearer {}", token))
    }

    /// Alias for bearer_token - set Authorization header with Bearer token
    pub fn with_auth(self, token: &str) -> Self {
        self.bearer_token(token)
    }

    /// Set the test bypass user identity when the `test-auth-bypass` feature is enabled.
    #[cfg(feature = "test-auth-bypass")]
    pub fn with_test_user(self, user_id: &str) -> Self {
        self.header(TEST_USER_ID_HEADER, user_id)
    }

    /// Set synthetic claims for test bypass when the `test-auth-bypass` feature is enabled.
    #[cfg(feature = "test-auth-bypass")]
    pub fn with_test_claims<T: Serialize>(self, claims: &T) -> Self {
        let encoded = encode_test_claims_header(claims);
        self.header(TEST_CLAIMS_HEADER, &encoded)
    }

    /// Add query parameters to the request URI
    pub fn with_query(mut self, params: &[(&str, &str)]) -> Self {
        let uri = self.request.uri().clone();
        let mut query_parts = vec![];

        // Get existing query string if present
        if let Some(query) = uri.query() {
            query_parts.push(query.to_string());
        }

        // Add new parameters
        for (key, value) in params {
            query_parts.push(format!(
                "{}={}",
                urlencoding::encode(key),
                urlencoding::encode(value)
            ));
        }

        // Build new URI with query string
        let path = uri.path();
        let new_uri = if query_parts.is_empty() {
            path.to_string()
        } else {
            format!("{}?{}", path, query_parts.join("&"))
        };

        *self.request.uri_mut() = new_uri.parse().unwrap();
        self
    }

    /// Set JSON body from a serializable type
    pub fn json_body<T: Serialize>(mut self, body: &T) -> Self {
        let json = serde_json::to_string(body).unwrap();
        *self.request.body_mut() = Body::from(json);
        self.request
            .headers_mut()
            .insert(header::CONTENT_TYPE, "application/json".parse().unwrap());
        self.request
            .headers_mut()
            .insert(header::ACCEPT, "application/json".parse().unwrap());
        self
    }

    /// Alias for json_body
    pub fn json<T: Serialize>(self, body: &T) -> Self {
        self.json_body(body)
    }

    /// Convenience alias for `json_body`.
    pub fn with_json<T: Serialize>(self, body: &T) -> Self {
        self.json_body(body)
    }

    /// Set URL-encoded form data from a serializable type.
    pub fn form_body<T: Serialize>(mut self, body: &T) -> Self {
        let encoded = serde_urlencoded::to_string(body).unwrap();
        *self.request.body_mut() = Body::from(encoded);
        self.request.headers_mut().insert(
            header::CONTENT_TYPE,
            "application/x-www-form-urlencoded".parse().unwrap(),
        );
        self
    }

    /// Alias for `form_body`.
    pub fn form<T: Serialize>(self, body: &T) -> Self {
        self.form_body(body)
    }

    /// Convenience alias for `form_body`.
    pub fn with_form<T: Serialize>(self, body: &T) -> Self {
        self.form_body(body)
    }

    /// Set plain text body
    pub fn text_body(mut self, body: impl Into<String>) -> Self {
        *self.request.body_mut() = Body::from(body.into());
        self
    }

    /// Execute the request and get an assertion builder
    pub async fn execute(self) -> ScenarioAssert {
        let response = self.app.oneshot(self.request).await.unwrap();
        ScenarioAssert { response }
    }

    /// Alias for execute
    pub async fn send(self) -> ScenarioAssert {
        self.execute().await
    }
}

/// Assertion builder for test responses
pub struct ScenarioAssert {
    response: axum::response::Response,
}

impl ScenarioAssert {
    /// Assert the response status code
    pub fn assert_status(self, expected: StatusCode) -> Self {
        assert_eq!(
            self.response.status(),
            expected,
            "Expected status {}, got {}",
            expected,
            self.response.status()
        );
        self
    }

    /// Assert status is 200 OK
    pub fn assert_ok(self) -> Self {
        self.assert_status(StatusCode::OK)
    }

    /// Assert status is 201 Created
    pub fn assert_created(self) -> Self {
        self.assert_status(StatusCode::CREATED)
    }

    /// Assert status is 400 Bad Request
    pub fn assert_bad_request(self) -> Self {
        self.assert_status(StatusCode::BAD_REQUEST)
    }

    /// Assert status is 401 Unauthorized
    pub fn assert_unauthorized(self) -> Self {
        self.assert_status(StatusCode::UNAUTHORIZED)
    }

    /// Assert status is 404 Not Found
    pub fn assert_not_found(self) -> Self {
        self.assert_status(StatusCode::NOT_FOUND)
    }

    /// Assert status is 500 Internal Server Error
    pub fn assert_server_error(self) -> Self {
        self.assert_status(StatusCode::INTERNAL_SERVER_ERROR)
    }

    /// Assert a header exists with the given value
    pub fn assert_header(self, key: &str, expected: &str) -> Self {
        let value = self
            .response
            .headers()
            .get(key)
            .unwrap_or_else(|| panic!("Header '{}' not found", key))
            .to_str()
            .unwrap();
        assert_eq!(value, expected, "Header '{}' value mismatch", key);
        self
    }

    /// Assert a header exists
    pub fn assert_header_exists(self, key: &str) -> Self {
        self.response
            .headers()
            .get(key)
            .unwrap_or_else(|| panic!("Header '{}' not found", key));
        self
    }

    /// Assert the response is an HTTP redirect and has a Location header.
    pub fn assert_redirect(self) -> Self {
        let status = self.response.status();
        assert!(
            status.is_redirection(),
            "Expected redirect status, got {}",
            status
        );
        self.assert_header_exists(header::LOCATION.as_str())
    }

    /// Assert the response redirects to the expected location.
    pub fn assert_redirect_to(self, expected: &str) -> Self {
        self.assert_redirect()
            .assert_header(header::LOCATION.as_str(), expected)
    }

    /// Assert status is one of the expected codes
    pub fn assert_status_any(self, expected: &[StatusCode]) -> Self {
        let status = self.response.status();
        assert!(
            expected.contains(&status),
            "Expected status in {:?}, got {}",
            expected,
            status
        );
        self
    }

    /// Assert the response content type is JSON
    pub fn assert_json(self) -> Self {
        let content_type = self
            .response
            .headers()
            .get(header::CONTENT_TYPE)
            .expect("Content-Type header not found")
            .to_str()
            .unwrap();
        assert!(
            content_type.contains("application/json"),
            "Expected JSON content type, got: {}",
            content_type
        );
        self
    }

    /// Assert status is OK and response is JSON.
    pub fn assert_json_ok(self) -> Self {
        self.assert_ok().assert_json()
    }

    /// Get the response body as bytes
    pub async fn body_bytes(self) -> Vec<u8> {
        axum::body::to_bytes(self.response.into_body(), usize::MAX)
            .await
            .unwrap()
            .to_vec()
    }

    /// Get the response body as a string
    pub async fn body_string(self) -> String {
        String::from_utf8(self.body_bytes().await).unwrap()
    }

    /// Parse the JSON response body into a type
    pub async fn json<T: for<'de> Deserialize<'de>>(self) -> T {
        let bytes = self.body_bytes().await;
        serde_json::from_slice(&bytes).expect("Failed to parse JSON response")
    }

    /// Parse the JSON response body into a serde_json::Value
    pub async fn json_value(self) -> serde_json::Value {
        self.json().await
    }

    /// Parse the JSON response body into a concrete type
    pub async fn json_into<T: for<'de> Deserialize<'de>>(self) -> T {
        self.json().await
    }

    /// Assert JSON field equals a value using JSONPath-like syntax
    pub async fn assert_json_field(self, path: &str, expected: serde_json::Value) -> Self {
        let (parts, bytes) = self.into_parts_and_body().await;
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        let actual = json_path_get(&json, path)
            .unwrap_or_else(|| panic!("Path '{}' not found in JSON", path));

        assert_eq!(actual, &expected, "JSON path '{}' value mismatch", path);

        Self::from_parts_and_body(parts, bytes)
    }

    /// Assert JSON contains the expected subset
    pub async fn assert_json_contains(self, expected: serde_json::Value) -> Self {
        let (parts, bytes) = self.into_parts_and_body().await;
        let json: serde_json::Value = serde_json::from_slice(&bytes).unwrap();

        assert!(
            json_contains(&json, &expected),
            "Expected JSON to contain {:?}, got {:?}",
            expected,
            json
        );

        Self::from_parts_and_body(parts, bytes)
    }

    /// Alias for assert_json_field - assert JSON path equals expected value
    pub async fn assert_json_path(self, path: &str, expected: serde_json::Value) -> Self {
        self.assert_json_field(path, expected).await
    }

    /// Shorthand for assert_json_path
    pub async fn json_path_eq(self, path: &str, expected: serde_json::Value) -> Self {
        self.assert_json_path(path, expected).await
    }

    /// Assert the response body contains the given text
    pub async fn assert_contains(self, text: &str) -> Self {
        let (parts, bytes) = self.into_parts_and_body().await;
        let body = String::from_utf8(bytes.to_vec()).unwrap();
        assert!(
            body.contains(text),
            "Response body does not contain '{}'. Body: {}",
            text,
            body
        );
        Self::from_parts_and_body(parts, Bytes::from(body))
    }

    /// Dump the request and response for debugging
    pub async fn dump(self) -> Self {
        let status = self.response.status();
        let headers: Vec<(String, String)> = self
            .response
            .headers()
            .iter()
            .map(|(k, v)| (k.to_string(), v.to_str().unwrap_or("<invalid>").to_string()))
            .collect();
        let (parts, bytes) = self.into_parts_and_body().await;
        let body = String::from_utf8(bytes.to_vec()).unwrap();

        eprintln!("=== Response Dump ===");
        eprintln!("Status: {}", status);
        eprintln!("Headers:");
        for (key, value) in &headers {
            eprintln!("  {}: {}", key, value);
        }
        eprintln!("Body: {}", body);
        eprintln!("===================");

        Self::from_parts_and_body(parts, Bytes::from(body))
    }

    /// Get the underlying response for custom assertions
    pub fn response(self) -> axum::response::Response {
        self.response
    }

    async fn into_parts_and_body(self) -> (axum::http::response::Parts, Bytes) {
        let (parts, body) = self.response.into_parts();
        let bytes = axum::body::to_bytes(body, usize::MAX).await.unwrap();
        (parts, bytes)
    }

    fn from_parts_and_body(parts: axum::http::response::Parts, body: Bytes) -> Self {
        Self {
            response: axum::response::Response::from_parts(parts, Body::from(body)),
        }
    }
}

/// Simple JSON path getter (supports dot notation like "data.name" and array indexing like "checks.0.name")
fn json_path_get<'a>(json: &'a serde_json::Value, path: &str) -> Option<&'a serde_json::Value> {
    let parts: Vec<&str> = path.split('.').collect();
    let mut current = json;

    for part in parts {
        // Check if this part is an array index
        if let Ok(index) = part.parse::<usize>() {
            current = current.get(index)?;
        } else {
            current = current.get(part)?;
        }
    }

    Some(current)
}

fn json_contains(actual: &serde_json::Value, expected: &serde_json::Value) -> bool {
    match (actual, expected) {
        (serde_json::Value::Object(actual_map), serde_json::Value::Object(expected_map)) => {
            expected_map.iter().all(|(key, expected_value)| {
                actual_map
                    .get(key)
                    .map(|actual_value| json_contains(actual_value, expected_value))
                    .unwrap_or(false)
            })
        }
        (serde_json::Value::Array(actual_array), serde_json::Value::Array(expected_array)) => {
            expected_array.iter().all(|expected_value| {
                actual_array
                    .iter()
                    .any(|actual_value| json_contains(actual_value, expected_value))
            })
        }
        _ => actual == expected,
    }
}

/// Convenience function to create a GET request scenario
pub fn get(app: Router, uri: &str) -> Scenario {
    Scenario::new(app).method(Method::GET).uri(uri)
}

/// Convenience function to create a POST request scenario
pub fn post(app: Router, uri: &str) -> Scenario {
    Scenario::new(app).method(Method::POST).uri(uri)
}

/// Convenience function to create a PUT request scenario
pub fn put(app: Router, uri: &str) -> Scenario {
    Scenario::new(app).method(Method::PUT).uri(uri)
}

/// Convenience function to create a DELETE request scenario
pub fn delete(app: Router, uri: &str) -> Scenario {
    Scenario::new(app).method(Method::DELETE).uri(uri)
}

/// Convenience function to create a PATCH request scenario
pub fn patch(app: Router, uri: &str) -> Scenario {
    Scenario::new(app).method(Method::PATCH).uri(uri)
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::{Json, Router, routing::get as axum_get};
    use serde_json::json;

    async fn hello_handler() -> Json<serde_json::Value> {
        Json(json!({"message": "Hello, World!"}))
    }

    async fn echo_handler(
        axum::extract::Query(params): axum::extract::Query<
            std::collections::HashMap<String, String>,
        >,
    ) -> Json<serde_json::Value> {
        Json(json!({"params": params}))
    }

    #[tokio::test]
    async fn test_basic_get() {
        let app = Router::new().route("/hello", axum_get(hello_handler));

        let response = get(app, "/hello").send().await.assert_json_ok();

        let body = response.json_value().await;
        assert_eq!(body["message"], "Hello, World!");
    }

    #[tokio::test]
    async fn test_with_query_params() {
        let app = Router::new().route("/echo", axum_get(echo_handler));

        let response = get(app, "/echo")
            .with_query(&[("key", "value"), ("foo", "bar")])
            .execute()
            .await
            .assert_ok();

        let body: serde_json::Value = response.json().await;
        assert!(body["params"].is_object());
    }

    #[tokio::test]
    async fn test_json_alias() {
        async fn post_handler(
            axum::Json(payload): axum::Json<serde_json::Value>,
        ) -> axum::Json<serde_json::Value> {
            axum::Json(payload)
        }

        let app = Router::new().route("/echo", axum::routing::post(post_handler));

        let response = post(app, "/echo")
            .json(&json!({"key": "value"}))
            .send()
            .await
            .assert_json_ok();

        let body: serde_json::Value = response.json().await;
        assert_eq!(body["key"], json!("value"));
    }

    #[tokio::test]
    async fn test_with_auth() {
        let app = Router::new().route("/hello", axum_get(hello_handler));

        // Test that with_auth sets the Authorization header
        // We can't easily verify this without inspecting the request,
        // so we just verify the request succeeds
        get(app, "/hello")
            .with_auth("test-token-123")
            .execute()
            .await
            .assert_ok();
    }

    #[tokio::test]
    async fn test_assert_json_path() {
        let app = Router::new().route("/hello", axum_get(hello_handler));

        let response = get(app, "/hello").send().await.assert_ok();

        response
            .json_path_eq("message", json!("Hello, World!"))
            .await;
    }

    #[tokio::test]
    async fn test_assert_contains() {
        let app = Router::new().route("/hello", axum_get(hello_handler));

        let response = get(app, "/hello").execute().await.assert_ok();

        response.assert_contains("Hello").await;
    }

    #[tokio::test]
    async fn test_assert_contains_preserves_headers() {
        async fn handler() -> axum::response::Response {
            axum::response::Response::builder()
                .status(StatusCode::OK)
                .header("x-test", "1")
                .body(Body::from("hello"))
                .unwrap()
        }

        let app = Router::new().route("/hello", axum::routing::get(handler));

        get(app, "/hello")
            .send()
            .await
            .assert_contains("hello")
            .await
            .assert_header("x-test", "1");
    }

    #[tokio::test]
    async fn test_assert_json_contains() {
        let app = Router::new().route("/hello", axum_get(hello_handler));

        get(app, "/hello")
            .send()
            .await
            .assert_json_ok()
            .assert_json_contains(json!({"message": "Hello, World!"}))
            .await;
    }

    #[tokio::test]
    async fn test_assert_json_field_preserves_headers() {
        async fn handler() -> axum::response::Response {
            axum::response::Response::builder()
                .status(StatusCode::OK)
                .header("x-test", "1")
                .header(header::CONTENT_TYPE, "application/json")
                .body(Body::from(r#"{"message":"hello"}"#))
                .unwrap()
        }

        let app = Router::new().route("/hello", axum::routing::get(handler));

        get(app, "/hello")
            .send()
            .await
            .assert_json_field("message", json!("hello"))
            .await
            .assert_header("x-test", "1");
    }

    #[tokio::test]
    async fn test_assert_status_any_and_header_exists() {
        async fn handler() -> axum::response::Response {
            let mut response = axum::response::Response::new(Body::from("ok"));
            response
                .headers_mut()
                .insert("x-test", "1".parse().unwrap());
            *response.status_mut() = StatusCode::OK;
            response
        }

        let app = Router::new().route("/test", axum::routing::get(handler));

        get(app, "/test")
            .send()
            .await
            .assert_status_any(&[StatusCode::OK, StatusCode::CREATED])
            .assert_header_exists("x-test");
    }

    #[tokio::test]
    async fn test_form_alias() {
        #[derive(Deserialize)]
        struct LoginForm {
            email: String,
        }

        async fn form_handler(axum::Form(form): axum::Form<LoginForm>) -> Json<serde_json::Value> {
            Json(json!({ "email": form.email }))
        }

        let app = Router::new().route("/form", axum::routing::post(form_handler));

        let response = post(app, "/form")
            .with_form(&[("email", "test@example.com")])
            .send()
            .await
            .assert_json_ok();

        assert_eq!(
            response.json_value().await["email"],
            json!("test@example.com")
        );
    }

    #[tokio::test]
    async fn test_assert_redirect_to() {
        async fn redirect_handler() -> axum::response::Response {
            axum::response::Response::builder()
                .status(StatusCode::FOUND)
                .header(header::LOCATION, "/target")
                .body(Body::empty())
                .unwrap()
        }

        let app = Router::new().route("/redirect", axum::routing::get(redirect_handler));

        get(app, "/redirect")
            .send()
            .await
            .assert_redirect_to("/target");
    }
}