Skip to main content

jsonrpsee_test_utils/
mocks.rs

1// Copyright 2019-2021 Parity Technologies (UK) Ltd.
2//
3// Permission is hereby granted, free of charge, to any
4// person obtaining a copy of this software and associated
5// documentation files (the "Software"), to deal in the
6// Software without restriction, including without
7// limitation the rights to use, copy, modify, merge,
8// publish, distribute, sublicense, and/or sell copies of
9// the Software, and to permit persons to whom the Software
10// is furnished to do so, subject to the following
11// conditions:
12//
13// The above copyright notice and this permission notice
14// shall be included in all copies or substantial portions
15// of the Software.
16//
17// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
18// ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
19// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
20// PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
21// SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
22// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
23// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
24// IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
25// DEALINGS IN THE SOFTWARE.
26
27use std::{io, net::SocketAddr};
28
29use futures_util::{SinkExt, StreamExt};
30use serde::{Deserialize, Serialize};
31use tokio::net::TcpStream;
32use tokio_tungstenite::{
33    client_async,
34    tungstenite::{self, Message},
35    WebSocketStream,
36};
37
38pub use hyper::{HeaderMap, StatusCode, Uri};
39
40type Error = Box<dyn std::error::Error + Send + Sync + 'static>;
41
42/// Request Id
43#[derive(Debug, PartialEq, Clone, Hash, Eq, Deserialize, Serialize)]
44#[serde(deny_unknown_fields)]
45#[serde(untagged)]
46pub enum Id {
47    /// No id (notification)
48    Null,
49    /// Numeric id
50    Num(u64),
51    /// String id
52    Str(String),
53}
54
55#[derive(Debug)]
56pub struct HttpResponse {
57    pub status: StatusCode,
58    pub header: HeaderMap,
59    pub body: String,
60}
61
62/// The error of [`WebSocketTestClient::receive`] once the server closed the connection.
63pub const CONNECTION_CLOSED: &str = "connection closed";
64
65/// WebSocket client to construct with arbitrary payload to construct bad payloads.
66pub struct WebSocketTestClient {
67    stream: WebSocketStream<TcpStream>,
68}
69
70impl std::fmt::Debug for WebSocketTestClient {
71    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
72        write!(f, "WebSocketTestClient")
73    }
74}
75
76#[derive(Debug)]
77pub enum WebSocketTestError {
78    RejectedWithStatusCode(u16),
79    Handshake(tungstenite::Error),
80}
81
82impl From<io::Error> for WebSocketTestError {
83    fn from(err: io::Error) -> Self {
84        WebSocketTestError::Handshake(err.into())
85    }
86}
87
88impl WebSocketTestClient {
89    pub async fn new(url: SocketAddr) -> Result<Self, WebSocketTestError> {
90        let socket = TcpStream::connect(url).await?;
91        match client_async("ws://test-client/", socket).await {
92            Ok((stream, _)) => Ok(Self { stream }),
93            Err(tungstenite::Error::Http(response)) => {
94                Err(WebSocketTestError::RejectedWithStatusCode(response.status().as_u16()))
95            }
96            Err(err) => Err(WebSocketTestError::Handshake(err)),
97        }
98    }
99
100    pub async fn send_request_text(&mut self, msg: impl AsRef<str>) -> Result<String, Error> {
101        self.send(msg).await?;
102        self.receive().await
103    }
104
105    pub async fn send(&mut self, msg: impl AsRef<str>) -> Result<(), Error> {
106        self.stream.send(Message::text(msg.as_ref())).await.map_err(Into::into)
107    }
108
109    pub async fn send_request_binary(&mut self, msg: &[u8]) -> Result<String, Error> {
110        self.stream.send(Message::binary(msg.to_vec())).await?;
111        self.receive().await
112    }
113
114    /// Returns the next text or binary message. Pings are answered by `tungstenite` with the next
115    /// read.
116    pub async fn receive(&mut self) -> Result<String, Error> {
117        loop {
118            match self.stream.next().await {
119                Some(Ok(Message::Text(text))) => return Ok(text.as_str().to_owned()),
120                Some(Ok(Message::Binary(data))) => {
121                    return String::from_utf8(data.into()).map_err(Into::into)
122                }
123                Some(Ok(Message::Close(_))) | None => return Err(CONNECTION_CLOSED.into()),
124                Some(Ok(_)) => {}
125                Some(Err(err)) => return Err(err.into()),
126            }
127        }
128    }
129
130    pub async fn close(&mut self) -> Result<(), Error> {
131        self.stream.close(None).await.map_err(Into::into)
132    }
133
134    /// Returns the connection, to write and read raw frames.
135    pub fn into_inner(self) -> TcpStream {
136        self.stream.into_inner()
137    }
138}