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
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
use std::fmt;
use std::future::Future;
use std::pin::Pin;
use std::sync::{Arc, LazyLock, Mutex};

use axum::{
    Router,
    body::{Body, to_bytes},
    http::{HeaderMap, Method, Request, StatusCode, Uri, header},
};
use serde::Serialize;
use serde::de::DeserializeOwned;
use tower::ServiceExt;

#[cfg(feature = "test-auth-bypass")]
use crate::auth::extractors::{TEST_CLAIMS_HEADER, TEST_USER_ID_HEADER, encode_test_claims_header};
use crate::{App, Config, ConfigBuilder};

type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
type BeforeEachHook = Arc<dyn for<'a> Fn(&'a mut Request<Body>) -> BoxFuture<'a, ()> + Send + Sync>;
type AfterEachHook = Arc<dyn for<'a> Fn(&'a ScenarioOutcome) -> BoxFuture<'a, ()> + Send + Sync>;
type ScenarioAssertion = Box<dyn Fn(&ScenarioOutcome) -> Result<(), String> + Send + Sync>;
type AppTransform = Box<dyn FnOnce(App) -> App + Send>;
type ConfigTransform = Box<dyn FnOnce(Config) -> Config + Send>;

static TEST_HOST_ENV_LOCK: LazyLock<Mutex<()>> = LazyLock::new(|| Mutex::new(()));

enum ConfigSource {
    Built(Config),
    Builder(ConfigBuilder),
}

struct EnvOverride {
    key: String,
    value: Option<String>,
}

struct ScopedEnvOverrides {
    previous: Vec<(String, Option<String>)>,
}

impl ScopedEnvOverrides {
    fn apply(overrides: &[EnvOverride]) -> Self {
        let previous = overrides
            .iter()
            .map(|override_| (override_.key.clone(), std::env::var(&override_.key).ok()))
            .collect::<Vec<_>>();

        for override_ in overrides {
            unsafe {
                if let Some(value) = &override_.value {
                    std::env::set_var(&override_.key, value);
                } else {
                    std::env::remove_var(&override_.key);
                }
            }
        }

        Self { previous }
    }
}

impl Drop for ScopedEnvOverrides {
    fn drop(&mut self) {
        for (key, value) in self.previous.iter().rev() {
            unsafe {
                if let Some(value) = value {
                    std::env::set_var(key, value);
                } else {
                    std::env::remove_var(key);
                }
            }
        }
    }
}

fn build_host(
    app: App,
    with_middleware: bool,
    before_each: Option<BeforeEachHook>,
    after_each: Option<AfterEachHook>,
) -> TestHost {
    let mut host = if with_middleware {
        TestHost::new(app)
    } else {
        TestHost::without_middleware(app)
    };
    host.before_each = before_each;
    host.after_each = after_each;
    host
}

/// Bootstrap a `TestHost` from config and test-time environment overrides.
///
/// This is the Alba-style path when a spec needs to shape runtime settings
/// before the app is materialized.
pub struct TestHostBootstrap {
    config_source: ConfigSource,
    config_transforms: Vec<ConfigTransform>,
    app_transforms: Vec<AppTransform>,
    env_overrides: Vec<EnvOverride>,
    load_from_env: bool,
    with_middleware: bool,
    before_each: Option<BeforeEachHook>,
    after_each: Option<AfterEachHook>,
}

/// Builder for constructing a `TestHost` with test-time overrides.
///
/// This allows tests to swap dependencies or mutate the `App` before the host
/// is materialized, which is the closest Tideway analogue to Alba host setup.
pub struct TestHostBuilder {
    app: App,
    with_middleware: bool,
    before_each: Option<BeforeEachHook>,
    after_each: Option<AfterEachHook>,
}

/// Reusable Alba-style host for in-process Tideway integration tests.
///
/// Unlike the lower-level `Scenario` helper, `TestHost` reuses a single router,
/// supports before/after hooks, and applies a default `200 OK` expectation unless
/// you explicitly override it.
///
/// # Example
///
/// ```rust,ignore
/// use tideway::testing::TestHost;
///
/// let host = TestHost::new(app).before_each(|request| {
///     request
///         .headers_mut()
///         .insert("x-trace", "spec".parse().unwrap());
/// });
///
/// let response = host
///     .scenario(|scenario| {
///         scenario.get("/health");
///         scenario.header_should_exist("x-request-id");
///     })
///     .await;
///
/// assert_eq!(response.status(), axum::http::StatusCode::OK);
/// ```
pub struct TestHost {
    router: Router,
    before_each: Option<BeforeEachHook>,
    after_each: Option<AfterEachHook>,
}

