laravel-rust 0.1.0

Laravel for Rust: a full-stack Rust web framework, inspired by PHP Laravel
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
use std::future::{Future, IntoFuture};
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::panic::Location;
use std::pin::Pin;
use std::sync::atomic::AtomicBool;

use ::url::Url;
use axum::body::Body;
use bytes::Bytes;
use http::{HeaderMap, HeaderName, HeaderValue, Method, header};
use http_body_util::BodyExt;
use serde::Serialize;
use serde_json::{Map, Value};
use tower::ServiceExt;

use super::TestResponse;
use crate::cookie::PlaintextCookies;
use crate::errors::{Handled, RecordReports};
use crate::foundation::{Application, RecordRoot};
use crate::http::client::Attachment;
use crate::session::{Session, SessionSeed};
use crate::view::RenderedView;

/// Sends requests to the application in tests, without opening a socket.
///
/// Each method returns a [`TestRequest`] to customize and await. The methods live on this trait
/// rather than on [`Application`] itself, so tests import the trait, usually through
/// [`testing::prelude`](super::prelude).
///
/// ```no_run
/// use laravel::testing::MakesHttpRequests;
///
/// # async fn test(app: laravel::Application) {
/// app.get("/posts").await.assert_ok().assert_see("Posts");
/// # }
/// ```
///
/// A URI with a scheme, such as `https://example.com/users`, is a full URL. Any other URI is a
/// path, with or without its leading `/`, so `users` requests `/users`. A request to a path goes
/// to the scheme, host, and port in `APP_URL`. When the request has a `Host` header, it goes to
/// that host instead, with `APP_URL`'s scheme.
///
/// Requests come from `127.0.0.1` and send `Sec-Fetch-Site: same-origin`, as a browser does on
/// the application's own pages, so CSRF protection lets them through. To test the protection,
/// send `sec-fetch-site: cross-site` with [`header`](TestRequest::header).
///
/// # Panics
///
/// Each method panics when the URI is invalid.
pub trait MakesHttpRequests {
    /// Send a request with any method to the application.
    #[track_caller]
    fn request(&self, method: Method, uri: impl AsRef<str>) -> TestRequest;

    /// Send a `GET` request to the application.
    #[track_caller]
    fn get(&self, uri: impl AsRef<str>) -> TestRequest {
        self.request(Method::GET, uri)
    }

    /// Send a `POST` request to the application.
    #[track_caller]
    fn post(&self, uri: impl AsRef<str>) -> TestRequest {
        self.request(Method::POST, uri)
    }

    /// Send a `PUT` request to the application.
    #[track_caller]
    fn put(&self, uri: impl AsRef<str>) -> TestRequest {
        self.request(Method::PUT, uri)
    }

    /// Send a `PATCH` request to the application.
    #[track_caller]
    fn patch(&self, uri: impl AsRef<str>) -> TestRequest {
        self.request(Method::PATCH, uri)
    }

    /// Send a `DELETE` request to the application.
    #[track_caller]
    fn delete(&self, uri: impl AsRef<str>) -> TestRequest {
        self.request(Method::DELETE, uri)
    }
}

impl MakesHttpRequests for Application {
    #[track_caller]
    fn request(&self, method: Method, uri: impl AsRef<str>) -> TestRequest {
        TestRequest::new(self.clone(), method, uri.as_ref())
    }
}

#[track_caller]
fn parse_uri(uri: &str) -> http::Uri {
    let parsed = match uri.parse::<http::Uri>() {
        Ok(parsed) if parsed.scheme().is_some() || uri.starts_with('/') => Ok(parsed),
        _ => format!("/{uri}").parse::<http::Uri>(),
    };

    parsed.unwrap_or_else(|error| panic!("the test request URI `{uri}` is invalid: {error}"))
}

fn app_url(application: &Application) -> Option<Url> {
    Url::parse(&application.config().app.url)
        .ok()
        .filter(|url| matches!(url.scheme(), "http" | "https"))
}

