Skip to content

Commit

Permalink
feat(contracts): add a test-utils crate
Browse files Browse the repository at this point in the history
  • Loading branch information
alexfertel committed Mar 20, 2024
1 parent fe89215 commit 8207d37
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 2 deletions.
9 changes: 8 additions & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
[workspace]
members = ["contracts/token", "lib/crypto", "lib/wavm-shims"]
members = ["contracts/*", "lib/*"]
# Explicitly set the resolver to version 2, which is the default for packages
# with edition >= 2021.
# https://doc.rust-lang.org/edition-guide/rust-2021/default-cargo-resolver.html
Expand Down
12 changes: 12 additions & 0 deletions contracts/test-utils/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
[package]
name = "test-utils"
categories = []
description = "Test utilities"
edition.workspace = true
keywords.workspace = true
license.workspace = true
repository.workspace = true
version = "0.1.0"

[dependencies]
wavm-shims = { path = "../../lib/wavm-shims" }
26 changes: 26 additions & 0 deletions contracts/test-utils/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
//! Unit-testing utilities for Stylus contracts.
use std::sync::{Mutex, MutexGuard};

pub use wavm_shims::*;

/// A global static mutex.
///
/// We use this for scenarios where concurrent mutation of storage is wanted.
/// For example, when a test harness is running, this ensures each test
/// accesses storage in an non-overlapping manner.
///
/// See [`with_storage`].
pub static STORAGE_MUTEX: Mutex<()> = Mutex::new(());

/// Acquires access to storage.
pub fn acquire_storage() -> MutexGuard<'static, ()> {
STORAGE_MUTEX.lock().unwrap()
}

/// Decorates a closure by running it with exclusive access to storage.
pub fn with_storage<C: Default>(closure: impl FnOnce(&mut C)) {
let _lock = acquire_storage();
let mut contract = C::default();
closure(&mut contract);
reset_storage();
}

0 comments on commit 8207d37

Please sign in to comment.