impl TestHost {
    /// Create a bootstrap builder from default config.
    pub fn bootstrap() -> TestHostBootstrap {
        TestHostBootstrap::new()
    }

    /// Create a bootstrap builder from an explicit config.
    pub fn from_config(config: Config) -> TestHostBootstrap {
        TestHostBootstrap::from_config(config)
    }

    /// Create a bootstrap builder from a `ConfigBuilder`.
    pub fn from_config_builder(builder: ConfigBuilder) -> TestHostBootstrap {
        TestHostBootstrap::from_config_builder(builder)
    }

    /// Create a builder from an application for test-time overrides.
    pub fn builder(app: App) -> TestHostBuilder {
        TestHostBuilder::new(app)
    }

    /// Build a test host from a Tideway `App`, including middleware.
    pub fn new(app: App) -> Self {
        Self::from_router(app.into_router_with_middleware())
    }

    /// Build a test host from a Tideway `App` without middleware.
    pub fn without_middleware(app: App) -> Self {
        Self::from_router(app.into_router())
    }

    /// Build a test host from an Axum router.
    pub fn from_router(router: Router) -> Self {
        Self {
            router,
            before_each: None,
            after_each: None,
        }
    }

    /// Register a synchronous action that runs before every scenario.
    ///
    /// Like Alba, hooks are not additive: the last registered hook wins.
    pub fn before_each<F>(mut self, hook: F) -> Self
    where
        F: Fn(&mut Request<Body>) + Send + Sync + 'static,
    {
        self.before_each = Some(Arc::new(move |request| {
            hook(request);
            Box::pin(async {})
        }));
        self
    }

    /// Register an asynchronous action that runs before every scenario.
    ///
    /// Like Alba, hooks are not additive: the last registered hook wins.
    pub fn before_each_async<F>(mut self, hook: F) -> Self
    where
        F: for<'a> Fn(&'a mut Request<Body>) -> BoxFuture<'a, ()> + Send + Sync + 'static,
    {
        self.before_each = Some(Arc::new(hook));
        self
    }

    /// Register a synchronous action that runs after every scenario request completes.
    ///
    /// Like Alba, hooks are not additive: the last registered hook wins.
    pub fn after_each<F>(mut self, hook: F) -> Self
    where
        F: Fn(&ScenarioOutcome) + Send + Sync + 'static,
    {
        self.after_each = Some(Arc::new(move |outcome| {
            hook(outcome);
            Box::pin(async {})
        }));
        self
    }

    /// Register an asynchronous action that runs after every scenario request completes.
    ///
    /// Like Alba, hooks are not additive: the last registered hook wins.
    pub fn after_each_async<F>(mut self, hook: F) -> Self
    where
        F: for<'a> Fn(&'a ScenarioOutcome) -> BoxFuture<'a, ()> + Send + Sync + 'static,
    {
        self.after_each = Some(Arc::new(hook));
        self
    }

    /// Execute a scenario and panic if any declarative assertion fails.
    pub async fn scenario<F>(&self, configure: F) -> ScenarioOutcome
    where
        F: FnOnce(&mut HostScenario),
    {
        self.try_scenario(configure)
            .await
            .unwrap_or_else(|error| panic!("{error}"))
    }

    /// Execute a scenario and return a structured failure instead of panicking.
    pub async fn try_scenario<F>(&self, configure: F) -> Result<ScenarioOutcome, ScenarioFailure>
    where
        F: FnOnce(&mut HostScenario),
    {
        let mut scenario = HostScenario::new();
        configure(&mut scenario);

        let HostScenario {
            request,
            expected_status,
            ignore_status_code,
            assertions,
        } = scenario;

        let mut request = request;
        if let Some(hook) = &self.before_each {
            hook(&mut request).await;
        }

        let request_summary = RequestSummary::from_request(&request);

        let response = self
            .router
            .clone()
            .oneshot(request)
            .await
            .expect("test host request should succeed");

        let outcome = ScenarioOutcome::from_response(request_summary.clone(), response).await;

        if let Some(hook) = &self.after_each {
            hook(&outcome).await;
        }

        let mut failures = Vec::new();
        if !ignore_status_code {
            let expected_status = expected_status.unwrap_or(StatusCode::OK);
            if outcome.status() != expected_status {
                failures.push(format!(
                    "Expected status {}, got {}",
                    expected_status,
                    outcome.status()
                ));
            }
        }

        for assertion in assertions {
            if let Err(message) = assertion(&outcome) {
                failures.push(message);
            }
        }

        if failures.is_empty() {
            Ok(outcome)
        } else {
            Err(ScenarioFailure {
                request: request_summary,
                failures,
            })
        }
    }
}