fn host(uri: &http::Uri, app_url: Option<&Url>) -> HeaderValue {
    let host = match (uri.authority(), app_url) {
        (Some(authority), _) => authority.as_str(),
        (None, Some(url)) => &url[::url::Position::BeforeHost..::url::Position::AfterPort],
        (None, None) => "localhost",
    };

    HeaderValue::try_from(host).expect("a parsed host is a valid header")
}

/// A request to send to the application, from [`MakesHttpRequests`].
///
/// Its methods add headers, cookies, a body, a session, or a user. Awaiting the request boots
/// the application if needed, sends the request, and returns a [`TestResponse`].
///
/// ```no_run
/// use laravel::testing::MakesHttpRequests;
///
/// # async fn test(app: laravel::Application) {
/// app.post("/api/users")
///     .header("accept-language", "fr")
///     .json(serde_json::json!({ "name": "Abigail" }))
///     .await
///     .assert_created();
/// # }
/// ```
///
/// # Panics
///
/// Awaiting the request panics when the application fails to boot, or when a problem with its
/// `#[laravel::auth::page]` handlers stops it from serving requests. It also panics in these
/// cases:
///
/// - An [attached](Self::attach) file can't be read.
/// - The request attaches a file and also has a [`json`](Self::json) or raw
///   [`body`](Self::body).
/// - [`follow_redirects`](Self::follow_redirects) follows more than ten redirects.
#[derive(Debug, Clone)]
#[must_use = "a test request does nothing unless awaited"]
pub struct TestRequest {
    application: Application,
    method: Method,
    uri: http::Uri,
    headers: HeaderMap,
    cookies: Vec<RequestCookie>,
    body: Bytes,
    attachments: Vec<(String, Attachment)>,
    session: Option<Map<String, Value>>,
    extensions: http::Extensions,
    ip: IpAddr,
    follow_redirects: bool,
    location: &'static Location<'static>,
}

impl TestRequest {
    #[track_caller]
    fn new(application: Application, method: Method, uri: &str) -> Self {
        let uri = parse_uri(uri);
        let mut headers = HeaderMap::new();
        headers.insert(header::HOST, host(&uri, app_url(&application).as_ref()));
        headers.insert("sec-fetch-site", HeaderValue::from_static("same-origin"));

        Self {
            application,
            method,
            uri,
            headers,
            cookies: Vec::new(),
            body: Bytes::new(),
            attachments: Vec::new(),
            session: None,
            extensions: http::Extensions::new(),
            ip: IpAddr::V4(Ipv4Addr::LOCALHOST),
            follow_redirects: false,
            location: Location::caller(),
        }
    }

    /// Add a header, replacing any header with the same name.
    ///
    /// The value may be any string type, such as `.header("x-team", format!("team-{id}"))`.
    ///
    /// # Panics
    ///
    /// Panics when the name or value isn't a valid header.
    #[track_caller]
    pub fn header(mut self, name: &str, value: impl AsRef<str>) -> Self {
        let value = value.as_ref();
        let name = HeaderName::try_from(name)
            .unwrap_or_else(|error| panic!("the test request header name `{name}` is invalid: {error}"));
        let value = HeaderValue::try_from(value)
            .unwrap_or_else(|error| panic!("the test request header `{name}` value `{value}` is invalid: {error}"));
        self.headers.insert(name, value);
        self
    }

