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
use crate::{JsonRpcClient, ProviderError};
use async_trait::async_trait;
use serde::{de::DeserializeOwned, Serialize};
use serde_json::Value;
use std::{
borrow::Borrow,
collections::VecDeque,
sync::{Arc, Mutex},
};
use thiserror::Error;
#[derive(Debug)]
enum MockParams {
Value(Value),
Zst,
}
#[derive(Clone, Debug)]
pub struct MockProvider {
requests: Arc<Mutex<VecDeque<(String, MockParams)>>>,
responses: Arc<Mutex<VecDeque<Value>>>,
}
impl Default for MockProvider {
fn default() -> Self {
Self::new()
}
}
#[cfg_attr(target_arch = "wasm32", async_trait(?Send))]
#[cfg_attr(not(target_arch = "wasm32"), async_trait)]
impl JsonRpcClient for MockProvider {
type Error = MockError;
async fn request<T: Serialize + Send + Sync, R: DeserializeOwned>(
&self,
method: &str,
params: T,
) -> Result<R, MockError> {
let params = if std::mem::size_of::<T>() == 0 {
MockParams::Zst
} else {
MockParams::Value(serde_json::to_value(params)?)
};
self.requests.lock().unwrap().push_back((method.to_owned(), params));
let mut data = self.responses.lock().unwrap();
let element = data.pop_back().ok_or(MockError::EmptyResponses)?;
let res: R = serde_json::from_value(element)?;
Ok(res)
}
}
impl MockProvider {
pub fn assert_request<T: Serialize + Send + Sync>(
&self,
method: &str,
data: T,
) -> Result<(), MockError> {
let (m, inp) = self.requests.lock().unwrap().pop_front().ok_or(MockError::EmptyRequests)?;
assert_eq!(m, method);
assert!(!matches!(inp, MockParams::Value(serde_json::Value::Null)));
if std::mem::size_of::<T>() == 0 {
assert!(matches!(inp, MockParams::Zst));
} else if let MockParams::Value(inp) = inp {
assert_eq!(serde_json::to_value(data).expect("could not serialize data"), inp);
} else {
unreachable!("Zero sized types must be denoted with MockParams::Zst")
}
Ok(())
}
pub fn new() -> Self {
Self {
requests: Arc::new(Mutex::new(VecDeque::new())),
responses: Arc::new(Mutex::new(VecDeque::new())),
}
}
pub fn push<T: Serialize + Send + Sync, K: Borrow<T>>(&self, data: K) -> Result<(), MockError> {
let value = serde_json::to_value(data.borrow())?;
self.responses.lock().unwrap().push_back(value);
Ok(())
}
}
#[derive(Error, Debug)]
pub enum MockError {
#[error(transparent)]
SerdeJson(#[from] serde_json::Error),
#[error("empty responses array, please push some requests")]
EmptyRequests,
#[error("empty responses array, please push some responses")]
EmptyResponses,
}
impl From<MockError> for ProviderError {
fn from(src: MockError) -> Self {
ProviderError::JsonRpcClientError(Box::new(src))
}
}
#[cfg(test)]
#[cfg(not(target_arch = "wasm32"))]
mod tests {
use super::*;
use crate::Middleware;
use ethers_core::types::U64;
#[tokio::test]
async fn pushes_request_and_response() {
let mock = MockProvider::new();
mock.push(U64::from(12)).unwrap();
let block: U64 = mock.request("eth_blockNumber", ()).await.unwrap();
mock.assert_request("eth_blockNumber", ()).unwrap();
assert_eq!(block.as_u64(), 12);
}
#[tokio::test]
async fn empty_responses() {
let mock = MockProvider::new();
let err = mock.request::<_, ()>("eth_blockNumber", ()).await.unwrap_err();
match err {
MockError::EmptyResponses => {}
_ => panic!("expected empty responses"),
};
}
#[tokio::test]
async fn empty_requests() {
let mock = MockProvider::new();
let err = mock.assert_request("eth_blockNumber", ()).unwrap_err();
match err {
MockError::EmptyRequests => {}
_ => panic!("expected empty request"),
};
}
#[tokio::test]
async fn composes_with_provider() {
let (provider, mock) = crate::Provider::mocked();
mock.push(U64::from(12)).unwrap();
let block = provider.get_block_number().await.unwrap();
assert_eq!(block.as_u64(), 12);
}
}