abstract_testing/mock_querier.rs
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 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
use std::{collections::HashMap, ops::Deref};
use abstract_std::{
native_addrs,
objects::{
gov_type::GovernanceDetails, ownership::Ownership,
storage_namespaces::OWNERSHIP_STORAGE_KEY,
},
};
use cosmwasm_std::{
testing::MockApi, Addr, Binary, CodeInfoResponse, ContractInfoResponse, ContractResult, Empty,
QuerierWrapper, SystemResult, WasmQuery,
};
use cw2::{ContractVersion, CONTRACT};
use cw_storage_plus::{Item, Map, PrimaryKey};
use serde::{de::DeserializeOwned, Serialize};
use crate::prelude::*;
type BinaryQueryResult = Result<Binary, String>;
type FallbackHandler = dyn for<'a> Fn(&'a Addr, &'a Binary) -> BinaryQueryResult;
type SmartHandler = dyn for<'a> Fn(&'a Binary) -> BinaryQueryResult;
type RawHandler = dyn for<'a> Fn(&'a str) -> BinaryQueryResult;
/// [`MockQuerierBuilder`] is a helper to build a [`MockQuerier`].
/// Usage:
///
/// ```
/// use cosmwasm_std::{from_json, to_json_binary};
/// use abstract_testing::MockQuerierBuilder;
/// use cosmwasm_std::testing::{MockQuerier, MockApi};
/// use abstract_sdk::mock_module::MockModuleExecuteMsg;
///
/// let api = MockApi::default();
/// let contract_address = api.addr_make("contract_address");
/// let querier = MockQuerierBuilder::default().with_smart_handler(&contract_address, |msg| {
/// // handle the message
/// let res = match from_json::<MockModuleExecuteMsg>(msg).unwrap() {
/// // handle the message
/// _ => panic!("unexpected message"),
/// };
///
/// Ok(to_json_binary(&msg).unwrap())
/// }).build();
/// ```
pub struct MockQuerierBuilder {
base: MockQuerier,
fallback_raw_handler: Box<FallbackHandler>,
fallback_smart_handler: Box<FallbackHandler>,
smart_handlers: HashMap<Addr, Box<SmartHandler>>,
raw_handlers: HashMap<Addr, Box<RawHandler>>,
raw_mappings: HashMap<Addr, HashMap<Binary, Binary>>,
contract_admin: HashMap<Addr, Addr>,
// Used for Address generation
pub api: MockApi,
}
impl Default for MockQuerierBuilder {
/// Create a default
fn default() -> Self {
Self::new(MockApi::default())
}
}
impl MockQuerierBuilder {
pub fn new(api: MockApi) -> Self {
let raw_fallback: fn(&Addr, &Binary) -> BinaryQueryResult = |addr, key| {
let str_key = std::str::from_utf8(key.as_slice()).unwrap();
Err(format!(
"No raw query handler for {addr:?} with key {str_key:?}"
))
};
let smart_fallback: fn(&Addr, &Binary) -> BinaryQueryResult = |addr, key| {
let str_key = std::str::from_utf8(key.as_slice()).unwrap();
Err(format!(
"unexpected smart-query on contract: {addr:?} {str_key:?}"
))
};
Self {
base: MockQuerier::default(),
fallback_raw_handler: Box::from(raw_fallback),
fallback_smart_handler: Box::from(smart_fallback),
smart_handlers: HashMap::default(),
raw_handlers: HashMap::default(),
raw_mappings: HashMap::default(),
contract_admin: HashMap::default(),
api,
}
}
}
pub fn map_key<'a, K, V>(map: &Map<K, V>, key: K) -> String
where
V: Serialize + DeserializeOwned,
K: PrimaryKey<'a>,
{
String::from_utf8(raw_map_key(map, key)).unwrap()
}
pub fn raw_map_key<'a, K, V>(map: &Map<K, V>, key: K) -> Vec<u8>
where
V: Serialize + DeserializeOwned,
K: PrimaryKey<'a>,
{
map.key(key).deref().to_vec()
}
impl MockQuerierBuilder {
pub fn with_fallback_smart_handler<SH>(mut self, handler: SH) -> Self
where
SH: 'static + Fn(&Addr, &Binary) -> BinaryQueryResult,
{
self.fallback_smart_handler = Box::new(handler);
self
}
pub fn with_fallback_raw_handler<RH>(mut self, handler: RH) -> Self
where
RH: 'static + Fn(&Addr, &Binary) -> BinaryQueryResult,
{
self.fallback_raw_handler = Box::new(handler);
self
}
/// Add a smart query contract handler to the mock querier. The handler will be called when the
/// contract address is queried with the given message.
/// Usage:
/// ```rust
/// use cosmwasm_std::{from_json, to_json_binary};
/// use abstract_testing::MockQuerierBuilder;
/// use cosmwasm_std::testing::{MockQuerier, MockApi};
/// use abstract_sdk::mock_module::{MockModuleQueryMsg, MockModuleQueryResponse};
///
/// let api = MockApi::default();
/// let contract_address = api.addr_make("contract_address");
/// let querier = MockQuerierBuilder::default().with_smart_handler(&contract_address, |msg| {
/// // handle the message
/// let res = match from_json::<MockModuleQueryMsg>(msg).unwrap() {
/// // handle the message
/// MockModuleQueryMsg =>
/// return to_json_binary(&MockModuleQueryResponse {}).map_err(|e| e.to_string())
/// };
/// }).build();
///
/// ```
pub fn with_smart_handler<SH>(mut self, contract: &Addr, handler: SH) -> Self
where
SH: 'static + Fn(&Binary) -> BinaryQueryResult,
{
self.smart_handlers
.insert(contract.clone(), Box::new(handler));
self
}
/// Add a raw query contract handler to the mock querier. The handler will be called when the
/// contract address is queried with the given message.
/// Usage:
///
/// ```rust
/// use cosmwasm_std::{from_json, to_json_binary};
/// use abstract_testing::MockQuerierBuilder;
/// use cosmwasm_std::testing::{MockQuerier, MockApi};
/// use abstract_sdk::mock_module::{MockModuleQueryMsg, MockModuleQueryResponse};
///
/// let api = MockApi::default();
/// let contract_address = api.addr_make("contract1");
/// let querier = MockQuerierBuilder::default().with_raw_handler(&contract_address, |key: &str| {
/// // Example: Let's say, in the raw storage, the key "the key" maps to the value "the value"
/// match key {
/// "the key" => to_json_binary("the value").map_err(|e| e.to_string()),
/// _ => to_json_binary("").map_err(|e| e.to_string())
/// }
/// }).build();
/// ```
pub fn with_raw_handler<RH>(mut self, contract: &Addr, handler: RH) -> Self
where
RH: 'static + Fn(&str) -> BinaryQueryResult,
{
self.raw_handlers
.insert(contract.clone(), Box::new(handler));
self
}
fn insert_contract_key_value(&mut self, contract: &Addr, key: Vec<u8>, value: Binary) {
let raw_map = self.raw_mappings.entry(contract.clone()).or_default();
raw_map.insert(Binary::new(key), value);
}
/// Add a map entry to the querier for the given contract.
/// ```rust
/// use cw_storage_plus::Map;
/// use cosmwasm_std::testing::MockApi;
/// use abstract_testing::MockQuerierBuilder;
///
/// let api = MockApi::default();
/// let contract_address = api.addr_make("contract1");
///
/// const MAP: Map<String, String> = Map::new("map");
///
/// MockQuerierBuilder::default()
/// .with_contract_map_entry(
/// &contract_address,
/// MAP,
/// ("key".to_string(), "value".to_string())
/// );
pub fn with_contract_map_entry<'a, K, V>(
self,
contract: &Addr,
cw_map: Map<K, V>,
entry: (K, V),
) -> Self
where
K: PrimaryKey<'a>,
V: Serialize + DeserializeOwned,
{
self.with_contract_map_entries(contract, cw_map, vec![entry])
}
pub fn with_contract_map_entries<'a, K, V>(
mut self,
contract: &Addr,
cw_map: Map<K, V>,
entries: Vec<(K, V)>,
) -> Self
where
K: PrimaryKey<'a>,
V: Serialize + DeserializeOwned,
{
for (key, value) in entries {
self.insert_contract_key_value(
contract,
raw_map_key(&cw_map, key),
to_json_binary(&value).unwrap(),
);
}
self
}
/// Add an empty map key to the querier for the given contract.
/// This is useful when you want the item to exist, but not have a value.
pub fn with_contract_map_key<'a, K, V>(
mut self,
contract: &Addr,
cw_map: Map<K, V>,
key: K,
) -> Self
where
K: PrimaryKey<'a>,
V: Serialize + DeserializeOwned,
{
self.insert_contract_key_value(contract, raw_map_key(&cw_map, key), Binary::default());
self
}
/// Add an empty item key to the querier for the given contract.
/// This is useful when you want the item to exist, but not have a value.
pub fn with_empty_contract_item<T>(mut self, contract: &Addr, cw_item: Item<T>) -> Self
where
T: Serialize + DeserializeOwned,
{
self.insert_contract_key_value(contract, cw_item.as_slice().to_vec(), Binary::default());
self
}
/// Include a contract item in the mock querier.
/// ```rust
/// use cw_storage_plus::Item;
/// use cosmwasm_std::testing::MockApi;
/// use abstract_testing::MockQuerierBuilder;
///
/// let api = MockApi::default();
/// let contract_address = api.addr_make("contract1");
///
/// const ITEM: Item<String> = Item::new("item");
///
/// MockQuerierBuilder::default()
/// .with_contract_item(
/// &contract_address,
/// ITEM,
/// &"value".to_string(),
/// );
/// ```
pub fn with_contract_item<T>(mut self, contract: &Addr, cw_item: Item<T>, value: &T) -> Self
where
T: Serialize + DeserializeOwned,
{
self.insert_contract_key_value(
contract,
cw_item.as_slice().to_vec(),
to_json_binary(value).unwrap(),
);
self
}
/// Add a specific version of the contract to the mock querier.
/// ```rust
/// use abstract_testing::MockQuerierBuilder;
/// use cosmwasm_std::testing::MockApi;
///
/// let api = MockApi::default();
/// let contract_address = api.addr_make("contract1");
///
/// MockQuerierBuilder::default()
/// .with_contract_version(&contract_address, "contract1", "v1.0.0");
/// ```
pub fn with_contract_version(
self,
contract: &Addr,
name: impl Into<String>,
version: impl Into<String>,
) -> Self {
self.with_contract_item(
contract,
CONTRACT,
&ContractVersion {
contract: name.into(),
version: version.into(),
},
)
}
/// set the SDK-level contract admin for a contract.
pub fn with_contract_admin(mut self, contract: &Addr, admin: &Addr) -> Self {
self.contract_admin.insert(contract.clone(), admin.clone());
self
}
/// Build the [`MockQuerier`].
pub fn build(mut self) -> MockQuerier {
self.base.update_wasm(move |wasm| {
let res = match wasm {
WasmQuery::Raw { contract_addr, key } => {
let str_key = std::str::from_utf8(key.as_slice()).unwrap();
let addr = Addr::unchecked(contract_addr);
// First check for raw mappings
if let Some(raw_map) = self.raw_mappings.get(&addr) {
if let Some(value) = raw_map.get(key) {
return SystemResult::Ok(ContractResult::Ok(value.clone()));
}
}
// Then check the handlers
let raw_handler = self.raw_handlers.get(&addr);
match raw_handler {
Some(handler) => (*handler)(str_key),
None => (*self.fallback_raw_handler)(&addr, key),
}
}
WasmQuery::Smart { contract_addr, msg } => {
let addr = Addr::unchecked(contract_addr);
let contract_handler = self.smart_handlers.get(&addr);
match contract_handler {
Some(handler) => (*handler)(msg),
None => (*self.fallback_smart_handler)(&addr, msg),
}
}
WasmQuery::ContractInfo { contract_addr } => {
let addr = Addr::unchecked(contract_addr);
let creator = self.api.addr_make(crate::OWNER);
let info = ContractInfoResponse::new(
1,
creator,
self.contract_admin.get(&addr).map(Addr::unchecked),
false,
None,
);
Ok(to_json_binary(&info).unwrap())
}
WasmQuery::CodeInfo { code_id } => {
let creator = self.api.addr_make(crate::OWNER);
let checksum = native_addrs::BLOB_CHECKSUM;
let code_info = CodeInfoResponse::new(*code_id, creator, checksum.into());
Ok(to_json_binary(&code_info).unwrap())
}
unexpected => panic!("Unexpected query: {unexpected:?}"),
};
match res {
Ok(res) => SystemResult::Ok(ContractResult::Ok(res)),
Err(e) => SystemResult::Ok(ContractResult::Err(e)),
}
});
self.base
}
}
pub trait MockQuerierOwnership {
/// Add the [`cw_gov_ownable::Ownership`] to the querier.
fn with_owner(self, contract: &Addr, owner: Option<&Addr>) -> Self;
}
impl MockQuerierOwnership for MockQuerierBuilder {
fn with_owner(mut self, contract: &Addr, owner: Option<&Addr>) -> Self {
let owner = if let Some(owner) = owner {
GovernanceDetails::Monarchy {
monarch: owner.clone(),
}
} else {
GovernanceDetails::Renounced {}
};
self = self.with_contract_item(
contract,
Item::new(OWNERSHIP_STORAGE_KEY),
&Ownership {
owner,
pending_owner: None,
pending_expiry: None,
},
);
self
}
}
pub fn wrap_querier(querier: &MockQuerier) -> QuerierWrapper<'_, Empty> {
QuerierWrapper::<Empty>::new(querier)
}
#[cfg(test)]
mod tests {
use abstract_std::{
account::state::{ACCOUNT_ID, ACCOUNT_MODULES},
objects::ABSTRACT_ACCOUNT_ID,
registry::state::ACCOUNT_ADDRESSES,
};
use super::*;
use cosmwasm_std::testing::mock_dependencies;
mod account {
use abstract_std::registry::Account;
use crate::abstract_mock_querier_builder;
use super::*;
#[test]
fn should_return_admin_account_address() {
let mut deps = mock_dependencies();
deps.querier = abstract_mock_querier(deps.api);
let abstr = AbstractMockAddrs::new(deps.api);
let actual = ACCOUNT_ADDRESSES.query(
&wrap_querier(&deps.querier),
abstr.registry,
&ABSTRACT_ACCOUNT_ID,
);
let expected = abstr.account;
assert_eq!(actual, Ok(Some(expected)));
}
#[test]
fn should_return_account_address() {
let mut deps = mock_dependencies();
let account = Account::new(deps.api.addr_make("my_account"));
deps.querier = abstract_mock_querier_builder(deps.api)
.account(&account, TEST_ACCOUNT_ID)
.build();
let abstr = AbstractMockAddrs::new(deps.api);
let actual = ACCOUNT_ADDRESSES.query(
&wrap_querier(&deps.querier),
abstr.registry,
&TEST_ACCOUNT_ID,
);
assert_eq!(actual, Ok(Some(account)));
}
}
mod queries {
use super::*;
use abstract_sdk::mock_module::{MockModuleQueryMsg, MockModuleQueryResponse};
use cosmwasm_std::QueryRequest;
#[test]
fn smart_query() {
let api = MockApi::default();
// ## ANCHOR: smart_query
let contract_address = api.addr_make("contract_address");
let querier = MockQuerierBuilder::default()
.with_smart_handler(&contract_address, |msg| {
// handle the message
let MockModuleQueryMsg {} = from_json::<MockModuleQueryMsg>(msg).unwrap();
to_json_binary(&MockModuleQueryResponse {}).map_err(|e| e.to_string())
})
.build();
// ## ANCHOR_END: smart_query
let resp_bin = querier
.handle_query(&QueryRequest::Wasm(WasmQuery::Smart {
contract_addr: contract_address.to_string(),
msg: to_json_binary(&MockModuleQueryMsg {}).unwrap(),
}))
.unwrap()
.unwrap();
let resp: MockModuleQueryResponse = from_json(resp_bin).unwrap();
assert_eq!(resp, MockModuleQueryResponse {});
}
#[test]
fn raw_query() {
let api = MockApi::default();
// ## ANCHOR: raw_query
let contract_address = api.addr_make("contract_address");
let querier = MockQuerierBuilder::default()
.with_raw_handler(&contract_address, |key: &str| {
// Example: Let's say, in the raw storage, the key "the_key" maps to the value "the_value"
match key {
"the_key" => to_json_binary("the_value").map_err(|e| e.to_string()),
_ => to_json_binary("").map_err(|e| e.to_string()),
}
})
.build();
// ## ANCHOR_END: raw_query
let resp_bin = querier
.handle_query(&QueryRequest::Wasm(WasmQuery::Raw {
contract_addr: contract_address.to_string(),
key: Binary::from("the_key".joined_key()),
}))
.unwrap()
.unwrap();
let resp: String = from_json(resp_bin).unwrap();
assert_eq!(resp, "the_value");
}
}
mod account_id {
use crate::abstract_mock_querier_builder;
use super::*;
#[test]
fn should_return_admin_acct_id() {
let mut deps = mock_dependencies();
deps.querier = abstract_mock_querier(deps.api);
let root_account = admin_account(deps.api);
let actual =
ACCOUNT_ID.query(&wrap_querier(&deps.querier), root_account.addr().clone());
assert_eq!(actual, Ok(ABSTRACT_ACCOUNT_ID));
}
#[test]
fn should_return_test_acct_id() {
let mut deps = mock_dependencies();
let test_base = test_account(deps.api);
deps.querier = abstract_mock_querier_builder(deps.api)
.account(&test_base, TEST_ACCOUNT_ID)
.build();
let actual = ACCOUNT_ID.query(&wrap_querier(&deps.querier), test_base.into_addr());
assert_eq!(actual, Ok(TEST_ACCOUNT_ID));
}
}
mod account_modules {
use super::*;
#[test]
fn should_return_test_module_address_for_test_module() {
let mut deps = mock_dependencies();
deps.querier = abstract_mock_querier(deps.api);
let abstr = AbstractMockAddrs::new(deps.api);
let actual = ACCOUNT_MODULES.query(
&wrap_querier(&deps.querier),
abstr.account.into_addr(),
TEST_MODULE_ID,
);
assert_eq!(actual, Ok(Some(abstr.module_address)));
}
// #[test]
// fn should_return_none_for_unknown_module() {
// let mut deps = mock_dependencies();
// deps.querier = querier();
//
// let actual = ACCOUNT_MODULES.query(
// &wrap_querier(&deps.querier),
// Addr::unchecked(TEST_ACCOUNT),
// "unknown_module",
// );
//
// assert_that!(actual).is_ok().is_none();
// }
}
}