impl TestHostBootstrap {
    pub fn new() -> Self {
        Self {
            config_source: ConfigSource::Builder(ConfigBuilder::new()),
            config_transforms: Vec::new(),
            app_transforms: Vec::new(),
            env_overrides: Vec::new(),
            load_from_env: false,
            with_middleware: true,
            before_each: None,
            after_each: None,
        }
    }

    pub fn from_config(config: Config) -> Self {
        Self {
            config_source: ConfigSource::Built(config),
            ..Self::new()
        }
    }

    pub fn from_config_builder(builder: ConfigBuilder) -> Self {
        Self {
            config_source: ConfigSource::Builder(builder),
            ..Self::new()
        }
    }

    /// Transform the final config before the app is materialized.
    pub fn configure_config<F>(mut self, configure: F) -> Self
    where
        F: FnOnce(Config) -> Config + Send + 'static,
    {
        self.config_transforms.push(Box::new(configure));
        self
    }

    /// Transform the `ConfigBuilder` before it is built.
    pub fn configure_config_builder<F>(mut self, configure: F) -> Self
    where
        F: FnOnce(ConfigBuilder) -> ConfigBuilder,
    {
        let builder = match self.config_source {
            ConfigSource::Built(config) => ConfigBuilder::from_config(config),
            ConfigSource::Builder(builder) => builder,
        };
        self.config_source = ConfigSource::Builder(configure(builder));
        self
    }

    /// Load config from the environment at build time.
    pub fn from_env(mut self) -> Self {
        self.load_from_env = true;
        self
    }

    /// Transform the app after config has been materialized.
    pub fn configure_app<F>(mut self, configure: F) -> Self
    where
        F: FnOnce(App) -> App + Send + 'static,
    {
        self.app_transforms.push(Box::new(configure));
        self
    }

    /// Transform the app context before the host is built.
    pub fn configure_context<F>(self, configure: F) -> Self
    where
        F: FnOnce(crate::app::AppContextBuilder) -> crate::app::AppContextBuilder + Send + 'static,
    {
        self.configure_app(move |app| app.map_context(configure))
    }

    /// Override an environment variable while config is being materialized.
    pub fn with_env_var(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
        self.set_env_override(key.into(), Some(value.into()));
        self
    }

    /// Remove an environment variable while config is being materialized.
    pub fn without_env_var(mut self, key: impl Into<String>) -> Self {
        self.set_env_override(key.into(), None);
        self
    }

    /// Build the host without Tideway's middleware stack.
    pub fn without_middleware(mut self) -> Self {
        self.with_middleware = false;
        self
    }

    /// Build the host with Tideway's middleware stack applied.
    pub fn with_middleware(mut self) -> Self {
        self.with_middleware = true;
        self
    }

    /// Register a synchronous action that runs before every scenario.
    pub fn before_each<F>(mut self, hook: F) -> Self
    where
        F: Fn(&mut Request<Body>) + Send + Sync + 'static,
    {
        self.before_each = Some(Arc::new(move |request| {
            hook(request);
            Box::pin(async {})
        }));
        self
    }

