1
0
Fork 0
mirror of https://github.com/actix/actix-web.git synced 2024-11-05 16:39:36 +00:00
actix-web/actix-web-actors/tests/test_ws.rs

69 lines
2.1 KiB
Rust
Raw Normal View History

2019-03-18 05:02:03 +00:00
use actix::prelude::*;
use actix_http::HttpService;
use actix_http_test::TestServer;
use actix_web::{web, App, HttpRequest};
use actix_web_actors::*;
use bytes::{Bytes, BytesMut};
use futures::{Sink, Stream};
struct Ws;
impl Actor for Ws {
2019-03-18 05:11:50 +00:00
type Context = ws::WebsocketContext<Self>;
2019-03-18 05:02:03 +00:00
}
2019-03-18 05:31:10 +00:00
impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
2019-03-18 05:02:03 +00:00
match msg {
2019-03-18 05:31:10 +00:00
ws::Message::Ping(msg) => ctx.pong(&msg),
ws::Message::Text(text) => ctx.text(text),
ws::Message::Binary(bin) => ctx.binary(bin),
ws::Message::Close(reason) => ctx.close(reason),
2019-03-18 05:02:03 +00:00
_ => (),
}
}
}
#[test]
fn test_simple() {
2019-03-25 00:00:59 +00:00
let mut srv =
TestServer::new(|| {
HttpService::new(App::new().service(web::resource("/").to(
|req: HttpRequest, stream: web::Payload| ws::start(Ws, &req, stream),
)))
});
2019-03-18 05:02:03 +00:00
// client service
let framed = srv.ws().unwrap();
let framed = srv
2019-03-18 05:11:50 +00:00
.block_on(framed.send(ws::Message::Text("text".to_string())))
2019-03-18 05:02:03 +00:00
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
2019-03-18 05:11:50 +00:00
assert_eq!(item, Some(ws::Frame::Text(Some(BytesMut::from("text")))));
2019-03-18 05:02:03 +00:00
let framed = srv
2019-03-18 05:11:50 +00:00
.block_on(framed.send(ws::Message::Binary("text".into())))
2019-03-18 05:02:03 +00:00
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(
item,
2019-03-18 05:11:50 +00:00
Some(ws::Frame::Binary(Some(Bytes::from_static(b"text").into())))
2019-03-18 05:02:03 +00:00
);
let framed = srv
2019-03-18 05:11:50 +00:00
.block_on(framed.send(ws::Message::Ping("text".into())))
2019-03-18 05:02:03 +00:00
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
2019-03-18 05:11:50 +00:00
assert_eq!(item, Some(ws::Frame::Pong("text".to_string().into())));
2019-03-18 05:02:03 +00:00
let framed = srv
2019-03-18 05:11:50 +00:00
.block_on(framed.send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))))
2019-03-18 05:02:03 +00:00
.unwrap();
let (item, _framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
2019-03-18 05:11:50 +00:00
assert_eq!(
item,
Some(ws::Frame::Close(Some(ws::CloseCode::Normal.into())))
);
2019-03-18 05:02:03 +00:00
}