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
use ::anyhow::Context;
use ::bytes::Bytes;
use ::cookie::Cookie;
use ::cookie::CookieJar;
use ::http::header::AsHeaderName;
use ::http::header::HeaderName;
use ::http::header::SET_COOKIE;
use ::http::response::Parts;
use ::http::HeaderMap;
use ::http::HeaderValue;
use ::http::StatusCode;
use ::serde::de::DeserializeOwned;
use ::std::convert::AsRef;
use ::std::fmt::Debug;
use ::std::fmt::Display;
use url::Url;

///
/// The `TestResponse` is the result of a request created using a [`TestServer`](crate::TestServer).
/// The `TestServer` builds a [`TestRequest`](crate::TestRequest), which when awaited,
/// will produce the response.
///
/// ```rust
/// # async fn test() -> Result<(), Box<dyn ::std::error::Error>> {
/// #
/// use ::axum::Json;
/// use ::axum::routing::Router;
/// use ::axum::routing::get;
/// use ::serde::Deserialize;
/// use ::serde::Serialize;
///
/// use ::axum_test::TestServer;
///
/// let app = Router::new()
///     .route(&"/test", get(|| async { "hello!" }));
///
/// let server = TestServer::new(app)?;
///
/// // This builds a `TestResponse`
/// let response = server.get(&"/todo").await;
/// #
/// # Ok(())
/// # }
/// ```
///
/// # Extracting Response
///
/// The functions [`TestResponse::json()`](crate::TestResponse::json()), [`TestResponse::text()`](crate::TestResponse::text()),
/// and [`TestResponse::form()`](crate::TestResponse::form()),
/// allow you to extract the underlying response content in different formats.
///
/// ```rust
/// # async fn test() -> Result<(), Box<dyn ::std::error::Error>> {
/// #
/// # use ::axum::Json;
/// # use ::axum::routing::Router;
/// # use ::axum::routing::get;
/// # use ::serde::Deserialize;
/// # use ::serde::Serialize;
/// # use ::axum_test::TestServer;
/// #
/// # #[derive(Serialize, Deserialize, Debug)]
/// # struct Todo {}
/// #
/// # let app = Router::new()
/// #     .route(&"/test", get(|| async { "hello!" }));
/// #
/// # let server = TestServer::new(app)?;
/// let todo_response = server.get(&"/todo")
///         .await
///         .json::<Todo>();
///
/// let response_as_raw_text = server.get(&"/todo")
///         .await
///         .text();
/// #
/// # Ok(())
/// # }
/// ```
///
/// [`TestResponse::as_bytes()`](crate::TestResponse::as_bytes()) and [`TestResponse::into_bytes()`](crate::TestResponse::into_bytes()),
/// offer the underlying raw bytes to allow custom decoding.
///
/// Full code examples can be found within their documentation.
///
/// # Assertions
///
/// The result of a response can also be asserted using the many assertion functions.
///
/// ```rust
/// # async fn test() -> Result<(), Box<dyn ::std::error::Error>> {
/// #
/// use ::axum::Json;
/// use ::axum::routing::Router;
/// use ::axum::routing::get;
/// use ::serde::Deserialize;
/// use ::serde::Serialize;
///
/// use ::axum_test::TestServer;
///
/// let app = Router::new()
///     .route(&"/test", get(|| async { "hello!" }));
///
/// let server = TestServer::new(app)?;
///
/// let response = server.get(&"/todo").await;
///
/// // These assertions will panic if they are not fulfilled by the response.
/// response.assert_status_ok();
/// response.assert_text("hello!");
/// #
/// # Ok(())
/// # }
/// ```
///
#[derive(Clone, Debug)]
pub struct TestResponse {
    /// This is the path that the user requested.
    user_requested_path: String,
    /// This is the actual url that was used for the request.
    full_request_url: Url,
    headers: HeaderMap<HeaderValue>,
    status_code: StatusCode,
    response_body: Bytes,
}

