test: update tests with Error handling

This commit is contained in:
Magamedrasul Ibragimov 2022-11-06 15:25:19 +03:00
parent bd9711d954
commit afa7b33299
4 changed files with 48 additions and 33 deletions

View File

@ -22,7 +22,7 @@ pub type Value = Vec<u8>;
/// Denotes `Error` type, for handling DB interaction errors /// Denotes `Error` type, for handling DB interaction errors
#[derive(Debug)] #[derive(Debug)]
pub struct Error(String); pub struct Error(pub String);
impl std::fmt::Display for Error { impl std::fmt::Display for Error {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {

View File

@ -101,7 +101,7 @@ where
/// Sets a leaf at the specified tree index /// Sets a leaf at the specified tree index
pub fn set(&mut self, key: usize, leaf: H::Fr) -> Result<()> { pub fn set(&mut self, key: usize, leaf: H::Fr) -> Result<()> {
if key < self.capacity() { if key >= self.capacity() {
return Err(Error("Merkle Tree is full!".to_string())); return Err(Error("Merkle Tree is full!".to_string()));
} }
@ -153,7 +153,7 @@ where
/// Deletes a leaf at the `key` by setting it to its default value /// Deletes a leaf at the `key` by setting it to its default value
pub fn delete(&mut self, key: usize) -> Result<()> { pub fn delete(&mut self, key: usize) -> Result<()> {
if key < self.next_index { if key >= self.next_index {
return Err(Error("The key doesn't exist!".to_string())); return Err(Error("The key doesn't exist!".to_string()));
} }

View File

@ -10,20 +10,22 @@ struct MyKeccak(Keccak);
struct MyFr([u8; 32]); struct MyFr([u8; 32]);
impl Database for MemoryDB { impl Database for MemoryDB {
fn new(_dbpath: &str) -> Self { fn new(_dbpath: &str) -> Result<Self> {
MemoryDB(HashMap::new()) Ok(MemoryDB(HashMap::new()))
} }
fn load(_dbpath: &str) -> Self { fn load(_dbpath: &str) -> Result<Self> {
panic!("Cannot load in-memory db!") Err(Error("Cannot load in-memory DB".to_string()))
} }
fn get(&self, key: DBKey) -> Option<Value> { fn get(&self, key: DBKey) -> Result<Option<Value>> {
self.0.get(&key).cloned() Ok(self.0.get(&key).cloned())
} }
fn put(&mut self, key: DBKey, value: Value) { fn put(&mut self, key: DBKey, value: Value) -> Result<()> {
self.0.insert(key, value); self.0.insert(key, value);
Ok(())
} }
} }
@ -59,8 +61,8 @@ impl Hasher for MyKeccak {
} }
#[test] #[test]
fn insert_delete() { fn insert_delete() -> Result<()> {
let mut mt = MerkleTree::<MemoryDB, MyKeccak>::new(2, "abacaba"); let mut mt = MerkleTree::<MemoryDB, MyKeccak>::new(2, "abacaba")?;
assert_eq!(mt.capacity(), 4); assert_eq!(mt.capacity(), 4);
assert_eq!(mt.depth(), 2); assert_eq!(mt.depth(), 2);
@ -75,7 +77,7 @@ fn insert_delete() {
let default_tree_root = let default_tree_root =
hex!("b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"); hex!("b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30");
assert_eq!(mt.root(), MyFr(default_tree_root)); assert_eq!(mt.root()?, MyFr(default_tree_root));
let roots = [ let roots = [
hex!("c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95"), hex!("c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95"),
@ -85,13 +87,17 @@ fn insert_delete() {
]; ];
for i in 0..leaves.len() { for i in 0..leaves.len() {
mt.update_next(MyFr(leaves[i])); mt.update_next(MyFr(leaves[i]))?;
assert_eq!(mt.root(), MyFr(roots[i])); assert_eq!(mt.root()?, MyFr(roots[i]));
} }
for i in (0..leaves.len()).rev() { for i in (0..leaves.len()).rev() {
mt.delete(i); mt.delete(i)?;
} }
assert_eq!(mt.root(), MyFr(default_tree_root)); assert_eq!(mt.root()?, MyFr(default_tree_root));
assert!(mt.update_next(MyFr(leaves[0])).is_err());
Ok(())
} }

View File

@ -10,32 +10,37 @@ struct MySled(sled::Db);
struct MyFr([u8; 32]); struct MyFr([u8; 32]);
impl Database for MySled { impl Database for MySled {
fn new(dbpath: &str) -> Self { fn new(dbpath: &str) -> Result<Self> {
let db = sled::open(dbpath).unwrap(); let db = sled::open(dbpath).unwrap();
assert!(!db.was_recovered(), "Database exists, try load()!"); if db.was_recovered() {
return Err(Error("Database exists, try load()!".to_string()));
}
MySled(db) Ok(MySled(db))
} }
fn load(dbpath: &str) -> Self { fn load(dbpath: &str) -> Result<Self> {
let db = sled::open(dbpath).unwrap(); let db = sled::open(dbpath).unwrap();
if !db.was_recovered() { if !db.was_recovered() {
println!("Hello world"); println!("Hello world");
fs::remove_dir_all(dbpath).expect("Error removing db"); fs::remove_dir_all(dbpath).expect("Error removing db");
panic!("Trying to load non-existing database!"); return Err(Error("Trying to load non-existing database!".to_string()));
} }
MySled(db) Ok(MySled(db))
} }
fn get(&self, key: DBKey) -> Option<Value> { fn get(&self, key: DBKey) -> Result<Option<Value>> {
self.0.get(key).unwrap().map(|val| val.to_vec()) Ok(self.0.get(key).unwrap().map(|val| val.to_vec()))
} }
fn put(&mut self, key: DBKey, value: Value) { fn put(&mut self, key: DBKey, value: Value) -> Result<()> {
self.0.insert(key, value).unwrap(); self.0.insert(key, value).unwrap();
self.0.flush().unwrap(); self.0.flush().unwrap();
Ok(())
} }
} }
@ -71,8 +76,8 @@ impl Hasher for MyKeccak {
} }
#[test] #[test]
fn insert_delete() { fn insert_delete() -> Result<()> {
let mut mt = MerkleTree::<MySled, MyKeccak>::new(2, "abacaba"); let mut mt = MerkleTree::<MySled, MyKeccak>::new(2, "abacaba")?;
assert_eq!(mt.capacity(), 4); assert_eq!(mt.capacity(), 4);
assert_eq!(mt.depth(), 2); assert_eq!(mt.depth(), 2);
@ -87,7 +92,7 @@ fn insert_delete() {
let default_tree_root = let default_tree_root =
hex!("b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30"); hex!("b4c11951957c6f8f642c4af61cd6b24640fec6dc7fc607ee8206a99e92410d30");
assert_eq!(mt.root(), MyFr(default_tree_root)); assert_eq!(mt.root()?, MyFr(default_tree_root));
let roots = [ let roots = [
hex!("c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95"), hex!("c1ba1812ff680ce84c1d5b4f1087eeb08147a4d510f3496b2849df3a73f5af95"),
@ -97,15 +102,19 @@ fn insert_delete() {
]; ];
for i in 0..leaves.len() { for i in 0..leaves.len() {
mt.update_next(MyFr(leaves[i])); mt.update_next(MyFr(leaves[i]))?;
assert_eq!(mt.root(), MyFr(roots[i])); assert_eq!(mt.root()?, MyFr(roots[i]));
} }
for i in (0..leaves.len()).rev() { for i in (0..leaves.len()).rev() {
mt.delete(i); mt.delete(i)?;
} }
assert_eq!(mt.root(), MyFr(default_tree_root)); assert_eq!(mt.root()?, MyFr(default_tree_root));
assert!(mt.update_next(MyFr(leaves[0])).is_err());
fs::remove_dir_all("abacaba").expect("Error removing db"); fs::remove_dir_all("abacaba").expect("Error removing db");
Ok(())
} }