provwasm_mocks/
querier.rs

1use std::collections::HashMap;
2use std::marker::PhantomData;
3
4use cosmwasm_std::testing::{MockApi, MockQuerier, MockStorage};
5use cosmwasm_std::{
6    from_json, Binary, Coin, Empty, OwnedDeps, Querier, QuerierResult, QueryRequest, SystemError,
7    SystemResult,
8};
9use serde::de::DeserializeOwned;
10
11use provwasm_common::MockableQuerier;
12
13pub struct MockProvenanceQuerier<C: DeserializeOwned = Empty> {
14    /// Default CosmWASM mock querier.
15    pub mock_querier: MockQuerier<C>,
16    /// Registered custom queries using proto request for testing.
17    #[allow(clippy::complexity)]
18    pub registered_custom_queries: HashMap<String, Box<dyn Fn(&Binary) -> QuerierResult>>,
19}
20
21impl MockProvenanceQuerier {
22    /// Initialize a new [`MockProvenanceQuerier`].
23    /// * `balances` - Slice of balances passed to the `bank` module, where the first element
24    /// is the user address and the second element is the user's balance.
25    pub fn new(balances: &[(&str, &[Coin])]) -> Self {
26        MockProvenanceQuerier {
27            mock_querier: MockQuerier::new(balances),
28            registered_custom_queries: HashMap::new(),
29        }
30    }
31    /// Handle the query request.
32    pub fn handle_query(&self, request: &QueryRequest<Empty>) -> QuerierResult {
33        match request {
34            QueryRequest::Stargate { path, data } => {
35                if let Some(response_fn) = self.registered_custom_queries.get(path) {
36                    return response_fn(data);
37                }
38                SystemResult::Err(SystemError::UnsupportedRequest { kind: path.into() })
39            }
40            QueryRequest::Grpc(grpc_query) => {
41                if let Some(response_fn) = self.registered_custom_queries.get(&grpc_query.path) {
42                    return response_fn(&grpc_query.data);
43                }
44                SystemResult::Err(SystemError::UnsupportedRequest {
45                    kind: grpc_query.path.to_string(),
46                })
47            }
48            _ => self.mock_querier.handle_query(request),
49        }
50    }
51}
52
53impl MockableQuerier for MockProvenanceQuerier {
54    fn register_custom_query(
55        &mut self,
56        path: String,
57        response_fn: Box<dyn Fn(&Binary) -> QuerierResult>,
58    ) {
59        self.registered_custom_queries.insert(path, response_fn);
60    }
61}
62
63impl Querier for MockProvenanceQuerier {
64    fn raw_query(&self, bin_request: &[u8]) -> QuerierResult {
65        let request: QueryRequest<Empty> = match from_json(bin_request) {
66            Ok(v) => v,
67            Err(e) => {
68                return SystemResult::Err(SystemError::InvalidRequest {
69                    error: format!("Parsing query request: {}", e),
70                    request: bin_request.into(),
71                });
72            }
73        };
74        self.handle_query(&request)
75    }
76}
77
78impl Default for MockProvenanceQuerier {
79    fn default() -> Self {
80        MockProvenanceQuerier::new(&[])
81    }
82}
83
84/// Creates an instance of [`OwnedDeps`](cosmwasm_std::OwnedDeps) with a custom [`MockProvenanceQuerier`]
85/// to allow the user to mock the query responses of one or more Provenance's modules.
86pub fn mock_provenance_dependencies_with_custom_querier(
87    querier: MockProvenanceQuerier,
88) -> OwnedDeps<MockStorage, MockApi, MockProvenanceQuerier, Empty> {
89    OwnedDeps::<_, _, _, Empty> {
90        storage: MockStorage::default(),
91        api: MockApi::default(),
92        querier,
93        custom_query_type: PhantomData,
94    }
95}
96
97/// Creates an instance of [`OwnedDeps`](cosmwasm_std::OwnedDeps) that is capable of
98/// handling queries towards Provenance's modules.
99pub fn mock_provenance_dependencies(
100) -> OwnedDeps<MockStorage, MockApi, MockProvenanceQuerier, Empty> {
101    mock_provenance_dependencies_with_custom_querier(MockProvenanceQuerier::default())
102}
103
104#[cfg(test)]
105mod test {
106    use cosmwasm_std::{coin, from_binary, BalanceResponse, BankQuery};
107
108    use super::*;
109
110    #[test]
111    fn query_with_balances_2_0() {
112        let amount = coin(12345, "denom");
113        let querier = MockProvenanceQuerier::new(&[("alice", &[amount.clone()])]);
114        let deps = mock_provenance_dependencies_with_custom_querier(querier);
115        let bin = deps
116            .querier
117            .handle_query(
118                &BankQuery::Balance {
119                    address: "alice".into(),
120                    denom: "denom".into(),
121                }
122                .into(),
123            )
124            .unwrap()
125            .unwrap();
126
127        let res: BalanceResponse = from_binary(&bin).unwrap();
128        assert_eq!(res.amount, amount);
129    }
130}