    /// Register an asynchronous action that runs before every scenario.
    pub fn before_each_async<F>(mut self, hook: F) -> Self
    where
        F: for<'a> Fn(&'a mut Request<Body>) -> BoxFuture<'a, ()> + Send + Sync + 'static,
    {
        self.before_each = Some(Arc::new(hook));
        self
    }

    /// Register a synchronous action that runs after every scenario.
    pub fn after_each<F>(mut self, hook: F) -> Self
    where
        F: Fn(&ScenarioOutcome) + Send + Sync + 'static,
    {
        self.after_each = Some(Arc::new(move |outcome| {
            hook(outcome);
            Box::pin(async {})
        }));
        self
    }

    /// Register an asynchronous action that runs after every scenario.
    pub fn after_each_async<F>(mut self, hook: F) -> Self
    where
        F: for<'a> Fn(&'a ScenarioOutcome) -> BoxFuture<'a, ()> + Send + Sync + 'static,
    {
        self.after_each = Some(Arc::new(hook));
        self
    }

    pub fn build(self) -> TestHost {
        self.try_build()
            .expect("test host bootstrap should build successfully")
    }

    pub fn try_build(self) -> crate::Result<TestHost> {
        let _lock = TEST_HOST_ENV_LOCK.lock().unwrap();
        let _env = ScopedEnvOverrides::apply(&self.env_overrides);

        let builder = match self.config_source {
            ConfigSource::Built(config) => ConfigBuilder::from_config(config),
            ConfigSource::Builder(builder) => builder,
        };
        let mut config = if self.load_from_env {
            builder.from_env().build()?
        } else {
            builder.build()?
        };

        for transform in self.config_transforms {
            config = transform(config);
        }
        let config = ConfigBuilder::from_config(config).build()?;

        let mut app = App::with_config(config);
        for transform in self.app_transforms {
            app = transform(app);
        }

        Ok(build_host(
            app,
            self.with_middleware,
            self.before_each,
            self.after_each,
        ))
    }

    fn set_env_override(&mut self, key: String, value: Option<String>) {
        if let Some(existing) = self
            .env_overrides
            .iter_mut()
            .find(|existing| existing.key == key)
        {
            existing.value = value;
        } else {
            self.env_overrides.push(EnvOverride { key, value });
        }
    }
}

impl TestHostBuilder {
    pub fn new(app: App) -> Self {
        Self {
            app,
            with_middleware: true,
            before_each: None,
            after_each: None,
        }
    }

    /// Transform the underlying app before the host is built.
    pub fn configure_app<F>(mut self, configure: F) -> Self
    where
        F: FnOnce(App) -> App,
    {
        self.app = configure(self.app);
        self
    }

    /// Transform the app context before the host is built.
    pub fn configure_context<F>(mut self, configure: F) -> Self
    where
        F: FnOnce(crate::app::AppContextBuilder) -> crate::app::AppContextBuilder,
    {
        self.app = self.app.map_context(configure);
        self
    }

    /// Build the host without Tideway's middleware stack.
    pub fn without_middleware(mut self) -> Self {
        self.with_middleware = false;
        self
    }

    /// Build the host with Tideway's middleware stack applied.
    pub fn with_middleware(mut self) -> Self {
        self.with_middleware = true;
        self
    }

    /// Register a synchronous action that runs before every scenario.
    pub fn before_each<F>(mut self, hook: F) -> Self
    where
        F: Fn(&mut Request<Body>) + Send + Sync + 'static,
    {
        self.before_each = Some(Arc::new(move |request| {
            hook(request);
            Box::pin(async {})
        }));
        self
    }

    /// Register an asynchronous action that runs before every scenario.
    pub fn before_each_async<F>(mut self, hook: F) -> Self
    where
        F: for<'a> Fn(&'a mut Request<Body>) -> BoxFuture<'a, ()> + Send + Sync + 'static,
    {
        self.before_each = Some(Arc::new(hook));
        self
    }

    /// Register a synchronous action that runs after every scenario.
    pub fn after_each<F>(mut self, hook: F) -> Self
    where
        F: Fn(&ScenarioOutcome) + Send + Sync + 'static,
    {
        self.after_each = Some(Arc::new(move |outcome| {
            hook(outcome);
            Box::pin(async {})
        }));
        self
    }

    /// Register an asynchronous action that runs after every scenario.
    pub fn after_each_async<F>(mut self, hook: F) -> Self
    where
        F: for<'a> Fn(&'a ScenarioOutcome) -> BoxFuture<'a, ()> + Send + Sync + 'static,
    {
        self.after_each = Some(Arc::new(hook));
        self
    }

    pub fn build(self) -> TestHost {
        build_host(
            self.app,
            self.with_middleware,
            self.before_each,
            self.after_each,
        )
    }
}

/// Declarative scenario builder used by `TestHost::scenario`.
pub struct HostScenario {
    request: Request<Body>,
    expected_status: Option<StatusCode>,
    ignore_status_code: bool,
    assertions: Vec<ScenarioAssertion>,
}

impl HostScenario {
    fn new() -> Self {
        Self {
            request: Request::builder()
                .method(Method::GET)
                .uri("/")
                .body(Body::empty())
                .unwrap(),
            expected_status: None,
            ignore_status_code: false,
            assertions: Vec::new(),
        }
    }

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

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

