-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
Copy pathmod.rs
1092 lines (878 loc) · 31.4 KB
/
mod.rs
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
use crate::{
body::{Body, Bytes},
error_handling::HandleErrorLayer,
extract::{self, DefaultBodyLimit, FromRef, Path, State},
handler::{Handler, HandlerWithoutStateExt},
response::{IntoResponse, Response},
routing::{
delete, get, get_service, on, on_service, patch, patch_service,
path_router::path_for_nested_route, post, MethodFilter,
},
test_helpers::{
tracing_helpers::{capture_tracing, TracingEvent},
*,
},
BoxError, Extension, Json, Router,
};
use axum_core::extract::Request;
use futures_util::stream::StreamExt;
use http::{
header::CONTENT_LENGTH,
header::{ALLOW, HOST},
HeaderMap, Method, StatusCode, Uri,
};
use serde::Deserialize;
use serde_json::json;
use std::{
convert::Infallible,
future::{ready, Ready},
sync::atomic::{AtomicBool, AtomicUsize, Ordering},
task::{Context, Poll},
time::Duration,
};
use tower::{service_fn, util::MapResponseLayer, ServiceExt};
use tower_http::{
limit::RequestBodyLimitLayer, timeout::TimeoutLayer,
validate_request::ValidateRequestHeaderLayer,
};
use tower_service::Service;
mod fallback;
mod get_to_head;
mod handle_error;
mod merge;
mod nest;
#[crate::test]
async fn hello_world() {
async fn root(_: Request) -> &'static str {
"Hello, World!"
}
async fn foo(_: Request) -> &'static str {
"foo"
}
async fn users_create(_: Request) -> &'static str {
"users#create"
}
let app = Router::new()
.route("/", get(root).post(foo))
.route("/users", post(users_create));
let client = TestClient::new(app);
let res = client.get("/").send().await;
let body = res.text().await;
assert_eq!(body, "Hello, World!");
let res = client.post("/").send().await;
let body = res.text().await;
assert_eq!(body, "foo");
let res = client.post("/users").send().await;
let body = res.text().await;
assert_eq!(body, "users#create");
}
#[crate::test]
async fn routing() {
let app = Router::new()
.route(
"/users",
get(|_: Request| async { "users#index" }).post(|_: Request| async { "users#create" }),
)
.route("/users/:id", get(|_: Request| async { "users#show" }))
.route(
"/users/:id/action",
get(|_: Request| async { "users#action" }),
);
let client = TestClient::new(app);
let res = client.get("/").send().await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
let res = client.get("/users").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "users#index");
let res = client.post("/users").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "users#create");
let res = client.get("/users/1").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "users#show");
let res = client.get("/users/1/action").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "users#action");
}
#[crate::test]
async fn router_type_doesnt_change() {
let app: Router = Router::new()
.route(
"/",
on(MethodFilter::GET, |_: Request| async { "hi from GET" })
.on(MethodFilter::POST, |_: Request| async { "hi from POST" }),
)
.layer(tower_http::compression::CompressionLayer::new());
let client = TestClient::new(app);
let res = client.get("/").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "hi from GET");
let res = client.post("/").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "hi from POST");
}
#[crate::test]
async fn routing_between_services() {
use std::convert::Infallible;
use tower::service_fn;
async fn handle(_: Request) -> &'static str {
"handler"
}
let app = Router::new()
.route(
"/one",
get_service(service_fn(|_: Request| async {
Ok::<_, Infallible>(Response::new(Body::from("one get")))
}))
.post_service(service_fn(|_: Request| async {
Ok::<_, Infallible>(Response::new(Body::from("one post")))
}))
.on_service(
MethodFilter::PUT,
service_fn(|_: Request| async {
Ok::<_, Infallible>(Response::new(Body::from("one put")))
}),
),
)
.route("/two", on_service(MethodFilter::GET, handle.into_service()));
let client = TestClient::new(app);
let res = client.get("/one").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "one get");
let res = client.post("/one").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "one post");
let res = client.put("/one").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "one put");
let res = client.get("/two").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "handler");
}
#[crate::test]
async fn middleware_on_single_route() {
use tower_http::{compression::CompressionLayer, trace::TraceLayer};
async fn handle(_: Request) -> &'static str {
"Hello, World!"
}
let app = Router::new().route(
"/",
get(handle.layer((TraceLayer::new_for_http(), CompressionLayer::new()))),
);
let client = TestClient::new(app);
let res = client.get("/").send().await;
let body = res.text().await;
assert_eq!(body, "Hello, World!");
}
#[crate::test]
async fn service_in_bottom() {
async fn handler(_req: Request) -> Result<Response<Body>, Infallible> {
Ok(Response::new(Body::empty()))
}
let app = Router::new().route("/", get_service(service_fn(handler)));
TestClient::new(app);
}
#[crate::test]
async fn wrong_method_handler() {
let app = Router::new()
.route("/", get(|| async {}).post(|| async {}))
.route("/foo", patch(|| async {}));
let client = TestClient::new(app);
let res = client.patch("/").send().await;
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(res.headers()[ALLOW], "GET,HEAD,POST");
let res = client.patch("/foo").send().await;
assert_eq!(res.status(), StatusCode::OK);
let res = client.post("/foo").send().await;
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(res.headers()[ALLOW], "PATCH");
let res = client.get("/bar").send().await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
#[crate::test]
async fn wrong_method_service() {
#[derive(Clone)]
struct Svc;
impl<R> Service<R> for Svc {
type Response = Response;
type Error = Infallible;
type Future = Ready<Result<Self::Response, Self::Error>>;
fn poll_ready(&mut self, _cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
Poll::Ready(Ok(()))
}
fn call(&mut self, _req: R) -> Self::Future {
ready(Ok(().into_response()))
}
}
let app = Router::new()
.route("/", get_service(Svc).post_service(Svc))
.route("/foo", patch_service(Svc));
let client = TestClient::new(app);
let res = client.patch("/").send().await;
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(res.headers()[ALLOW], "GET,HEAD,POST");
let res = client.patch("/foo").send().await;
assert_eq!(res.status(), StatusCode::OK);
let res = client.post("/foo").send().await;
assert_eq!(res.status(), StatusCode::METHOD_NOT_ALLOWED);
assert_eq!(res.headers()[ALLOW], "PATCH");
let res = client.get("/bar").send().await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
#[crate::test]
async fn multiple_methods_for_one_handler() {
async fn root(_: Request) -> &'static str {
"Hello, World!"
}
let app = Router::new().route("/", on(MethodFilter::GET.or(MethodFilter::POST), root));
let client = TestClient::new(app);
let res = client.get("/").send().await;
assert_eq!(res.status(), StatusCode::OK);
let res = client.post("/").send().await;
assert_eq!(res.status(), StatusCode::OK);
}
#[crate::test]
async fn wildcard_sees_whole_url() {
let app = Router::new().route("/api/*rest", get(|uri: Uri| async move { uri.to_string() }));
let client = TestClient::new(app);
let res = client.get("/api/foo/bar").send().await;
assert_eq!(res.text().await, "/api/foo/bar");
}
#[crate::test]
async fn middleware_applies_to_routes_above() {
let app = Router::new()
.route("/one", get(std::future::pending::<()>))
.layer(TimeoutLayer::new(Duration::ZERO))
.route("/two", get(|| async {}));
let client = TestClient::new(app);
let res = client.get("/one").send().await;
assert_eq!(res.status(), StatusCode::REQUEST_TIMEOUT);
let res = client.get("/two").send().await;
assert_eq!(res.status(), StatusCode::OK);
}
#[crate::test]
async fn not_found_for_extra_trailing_slash() {
let app = Router::new().route("/foo", get(|| async {}));
let client = TestClient::new(app);
let res = client.get("/foo/").send().await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
let res = client.get("/foo").send().await;
assert_eq!(res.status(), StatusCode::OK);
}
#[crate::test]
async fn not_found_for_missing_trailing_slash() {
let app = Router::new().route("/foo/", get(|| async {}));
let client = TestClient::new(app);
let res = client.get("/foo").send().await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
}
#[crate::test]
async fn with_and_without_trailing_slash() {
let app = Router::new()
.route("/foo", get(|| async { "without tsr" }))
.route("/foo/", get(|| async { "with tsr" }));
let client = TestClient::new(app);
let res = client.get("/foo/").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "with tsr");
let res = client.get("/foo").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "without tsr");
}
// for https://github.com/tokio-rs/axum/issues/420
#[crate::test]
async fn wildcard_doesnt_match_just_trailing_slash() {
let app = Router::new().route(
"/x/*path",
get(|Path(path): Path<String>| async move { path }),
);
let client = TestClient::new(app);
let res = client.get("/x").send().await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
let res = client.get("/x/").send().await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
let res = client.get("/x/foo/bar").send().await;
assert_eq!(res.status(), StatusCode::OK);
assert_eq!(res.text().await, "foo/bar");
}
#[crate::test]
async fn what_matches_wildcard() {
let app = Router::new()
.route("/*key", get(|| async { "root" }))
.route("/x/*key", get(|| async { "x" }))
.fallback(|| async { "fallback" });
let client = TestClient::new(app);
let get = |path| {
let f = client.get(path).send();
async move { f.await.text().await }
};
assert_eq!(get("/").await, "fallback");
assert_eq!(get("/a").await, "root");
assert_eq!(get("/a/").await, "root");
assert_eq!(get("/a/b").await, "root");
assert_eq!(get("/a/b/").await, "root");
assert_eq!(get("/x").await, "root");
assert_eq!(get("/x/").await, "root");
assert_eq!(get("/x/a").await, "x");
assert_eq!(get("/x/a/").await, "x");
assert_eq!(get("/x/a/b").await, "x");
assert_eq!(get("/x/a/b/").await, "x");
}
#[crate::test]
async fn static_and_dynamic_paths() {
let app = Router::new()
.route(
"/:key",
get(|Path(key): Path<String>| async move { format!("dynamic: {key}") }),
)
.route("/foo", get(|| async { "static" }));
let client = TestClient::new(app);
let res = client.get("/bar").send().await;
assert_eq!(res.text().await, "dynamic: bar");
let res = client.get("/foo").send().await;
assert_eq!(res.text().await, "static");
}
#[crate::test]
#[should_panic(expected = "Paths must start with a `/`. Use \"/\" for root routes")]
async fn empty_route() {
let app = Router::new().route("", get(|| async {}));
TestClient::new(app);
}
#[crate::test]
async fn middleware_still_run_for_unmatched_requests() {
#[derive(Clone)]
struct CountMiddleware<S>(S);
static COUNT: AtomicUsize = AtomicUsize::new(0);
impl<R, S> Service<R> for CountMiddleware<S>
where
S: Service<R>,
{
type Response = S::Response;
type Error = S::Error;
type Future = S::Future;
fn poll_ready(&mut self, cx: &mut Context<'_>) -> Poll<Result<(), Self::Error>> {
self.0.poll_ready(cx)
}
fn call(&mut self, req: R) -> Self::Future {
COUNT.fetch_add(1, Ordering::SeqCst);
self.0.call(req)
}
}
let app = Router::new()
.route("/", get(|| async {}))
.layer(tower::layer::layer_fn(CountMiddleware));
let client = TestClient::new(app);
assert_eq!(COUNT.load(Ordering::SeqCst), 0);
client.get("/").send().await;
assert_eq!(COUNT.load(Ordering::SeqCst), 1);
client.get("/not-found").send().await;
assert_eq!(COUNT.load(Ordering::SeqCst), 2);
}
#[crate::test]
#[should_panic(expected = "\
Invalid route: `Router::route_service` cannot be used with `Router`s. \
Use `Router::nest` instead\
")]
async fn routing_to_router_panics() {
TestClient::new(Router::new().route_service("/", Router::new()));
}
#[crate::test]
async fn route_layer() {
let app = Router::new()
.route("/foo", get(|| async {}))
.route_layer(ValidateRequestHeaderLayer::bearer("password"));
let client = TestClient::new(app);
let res = client
.get("/foo")
.header("authorization", "Bearer password")
.send()
.await;
assert_eq!(res.status(), StatusCode::OK);
let res = client.get("/foo").send().await;
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
let res = client.get("/not-found").send().await;
assert_eq!(res.status(), StatusCode::NOT_FOUND);
// it would be nice if this would return `405 Method Not Allowed`
// but that requires knowing more about which method route we're calling, which we
// don't know currently since its just a generic `Service`
let res = client.post("/foo").send().await;
assert_eq!(res.status(), StatusCode::UNAUTHORIZED);
}
#[crate::test]
async fn different_methods_added_in_different_routes() {
let app = Router::new()
.route("/", get(|| async { "GET" }))
.route("/", post(|| async { "POST" }));
let client = TestClient::new(app);
let res = client.get("/").send().await;
let body = res.text().await;
assert_eq!(body, "GET");
let res = client.post("/").send().await;
let body = res.text().await;
assert_eq!(body, "POST");
}
#[crate::test]
#[should_panic(expected = "Cannot merge two `Router`s that both have a fallback")]
async fn merging_routers_with_fallbacks_panics() {
async fn fallback() {}
let one = Router::new().fallback(fallback);
let two = Router::new().fallback(fallback);
TestClient::new(one.merge(two));
}
#[test]
#[should_panic(expected = "Overlapping method route. Handler for `GET /foo/bar` already exists")]
fn routes_with_overlapping_method_routes() {
async fn handler() {}
let _: Router = Router::new()
.route("/foo/bar", get(handler))
.route("/foo/bar", get(handler));
}
#[test]
#[should_panic(expected = "Overlapping method route. Handler for `GET /foo/bar` already exists")]
fn merging_with_overlapping_method_routes() {
async fn handler() {}
let app: Router = Router::new().route("/foo/bar", get(handler));
_ = app.clone().merge(app);
}
#[crate::test]
async fn merging_routers_with_same_paths_but_different_methods() {
let one = Router::new().route("/", get(|| async { "GET" }));
let two = Router::new().route("/", post(|| async { "POST" }));
let client = TestClient::new(one.merge(two));
let res = client.get("/").send().await;
let body = res.text().await;
assert_eq!(body, "GET");
let res = client.post("/").send().await;
let body = res.text().await;
assert_eq!(body, "POST");
}
#[crate::test]
async fn head_content_length_through_hyper_server() {
let app = Router::new()
.route("/", get(|| async { "foo" }))
.route("/json", get(|| async { Json(json!({ "foo": 1 })) }));
let client = TestClient::new(app);
let res = client.head("/").send().await;
assert_eq!(res.headers()["content-length"], "3");
assert!(res.text().await.is_empty());
let res = client.head("/json").send().await;
assert_eq!(res.headers()["content-length"], "9");
assert!(res.text().await.is_empty());
}
#[crate::test]
async fn head_content_length_through_hyper_server_that_hits_fallback() {
let app = Router::new().fallback(|| async { "foo" });
let client = TestClient::new(app);
let res = client.head("/").send().await;
assert_eq!(res.headers()["content-length"], "3");
}
#[crate::test]
async fn head_with_middleware_applied() {
use tower_http::compression::{predicate::SizeAbove, CompressionLayer};
let app = Router::new()
.nest(
"/",
Router::new().route("/", get(|| async { "Hello, World!" })),
)
.layer(CompressionLayer::new().compress_when(SizeAbove::new(0)));
let client = TestClient::new(app);
// send GET request
let res = client
.get("/")
.header("accept-encoding", "gzip")
.send()
.await;
assert_eq!(res.headers()["transfer-encoding"], "chunked");
// cannot have `transfer-encoding: chunked` and `content-length`
assert!(!res.headers().contains_key("content-length"));
// send HEAD request
let res = client
.head("/")
.header("accept-encoding", "gzip")
.send()
.await;
// no response body so no `transfer-encoding`
assert!(!res.headers().contains_key("transfer-encoding"));
// no content-length since we cannot know it since the response
// is compressed
assert!(!res.headers().contains_key("content-length"));
}
#[crate::test]
#[should_panic(expected = "Paths must start with a `/`")]
async fn routes_must_start_with_slash() {
let app = Router::new().route(":foo", get(|| async {}));
TestClient::new(app);
}
#[crate::test]
async fn body_limited_by_default() {
let app = Router::new()
.route("/bytes", post(|_: Bytes| async {}))
.route("/string", post(|_: String| async {}))
.route("/json", post(|_: Json<serde_json::Value>| async {}));
let client = TestClient::new(app);
for uri in ["/bytes", "/string", "/json"] {
println!("calling {uri}");
let stream = futures_util::stream::repeat("a".repeat(1000)).map(Ok::<_, hyper::Error>);
let body = reqwest::Body::wrap_stream(stream);
let res_future = client
.post(uri)
.header("content-type", "application/json")
.body(body)
.send();
let res = tokio::time::timeout(Duration::from_secs(3), res_future)
.await
.expect("never got response");
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
}
#[crate::test]
async fn disabling_the_default_limit() {
let app = Router::new()
.route("/", post(|_: Bytes| async {}))
.layer(DefaultBodyLimit::disable());
let client = TestClient::new(app);
// `DEFAULT_LIMIT` is 2mb so make a body larger than that
let body = reqwest::Body::from("a".repeat(3_000_000));
let res = client.post("/").body(body).send().await;
assert_eq!(res.status(), StatusCode::OK);
}
#[crate::test]
async fn limited_body_with_content_length() {
const LIMIT: usize = 3;
let app = Router::new()
.route(
"/",
post(|headers: HeaderMap, _body: Bytes| async move {
assert!(headers.get(CONTENT_LENGTH).is_some());
}),
)
.layer(RequestBodyLimitLayer::new(LIMIT));
let client = TestClient::new(app);
let res = client.post("/").body("a".repeat(LIMIT)).send().await;
assert_eq!(res.status(), StatusCode::OK);
let res = client.post("/").body("a".repeat(LIMIT * 2)).send().await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
#[crate::test]
async fn changing_the_default_limit() {
let new_limit = 2;
let app = Router::new()
.route("/", post(|_: Bytes| async {}))
.layer(DefaultBodyLimit::max(new_limit));
let client = TestClient::new(app);
let res = client
.post("/")
.body(reqwest::Body::from("a".repeat(new_limit)))
.send()
.await;
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post("/")
.body(reqwest::Body::from("a".repeat(new_limit + 1)))
.send()
.await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
#[crate::test]
async fn changing_the_default_limit_differently_on_different_routes() {
let limit1 = 2;
let limit2 = 10;
let app = Router::new()
.route(
"/limit1",
post(|_: Bytes| async {}).layer(DefaultBodyLimit::max(limit1)),
)
.route(
"/limit2",
post(|_: Bytes| async {}).layer(DefaultBodyLimit::max(limit2)),
)
.route("/default", post(|_: Bytes| async {}));
let client = TestClient::new(app);
let res = client
.post("/limit1")
.body(reqwest::Body::from("a".repeat(limit1)))
.send()
.await;
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post("/limit1")
.body(reqwest::Body::from("a".repeat(limit2)))
.send()
.await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
let res = client
.post("/limit2")
.body(reqwest::Body::from("a".repeat(limit1)))
.send()
.await;
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post("/limit2")
.body(reqwest::Body::from("a".repeat(limit2)))
.send()
.await;
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post("/limit2")
.body(reqwest::Body::from("a".repeat(limit1 + limit2)))
.send()
.await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
let res = client
.post("/default")
.body(reqwest::Body::from("a".repeat(limit1 + limit2)))
.send()
.await;
assert_eq!(res.status(), StatusCode::OK);
let res = client
.post("/default")
// `DEFAULT_LIMIT` is 2mb so make a body larger than that
.body(reqwest::Body::from("a".repeat(3_000_000)))
.send()
.await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
#[crate::test]
async fn limited_body_with_streaming_body() {
const LIMIT: usize = 3;
let app = Router::new()
.route(
"/",
post(|headers: HeaderMap, _body: Bytes| async move {
assert!(headers.get(CONTENT_LENGTH).is_none());
}),
)
.layer(RequestBodyLimitLayer::new(LIMIT));
let client = TestClient::new(app);
let stream = futures_util::stream::iter(vec![Ok::<_, hyper::Error>("a".repeat(LIMIT))]);
let res = client
.post("/")
.body(reqwest::Body::wrap_stream(stream))
.send()
.await;
assert_eq!(res.status(), StatusCode::OK);
let stream = futures_util::stream::iter(vec![Ok::<_, hyper::Error>("a".repeat(LIMIT * 2))]);
let res = client
.post("/")
.body(reqwest::Body::wrap_stream(stream))
.send()
.await;
assert_eq!(res.status(), StatusCode::PAYLOAD_TOO_LARGE);
}
#[crate::test]
async fn extract_state() {
#[derive(Clone)]
struct AppState {
value: i32,
inner: InnerState,
}
#[derive(Clone)]
struct InnerState {
value: i32,
}
impl FromRef<AppState> for InnerState {
fn from_ref(state: &AppState) -> Self {
state.inner.clone()
}
}
async fn handler(State(outer): State<AppState>, State(inner): State<InnerState>) {
assert_eq!(outer.value, 1);
assert_eq!(inner.value, 2);
}
let state = AppState {
value: 1,
inner: InnerState { value: 2 },
};
let app = Router::new().route("/", get(handler)).with_state(state);
let client = TestClient::new(app);
let res = client.get("/").send().await;
assert_eq!(res.status(), StatusCode::OK);
}
#[crate::test]
async fn explicitly_set_state() {
let app = Router::new()
.route_service(
"/",
get(|State(state): State<&'static str>| async move { state }).with_state("foo"),
)
.with_state("...");
let client = TestClient::new(app);
let res = client.get("/").send().await;
assert_eq!(res.text().await, "foo");
}
#[crate::test]
async fn layer_response_into_response() {
fn map_response<B>(_res: Response<B>) -> Result<Response<B>, impl IntoResponse> {
let headers = [("x-foo", "bar")];
let status = StatusCode::IM_A_TEAPOT;
Err((headers, status))
}
let app = Router::new()
.route("/", get(|| async {}))
.layer(MapResponseLayer::new(map_response));
let client = TestClient::new(app);
let res = client.get("/").send().await;
assert_eq!(res.headers()["x-foo"], "bar");
assert_eq!(res.status(), StatusCode::IM_A_TEAPOT);
}
#[allow(dead_code)]
fn method_router_fallback_with_state() {
async fn fallback(_: State<&'static str>) {}
async fn not_found(_: State<&'static str>) {}
let state = "foo";
let _: Router = Router::new()
.fallback(get(fallback).fallback(not_found))
.with_state(state);
}
#[test]
fn test_path_for_nested_route() {
assert_eq!(path_for_nested_route("/", "/"), "/");
assert_eq!(path_for_nested_route("/a", "/"), "/a");
assert_eq!(path_for_nested_route("/", "/b"), "/b");
assert_eq!(path_for_nested_route("/a/", "/"), "/a/");
assert_eq!(path_for_nested_route("/", "/b/"), "/b/");
assert_eq!(path_for_nested_route("/a", "/b"), "/a/b");
assert_eq!(path_for_nested_route("/a/", "/b"), "/a/b");
assert_eq!(path_for_nested_route("/a", "/b/"), "/a/b/");
assert_eq!(path_for_nested_route("/a/", "/b/"), "/a/b/");
}
#[crate::test]
async fn state_isnt_cloned_too_much() {
static SETUP_DONE: AtomicBool = AtomicBool::new(false);
static COUNT: AtomicUsize = AtomicUsize::new(0);
struct AppState;
impl Clone for AppState {
fn clone(&self) -> Self {
#[rustversion::since(1.65)]
#[track_caller]
fn count() {
if SETUP_DONE.load(Ordering::SeqCst) {
let bt = std::backtrace::Backtrace::force_capture();
let bt = bt
.to_string()
.lines()
.filter(|line| line.contains("axum") || line.contains("./src"))
.collect::<Vec<_>>()
.join("\n");
println!("AppState::Clone:\n===============\n{bt}\n");
COUNT.fetch_add(1, Ordering::SeqCst);
}
}
#[rustversion::not(since(1.65))]
fn count() {
if SETUP_DONE.load(Ordering::SeqCst) {
COUNT.fetch_add(1, Ordering::SeqCst);
}
}
count();
Self
}
}
let app = Router::new()
.route("/", get(|_: State<AppState>| async {}))
.with_state(AppState);
let client = TestClient::new(app);
// ignore clones made during setup
SETUP_DONE.store(true, Ordering::SeqCst);
client.get("/").send().await;
assert_eq!(COUNT.load(Ordering::SeqCst), 5);
}
#[crate::test]
async fn logging_rejections() {
#[derive(Deserialize, Eq, PartialEq, Debug)]
#[serde(deny_unknown_fields)]
struct RejectionEvent {
message: String,
status: u16,
body: String,
rejection_type: String,
}
let events = capture_tracing::<RejectionEvent, _, _>(|| async {
let app = Router::new()
.route("/extension", get(|_: Extension<Infallible>| async {}))
.route("/string", post(|_: String| async {}));
let client = TestClient::new(app);
assert_eq!(
client.get("/extension").send().await.status(),
StatusCode::INTERNAL_SERVER_ERROR