1
0
mirror of https://github.com/actix/actix-extras.git synced 2024-11-24 16:02:59 +01:00
actix-extras/actix-http/tests/test_ws.rs

86 lines
2.5 KiB
Rust
Raw Normal View History

use actix_codec::{AsyncRead, AsyncWrite, Framed};
use actix_http::{body, h1, ws, Error, HttpService, Request, Response};
2019-11-26 06:25:50 +01:00
use actix_http_test::TestServer;
2019-12-11 14:20:20 +01:00
use actix_utils::framed::Dispatcher;
2019-12-05 18:35:43 +01:00
use bytes::BytesMut;
2019-11-19 13:54:19 +01:00
use futures::future;
use futures::{SinkExt, StreamExt};
2019-11-19 13:54:19 +01:00
async fn ws_service<T: AsyncRead + AsyncWrite + Unpin>(
(req, mut framed): (Request, Framed<T, h1::Codec>),
) -> Result<(), Error> {
let res = ws::handshake(req.head()).unwrap().message_body(());
framed
.send((res, body::BodySize::None).into())
2019-11-19 13:54:19 +01:00
.await
.unwrap();
2019-12-11 14:20:20 +01:00
Dispatcher::new(framed.into_framed(ws::Codec::new()), service)
2019-11-19 13:54:19 +01:00
.await
.map_err(|_| panic!())
}
2019-11-19 13:54:19 +01:00
async fn service(msg: ws::Frame) -> Result<ws::Message, Error> {
let msg = match msg {
ws::Frame::Ping(msg) => ws::Message::Pong(msg),
ws::Frame::Text(text) => {
ws::Message::Text(String::from_utf8_lossy(&text.unwrap()).to_string())
}
ws::Frame::Binary(bin) => ws::Message::Binary(bin.unwrap().freeze()),
ws::Frame::Close(reason) => ws::Message::Close(reason),
_ => panic!(),
};
2019-11-19 13:54:19 +01:00
Ok(msg)
}
2019-11-26 06:25:50 +01:00
#[actix_rt::test]
async fn test_simple() {
let mut srv = TestServer::start(|| {
HttpService::build()
2019-12-08 14:25:24 +01:00
.upgrade(actix_service::fn_service(ws_service))
2019-11-26 06:25:50 +01:00
.finish(|_| future::ok::<_, ()>(Response::NotFound()))
2019-12-02 12:33:11 +01:00
.tcp()
2019-11-26 06:25:50 +01:00
});
2019-11-26 06:25:50 +01:00
// client service
let mut framed = srv.ws().await.unwrap();
framed
.send(ws::Message::Text("text".to_string()))
.await
.unwrap();
let (item, mut framed) = framed.into_future().await;
assert_eq!(
item.unwrap().unwrap(),
ws::Frame::Text(Some(BytesMut::from("text")))
);
2019-11-26 06:25:50 +01:00
framed
.send(ws::Message::Binary("text".into()))
.await
.unwrap();
let (item, mut framed) = framed.into_future().await;
assert_eq!(
item.unwrap().unwrap(),
2019-12-05 18:35:43 +01:00
ws::Frame::Binary(Some(BytesMut::from(&b"text"[..]).into()))
2019-11-26 06:25:50 +01:00
);
2019-11-26 06:25:50 +01:00
framed.send(ws::Message::Ping("text".into())).await.unwrap();
let (item, mut framed) = framed.into_future().await;
assert_eq!(
item.unwrap().unwrap(),
ws::Frame::Pong("text".to_string().into())
);
2019-11-26 06:25:50 +01:00
framed
.send(ws::Message::Close(Some(ws::CloseCode::Normal.into())))
.await
.unwrap();
2019-11-26 06:25:50 +01:00
let (item, _framed) = framed.into_future().await;
assert_eq!(
item.unwrap().unwrap(),
ws::Frame::Close(Some(ws::CloseCode::Normal.into()))
);
}