7
7
use axum:: {
8
8
extract:: { FromRequestParts , Path } ,
9
9
http:: { request:: Parts , StatusCode } ,
10
- response:: { IntoResponse , Response } ,
10
+ response:: { Html , IntoResponse , Response } ,
11
11
routing:: get,
12
12
RequestPartsExt , Router ,
13
13
} ;
@@ -25,7 +25,7 @@ async fn main() {
25
25
. init ( ) ;
26
26
27
27
// build our application with some routes
28
- let app = Router :: new ( ) . route ( "/{version}/foo" , get ( handler ) ) ;
28
+ let app = app ( ) ;
29
29
30
30
// run it
31
31
let listener = tokio:: net:: TcpListener :: bind ( "127.0.0.1:3000" )
@@ -35,8 +35,12 @@ async fn main() {
35
35
axum:: serve ( listener, app) . await . unwrap ( ) ;
36
36
}
37
37
38
- async fn handler ( version : Version ) {
39
- println ! ( "received request with version {version:?}" ) ;
38
+ fn app ( ) -> Router {
39
+ Router :: new ( ) . route ( "/{version}/foo" , get ( handler) )
40
+ }
41
+
42
+ async fn handler ( version : Version ) -> Html < String > {
43
+ Html ( format ! ( "received request with version {version:?}" ) )
40
44
}
41
45
42
46
#[ derive( Debug ) ]
68
72
}
69
73
}
70
74
}
75
+
76
+ #[ cfg( test) ]
77
+ mod tests {
78
+ use super :: * ;
79
+ use axum:: { body:: Body , http:: Request , http:: StatusCode } ;
80
+ use http_body_util:: BodyExt ;
81
+ use tower:: ServiceExt ;
82
+
83
+ #[ tokio:: test]
84
+ async fn test_v1 ( ) {
85
+ let response = app ( )
86
+ . oneshot (
87
+ Request :: builder ( )
88
+ . uri ( "/v1/foo" )
89
+ . body ( Body :: empty ( ) )
90
+ . unwrap ( ) ,
91
+ )
92
+ . await
93
+ . unwrap ( ) ;
94
+
95
+ assert_eq ! ( response. status( ) , StatusCode :: OK ) ;
96
+ let body = response. into_body ( ) ;
97
+ let bytes = body. collect ( ) . await . unwrap ( ) . to_bytes ( ) ;
98
+ let html = String :: from_utf8 ( bytes. to_vec ( ) ) . unwrap ( ) ;
99
+
100
+ assert_eq ! ( html, "received request with version V1" ) ;
101
+ }
102
+
103
+ #[ tokio:: test]
104
+ async fn test_v4 ( ) {
105
+ let response = app ( )
106
+ . oneshot (
107
+ Request :: builder ( )
108
+ . uri ( "/v4/foo" )
109
+ . body ( Body :: empty ( ) )
110
+ . unwrap ( ) ,
111
+ )
112
+ . await
113
+ . unwrap ( ) ;
114
+
115
+ assert_eq ! ( response. status( ) , StatusCode :: NOT_FOUND ) ;
116
+ let body = response. into_body ( ) ;
117
+ let bytes = body. collect ( ) . await . unwrap ( ) . to_bytes ( ) ;
118
+ let html = String :: from_utf8 ( bytes. to_vec ( ) ) . unwrap ( ) ;
119
+
120
+ assert_eq ! ( html, "unknown version" ) ;
121
+ }
122
+ }
0 commit comments