1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-22 17:41:11 +00:00
actix-web/awc/tests/test_ws.rs

69 lines
2.4 KiB
Rust
Raw Normal View History

2018-11-19 05:48:20 +00:00
use std::io;
2018-10-05 21:30:40 +00:00
2018-12-11 02:08:33 +00:00
use actix_codec::Framed;
2019-05-12 15:34:51 +00:00
use actix_http::{body::BodySize, h1, ws, Error, HttpService, Request, Response};
2019-12-12 17:08:38 +00:00
use actix_http_test::test_server;
2021-04-01 14:26:13 +00:00
use actix_utils::future::ok;
use bytes::Bytes;
2021-04-01 14:26:13 +00:00
use futures_util::{SinkExt as _, StreamExt as _};
2018-10-05 21:30:40 +00:00
2019-11-20 18:35:07 +00:00
async fn ws_service(req: ws::Frame) -> Result<ws::Message, io::Error> {
2018-10-05 21:30:40 +00:00
match req {
2019-11-20 18:35:07 +00:00
ws::Frame::Ping(msg) => Ok(ws::Message::Pong(msg)),
ws::Frame::Text(text) => Ok(ws::Message::Text(
String::from_utf8(Vec::from(text.as_ref())).unwrap().into(),
2018-10-10 20:20:00 +00:00
)),
ws::Frame::Binary(bin) => Ok(ws::Message::Binary(bin)),
2019-11-20 18:35:07 +00:00
ws::Frame::Close(reason) => Ok(ws::Message::Close(reason)),
_ => Ok(ws::Message::Close(None)),
2018-10-05 21:30:40 +00:00
}
}
2019-11-26 05:25:50 +00:00
#[actix_rt::test]
async fn test_simple() {
2019-12-12 17:08:38 +00:00
let mut srv = test_server(|| {
2019-11-26 05:25:50 +00:00
HttpService::build()
.upgrade(|(req, mut framed): (Request, Framed<_, _>)| {
async move {
let res = ws::handshake_response(req.head()).finish();
// send handshake response
framed
.send(h1::Message::Item((res.drop_body(), BodySize::None)))
.await?;
2019-11-20 18:35:07 +00:00
2021-02-12 00:27:20 +00:00
// start WebSocket service
let framed = framed.replace_codec(ws::Codec::new());
2019-12-11 13:20:20 +00:00
ws::Dispatcher::with(framed, ws_service).await
2019-11-26 05:25:50 +00:00
}
})
.finish(|_| ok::<_, Error>(Response::not_found()))
2019-12-02 11:33:11 +00:00
.tcp()
2020-03-08 07:42:45 +00:00
})
.await;
2018-10-05 21:30:40 +00:00
2019-11-26 05:25:50 +00:00
// client service
let mut framed = srv.ws().await.unwrap();
framed.send(ws::Message::Text("text".into())).await.unwrap();
2019-11-26 05:25:50 +00:00
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Text(Bytes::from_static(b"text")));
2019-11-26 05:25:50 +00:00
framed
.send(ws::Message::Binary("text".into()))
.await
.unwrap();
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Binary(Bytes::from_static(b"text")));
2019-11-26 05:25:50 +00:00
framed.send(ws::Message::Ping("text".into())).await.unwrap();
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Pong("text".to_string().into()));
2019-11-26 05:25:50 +00:00
framed
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
.await
.unwrap();
2019-11-26 05:25:50 +00:00
let item = framed.next().await.unwrap().unwrap();
assert_eq!(item, ws::Frame::Close(Some(ws::CloseCode::Normal.into())));
2018-10-05 21:30:40 +00:00
}