main.rs
This file
Path
examples/testing-websockets/src/main.rs
148 lines · 4.7 KiB · Rust
Last changed by
chore: fix typos (#3758)David Pedersenbefore adoption5bc0046
History of this fileTake it
1//! Run with2//!3//! ```not_rust4//! cargo test -p example-testing-websockets5//! ```67use axum::{8 extract::{9 ws::{Message, WebSocket},10 WebSocketUpgrade,11 },12 response::Response,13 routing::get,14 Router,15};16use futures_util::{Sink, SinkExt, Stream, StreamExt};1718#[tokio::main]19async fn main() {20 let listener = tokio::net::TcpListener::bind("127.0.0.1:3000")21 .await22 .unwrap();23 println!("listening on {}", listener.local_addr().unwrap());24 axum::serve(listener, app()).await;25}2627fn app() -> Router {28 // WebSocket routes can generally be tested in two ways:29 //30 // - Integration tests where you run the server and connect with a real WebSocket client.31 // - Unit tests where you mock the socket as some generic send/receive type32 //33 // Which version you pick is up to you. Generally we recommend the integration test version34 // unless your app has a lot of setup that makes it hard to run in a test.35 Router::new()36 .route("/integration-testable", get(integration_testable_handler))37 .route("/unit-testable", get(unit_testable_handler))38}3940// A WebSocket handler that echos any message it receives.41//42// This one we'll be integration testing so it can be written in the regular way.43async fn integration_testable_handler(ws: WebSocketUpgrade) -> Response {44 ws.on_upgrade(integration_testable_handle_socket)45}4647async fn integration_testable_handle_socket(mut socket: WebSocket) {48 while let Some(Ok(msg)) = socket.recv().await {49 if let Message::Text(msg) = msg {50 if socket51 .send(Message::Text(format!("You said: {msg}").into()))52 .await53 .is_err()54 {55 break;56 }57 }58 }59}6061// The unit testable version requires some changes.62//63// By splitting the socket into an `impl Sink` and `impl Stream` we can test without providing a64// real socket and instead using channels, which also implement `Sink` and `Stream`.65async fn unit_testable_handler(ws: WebSocketUpgrade) -> Response {66 ws.on_upgrade(|socket| {67 let (write, read) = socket.split();68 unit_testable_handle_socket(write, read)69 })70}7172// The implementation is largely the same as `integration_testable_handle_socket` except we call73// methods from `SinkExt` and `StreamExt`.74async fn unit_testable_handle_socket<W, R>(mut write: W, mut read: R)75where76 W: Sink<Message> + Unpin,77 R: Stream<Item = Result<Message, axum::Error>> + Unpin,78{79 while let Some(Ok(msg)) = read.next().await {80 if let Message::Text(msg) = msg {81 if write82 .send(Message::Text(format!("You said: {msg}").into()))83 .await84 .is_err()85 {86 break;87 }88 }89 }90}9192#[cfg(test)]93mod tests {94 use super::*;95 use std::{96 future::IntoFuture,97 net::{Ipv4Addr, SocketAddr},98 };99 use tokio_tungstenite::tungstenite;100101 // We can integration test one handler by running the server in a background task and102 // connecting to it like any other client would.103 #[tokio::test]104 async fn integration_test() {105 let listener = tokio::net::TcpListener::bind(SocketAddr::from((Ipv4Addr::UNSPECIFIED, 0)))106 .await107 .unwrap();108 let addr = listener.local_addr().unwrap();109 tokio::spawn(axum::serve(listener, app()).into_future());110111 let (mut socket, _response) =112 tokio_tungstenite::connect_async(format!("ws://{addr}/integration-testable"))113 .await114 .unwrap();115116 socket117 .send(tungstenite::Message::text("foo"))118 .await119 .unwrap();120121 let msg = match socket.next().await.unwrap().unwrap() {122 tungstenite::Message::Text(msg) => msg,123 other => panic!("expected a text message but got {other:?}"),124 };125126 assert_eq!(msg.as_str(), "You said: foo");127 }128129 // We can unit test the other handler by creating channels to read and write from.130 #[tokio::test]131 async fn unit_test() {132 // Need to use "futures" channels rather than "tokio" channels as they implement `Sink` and133 // `Stream`134 let (socket_write, mut test_rx) = futures_channel::mpsc::channel(1024);135 let (mut test_tx, socket_read) = futures_channel::mpsc::channel(1024);136137 tokio::spawn(unit_testable_handle_socket(socket_write, socket_read));138139 test_tx.send(Ok(Message::Text("foo".into()))).await.unwrap();140141 let msg = match test_rx.next().await.unwrap() {142 Message::Text(msg) => msg,143 other => panic!("expected a text message but got {other:?}"),144 };145146 assert_eq!(msg.as_str(), "You said: foo");147 }148}