use futures_util::{SinkExt, StreamExt}; use hyper::StatusCode; use regex::Regex; use tokio_tungstenite::{connect_async, tungstenite::Message}; type Test = Result<(), Box>; #[tokio::test] async fn hello_endpoint() -> Test { let resp = reqwest::get("http://localhost:8080/hello").await?; assert_eq!(resp.status(), StatusCode::OK); assert_eq!(resp.text().await?, "Hello World!"); Ok(()) } #[tokio::test] async fn websocket_connect() -> Test { let connected = Regex::new(r"^(\d+) joined$").unwrap(); let msg = Regex::new(r"^(\d+): (.*)$").unwrap(); let (mut socket, response) = connect_async("ws://localhost:8080/socket").await?; assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS); { let resp = socket.next().await.unwrap().unwrap(); let resp = resp.to_text()?; assert_eq!(resp, "Started a connection!"); } let id = { let resp = socket.next().await.unwrap().unwrap(); let resp = resp.to_text()?; let res = connected.captures(resp).unwrap(); res.get(1).unwrap().as_str().to_string() }; socket.send(Message::Text("hi!".to_string())).await?; socket.flush().await?; { let resp = socket.next().await.unwrap().unwrap(); let resp = resp.to_text()?; let res = msg.captures(resp).expect(resp); let new_id = res.get(1).unwrap().as_str(); let new_msg = res.get(2).unwrap().as_str(); assert_eq!(new_id, id); assert_eq!(new_msg, "hi!"); } socket.close(None).await?; { let resp = socket.next().await.unwrap().unwrap(); assert_eq!(resp, Message::Close(None)); } assert!(socket.next().await.is_none()); Ok(()) }