impl TestResponse {
    pub(crate) fn new(
        user_requested_path: String,
        full_request_url: Url,
        parts: Parts,
        response_body: Bytes,
    ) -> Self {
        Self {
            user_requested_path,
            full_request_url,
            headers: parts.headers,
            status_code: parts.status,
            response_body,
        }
    }

    /// Returns the underlying response, extracted as a UTF-8 string.
    ///
    /// # Example
    ///
    /// ```rust
    /// # async fn test() -> Result<(), Box<dyn ::std::error::Error>> {
    /// #
    /// use ::axum::Json;
    /// use ::axum::routing::Router;
    /// use ::axum::routing::get;
    /// use ::serde_json::json;
    /// use ::serde_json::Value;
    ///
    /// use ::axum_test::TestServer;
    ///
    /// async fn route_get_todo() -> Json<Value> {
    ///     Json(json!({
    ///         "description": "buy milk",
    ///     }))
    /// }
    ///
    /// let app = Router::new()
    ///     .route(&"/todo", get(route_get_todo));
    ///
    /// let server = TestServer::new(app)?;
    /// let response = server.get(&"/todo").await;
    ///
    /// // Extract the response as a string on it's own.
    /// let raw_text = response.text();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn text(&self) -> String {
        String::from_utf8_lossy(&self.as_bytes()).to_string()
    }

    /// Deserializes the response, as JSON, into the type given.
    ///
    /// If deserialization fails then this will panic.
    ///
    /// # Example
    ///
    /// ```rust
    /// # async fn test() -> Result<(), Box<dyn ::std::error::Error>> {
    /// #
    /// use ::axum::Json;
    /// use ::axum::routing::Router;
    /// use ::axum::routing::get;
    /// use ::serde::Deserialize;
    /// use ::serde::Serialize;
    ///
    /// use ::axum_test::TestServer;
    ///
    /// #[derive(Serialize, Deserialize, Debug)]
    /// struct Todo {
    ///     description: String,
    /// }
    ///
    /// async fn route_get_todo() -> Json<Todo> {
    ///     Json(Todo {
    ///         description: "buy milk".to_string(),
    ///     })
    /// }
    ///
    /// let app = Router::new()
    ///     .route(&"/todo", get(route_get_todo));
    ///
    /// let server = TestServer::new(app)?;
    /// let response = server.get(&"/todo").await;
    ///
    /// // Extract the response as a `Todo` item.
    /// let todo = response.json::<Todo>();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn json<T>(&self) -> T
    where
        T: DeserializeOwned,
    {
        serde_json::from_slice::<T>(&self.as_bytes())
            .with_context(|| {
                format!(
                    "Deserializing response from JSON for request {}",
                    self.user_requested_path
                )
            })
            .unwrap()
    }

    /// Deserializes the response, as an urlencoded Form, into the type given.
    ///
    /// If deserialization fails then this will panic.
    ///
    /// # Example
    ///
    /// ```rust
    /// # async fn test() -> Result<(), Box<dyn ::std::error::Error>> {
    /// #
    /// use ::axum::Form;
    /// use ::axum::routing::Router;
    /// use ::axum::routing::get;
    /// use ::serde::Deserialize;
    /// use ::serde::Serialize;
    ///
    /// use ::axum_test::TestServer;
    ///
    /// #[derive(Serialize, Deserialize, Debug)]
    /// struct Todo {
    ///     description: String,
    /// }
    ///
    /// async fn route_get_todo() -> Form<Todo> {
    ///     Form(Todo {
    ///         description: "buy milk".to_string(),
    ///     })
    /// }
    ///
    /// let app = Router::new()
    ///     .route(&"/todo", get(route_get_todo));
    ///
    /// let server = TestServer::new(app)?;
    /// let response = server.get(&"/todo").await;
    ///
    /// // Extract the response as a `Todo` item.
    /// let todo = response.form::<Todo>();
    /// #
    /// # Ok(())
    /// # }
    /// ```
    #[must_use]
    pub fn form<T>(&self) -> T
    where
        T: DeserializeOwned,
    {
        serde_urlencoded::from_bytes::<T>(&self.as_bytes())
            .with_context(|| {
                format!(
                    "Deserializing response from Form for request {}",
                    self.user_requested_path
                )
            })
            .unwrap()
    }

    /// Returns the raw underlying response as `Bytes`.
    #[must_use]
    pub fn as_bytes<'a>(&'a self) -> &'a Bytes {
        &self.response_body
    }

    /// Consumes this returning the underlying `Bytes`
    /// in the response.
    #[must_use]
    pub fn into_bytes<'a>(self) -> Bytes {
        self.response_body
    }

    /// The status_code of the response.
    #[must_use]
    pub fn status_code(&self) -> StatusCode {
        self.status_code
    }

    /// The full URL that was used to produce this response.
    #[must_use]
    pub fn request_url(&self) -> Url {
        self.full_request_url.clone()
    }

    /// Finds a header with the given name.
    /// If there are multiple headers with the same name,
    /// then only the first [`HeaderValue`](::http::HeaderValue) will be returned.
    ///
    /// `None` is returned when no header was found.
    #[must_use]
    pub fn maybe_header<N>(&self, header_name: N) -> Option<HeaderValue>
    where
        N: AsHeaderName,
    {
        self.headers.get(header_name).map(|h| h.to_owned())
    }

    /// Returns the headers returned from the response.
    #[must_use]
    pub fn headers<'a>(&'a self) -> &'a HeaderMap<HeaderValue> {
        &self.headers
    }

    /// Finds a header with the given name.
    /// If there are multiple headers with the same name,
    /// then only the first will be returned.
    ///
    /// If no header is found, then this will panic.
    #[must_use]
    pub fn header<N>(&self, header_name: N) -> HeaderValue
    where
        N: AsHeaderName + Display + Clone,
    {
        let debug_header = header_name.clone();
        self.headers
            .get(header_name)
            .map(|h| h.to_owned())
            .with_context(|| {
                format!(
                    "Cannot find header {} for response {}",
                    debug_header, self.user_requested_path
                )
            })
            .unwrap()
    }

    /// Iterates over all of the headers contained in the response.
    pub fn iter_headers<'a>(&'a self) -> impl Iterator<Item = (&'a HeaderName, &'a HeaderValue)> {
        self.headers.iter()
    }

    /// Iterates over all of the headers for a specific name, contained in the response.
    pub fn iter_headers_by_name<'a, N>(
        &'a self,
        header_name: N,
    ) -> impl Iterator<Item = &'a HeaderValue>
    where
        N: AsHeaderName,
    {
        self.headers.get_all(header_name).iter()
    }

    /// Finds a [`Cookie`] with the given name.
    /// If there are multiple matching cookies,
    /// then only the first will be returned.
    ///
    /// `None` is returned if no Cookie is found.
    #[must_use]
    pub fn maybe_cookie(&self, cookie_name: &str) -> Option<Cookie<'static>> {
        for cookie in self.iter_cookies() {
            if cookie.name() == cookie_name {
                return Some(cookie.into_owned());
            }
        }

        None
    }

    /// Finds a [`Cookie`](::cookie::Cookie) with the given name.
    /// If there are multiple matching cookies,
    /// then only the first will be returned.
    ///
    /// If no `Cookie` is found, then this will panic.
    #[must_use]
    pub fn cookie(&self, cookie_name: &str) -> Cookie<'static> {
        self.maybe_cookie(cookie_name)
            .with_context(|| {
                format!(
                    "Cannot find cookie {} for response {}",
                    cookie_name, self.user_requested_path
                )
            })
            .unwrap()
    }

    /// Returns all of the cookies contained in the response,
    /// within a [`CookieJar`](::cookie::CookieJar) object.
    ///
    /// See the `cookie` crate for details.
    #[must_use]
    pub fn cookies(&self) -> CookieJar {
        let mut cookies = CookieJar::new();

        for cookie in self.iter_cookies() {
            cookies.add(cookie.into_owned());
        }

        cookies
    }

    /// Iterate over all of the cookies in the response.
    #[must_use]
    pub fn iter_cookies<'a>(&'a self) -> impl Iterator<Item = Cookie<'a>> {
        self.iter_headers_by_name(SET_COOKIE).map(|header| {
            let header_str = header
                .to_str()
                .with_context(|| {
                    format!(
                        "Reading header 'Set-Cookie' as string for response {}",
                        self.user_requested_path
                    )
                })
                .unwrap();

            Cookie::parse(header_str)
                .with_context(|| {
                    format!(
                        "Parsing 'Set-Cookie' header for response {}",
                        self.user_requested_path
                    )
                })
                .unwrap()
        })
    }

    /// This performs an assertion comparing the whole body of the response,
    /// against the text provided.
    #[track_caller]
    pub fn assert_text<C>(&self, other: C)
    where
        C: AsRef<str>,
    {
        let other_contents = other.as_ref();
        assert_eq!(&self.text(), other_contents);
    }

    /// Deserializes the contents of the request as JSON,
    /// and asserts it matches the value given.
    ///
    /// If `other` does not match, or the response is not JSON,
    /// then this will panic.
    #[track_caller]
    pub fn assert_json<T>(&self, other: &T)
    where
        T: DeserializeOwned + PartialEq<T> + Debug,
    {
        let own_json: T = self.json();
        assert_eq!(own_json, *other);
    }

    /// Deserializes the contents of the request as an url encoded form,
    /// and asserts it matches the value given.
    ///
    /// If `other` does not match, or the response cannot be deserialized,
    /// then this will panic.
    #[track_caller]
    pub fn assert_form<T>(&self, other: &T)
    where
        T: DeserializeOwned + PartialEq<T> + Debug,
    {
        let own_json: T = self.form();
        assert_eq!(own_json, *other);
    }

    /// This will panic if the status code is **within** the 2xx range.
    /// i.e. The range from 200-299.
    #[track_caller]
    pub fn assert_status_success(&self) {
        let status_code = self.status_code.as_u16();
        assert!(
            200 <= status_code && status_code <= 299,
            "Expect status code _within_ 2xx range, got {}",
            status_code
        );
    }

    /// This will panic if the status code is **outside** the 2xx range.
    /// i.e. A status code less than 200, or 300 or more.
    #[track_caller]
    pub fn assert_status_failure(&self) {
        let status_code = self.status_code.as_u16();
        assert!(
            status_code < 200 || 299 < status_code,
            "Expect status code _outside_ 2xx range, got {}",
            status_code
        );
    }

    /// Assert the response status code is 400.
    #[track_caller]
    pub fn assert_status_bad_request(&self) {
        self.assert_status(StatusCode::BAD_REQUEST)
    }

    /// Assert the response status code is 404.
    #[track_caller]
    pub fn assert_status_not_found(&self) {
        self.assert_status(StatusCode::NOT_FOUND)
    }

    /// Assert the response status code is 401.
    #[track_caller]
    pub fn assert_status_unauthorized(&self) {
        self.assert_status(StatusCode::UNAUTHORIZED)
    }

    /// Assert the response status code is 403.
    #[track_caller]
    pub fn assert_status_forbidden(&self) {
        self.assert_status(StatusCode::FORBIDDEN)
    }

    /// Assert the response status code is 200.
    #[track_caller]
    pub fn assert_status_ok(&self) {
        self.assert_status(StatusCode::OK)
    }

    /// Assert the response status code is **not** 200.
    #[track_caller]
    pub fn assert_status_not_ok(&self) {
        self.assert_not_status(StatusCode::OK)
    }

    /// Assert the response status code matches the one given.
    #[track_caller]
    pub fn assert_status(&self, status_code: StatusCode) {
        assert_eq!(self.status_code(), status_code);
    }

    /// Assert the response status code does **not** match the one given.
    #[track_caller]
    pub fn assert_not_status(&self, status_code: StatusCode) {
        assert_ne!(self.status_code(), status_code);
    }
}