    /// Configure a GET request.
    pub fn get(&mut self, uri: &str) -> &mut Self {
        self.method(Method::GET).uri(uri)
    }

    /// Configure a POST request.
    pub fn post(&mut self, uri: &str) -> &mut Self {
        self.method(Method::POST).uri(uri)
    }

    /// Configure a PUT request.
    pub fn put(&mut self, uri: &str) -> &mut Self {
        self.method(Method::PUT).uri(uri)
    }

    /// Configure a DELETE request.
    pub fn delete(&mut self, uri: &str) -> &mut Self {
        self.method(Method::DELETE).uri(uri)
    }

    /// Configure a PATCH request.
    pub fn patch(&mut self, uri: &str) -> &mut Self {
        self.method(Method::PATCH).uri(uri)
    }

    /// Add a request header.
    pub fn header(&mut self, key: &str, value: &str) -> &mut Self {
        use axum::http::HeaderName;

        self.request.headers_mut().insert(
            HeaderName::from_bytes(key.as_bytes()).unwrap(),
            value.parse().unwrap(),
        );
        self
    }

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

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

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

    /// Convenience alias for `bearer_token`.
    pub fn with_auth(&mut self, token: &str) -> &mut 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(&mut self, user_id: &str) -> &mut 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>(&mut self, claims: &T) -> &mut 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)]) -> &mut Self {
        let uri = self.request.uri().clone();
        let mut query_parts = vec![];

        if let Some(query) = uri.query() {
            query_parts.push(query.to_string());
        }

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

        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 a JSON request body.
    pub fn json<T: Serialize>(&mut self, body: &T) -> &mut 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
    }

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

    /// Set URL-encoded form data from a serializable type.
    pub fn form<T: Serialize>(&mut self, body: &T) -> &mut 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
    }

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

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

    /// Expect a specific status code.
    pub fn status_code_should_be(&mut self, status: u16) -> &mut Self {
        self.expected_status = Some(
            StatusCode::from_u16(status)
                .unwrap_or_else(|_| panic!("Invalid HTTP status code: {status}")),
        );
        self.ignore_status_code = false;
        self
    }

    /// Expect `200 OK`.
    pub fn status_code_should_be_ok(&mut self) -> &mut Self {
        self.status_code_should_be(StatusCode::OK.as_u16())
    }

    /// Disable the default status code expectation.
    pub fn ignore_status_code(&mut self) -> &mut Self {
        self.ignore_status_code = true;
        self
    }

    /// Assert that the response contains a header with the expected value.
    pub fn header_should_be(&mut self, key: &str, expected: &str) -> &mut Self {
        let key = key.to_string();
        let expected = expected.to_string();
        self.assert_with(move |outcome| {
            let Some(actual) = outcome.header(&key) else {
                return Err(format!("Expected header '{key}' to exist"));
            };

            if actual == expected {
                Ok(())
            } else {
                Err(format!(
                    "Expected header '{key}' to be '{expected}', got '{actual}'"
                ))
            }
        })
    }

    /// Assert that the response contains a header.
    pub fn header_should_exist(&mut self, key: &str) -> &mut Self {
        let key = key.to_string();
        self.assert_with(move |outcome| {
            if outcome.header(&key).is_some() {
                Ok(())
            } else {
                Err(format!("Expected header '{key}' to exist"))
            }
        })
    }

    /// Assert that the response is a redirect and has a matching `Location` header.
    pub fn redirect_to_should_be(&mut self, expected: &str) -> &mut Self {
        let expected = expected.to_string();
        self.assert_with(move |outcome| {
            if !outcome.status().is_redirection() {
                return Err(format!(
                    "Expected redirect status, got {}",
                    outcome.status()
                ));
            }

            let Some(location) = outcome.header(header::LOCATION.as_str()) else {
                return Err("Expected Location header to exist".to_string());
            };

            if location == expected {
                Ok(())
            } else {
                Err(format!(
                    "Expected redirect location '{expected}', got '{location}'"
                ))
            }
        })
    }

    /// Assert that the response body contains the given text.
    pub fn content_should_contain(&mut self, text: &str) -> &mut Self {
        let text = text.to_string();
        self.assert_with(move |outcome| {
            let body = outcome.body_string();
            if body.contains(&text) {
                Ok(())
            } else {
                Err(format!("Expected body to contain '{text}', got '{body}'"))
            }
        })
    }

    /// Assert that a JSON path matches the expected value.
    pub fn json_path_should_be(&mut self, path: &str, expected: serde_json::Value) -> &mut Self {
        let path = path.to_string();
        self.assert_with(move |outcome| {
            let json = parse_json_body(outcome)?;
            let Some(actual) = json_path_get(&json, &path) else {
                return Err(format!("Path '{path}' not found in JSON response"));
            };

            if actual == &expected {
                Ok(())
            } else {
                Err(format!(
                    "Expected JSON path '{path}' to equal {expected}, got {actual}"
                ))
            }
        })
    }

    /// Assert that the JSON response contains the expected subset.
    pub fn json_should_contain(&mut self, expected: serde_json::Value) -> &mut Self {
        self.assert_with(move |outcome| {
            let json = parse_json_body(outcome)?;
            if json_contains(&json, &expected) {
                Ok(())
            } else {
                Err(format!("Expected JSON to contain {expected}, got {json}"))
            }
        })
    }

    /// Add a custom assertion over the fully materialized response.
    pub fn assert_with<F>(&mut self, assertion: F) -> &mut Self
    where
        F: Fn(&ScenarioOutcome) -> Result<(), String> + Send + Sync + 'static,
    {
        self.assertions.push(Box::new(assertion));
        self
    }
}

