1
0
mirror of https://github.com/fafhrd91/actix-web synced 2024-11-27 17:52:56 +01:00
actix-web/actix-web-actors/tests/test_ws.rs

69 lines
2.1 KiB
Rust
Raw Normal View History

2019-03-18 06:02:03 +01: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 06:11:50 +01:00
type Context = ws::WebsocketContext<Self>;
2019-03-18 06:02:03 +01:00
}
2019-03-18 06:31:10 +01:00
impl StreamHandler<ws::Message, ws::ProtocolError> for Ws {
fn handle(&mut self, msg: ws::Message, ctx: &mut Self::Context) {
2019-03-18 06:02:03 +01:00
match msg {
2019-03-18 06:31:10 +01: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 06:02:03 +01:00
_ => (),
}
}
}
#[test]
fn test_simple() {
2019-03-25 01:00:59 +01: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 06:02:03 +01:00
// client service
let framed = srv.ws().unwrap();
let framed = srv
2019-03-18 06:11:50 +01:00
.block_on(framed.send(ws::Message::Text("text".to_string())))
2019-03-18 06:02:03 +01:00
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
2019-03-18 06:11:50 +01:00
assert_eq!(item, Some(ws::Frame::Text(Some(BytesMut::from("text")))));
2019-03-18 06:02:03 +01:00
let framed = srv
2019-03-18 06:11:50 +01:00
.block_on(framed.send(ws::Message::Binary("text".into())))
2019-03-18 06:02:03 +01:00
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
assert_eq!(
item,
2019-03-18 06:11:50 +01:00
Some(ws::Frame::Binary(Some(Bytes::from_static(b"text").into())))
2019-03-18 06:02:03 +01:00
);
let framed = srv
2019-03-18 06:11:50 +01:00
.block_on(framed.send(ws::Message::Ping("text".into())))
2019-03-18 06:02:03 +01:00
.unwrap();
let (item, framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
2019-03-18 06:11:50 +01:00
assert_eq!(item, Some(ws::Frame::Pong("text".to_string().into())));
2019-03-18 06:02:03 +01:00
let framed = srv
2019-03-18 06:11:50 +01:00
.block_on(framed.send(ws::Message::Close(Some(ws::CloseCode::Normal.into()))))
2019-03-18 06:02:03 +01:00
.unwrap();
let (item, _framed) = srv.block_on(framed.into_future()).map_err(|_| ()).unwrap();
2019-03-18 06:11:50 +01:00
assert_eq!(
item,
Some(ws::Frame::Close(Some(ws::CloseCode::Normal.into())))
);
2019-03-18 06:02:03 +01:00
}