impl From<TestResponse> for Bytes {
    fn from(response: TestResponse) -> Self {
        response.into_bytes()
    }
}

#[cfg(test)]
mod test_assert_success {
    use crate::TestServer;
    use ::axum::routing::get;
    use ::axum::routing::Router;
    use ::http::StatusCode;

    pub async fn route_get_pass() -> StatusCode {
        StatusCode::OK
    }

    pub async fn route_get_fail() -> StatusCode {
        StatusCode::SERVICE_UNAVAILABLE
    }

    #[tokio::test]
    async fn it_should_pass_when_200() {
        let router: Router = Router::new()
            .route(&"/pass", get(route_get_pass))
            .route(&"/fail", get(route_get_fail));

        let server = TestServer::new(router).unwrap();

        let response = server.get(&"/pass").await;

        response.assert_status_success()
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_panic_when_not_200() {
        let router: Router = Router::new()
            .route(&"/pass", get(route_get_pass))
            .route(&"/fail", get(route_get_fail));

        let server = TestServer::new(router).unwrap();

        let response = server.get(&"/fail").expect_failure().await;

        response.assert_status_success()
    }
}

#[cfg(test)]
mod test_assert_failure {
    use crate::TestServer;
    use ::axum::routing::get;
    use ::axum::routing::Router;
    use ::http::StatusCode;

