axum_test/
test_web_socket.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
use anyhow::anyhow;
use anyhow::Context;
use anyhow::Result;
use bytes::Bytes;
use futures_util::sink::SinkExt;
use futures_util::stream::StreamExt;
use hyper::upgrade::Upgraded;
use hyper_util::rt::TokioIo;
use serde::de::DeserializeOwned;
use serde::Serialize;
use std::fmt::Debug;
use std::fmt::Display;
use tokio_tungstenite::tungstenite::protocol::Role;
use tokio_tungstenite::WebSocketStream;

use crate::WsMessage;

#[cfg(feature = "pretty-assertions")]
use pretty_assertions::assert_eq;

pub struct TestWebSocket {
    stream: WebSocketStream<TokioIo<Upgraded>>,
}

impl TestWebSocket {
    pub(crate) async fn new(upgraded: Upgraded) -> Self {
        let upgraded_io = TokioIo::new(upgraded);
        let stream = WebSocketStream::from_raw_socket(upgraded_io, Role::Client, None).await;

        Self { stream }
    }

    pub async fn close(mut self) {
        self.stream
            .close(None)
            .await
            .expect("Failed to close WebSocket stream");
    }

    pub async fn send_text<T>(&mut self, raw_text: T)
    where
        T: Display,
    {
        let text = format!("{}", raw_text);
        self.send_message(WsMessage::Text(text)).await;
    }

    pub async fn send_json<J>(&mut self, body: &J)
    where
        J: ?Sized + Serialize,
    {
        let raw_json =
            ::serde_json::to_string(body).expect("It should serialize the content into Json");

        self.send_message(WsMessage::Text(raw_json)).await;
    }

    #[cfg(feature = "yaml")]
    pub async fn send_yaml<Y>(&mut self, body: &Y)
    where
        Y: ?Sized + Serialize,
    {
        let raw_yaml =
            ::serde_yaml::to_string(body).expect("It should serialize the content into Yaml");

        self.send_message(WsMessage::Text(raw_yaml)).await;
    }

    #[cfg(feature = "msgpack")]
    pub async fn send_msgpack<M>(&mut self, body: &M)
    where
        M: ?Sized + Serialize,
    {
        let body_bytes =
            ::rmp_serde::to_vec(body).expect("It should serialize the content into MsgPack");

        self.send_message(WsMessage::Binary(body_bytes)).await;
    }

    pub async fn send_message(&mut self, message: WsMessage) {
        self.stream.send(message).await.unwrap();
    }

    #[must_use]
    pub async fn receive_text(&mut self) -> String {
        let message = self.receive_message().await;

        message_to_text(message)
            .context("Failed to read message as a String")
            .unwrap()
    }

    #[must_use]
    pub async fn receive_json<T>(&mut self) -> T
    where
        T: DeserializeOwned,
    {
        let bytes = self.receive_bytes().await;
        serde_json::from_slice::<T>(&bytes)
            .context("Failed to deserialize message as Json")
            .unwrap()
    }

    #[cfg(feature = "yaml")]
    #[must_use]
    pub async fn receive_yaml<T>(&mut self) -> T
    where
        T: DeserializeOwned,
    {
        let bytes = self.receive_bytes().await;
        serde_yaml::from_slice::<T>(&bytes)
            .context("Failed to deserialize message as Yaml")
            .unwrap()
    }

    #[cfg(feature = "msgpack")]
    #[must_use]
    pub async fn receive_msgpack<T>(&mut self) -> T
    where
        T: DeserializeOwned,
    {
        let received_bytes = self.receive_bytes().await;
        rmp_serde::from_slice::<T>(&received_bytes)
            .context("Failed to deserializing message as MsgPack")
            .unwrap()
    }

    #[must_use]
    pub async fn receive_bytes(&mut self) -> Bytes {
        let message = self.receive_message().await;

        message_to_bytes(message)
            .context("Failed to read message as a Bytes")
            .unwrap()
    }

    #[must_use]
    pub async fn receive_message(&mut self) -> WsMessage {
        self.maybe_receive_message()
            .await
            .expect("No message found on WebSocket stream")
    }

