问题描述
这是我的测试:
assert_noop!(
TemplateModule::commit_Vote(
Origin::signed(5),count - 1,"2-Votinghash".as_bytes().to_vec()
),Error::<Test>::AlreadyCommitUsed
);
thread 'tests::commit_Vote' panicked at 'assertion Failed: `(left == right)`
left: `Err(dispatchError::Module { index: 1,error: 7,message: Some("AlreadyCommitUsed") })`,right: `Err(dispatchError::Module { index: 1,error: 4,message: Some("DepartmentNotAssociated") })`',pallets/template/src/tests.rs:106:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
当我添加 AlreadyCommitUsed 作为错误时,它给出了以下奇怪的不等式:
thread 'tests::commit_Vote' panicked at 'assertion Failed: `(left == right)`
left: `[218,23,247,200,228,182,117,227,150,32,248,47,209,207,246,198,19,20,74,185,125,35,94,161,128,199,114,155,238,228]`,right: `[128,69,167,50,250,133,59,10,41,100,95,141,187,236,154,67,174,251,17,219,45,146,204,77,245,38,131,122,48]`',pallets/template/src/tests.rs:106:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
#[weight = 10_000 + T::DbWeight::get().reads_writes(3,3)]
pub fn commit_Vote(origin,departmentid:u128,voting_cycle:u128,Vote_commit:Vec<u8>) -> dispatch::dispatchResult {
let who = ensure_signed(origin.clone())?;
Self::check_citizen_associated_department(who.clone(),departmentid)?;
let status = VoteStatus::get((departmentid,voting_cycle,Vote_commit.clone()));
match status {
Some(value) => {
if value == true {
Err(Error::<T>::AlreadyCommitUsed.into())
} else {
Err(Error::<T>::VoteRevealed.into())
}
}
None => {
Self::add_Vote(departmentid,Vote_commit)?;
Ok(())
}
}
}
这是我的辅助函数:
// Helper functions
impl<T: Config> Module<T> {
fn check_citizen_associated_department(
who: T::AccountId,departmentid: u128,) -> dispatch::dispatchResult {
let approved_peer_dep = PeerDepartments::<T>::get(&who);
match approved_peer_dep.binary_search(&departmentid) {
Ok(_) => {
Self::deposit_event(RawEvent::PeerDepartment(departmentid,who));
Ok(())
}
Err(_) => Err(Error::<T>::DepartmentNotAssociated.into()),}
}
}
是的,错误是由于辅助函数,删除 deposit_event
的 check_citizen_associated_department
后错误消失。不知道写辅助函数是否正确。
解决方法
这个错误:
thread 'tests::commit_vote' panicked at 'assertion failed: `(left == right)`
left: `[218,23,247,200,228,182,117,227,150,32,248,47,209,207,246,198,19,20,74,185,125,35,94,161,128,199,114,155,238,228]`,right: `[128,69,167,50,250,133,59,10,41,100,95,141,187,236,154,67,174,251,17,219,45,146,204,77,245,38,131,122,48]`',pallets/template/src/tests.rs:106:5
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
告诉你你的外部导致了错误,但你也改变了运行时的状态。这违反了如何使用 Substrate 的规则。
这就是 assert_noop!
宏的用途:
https://crates.parity.io/frame_support/macro.assert_noop.html
有一个策略是所有外部变量都必须是“首先检查,最后写入”,因为当您实际修改运行时状态时,应该不会发生错误。
问题似乎是您在 check_citizen_associated_department
中发出一个事件,该事件会修改状态,但随后可能会在 match status
中出错。
您需要修正您的逻辑,以便仅在您知道其他一切都会成功时才发出事件。