    pub async fn route_get_pass() -> StatusCode {
        StatusCode::OK
    }

    pub async fn route_get_fail() -> StatusCode {
        StatusCode::SERVICE_UNAVAILABLE
    }

    #[tokio::test]
    async fn it_should_pass_when_not_200() {
        let router: Router = Router::new()
            .route(&"/pass", get(route_get_pass))
            .route(&"/fail", get(route_get_fail));

        let server = TestServer::new(router).unwrap();

        let response = server.get(&"/fail").expect_failure().await;

        response.assert_status_failure()
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_panic_when_200() {
        let router: Router = Router::new()
            .route(&"/pass", get(route_get_pass))
            .route(&"/fail", get(route_get_fail));

        let server = TestServer::new(router).unwrap();

        let response = server.get(&"/pass").await;

        response.assert_status_failure()
    }
}

#[cfg(test)]
mod test_into_bytes {
    use crate::TestServer;
    use ::axum::routing::get;
    use ::axum::routing::Router;
    use ::axum::Json;
    use ::serde_json::json;
    use ::serde_json::Value;

    async fn route_get_json() -> Json<Value> {
        Json(json!({
            "message": "it works?"
        }))
    }

    #[tokio::test]
    async fn it_should_deserialize_into_json() {
        let app = Router::new().route(&"/json", get(route_get_json));

        let server = TestServer::new(app).unwrap();

        let bytes = server.get(&"/json").await.into_bytes();
        let text = String::from_utf8_lossy(&bytes);

        assert_eq!(text, r#"{"message":"it works?"}"#);
    }
}

#[cfg(test)]
mod test_json {
    use crate::TestServer;
    use ::axum::routing::get;
    use ::axum::routing::Router;
    use ::axum::Json;
    use ::serde::Deserialize;
    use ::serde::Serialize;

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct ExampleResponse {
        name: String,
        age: u32,
    }

