chik_sdk_coinset/
mock_client.rs

1use serde::de::DeserializeOwned;
2use serde::Serialize;
3use serde_json::Value;
4use std::collections::HashMap;
5use std::error::Error;
6use std::sync::Mutex;
7
8use crate::ChikRpcClient;
9
10#[derive(Debug)]
11pub struct MockRpcClient {
12    requests: Mutex<Vec<(String, Value)>>,
13    responses: HashMap<String, String>,
14}
15
16impl MockRpcClient {
17    pub fn new() -> Self {
18        Self {
19            requests: Mutex::new(Vec::new()),
20            responses: HashMap::new(),
21        }
22    }
23
24    pub fn mock_response(&mut self, url: &str, response: &str) {
25        self.responses.insert(url.to_string(), response.to_string());
26    }
27
28    pub fn get_requests(&self) -> Vec<(String, Value)> {
29        self.requests.lock().unwrap().clone()
30    }
31
32    pub fn post(&self, url: &str, json: Value) -> Result<String, Box<dyn Error>> {
33        self.requests.lock().unwrap().push((url.to_string(), json));
34
35        match self.responses.get(url) {
36            Some(response) => Ok(response.clone()),
37            None => Err("No mock response configured for URL".into()),
38        }
39    }
40}
41
42impl Default for MockRpcClient {
43    fn default() -> Self {
44        Self::new()
45    }
46}
47
48impl ChikRpcClient for MockRpcClient {
49    type Error = Box<dyn Error>;
50
51    fn base_url(&self) -> &'static str {
52        "http://api.example.com"
53    }
54
55    async fn make_post_request<R, B>(&self, endpoint: &str, body: B) -> Result<R, Self::Error>
56    where
57        B: Serialize,
58        R: DeserializeOwned,
59    {
60        let url = format!("{}/{}", self.base_url(), endpoint);
61        let body = serde_json::to_value(body)?;
62        let response = self.post(&url, body)?;
63        Ok(serde_json::from_str::<R>(&response)?)
64    }
65}