Repository: CosmWasm/cw-multi-test
Pull request #115 (2023-12-18 10:21:18)

Added tests to improve code coverage


Patch:
diff --git a/Cargo.lock b/Cargo.lock
index 3b15d77..2966172 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -868,18 +868,18 @@ dependencies = [
 
 [[package]]
 name = "thiserror"
-version = "1.0.50"
+version = "1.0.51"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f9a7210f5c9a7156bb50aa36aed4c95afb51df0df00713949448cf9e97d382d2"
+checksum = "f11c217e1416d6f036b870f14e0413d480dbf28edbee1f877abaf0206af43bb7"
 dependencies = [
  "thiserror-impl",
 ]
 
 [[package]]
 name = "thiserror-impl"
-version = "1.0.50"
+version = "1.0.51"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "266b2e40bc00e5a6c09c3584011e08b06f123c00362c92b975ba9843aaaa14b8"
+checksum = "01742297787513b79cf8e29d1056ede1313e2420b7b3b15d0a768b4921f549df"
 dependencies = [
  "proc-macro2",
  "quote",
diff --git a/src/bank.rs b/src/bank.rs
index d198e43..63a6f2a 100644
--- a/src/bank.rs
+++ b/src/bank.rs
@@ -193,7 +193,7 @@ impl Module for BankKeeper {
                 self.burn(&mut bank_storage, sender, amount)?;
                 Ok(AppResponse::default())
             }
-            m => bail!("Unsupported bank message: {:?}", m),
+            _ => unimplemented!("bank message: {msg:?}"),
         }
     }
 
@@ -248,7 +248,7 @@ impl Module for BankKeeper {
                 res.amount = amount;
                 Ok(to_json_binary(&res)?)
             }
-            q => bail!("Unsupported bank query: {:?}", q),
+            _ => unimplemented!("bank query: {request:?}",),
         }
     }
 }
diff --git a/src/error.rs b/src/error.rs
index bd2576e..013e0ae 100644
--- a/src/error.rs
+++ b/src/error.rs
@@ -65,6 +65,26 @@ impl Error {
         Self::EventTypeTooShort(ty.into())
     }
 
+    /// Creates an instance of the [Error](Self) for unsupported wasm queries.
+    pub fn unsupported_wasm_query(query: WasmQuery) -> Self {
+        Self::UnsupportedWasmQuery(query)
+    }
+
+    /// Creates an instance of the [Error](Self) for unsupported wasm messages.
+    pub fn unsupported_wasm_message(msg: WasmMsg) -> Self {
+        Self::UnsupportedWasmMsg(msg)
+    }
+
+    /// Creates an instance of the [Error](Self) for invalid contract code identifier.
+    pub fn invalid_contract_code_id() -> Self {
+        Self::InvalidCodeId
+    }
+
+    /// Creates an instance of the [Error](Self) for unregistered contract code identifier.
+    pub fn unregistered_code_id(code_id: u64) -> Self {
+        Self::UnregisteredCodeId(code_id)
+    }
+
     /// Creates an instance of the [Error](Self) for duplicated contract addresses.
     pub fn duplicated_contract_address(address: impl Into<String>) -> Self {
         Self::DuplicatedContractAddress(address.into())
diff --git a/src/prefixed_storage/mod.rs b/src/prefixed_storage/mod.rs
index 0e7a6e4..9e9da86 100644
--- a/src/prefixed_storage/mod.rs
+++ b/src/prefixed_storage/mod.rs
@@ -134,6 +134,35 @@ mod tests {
         assert_eq!(s2.get(b"elsewhere"), None);
     }
 
+    #[test]
+    fn prefixed_storage_range() {
+        // prepare prefixed storage
+        let mut storage = MockStorage::new();
+        let mut ps1 = PrefixedStorage::new(&mut storage, b"foo");
+        ps1.set(b"a", b"A");
+        ps1.set(b"l", b"L");
+        ps1.set(b"p", b"P");
+        ps1.set(b"z", b"Z");
+        assert_eq!(storage.get(b"\x00\x03fooa").unwrap(), b"A".to_vec());
+        assert_eq!(storage.get(b"\x00\x03fool").unwrap(), b"L".to_vec());
+        assert_eq!(storage.get(b"\x00\x03foop").unwrap(), b"P".to_vec());
+        assert_eq!(storage.get(b"\x00\x03fooz").unwrap(), b"Z".to_vec());
+        // query prefixed storage using range function
+        let ps2 = PrefixedStorage::new(&mut storage, b"foo");
+        assert_eq!(
+            vec![b"A".to_vec(), b"L".to_vec(), b"P".to_vec()],
+            ps2.range(Some(b"a"), Some(b"z"), Order::Ascending)
+                .map(|(_, value)| value)
+                .collect::<Vec<Vec<u8>>>()
+        );
+        assert_eq!(
+            vec![b"Z".to_vec(), b"P".to_vec(), b"L".to_vec(), b"A".to_vec()],
+            ps2.range(Some(b"a"), None, Order::Descending)
+                .map(|(_, value)| value)
+                .collect::<Vec<Vec<u8>>>()
+        );
+    }
+
     #[test]
     fn prefixed_storage_multilevel_set_and_get() {
         let mut storage = MockStorage::new();
@@ -167,6 +196,24 @@ mod tests {
         assert_eq!(s2.get(b"obar"), None);
     }
 
+    #[test]
+    #[should_panic(expected = "not implemented")]
+    #[allow(clippy::unnecessary_mut_passed)]
+    fn readonly_prefixed_storage_set() {
+        let mut storage = MockStorage::new();
+        let mut rps = ReadonlyPrefixedStorage::new(&mut storage, b"foo");
+        rps.set(b"bar", b"gotcha");
+    }
+
+    #[test]
+    #[should_panic(expected = "not implemented")]
+    #[allow(clippy::unnecessary_mut_passed)]
+    fn readonly_prefixed_storage_remove() {
+        let mut storage = MockStorage::new();
+        let mut rps = ReadonlyPrefixedStorage::new(&mut storage, b"foo");
+        rps.remove(b"gotcha");
+    }
+
     #[test]
     fn readonly_prefixed_storage_multilevel_get() {
         let mut storage = MockStorage::new();
diff --git a/src/wasm.rs b/src/wasm.rs
index 94c3c46..5ea2e96 100644
--- a/src/wasm.rs
+++ b/src/wasm.rs
@@ -192,7 +192,7 @@ where
                 res.checksum = code_data.checksum.clone();
                 to_json_binary(&res).map_err(Into::into)
             }
-            other => bail!(Error::UnsupportedWasmQuery(other)),
+            _ => unimplemented!("{}", Error::unsupported_wasm_query(request)),
         }
     }
 