    async fn route_get_json() -> Json<ExampleResponse> {
        Json(ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        })
    }

    #[tokio::test]
    async fn it_should_deserialize_into_json() {
        let app = Router::new().route(&"/json", get(route_get_json));

        let server = TestServer::new(app).unwrap();

        let response = server.get(&"/json").await.json::<ExampleResponse>();

        assert_eq!(
            response,
            ExampleResponse {
                name: "Joe".to_string(),
                age: 20,
            }
        );
    }
}

#[cfg(test)]
mod test_form {
    use crate::TestServer;
    use ::axum::routing::get;
    use ::axum::routing::Router;
    use ::axum::Form;
    use ::serde::Deserialize;
    use ::serde::Serialize;

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct ExampleResponse {
        name: String,
        age: u32,
    }

    async fn route_get_form() -> Form<ExampleResponse> {
        Form(ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        })
    }

    #[tokio::test]
    async fn it_should_deserialize_into_form() {
        let app = Router::new().route(&"/form", get(route_get_form));

        let server = TestServer::new(app).unwrap();

        let response = server.get(&"/form").await.form::<ExampleResponse>();

        assert_eq!(
            response,
            ExampleResponse {
                name: "Joe".to_string(),
                age: 20,
            }
        );
    }
}

#[cfg(test)]
mod test_assert_json {
    use crate::TestServer;

    use ::axum::routing::get;
    use ::axum::routing::Router;
    use ::axum::Form;
    use ::axum::Json;
    use ::serde::Deserialize;
    use ::serde::Serialize;

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct ExampleResponse {
        name: String,
        age: u32,
    }

    async fn route_get_form() -> Form<ExampleResponse> {
        Form(ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        })
    }

    async fn route_get_json() -> Json<ExampleResponse> {
        Json(ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        })
    }

    #[tokio::test]
    async fn it_should_match_json_returned() {
        let app = Router::new().route(&"/json", get(route_get_json));

        let server = TestServer::new(app).unwrap();

        server.get(&"/json").await.assert_json(&ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        });
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_panic_if_response_is_different() {
        let app = Router::new().route(&"/json", get(route_get_json));

        let server = TestServer::new(app).unwrap();

        server.get(&"/json").await.assert_json(&ExampleResponse {
            name: "Julia".to_string(),
            age: 25,
        });
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_panic_if_response_is_form() {
        let app = Router::new().route(&"/form", get(route_get_form));

        let server = TestServer::new(app).unwrap();

        server.get(&"/form").await.assert_json(&ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        });
    }
}

#[cfg(test)]
mod test_assert_form {
    use crate::TestServer;

    use ::axum::routing::get;
    use ::axum::routing::Router;
    use ::axum::Form;
    use ::axum::Json;
    use ::serde::Deserialize;
    use ::serde::Serialize;

    #[derive(Serialize, Deserialize, PartialEq, Debug)]
    struct ExampleResponse {
        name: String,
        age: u32,
    }

    async fn route_get_form() -> Form<ExampleResponse> {
        Form(ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        })
    }

    async fn route_get_json() -> Json<ExampleResponse> {
        Json(ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        })
    }

    #[tokio::test]
    async fn it_should_match_form_returned() {
        let app = Router::new().route(&"/form", get(route_get_form));

        let server = TestServer::new(app).unwrap();

        server.get(&"/form").await.assert_form(&ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        });
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_panic_if_response_is_different() {
        let app = Router::new().route(&"/form", get(route_get_form));

        let server = TestServer::new(app).unwrap();

        server.get(&"/form").await.assert_form(&ExampleResponse {
            name: "Julia".to_string(),
            age: 25,
        });
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_panic_if_response_is_json() {
        let app = Router::new().route(&"/json", get(route_get_json));

        let server = TestServer::new(app).unwrap();

        server.get(&"/json").await.assert_form(&ExampleResponse {
            name: "Joe".to_string(),
            age: 20,
        });
    }
}

#[cfg(test)]
mod test_text {
    use crate::TestServer;
    use ::axum::routing::get;
    use ::axum::routing::Router;

    #[tokio::test]
    async fn it_should_deserialize_into_text() {
        async fn route_get_text() -> String {
            "hello!".to_string()
        }

        let app = Router::new().route(&"/text", get(route_get_text));

        let server = TestServer::new(app).unwrap();

        let response = server.get(&"/text").await.text();

        assert_eq!(response, "hello!");
    }
}