Skip to content

Instantly share code, notes, and snippets.

@Mleekko
Created February 14, 2024 20:36
Show Gist options
  • Save Mleekko/c3d6689a8b993a468f83220579ab04eb to your computer and use it in GitHub Desktop.
Save Mleekko/c3d6689a8b993a468f83220579ab04eb to your computer and use it in GitHub Desktop.
TestRunner snapshot example
/* A proof-of-concept for reusing a TestRunner after long-running init (e.g. deploying the initial packages) to speed up tests. */
//
use std::sync::{Once};
static mut SNAP: Option<TestRunnerSnapshot> = None;
static mut DATA: Option<TestData> = None;
static INIT: Once = Once::new();
/* The data that is set during init and needs to be shared with all the tests */
#[derive(Clone)]
pub struct TestData {
pub public_key: Secp256k1PublicKey,
pub account_address: ComponentAddress,
// .....
pub some_resource: ResourceAddress,
}
// .....
pub struct TestEnvironment {
test_runner: TestRunner<NoExtension, InMemorySubstateDatabase>,
data: TestData,
}
impl TestEnvironment {
pub fn instantiate_test() -> Self {
unsafe {
/* With `Once` this block of code is executed just once, then all further invocations are skipped. */
INIT.call_once(|| {
let (test_runner, data) = Self::do_instantiate_test();
SNAP = Some(test_runner.create_snapshot().clone());
DATA = Some(data);
});
Self {
test_runner: TestRunnerBuilder::new().build_from_snapshot((&SNAP.as_ref()).unwrap().clone()),
data: (&DATA.as_ref()).unwrap().clone(),
}
}
}
fn do_instantiate_test() -> (TestRunner<NoExtension, InMemorySubstateDatabase>, TestData) {
let mut test_runner = TestRunnerBuilder::new().build();
// do your usual init here
// .....
return (test_runner, TestData {
public_key,
account_address,
// .....
some_resource,
});
}
}
#[test]
fn some_test() {
let mut test_env = TestEnvironment::instantiate_test();
// .....
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment