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
//! Mock client implementation for use in testing.

use crate::client::subscription::SubscriptionTx;
use crate::client::sync::{unbounded, ChannelRx, ChannelTx};
use crate::client::transport::router::SubscriptionRouter;
use crate::event::Event;
use crate::query::Query;
use crate::utils::uuid_str;
use crate::{Client, Error, Method, Request, Response, Result, Subscription, SubscriptionClient};
use async_trait::async_trait;
use std::collections::HashMap;

/// A mock client implementation for use in testing.
///
/// ## Examples
///
/// ```rust
/// use tendermint_rpc::{Client, Method, MockClient, MockRequestMatcher, MockRequestMethodMatcher};
///
/// const ABCI_INFO_RESPONSE: &str = r#"{
///   "jsonrpc": "2.0",
///   "id": "",
///   "result": {
///     "response": {
///       "data": "GaiaApp",
///       "version": "0.17.0",
///       "app_version": "1",
///       "last_block_height": "488120",
///       "last_block_app_hash": "2LnCw0fN+Zq/gs5SOuya/GRHUmtWftAqAkTUuoxl4g4="
///     }
///   }
/// }"#;
///
/// #[tokio::main]
/// async fn main() {
///     let matcher = MockRequestMethodMatcher::default()
///         .map(Method::AbciInfo, Ok(ABCI_INFO_RESPONSE.to_string()));
///     let (client, driver) = MockClient::new(matcher);
///     let driver_hdl = tokio::spawn(async move { driver.run().await });
///
///     let abci_info = client.abci_info().await.unwrap();
///     println!("Got mock ABCI info: {:?}", abci_info);
///     assert_eq!("GaiaApp".to_string(), abci_info.data);
///
///     client.close();
///     driver_hdl.await.unwrap();
/// }
/// ```
#[derive(Debug)]
pub struct MockClient<M: MockRequestMatcher> {
    matcher: M,
    driver_tx: ChannelTx<DriverCommand>,
}

#[async_trait]
impl<M: MockRequestMatcher> Client for MockClient<M> {
    async fn perform<R>(&self, request: R) -> Result<R::Response>
    where
        R: Request,
    {
        self.matcher.response_for(request).ok_or_else(|| {
            Error::client_internal_error("no matching response for incoming request")
        })?
    }
}

impl<M: MockRequestMatcher> MockClient<M> {
    /// Create a new mock RPC client using the given request matcher.
    pub fn new(matcher: M) -> (Self, MockClientDriver) {
        let (driver_tx, driver_rx) = unbounded();
        (
            Self { matcher, driver_tx },
            MockClientDriver::new(driver_rx),
        )
    }

    /// Publishes the given event to all subscribers whose query exactly
    /// matches that of the event.
    pub fn publish(&self, ev: &Event) {
        self.driver_tx
            .send(DriverCommand::Publish(Box::new(ev.clone())))
            .unwrap();
    }

    /// Signal to the mock client's driver to terminate.
    pub fn close(self) {
        self.driver_tx.send(DriverCommand::Terminate).unwrap();
    }
}

#[async_trait]
impl<M: MockRequestMatcher> SubscriptionClient for MockClient<M> {
    async fn subscribe(&self, query: Query) -> Result<Subscription> {
        let id = uuid_str();
        let (subs_tx, subs_rx) = unbounded();
        let (result_tx, mut result_rx) = unbounded();
        self.driver_tx.send(DriverCommand::Subscribe {
            id: id.clone(),
            query: query.clone(),
            subscription_tx: subs_tx,
            result_tx,
        })?;
        result_rx.recv().await.unwrap()?;
        Ok(Subscription::new(id, query, subs_rx))
    }

    async fn unsubscribe(&self, query: Query) -> Result<()> {
        let (result_tx, mut result_rx) = unbounded();
        self.driver_tx
            .send(DriverCommand::Unsubscribe { query, result_tx })?;
        result_rx.recv().await.unwrap()
    }

    fn close(self) -> Result<()> {
        Ok(())
    }
}

#[derive(Debug)]
pub enum DriverCommand {
    Subscribe {
        id: String,
        query: Query,
        subscription_tx: SubscriptionTx,
        result_tx: ChannelTx<Result<()>>,
    },
    Unsubscribe {
        query: Query,
        result_tx: ChannelTx<Result<()>>,
    },
    Publish(Box<Event>),
    Terminate,
}

#[derive(Debug)]
pub struct MockClientDriver {
    router: SubscriptionRouter,
    rx: ChannelRx<DriverCommand>,
}

impl MockClientDriver {
    pub fn new(rx: ChannelRx<DriverCommand>) -> Self {
        Self {
            router: SubscriptionRouter::default(),
            rx,
        }
    }

    pub async fn run(mut self) -> Result<()> {
        loop {
            tokio::select! {
            Some(cmd) = self.rx.recv() => match cmd {
                    DriverCommand::Subscribe { id, query, subscription_tx, result_tx } => {
                        self.subscribe(id, query, subscription_tx, result_tx);
                    }
                    DriverCommand::Unsubscribe { query, result_tx } => {
                        self.unsubscribe(query, result_tx);
                    }
                    DriverCommand::Publish(event) => self.publish(event.as_ref()),
                    DriverCommand::Terminate => return Ok(()),
                }
            }
        }
    }