    pub async fn assert_receive_json<T>(&mut self, expected: &T)
    where
        T: DeserializeOwned + PartialEq<T> + Debug,
    {
        assert_eq!(*expected, self.receive_json::<T>().await);
    }

    pub async fn assert_receive_text<C>(&mut self, expected: C)
    where
        C: AsRef<str>,
    {
        let expected_contents = expected.as_ref();
        assert_eq!(expected_contents, &self.receive_text().await);
    }

    pub async fn assert_receive_text_contains<C>(&mut self, expected: C)
    where
        C: AsRef<str>,
    {
        let expected_contents = expected.as_ref();
        let received = self.receive_text().await;
        let is_contained = received.contains(expected_contents);

        assert!(
            is_contained,
            "Failed to find '{expected_contents}', received '{received}'"
        );
    }

    #[cfg(feature = "yaml")]
    pub async fn assert_receive_yaml<T>(&mut self, expected: &T)
    where
        T: DeserializeOwned + PartialEq<T> + Debug,
    {
        assert_eq!(*expected, self.receive_yaml::<T>().await);
    }

    #[cfg(feature = "msgpack")]
    pub async fn assert_receive_msgpack<T>(&mut self, expected: &T)
    where
        T: DeserializeOwned + PartialEq<T> + Debug,
    {
        assert_eq!(*expected, self.receive_msgpack::<T>().await);
    }

    #[must_use]
    async fn maybe_receive_message(&mut self) -> Option<WsMessage> {
        let maybe_message = self.stream.next().await;

        match maybe_message {
            None => None,
            Some(message_result) => {
                let message =
                    message_result.expect("Failed to receive message from WebSocket stream");
                Some(message)
            }
        }
    }
}

fn message_to_text(message: WsMessage) -> Result<String> {
    let text = match message {
        WsMessage::Text(text) => text,
        WsMessage::Binary(data) => String::from_utf8(data).map_err(|err| err.utf8_error())?,
        WsMessage::Ping(data) => String::from_utf8(data).map_err(|err| err.utf8_error())?,
        WsMessage::Pong(data) => String::from_utf8(data).map_err(|err| err.utf8_error())?,
        WsMessage::Close(None) => String::new(),
        WsMessage::Close(Some(frame)) => frame.reason.into_owned(),
        WsMessage::Frame(_) => {
            return Err(anyhow!(
                "Unexpected Frame, did not expect Frame message whilst reading"
            ))
        }
    };

    Ok(text)
}

fn message_to_bytes(message: WsMessage) -> Result<Bytes> {
    let bytes = match message {
        WsMessage::Text(string) => string.into_bytes().into(),
        WsMessage::Binary(data) => data.into(),
        WsMessage::Ping(data) => data.into(),
        WsMessage::Pong(data) => data.into(),
        WsMessage::Close(None) => Bytes::new(),
        WsMessage::Close(Some(frame)) => frame.reason.into_owned().into_bytes().into(),
        WsMessage::Frame(_) => {
            return Err(anyhow!(
                "Unexpected Frame, did not expect Frame message whilst reading"
            ))
        }
    };

    Ok(bytes)
}

#[cfg(test)]
mod test_assert_receive_text {
    use crate::TestServer;

    use axum::extract::ws::Message;
    use axum::extract::ws::WebSocket;
    use axum::extract::WebSocketUpgrade;
    use axum::response::Response;
    use axum::routing::get;
    use axum::Router;

    fn new_test_app() -> TestServer {
        pub async fn route_get_websocket_ping_pong(ws: WebSocketUpgrade) -> Response {
            async fn handle_ping_pong(mut socket: WebSocket) {
                while let Some(maybe_message) = socket.recv().await {
                    let message_text = maybe_message.unwrap().into_text().unwrap();

                    let encoded_text = format!("Text: {message_text}");
                    let encoded_data = format!("Binary: {message_text}").into_bytes();

                    socket.send(Message::Text(encoded_text)).await.unwrap();
                    socket.send(Message::Binary(encoded_data)).await.unwrap();
                }
            }

            ws.on_upgrade(move |socket| handle_ping_pong(socket))
        }

        let app = Router::new().route(&"/ws-ping-pong", get(route_get_websocket_ping_pong));
        TestServer::builder().http_transport().build(app).unwrap()
    }

