#![cfg(any(feature = "std", feature = "runtime-benchmarks", feature = "try-runtime", test))]
#[must_use]
pub struct StorageNoopGuard(sp_std::vec::Vec<u8>);
impl Default for StorageNoopGuard {
fn default() -> Self {
Self(sp_io::storage::root(sp_runtime::StateVersion::V1))
}
}
impl Drop for StorageNoopGuard {
fn drop(&mut self) {
if sp_std::thread::panicking() {
return
}
assert_eq!(
sp_io::storage::root(sp_runtime::StateVersion::V1),
self.0,
"StorageNoopGuard detected wrongful storage changes.",
);
}
}
#[cfg(test)]
mod tests {
use super::*;
use sp_io::TestExternalities;
#[test]
#[should_panic(expected = "StorageNoopGuard detected wrongful storage changes.")]
fn storage_noop_guard_panics_on_changed() {
TestExternalities::default().execute_with(|| {
let _guard = StorageNoopGuard::default();
frame_support::storage::unhashed::put(b"key", b"value");
});
}
#[test]
fn storage_noop_guard_works_on_unchanged() {
TestExternalities::default().execute_with(|| {
let _guard = StorageNoopGuard::default();
frame_support::storage::unhashed::put(b"key", b"value");
frame_support::storage::unhashed::kill(b"key");
});
}
#[test]
#[should_panic(expected = "StorageNoopGuard detected wrongful storage changes.")]
fn storage_noop_guard_panics_on_early_drop() {
TestExternalities::default().execute_with(|| {
let guard = StorageNoopGuard::default();
frame_support::storage::unhashed::put(b"key", b"value");
sp_std::mem::drop(guard);
frame_support::storage::unhashed::kill(b"key");
});
}
#[test]
fn storage_noop_guard_works_on_changed_forget() {
TestExternalities::default().execute_with(|| {
let guard = StorageNoopGuard::default();
frame_support::storage::unhashed::put(b"key", b"value");
sp_std::mem::forget(guard);
});
}
#[test]
#[should_panic(expected = "Something else")]
fn storage_noop_guard_does_not_double_panic() {
TestExternalities::default().execute_with(|| {
let _guard = StorageNoopGuard::default();
frame_support::storage::unhashed::put(b"key", b"value");
panic!("Something else");
});
}
}