    fn subscribe(
        &mut self,
        id: String,
        query: Query,
        subscription_tx: SubscriptionTx,
        result_tx: ChannelTx<Result<()>>,
    ) {
        self.router.add(id, query, subscription_tx);
        result_tx.send(Ok(())).unwrap();
    }

    fn unsubscribe(&mut self, query: Query, result_tx: ChannelTx<Result<()>>) {
        self.router.remove_by_query(query);
        result_tx.send(Ok(())).unwrap();
    }

    fn publish(&mut self, event: &Event) {
        self.router.publish(event);
    }
}

/// A trait required by the [`MockClient`] that allows for different approaches
/// to mocking responses for specific requests.
///
/// [`MockClient`]: struct.MockClient.html
pub trait MockRequestMatcher: Send + Sync {
    /// Provide the corresponding response for the given request (if any).
    fn response_for<R>(&self, request: R) -> Option<Result<R::Response>>
    where
        R: Request;
}

/// Provides a simple [`MockRequestMatcher`] implementation that simply maps
/// requests with specific methods to responses.
///
/// [`MockRequestMatcher`]: trait.MockRequestMatcher.html
#[derive(Debug)]
pub struct MockRequestMethodMatcher {
    mappings: HashMap<Method, Result<String>>,
}

impl MockRequestMatcher for MockRequestMethodMatcher {
    fn response_for<R>(&self, request: R) -> Option<Result<R::Response>>
    where
        R: Request,
    {
        self.mappings.get(&request.method()).map(|res| match res {
            Ok(json) => R::Response::from_string(json),
            Err(e) => Err(e.clone()),
        })
    }
}

impl Default for MockRequestMethodMatcher {
    fn default() -> Self {
        Self {
            mappings: HashMap::new(),
        }
    }
}

impl MockRequestMethodMatcher {
    /// Maps all incoming requests with the given method such that their
    /// corresponding response will be `response`.
    ///
    /// Successful responses must be JSON-encoded.
    #[allow(dead_code)]
    pub fn map(mut self, method: Method, response: Result<String>) -> Self {
        self.mappings.insert(method, response);
        self
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::query::EventType;
    use futures::StreamExt;
    use std::path::PathBuf;
    use tendermint::block::Height;
    use tendermint::chain::Id;
    use tokio::fs;

    async fn read_json_fixture(name: &str) -> String {
        fs::read_to_string(PathBuf::from("./tests/support/").join(name.to_owned() + ".json"))
            .await
            .unwrap()
    }

    async fn read_event(name: &str) -> Event {
        Event::from_string(&read_json_fixture(name).await).unwrap()
    }

    #[tokio::test]
    async fn mock_client() {
        let abci_info_fixture = read_json_fixture("abci_info").await;
        let block_fixture = read_json_fixture("block").await;
        let matcher = MockRequestMethodMatcher::default()
            .map(Method::AbciInfo, Ok(abci_info_fixture))
            .map(Method::Block, Ok(block_fixture));
        let (client, driver) = MockClient::new(matcher);
        let driver_hdl = tokio::spawn(async move { driver.run().await });

        let abci_info = client.abci_info().await.unwrap();
        assert_eq!("GaiaApp".to_string(), abci_info.data);
        assert_eq!(Height::from(488120_u32), abci_info.last_block_height);

        let block = client.block(Height::from(10_u32)).await.unwrap().block;
        assert_eq!(Height::from(10_u32), block.header.height);
        assert_eq!("cosmoshub-2".parse::<Id>().unwrap(), block.header.chain_id);

        client.close();
        driver_hdl.await.unwrap().unwrap();
    }

    #[tokio::test]
    async fn mock_subscription_client() {
        let (client, driver) = MockClient::new(MockRequestMethodMatcher::default());
        let driver_hdl = tokio::spawn(async move { driver.run().await });

        let event1 = read_event("event_new_block_1").await;
        let event2 = read_event("event_new_block_2").await;
        let event3 = read_event("event_new_block_3").await;
        let events = vec![event1, event2, event3];

        let subs1 = client.subscribe(EventType::NewBlock.into()).await.unwrap();
        let subs2 = client.subscribe(EventType::NewBlock.into()).await.unwrap();
        assert_ne!(subs1.id().to_string(), subs2.id().to_string());

        // We can do this because the underlying channels can buffer the
        // messages as we publish them.
        let subs1_events = subs1.take(3);
        let subs2_events = subs2.take(3);
        for ev in &events {
            client.publish(ev);
        }

        // Here each subscription's channel is drained.
        let subs1_events = subs1_events.collect::<Vec<Result<Event>>>().await;
        let subs2_events = subs2_events.collect::<Vec<Result<Event>>>().await;

        assert_eq!(3, subs1_events.len());
        assert_eq!(3, subs2_events.len());

        for i in 0..3 {
            assert!(events[i].eq(subs1_events[i].as_ref().unwrap()));
        }

        client.close();
        driver_hdl.await.unwrap().unwrap();
    }
}