    /// Authenticate with a bearer token in the `Authorization` header, as an API client does.
    ///
    /// ```no_run
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test(app: laravel::Application, token: String) {
    /// app.get("/api/user").token(&token).await.assert_ok();
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics when the token can't be sent in a header.
    #[track_caller]
    pub fn token(self, token: impl AsRef<str>) -> Self {
        self.header("authorization", format!("Bearer {}", token.as_ref()))
    }

    /// Send a cookie with a plain-text value.
    ///
    /// The route reads the given value whether or not its middleware decrypts cookies, as the
    /// `web` group's [`EncryptCookies`](crate::cookie::EncryptCookies) does. The cookie replaces
    /// any cookie with the same name, including one from
    /// [`with_cookies_from`](Self::with_cookies_from).
    ///
    /// ```no_run
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test(app: laravel::Application) {
    /// app.get("/").cookie("theme", "dark").await.assert_see("dark");
    /// # }
    /// ```
    pub fn cookie(mut self, name: &str, value: impl AsRef<str>) -> Self {
        self.put_cookie(name, value.as_ref(), true);
        self
    }

    fn put_cookie(&mut self, name: &str, value: &str, plaintext: bool) {
        let cookie = RequestCookie {
            name: name.to_owned(),
            value: value.to_owned(),
            plaintext,
        };

        match self.cookies.iter_mut().find(|existing| existing.name == name) {
            Some(existing) => *existing = cookie,
            None => self.cookies.push(cookie),
        }
    }

    /// Send the cookies that a previous response set, as a browser would store them.
    ///
    /// The request doesn't send cookies that the response removed, such as with
    /// [`Response::without_cookie`](crate::http::Response::without_cookie). It also doesn't send
    /// cookies that expired on the application's clock after the response arrived.
    ///
    /// When the previous request used [`follow_redirects`](Self::follow_redirects), this request
    /// sends the cookies that every response along the redirects set. When two responses set
    /// the same cookie, the later value wins. A [`cookie`](Self::cookie) with the same name takes
    /// precedence over both.
    pub fn with_cookies_from(mut self, response: &TestResponse) -> Self {
        for cookie in response.cookies_on_the_way() {
            let given = self
                .cookies
                .iter()
                .any(|own| own.plaintext && own.name == cookie.name());

            if !given {
                self.receive_cookie(response, &cookie);
            }
        }
        self
    }

    fn receive_cookie(&mut self, response: &TestResponse, cookie: &cookie::Cookie<'_>) {
        if response.has_expired(cookie) {
            self.cookies.retain(|existing| existing.name != cookie.name());
        } else {
            self.put_cookie(cookie.name(), cookie.value(), false);
        }
    }

    /// Send a JSON body, and ask for a JSON response.
    ///
    /// This method sets both the `content-type` and `accept` headers to `application/json`.
    ///
    /// # Panics
    ///
    /// Panics when the body can't be serialized as JSON.
    #[track_caller]
    pub fn json(mut self, body: impl Serialize) -> Self {
        self.body = serde_json::to_vec(&body)
            .expect("the JSON body should serialize")
            .into();
        self.headers
            .insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json"));
        self.headers
            .insert(header::ACCEPT, HeaderValue::from_static("application/json"));
        self
    }

    /// Send a form body as `application/x-www-form-urlencoded`.
    ///
    /// When the request also [attaches](Self::attach) a file, the fields go in the multipart
    /// form instead.
    ///
    /// # Panics
    ///
    /// Panics when the body can't be serialized as a form.
    #[track_caller]
    pub fn form(mut self, body: impl Serialize) -> Self {
        self.body = serde_urlencoded::to_string(body)
            .expect("the form body should serialize")
            .into();
        self.headers.insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("application/x-www-form-urlencoded"),
        );
        self
    }

    /// Send a body exactly as given, such as a webhook's payload or input that isn't valid JSON.
    ///
    /// Set the body's `content-type` with [`header`](Self::header). If you call more than one of
    /// `body`, [`json`](Self::json), and [`form`](Self::form), the last call sets the body. A
    /// request with a raw body can't also [attach](Self::attach) files.
    ///
    /// ```no_run
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test(app: laravel::Application) {
    /// app.post("/webhooks/stripe")
    ///     .header("content-type", "application/json")
    ///     .body(r#"{"type": "invoice.paid"}"#)
    ///     .await
    ///     .assert_ok();
    /// # }
    /// ```
    pub fn body(mut self, content: impl Into<Bytes>) -> Self {
        self.body = content.into();
        self
    }

    /// Start the request's session with these values, such as a user's cart.
    ///
    /// Keys may use dot notation, and calling this method again adds more values. The route must
    /// start a session, as the `web` middleware group does.
    ///
    /// ```no_run
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test(app: laravel::Application) {
    /// app.get("/checkout")
    ///     .with_session(serde_json::json!({ "cart": [1, 2] }))
    ///     .await
    ///     .assert_ok();
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics when the values aren't a map, or can't be serialized.
    #[track_caller]
    pub fn with_session(mut self, values: impl Serialize) -> Self {
        let Value::Object(values) = serde_json::to_value(values).expect("the session values should serialize") else {
            panic!("the session values should be a map, such as `json!({{ \"cart\": [1] }})`");
        };
        self.session.get_or_insert_with(Map::new).extend(values);
        self
    }

    /// Send the request as a logged-in user, for the guard that authenticates the user's type.
    ///
    /// The user isn't stored in the session, and
    /// [`Authenticate::via`](crate::auth::Authenticate::via) doesn't run its guard. Redirects that
    /// the request follows are sent as the same user, even after a handler logs the user out.
    ///
    /// ```no_run
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test<U: laravel::auth::Authenticatable>(app: laravel::Application, user: U) {
    /// app.get("/dashboard").acting_as(&user).await.assert_ok();
    /// # }
    /// ```
    pub fn acting_as<U: crate::auth::Authenticatable>(mut self, user: &U) -> Self {
        crate::auth::RequestUser::insert(&mut self.extensions, user.clone());
        self
    }

    /// Send the request from a page of the application, in the `Referer` header as a browser
    /// does.
    ///
    /// [`Redirect::back`](crate::http::Redirect::back) then returns to that page, and
    /// [`assert_redirect_back`](super::TestResponse::assert_redirect_back) can check the
    /// redirect. A path resolves against the request's host.
    ///
    /// ```no_run
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test(app: laravel::Application) {
    /// app.post("/profile")
    ///     .from("/profile/edit")
    ///     .form([("email", "not-an-email")])
    ///     .await
    ///     .assert_redirect_back_with_errors(&["email"]);
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics when the page isn't a valid header value.
    #[track_caller]
    pub fn from(self, page: &str) -> Self {
        let url = match app_url(&self.application) {
            Some(app_url) if !page.contains("://") => {
                let host = self.headers.get(header::HOST).and_then(|host| host.to_str().ok());
                let root = format!("{}://{}", app_url.scheme(), host.unwrap_or("localhost"));
                Url::parse(&root)
                    .and_then(|root| root.join(page))
                    .map_or_else(|_| page.to_owned(), String::from)
            }
            _ => page.to_owned(),
        };

        self.header("referer", url)
    }

    /// Send the request from an IP address other than `127.0.0.1`.
    ///
    /// Use a load balancer's address to test
    /// [trusted proxies](crate::http::MiddlewareConfig::trust_proxies), or a client's address to
    /// test `request.ip()`:
    ///
    /// ```no_run
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test(app: laravel::Application) {
    /// app.get("/")
    ///     .with_ip([10, 0, 0, 1])
    ///     .header("x-forwarded-for", "203.0.113.7")
    ///     .await
    ///     .assert_ok();
    /// # }
    /// ```
    pub fn with_ip(mut self, ip: impl Into<IpAddr>) -> Self {
        self.ip = ip.into();
        self
    }

    /// Upload a file, as a form with a file input named `name` does.
    ///
    /// The request sends the file as `multipart/form-data`, along with any
    /// [`form`](TestRequest::form) fields. It can't also have a [`json`](TestRequest::json) or
    /// raw [`body`](TestRequest::body). Unless the [`Attachment`] sets a content type, the request
    /// guesses the type from the file name, as browsers do. A relative path resolves against the
    /// application's base path.
    ///
    /// ```no_run
    /// use laravel::http::client::Attachment;
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test(app: laravel::Application, png: Vec<u8>) {
    ///
    /// app.post("/avatar")
    ///     .attach("avatar", Attachment::from_data(png, "taylor.png"))
    ///     .form(&[("name", "Taylor")])
    ///     .await
    ///     .assert_ok();
    ///
    /// app.post("/avatar")
    ///     .attach("avatar", Attachment::from_path("tests/fixtures/taylor.png"))
    ///     .await
    ///     .assert_ok();
    /// # }
    /// ```
    pub fn attach(mut self, name: &str, attachment: impl Into<Attachment>) -> Self {
        self.attachments.push((name.to_owned(), attachment.into()));
        self
    }

    /// Follow the response's redirects, as a browser would, and return the response for the page
    /// they lead to, such as the page a form redirects to after it saves:
    ///
    /// ```no_run
    /// # use laravel::testing::MakesHttpRequests;
    /// # async fn test(app: laravel::Application) {
    /// app.post("/posts")
    ///     .form([("title", "Hello")])
    ///     .follow_redirects()
    ///     .await
    ///     .assert_ok()
    ///     .assert_see("Post created!");
    /// # }
    /// ```
    ///
    /// The request follows each redirect with a `GET`, or with the same method and body for a
    /// `307` or `308`. It sends the cookies that the responses set, so the session carries over.
    /// The request doesn't follow a redirect to another scheme or host, and returns that redirect
    /// response instead.
    ///
    /// # Panics
    ///
    /// Awaiting the request panics after ten redirects, which usually means a redirect loop.
    pub fn follow_redirects(mut self) -> Self {
        self.follow_redirects = true;
        self
    }

    async fn multipart(&mut self) {
        const BOUNDARY: &str = "laravel-rust-test-boundary";

        let is_form = self
            .headers
            .get(header::CONTENT_TYPE)
            .is_some_and(|content_type| content_type == "application/x-www-form-urlencoded");
        let fields: Vec<(String, String)> = if is_form {
            serde_urlencoded::from_bytes(&self.body).unwrap_or_default()
        } else {
            assert!(
                self.body.is_empty(),
                "files can't be attached to a JSON or raw body: give the other fields to `form` instead\n\nat {}",
                self.location
            );
            Vec::new()
        };

        let mut body = Vec::new();
        for (name, value) in fields {
            let name = escape_name(&name);
            body.extend_from_slice(
                format!("--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"\r\n\r\n{value}\r\n")
                    .as_bytes(),
            );
        }
        for (name, attachment) in std::mem::take(&mut self.attachments) {
            let (name, file_name) = (escape_name(&name), escape_name(&attachment.file_name));
            let content_type = attachment.content_type();
            let contents = attachment
                .read(&self.application.config().app.base_path)
                .await
                .unwrap_or_else(|error| {
                    let reason = std::error::Error::source(&error)
                        .map(ToString::to_string)
                        .unwrap_or_default();
                    panic!("{error}: {reason}\n\nat {}", self.location)
                });
            body.extend_from_slice(
                format!(
                    "--{BOUNDARY}\r\nContent-Disposition: form-data; name=\"{name}\"; filename=\"{file_name}\"\r\nContent-Type: {content_type}\r\n\r\n"
                )
                .as_bytes(),
            );
            body.extend_from_slice(&contents);
            body.extend_from_slice(b"\r\n");
        }
        body.extend_from_slice(format!("--{BOUNDARY}--\r\n").as_bytes());

        self.body = body.into();
        self.headers.insert(
            header::CONTENT_TYPE,
            HeaderValue::from_static("multipart/form-data; boundary=laravel-rust-test-boundary"),
        );
    }

    async fn send(mut self) -> TestResponse {
        if let Err(error) = self.application.boot().await {
            panic!("the application failed to boot: {error}\n\nat {}", self.location);
        }

        if !self.attachments.is_empty() {
            self.multipart().await;
        }

        let mut response = self.dispatch().await;
        let mut redirects = 0;

        while self.follow_redirects && self.follow(&response) {
            redirects += 1;
            if redirects > MAX_REDIRECTS {
                panic!(
                    "followed {MAX_REDIRECTS} redirects without arriving at a page, which is likely a redirect loop\n\n{}\n\nat {}",
                    response.summary(),
                    self.location
                );
            }

            let mut next = self.dispatch().await;
            let mut reported = std::mem::take(&mut response.reports);
            if let Some(handled) = response.handled.take().filter(|handled| handled.reported) {
                reported.insert(0, handled.error);
            }
            next.reports.splice(0..0, reported);
            next.earlier_cookies = response.cookies_on_the_way().collect();
            response = next;
        }

        response
    }

    async fn dispatch(&mut self) -> TestResponse {
        let mut headers = self.headers.clone();
        if !self.cookies.is_empty() {
            headers.insert(header::COOKIE, self.cookie_header());
        }
        if !self.body.is_empty() && !headers.contains_key(header::CONTENT_LENGTH) {
            headers.insert(header::CONTENT_LENGTH, HeaderValue::from(self.body.len()));
        }

        let mut request = http::Request::builder()
            .method(self.method.clone())
            .uri(self.url(&headers))
            .body(Body::from(self.body.clone()))
            .expect("the request URI was parsed when the request was made");
        *request.headers_mut() = headers;
        let path = request
            .uri()
            .path_and_query()
            .map_or("/", http::uri::PathAndQuery::as_str)
            .to_owned();

        request
            .extensions_mut()
            .insert(axum::extract::ConnectInfo(SocketAddr::new(self.ip, 0)));
        let reports = RecordReports::default();
        request.extensions_mut().insert(reports.clone());
        let root = RecordRoot::default();
        request.extensions_mut().insert(root.clone());

        request.extensions_mut().extend(self.extensions.clone());
        if let Some(values) = self.session.take() {
            request.extensions_mut().insert(SessionSeed(values));
        }
        request.extensions_mut().insert(self.plaintext_cookies());

        if let Err(problems) = self.application.check_auth_pages() {
            panic!("{problems}");
        }

        let response = self
            .application
            .router()
            .clone()
            .oneshot(request)
            .await
            .unwrap_or_else(|never| match never {});
        let (parts, body) = response.into_parts();
        // Snapshot the session before the body streams, so it's the session as it was saved...
        let session = parts.extensions.get::<Session>().map(Session::all);
        let (body, failed_body) = read_body(body).await;

        TestResponse {
            referer: self
                .headers
                .get(header::REFERER)
                .and_then(|value| value.to_str().ok())
                .map(str::to_owned),
            root: root
                .0
                .get()
                .cloned()
                .expect("the kernel records each test request's root"),
            path,
            handled: parts.extensions.get::<Handled>().cloned(),
            // Read reports after reading the body because streaming may report errors...
            reports: std::mem::take(&mut *reports.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)),
            view: parts.extensions.get::<RenderedView>().cloned(),
            session,
            status: parts.status,
            headers: parts.headers,
            body,
            failed_body,
            asserted_failed_body: AtomicBool::new(false),
            earlier_cookies: Vec::new(),
            received_at: self.application.clock().now(),
            requested_at: self.location,
            application: self.application.clone(),
            #[cfg(feature = "inertia")]
            request: self.clone(),
        }
    }

    /// This request as its client would send it again after `response`, with the cookies that
    /// `response` set.
    #[cfg(feature = "inertia")]
    pub(super) fn after(&self, response: &TestResponse) -> Self {
        let mut next = self.clone();
        for cookie in response.set_cookies() {
            next.receive_cookie(response, &cookie);
        }
        next
    }

    /// The Inertia visit that reloads a page from this request's client. The visit is a `GET` to
    /// the page's URL, with the reload's Inertia headers in place of this request's.
    #[cfg(feature = "inertia")]
    pub(super) fn reload(mut self, reload: &::inertia::testing::ReloadRequest) -> Self {
        let stale: Vec<HeaderName> = self
            .headers
            .keys()
            .filter(|name| name.as_str().starts_with("x-inertia"))
            .cloned()
            .collect();
        for name in stale.into_iter().chain([header::CONTENT_TYPE, header::CONTENT_LENGTH]) {
            self.headers.remove(name);
        }
        self.headers.extend(reload.headers().clone());

        self.method = Method::GET;
        self.uri = parse_uri(reload.url());
        self.body = Bytes::new();
        self.location = reload.location();
        self
    }

    fn url(&self, headers: &HeaderMap) -> http::Uri {
        let app_url = app_url(&self.application);
        let host = headers.get(header::HOST).and_then(|host| host.to_str().ok());

        match (app_url, host) {
            (Some(app_url), Some(host)) if self.uri.scheme().is_none() => {
                format!("{}://{host}{}", app_url.scheme(), self.uri)
                    .parse()
                    .unwrap_or_else(|_| self.uri.clone())
            }
            _ => self.uri.clone(),
        }
    }

    fn cookie_header(&self) -> HeaderValue {
        let own = self.headers.get(header::COOKIE).and_then(|value| value.to_str().ok());
        let cookies = self.cookies.iter().map(|cookie| {
            cookie::Cookie::new(cookie.name.as_str(), cookie.value.as_str())
                .encoded()
                .to_string()
        });
        let header = own.map(str::to_owned).into_iter().chain(cookies).collect::<Vec<_>>();

        HeaderValue::try_from(header.join("; ")).expect("encoded cookies are a valid header")
    }

    fn plaintext_cookies(&self) -> PlaintextCookies {
        PlaintextCookies(
            self.cookies
                .iter()
                .filter(|cookie| cookie.plaintext)
                .map(|cookie| (cookie.name.clone(), cookie.value.clone()))
                .collect(),
        )
    }

    fn follow(&mut self, response: &TestResponse) -> bool {
        let status = response.status.as_u16();
        let Some(location) = response
            .location()
            .filter(|_| matches!(status, 301 | 302 | 303 | 307 | 308) && response.failed_body.is_none())
        else {
            return false;
        };
        if response
            .root_url()
            .is_none_or(|root| root.origin() != location.origin())
        {
            return false;
        }

        if !matches!(status, 307 | 308) {
            if self.method != Method::HEAD {
                self.method = Method::GET;
            }
            self.body = Bytes::new();
            self.headers.remove(header::CONTENT_TYPE);
            self.headers.remove(header::CONTENT_LENGTH);
        }
        self.uri = location[..::url::Position::AfterQuery]
            .parse()
            .expect("a redirect within the application is a valid URI");
        for cookie in response.set_cookies() {
            self.receive_cookie(response, &cookie);
        }

        true
    }
}

async fn read_body(mut body: Body) -> (Bytes, Option<String>) {
    let mut bytes = Vec::new();
    let failed = loop {
        match body.frame().await {
            Some(Ok(frame)) => {
                if let Some(data) = frame.data_ref() {
                    bytes.extend_from_slice(data);
                }
            }
            Some(Err(error)) => break Some(error.to_string()),
            None => break None,
        }
    };

    (bytes.into(), failed)
}

#[derive(Debug, Clone)]
struct RequestCookie {
    name: String,
    value: String,
    plaintext: bool,
}

const MAX_REDIRECTS: usize = 10;

// Browsers escape these characters, so a name can't end its `Content-Disposition` value early...
fn escape_name(name: &str) -> String {
    name.replace('"', "%22").replace('\r', "%0D").replace('\n', "%0A")
}

impl IntoFuture for TestRequest {
    type Output = TestResponse;
    type IntoFuture = Pin<Box<dyn Future<Output = TestResponse> + Send>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.send())
    }
}