    #[tokio::test]
    async fn it_should_ping_pong_text_in_text_and_binary() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket.send_text("Hello World!").await;

        websocket.assert_receive_text("Text: Hello World!").await;
        websocket.assert_receive_text("Binary: Hello World!").await;
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_not_match_partial_text_match() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket.send_text("Hello World!").await;
        websocket.assert_receive_text("Hello World!").await;
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_not_match_different_text() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket.send_text("Hello World!").await;
        websocket.assert_receive_text("🦊").await;
    }
}

#[cfg(test)]
mod test_assert_receive_text_contains {
    use crate::TestServer;

    use axum::extract::ws::Message;
    use axum::extract::ws::WebSocket;
    use axum::extract::WebSocketUpgrade;
    use axum::response::Response;
    use axum::routing::get;
    use axum::Router;

    fn new_test_app() -> TestServer {
        pub async fn route_get_websocket_ping_pong(ws: WebSocketUpgrade) -> Response {
            async fn handle_ping_pong(mut socket: WebSocket) {
                while let Some(maybe_message) = socket.recv().await {
                    let message_text = maybe_message.unwrap().into_text().unwrap();
                    let encoded_text = format!("Text: {message_text}");

                    socket.send(Message::Text(encoded_text)).await.unwrap();
                }
            }

            ws.on_upgrade(move |socket| handle_ping_pong(socket))
        }

        let app = Router::new().route(&"/ws-ping-pong", get(route_get_websocket_ping_pong));
        TestServer::builder().http_transport().build(app).unwrap()
    }

    #[tokio::test]
    async fn it_should_assert_whole_text_match() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket.send_text("Hello World!").await;
        websocket
            .assert_receive_text_contains("Text: Hello World!")
            .await;
    }

    #[tokio::test]
    async fn it_should_assert_partial_text_match() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket.send_text("Hello World!").await;
        websocket.assert_receive_text_contains("Hello World!").await;
    }

    #[tokio::test]
    #[should_panic]
    async fn it_should_not_match_different_text() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket.send_text("Hello World!").await;
        websocket.assert_receive_text_contains("🦊").await;
    }
}

#[cfg(test)]
mod test_assert_receive_json {
    use crate::TestServer;

    use axum::extract::ws::Message;
    use axum::extract::ws::WebSocket;
    use axum::extract::WebSocketUpgrade;
    use axum::response::Response;
    use axum::routing::get;
    use axum::Router;
    use serde_json::json;
    use serde_json::Value;

    fn new_test_app() -> TestServer {
        pub async fn route_get_websocket_ping_pong(ws: WebSocketUpgrade) -> Response {
            async fn handle_ping_pong(mut socket: WebSocket) {
                while let Some(maybe_message) = socket.recv().await {
                    let message_text = maybe_message.unwrap().into_text().unwrap();
                    let decoded = serde_json::from_str::<Value>(&message_text).unwrap();

                    let encoded_text = serde_json::to_string(&json!({
                        "format": "text",
                        "message": decoded
                    }))
                    .unwrap();
                    let encoded_data = serde_json::to_vec(&json!({
                        "format": "binary",
                        "message": decoded
                    }))
                    .unwrap();

                    socket.send(Message::Text(encoded_text)).await.unwrap();
                    socket.send(Message::Binary(encoded_data)).await.unwrap();
                }
            }

            ws.on_upgrade(move |socket| handle_ping_pong(socket))
        }

        let app = Router::new().route(&"/ws-ping-pong", get(route_get_websocket_ping_pong));
        TestServer::builder().http_transport().build(app).unwrap()
    }

    #[tokio::test]
    async fn it_should_ping_pong_json_in_text_and_binary() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket
            .send_json(&json!({
                "hello": "world",
                "numbers": [1, 2, 3],
            }))
            .await;

        // Once for text
        websocket
            .assert_receive_json(&json!({
                "format": "text",
                "message": {
                    "hello": "world",
                    "numbers": [1, 2, 3],
                },
            }))
            .await;