/// Summary of the executed request for hooks and diagnostics.
#[derive(Clone, Debug)]
pub struct RequestSummary {
    method: Method,
    uri: Uri,
    headers: HeaderMap,
}

impl RequestSummary {
    fn from_request(request: &Request<Body>) -> Self {
        Self {
            method: request.method().clone(),
            uri: request.uri().clone(),
            headers: request.headers().clone(),
        }
    }

    pub fn method(&self) -> &Method {
        &self.method
    }

    pub fn uri(&self) -> &Uri {
        &self.uri
    }

    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    pub fn header(&self, key: &str) -> Option<&str> {
        self.headers.get(key).and_then(|value| value.to_str().ok())
    }
}

/// Materialized response snapshot returned by `TestHost`.
#[derive(Clone, Debug)]
pub struct ScenarioOutcome {
    request: RequestSummary,
    status: StatusCode,
    headers: HeaderMap,
    body: Vec<u8>,
}

impl ScenarioOutcome {
    async fn from_response(request: RequestSummary, response: axum::response::Response) -> Self {
        let status = response.status();
        let headers = response.headers().clone();
        let body = to_bytes(response.into_body(), usize::MAX)
            .await
            .expect("test host response body should be readable")
            .to_vec();

        Self {
            request,
            status,
            headers,
            body,
        }
    }

    pub fn request(&self) -> &RequestSummary {
        &self.request
    }

    pub fn status(&self) -> StatusCode {
        self.status
    }

    pub fn headers(&self) -> &HeaderMap {
        &self.headers
    }

    pub fn header(&self, key: &str) -> Option<&str> {
        self.headers.get(key).and_then(|value| value.to_str().ok())
    }

    pub fn body_bytes(&self) -> &[u8] {
        &self.body
    }

    pub fn body_string(&self) -> String {
        String::from_utf8_lossy(&self.body).into_owned()
    }

    pub fn json<T: DeserializeOwned>(&self) -> T {
        serde_json::from_slice(&self.body).expect("failed to parse JSON response")
    }

    pub fn json_value(&self) -> serde_json::Value {
        self.json()
    }
}

/// Structured failure returned by `TestHost::try_scenario`.
#[derive(Clone, Debug)]
pub struct ScenarioFailure {
    request: RequestSummary,
    failures: Vec<String>,
}

impl ScenarioFailure {
    pub fn request(&self) -> &RequestSummary {
        &self.request
    }

    pub fn failures(&self) -> &[String] {
        &self.failures
    }
}

impl fmt::Display for ScenarioFailure {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        writeln!(
            f,
            "Scenario failed for {} {}:",
            self.request.method(),
            self.request.uri()
        )?;

        for failure in &self.failures {
            writeln!(f, "- {failure}")?;
        }

        Ok(())
    }
}

impl std::error::Error for ScenarioFailure {}

fn parse_json_body(outcome: &ScenarioOutcome) -> Result<serde_json::Value, String> {
    serde_json::from_slice(outcome.body_bytes())
        .map_err(|error| format!("Expected JSON response body, got parse error: {error}"))
}

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 {
        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,
    }
}