@@ -30,3 +30,72 @@ pub async fn handle(ws: WebSocketUpgrade, State(state): State<UpgradeState>) ->
3030 }
3131 } )
3232}
33+
34+ #[ cfg( test) ]
35+ mod tests {
36+ use super :: * ;
37+ use futures_util:: SinkExt ;
38+ use std:: time:: Duration ;
39+ use tokio:: net:: TcpListener ;
40+ use tokio_tungstenite:: connect_async;
41+ use tokio_tungstenite:: tungstenite:: Message ;
42+
43+ #[ tokio:: test]
44+ async fn handle_sends_connection_request_through_channel ( ) {
45+ let ( shutdown_tx, _shutdown_rx) = watch:: channel ( false ) ;
46+ let ( conn_tx, mut conn_rx) = mpsc:: unbounded_channel :: < ConnectionRequest > ( ) ;
47+
48+ let state = UpgradeState {
49+ conn_tx,
50+ shutdown_tx : shutdown_tx. clone ( ) ,
51+ } ;
52+
53+ let app = axum:: Router :: new ( )
54+ . route ( "/ws" , axum:: routing:: get ( handle) )
55+ . with_state ( state) ;
56+
57+ let listener = TcpListener :: bind ( "127.0.0.1:0" ) . await . unwrap ( ) ;
58+ let addr = listener. local_addr ( ) . unwrap ( ) ;
59+ tokio:: spawn ( async move {
60+ axum:: serve ( listener, app) . await . unwrap ( ) ;
61+ } ) ;
62+
63+ let url = format ! ( "ws://{}/ws" , addr) ;
64+ let ( _ws, _) = connect_async ( & url) . await . unwrap ( ) ;
65+
66+ let req = tokio:: time:: timeout ( Duration :: from_secs ( 2 ) , conn_rx. recv ( ) )
67+ . await
68+ . expect ( "timeout waiting for ConnectionRequest" )
69+ . expect ( "channel closed" ) ;
70+
71+ assert ! ( !* req. shutdown_rx. borrow( ) ) ;
72+ }
73+
74+ #[ tokio:: test]
75+ async fn handle_logs_error_when_conn_rx_dropped ( ) {
76+ let ( shutdown_tx, _shutdown_rx) = watch:: channel ( false ) ;
77+ let ( conn_tx, conn_rx) = mpsc:: unbounded_channel :: < ConnectionRequest > ( ) ;
78+
79+ let state = UpgradeState {
80+ conn_tx,
81+ shutdown_tx : shutdown_tx. clone ( ) ,
82+ } ;
83+
84+ let app = axum:: Router :: new ( )
85+ . route ( "/ws" , axum:: routing:: get ( handle) )
86+ . with_state ( state) ;
87+
88+ let listener = TcpListener :: bind ( "127.0.0.1:0" ) . await . unwrap ( ) ;
89+ let addr = listener. local_addr ( ) . unwrap ( ) ;
90+ tokio:: spawn ( async move {
91+ axum:: serve ( listener, app) . await . unwrap ( ) ;
92+ } ) ;
93+
94+ drop ( conn_rx) ;
95+
96+ let url = format ! ( "ws://{}/ws" , addr) ;
97+ let ( _ws, _) = connect_async ( & url) . await . unwrap ( ) ;
98+
99+ tokio:: time:: sleep ( Duration :: from_millis ( 100 ) ) . await ;
100+ }
101+ }
0 commit comments