        // Again for binary
        websocket
            .assert_receive_json(&json!({
                "format": "binary",
                "message": {
                    "hello": "world",
                    "numbers": [1, 2, 3],
                },
            }))
            .await;
    }
}

#[cfg(feature = "yaml")]
#[cfg(test)]
mod test_assert_receive_yaml {
    use crate::TestServer;

    use axum::extract::ws::Message;
    use axum::extract::ws::WebSocket;
    use axum::extract::WebSocketUpgrade;
    use axum::response::Response;
    use axum::routing::get;
    use axum::Router;
    use serde_json::json;
    use serde_json::Value;

    fn new_test_app() -> TestServer {
        pub async fn route_get_websocket_ping_pong(ws: WebSocketUpgrade) -> Response {
            async fn handle_ping_pong(mut socket: WebSocket) {
                while let Some(maybe_message) = socket.recv().await {
                    let message_text = maybe_message.unwrap().into_text().unwrap();
                    let decoded = serde_yaml::from_str::<Value>(&message_text).unwrap();

                    let encoded_text = serde_yaml::to_string(&json!({
                        "format": "text",
                        "message": decoded
                    }))
                    .unwrap();
                    let encoded_data = serde_yaml::to_string(&json!({
                        "format": "binary",
                        "message": decoded
                    }))
                    .unwrap()
                    .into_bytes();

                    socket.send(Message::Text(encoded_text)).await.unwrap();
                    socket.send(Message::Binary(encoded_data)).await.unwrap();
                }
            }

            ws.on_upgrade(move |socket| handle_ping_pong(socket))
        }

        let app = Router::new().route(&"/ws-ping-pong", get(route_get_websocket_ping_pong));
        TestServer::builder().http_transport().build(app).unwrap()
    }

    #[tokio::test]
    async fn it_should_ping_pong_yaml_in_text_and_binary() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket
            .send_json(&json!({
                "hello": "world",
                "numbers": [1, 2, 3],
            }))
            .await;

        // Once for text
        websocket
            .assert_receive_yaml(&json!({
                "format": "text",
                "message": {
                    "hello": "world",
                    "numbers": [1, 2, 3],
                },
            }))
            .await;

        // Again for binary
        websocket
            .assert_receive_yaml(&json!({
                "format": "binary",
                "message": {
                    "hello": "world",
                    "numbers": [1, 2, 3],
                },
            }))
            .await;
    }
}

#[cfg(feature = "msgpack")]
#[cfg(test)]
mod test_assert_receive_msgpack {
    use crate::TestServer;

    use axum::extract::ws::Message;
    use axum::extract::ws::WebSocket;
    use axum::extract::WebSocketUpgrade;
    use axum::response::Response;
    use axum::routing::get;
    use axum::Router;
    use serde_json::json;
    use serde_json::Value;

    fn new_test_app() -> TestServer {
        pub async fn route_get_websocket_ping_pong(ws: WebSocketUpgrade) -> Response {
            async fn handle_ping_pong(mut socket: WebSocket) {
                while let Some(maybe_message) = socket.recv().await {
                    let message_data = maybe_message.unwrap().into_data();
                    let decoded = rmp_serde::from_slice::<Value>(&message_data).unwrap();

                    let encoded_data = ::rmp_serde::to_vec(&json!({
                        "format": "binary",
                        "message": decoded
                    }))
                    .unwrap();

                    socket.send(Message::Binary(encoded_data)).await.unwrap();
                }
            }

            ws.on_upgrade(move |socket| handle_ping_pong(socket))
        }

        let app = Router::new().route(&"/ws-ping-pong", get(route_get_websocket_ping_pong));
        TestServer::builder().http_transport().build(app).unwrap()
    }

    #[tokio::test]
    async fn it_should_ping_pong_msgpack_in_binary() {
        let server = new_test_app();

        let mut websocket = server
            .get_websocket(&"/ws-ping-pong")
            .await
            .into_websocket()
            .await;

        websocket
            .send_msgpack(&json!({
                "hello": "world",
                "numbers": [1, 2, 3],
            }))
            .await;

        websocket
            .assert_receive_msgpack(&json!({
                "format": "binary",
                "message": {
                    "hello": "world",
                    "numbers": [1, 2, 3],
                },
            }))
            .await;
    }
}