@@ -279,12 +279,12 @@ impl<ExecC, QueryC> WasmKeeper<ExecC, QueryC> {
     /// Returns code data of the contract with specified code id.
     fn code_data(&self, code_id: u64) -> AnyResult<&CodeData> {
         if code_id < 1 {
-            bail!(Error::InvalidCodeId);
+            bail!(Error::invalid_contract_code_id());
         }
         Ok(self
             .code_data
             .get((code_id - 1) as usize)
-            .ok_or(Error::UnregisteredCodeId(code_id))?)
+            .ok_or_else(|| Error::unregistered_code_id(code_id))?)
     }
 
     fn contract_namespace(&self, contract: &Addr) -> Vec<u8> {
@@ -553,9 +553,9 @@ where
         router: &dyn CosmosRouter<ExecC = ExecC, QueryC = QueryC>,
         block: &BlockInfo,
         sender: Addr,
-        wasm_msg: WasmMsg,
+        msg: WasmMsg,
     ) -> AnyResult<AppResponse> {
-        match wasm_msg {
+        match msg {
             WasmMsg::Execute {
                 contract_addr,
                 msg,
@@ -668,7 +668,7 @@ where
             WasmMsg::ClearAdmin { contract_addr } => {
                 self.update_admin(api, storage, sender, &contract_addr, None)
             }
-            msg => bail!(Error::UnsupportedWasmMsg(msg)),
+            _ => unimplemented!("{}", Error::unsupported_wasm_message(msg)),
         }
     }
 


Test patch:
diff --git a/src/tests/mod.rs b/src/tests/mod.rs
index 5337022..2f5d209 100644
--- a/src/tests/mod.rs
+++ b/src/tests/mod.rs
@@ -2,6 +2,7 @@
 
 mod test_app;
 mod test_custom_handler;
+mod test_error;
 mod test_gov;
 mod test_ibc;
 mod test_stargate;
diff --git a/src/tests/test_error.rs b/src/tests/test_error.rs
new file mode 100644
index 0000000..eb113e7
--- /dev/null
+++ b/src/tests/test_error.rs
@@ -0,0 +1,50 @@
+use crate::error::Error;
+use cosmwasm_std::{WasmMsg, WasmQuery};
+
+#[test]
+fn instantiating_error_should_work() {
+    assert_eq!(
+        "Empty attribute key. Value: alpha",
+        Error::empty_attribute_key("alpha").to_string()
+    );
+    assert_eq!(
+        "Empty attribute value. Key: beta",
+        Error::empty_attribute_value("beta").to_string()
+    );
+    assert_eq!(
+        "Attribute key starts with reserved prefix _: gamma",
+        Error::reserved_attribute_key("gamma").to_string()
+    );
+    assert_eq!(
+        "Event type too short: event_type",
+        Error::event_type_too_short("event_type").to_string()
+    );
+    assert_eq!(
+        r#"Unsupported wasm query: ContractInfo { contract_addr: "contract1984" }"#,
+        Error::unsupported_wasm_query(WasmQuery::ContractInfo {
+            contract_addr: "contract1984".to_string()
+        })
+        .to_string()
+    );
+    assert_eq!(
+        r#"Unsupported wasm message: Migrate { contract_addr: "contract1984", new_code_id: 1984, msg:  }"#,
+        Error::unsupported_wasm_message(WasmMsg::Migrate {
+            contract_addr: "contract1984".to_string(),
+            new_code_id: 1984,
+            msg: Default::default(),
+        })
+        .to_string()
+    );
+    assert_eq!(
+        "code id: invalid",
+        Error::invalid_contract_code_id().to_string()
+    );
+    assert_eq!(
+        "code id 53: no such code",
+        Error::unregistered_code_id(53).to_string()
+    );
+    assert_eq!(
+        "Contract with this address already exists: contract1984",
+        Error::duplicated_contract_address("contract1984").to_string()
+    );
+}