use crate::{Database, Error, Schema};
use ic_storage::{
AllocationGrants, GenericAllocationPolicy, MemoryAuthority, MemoryRequest, MemoryRuntime,
RuntimeMemory, SealedDeclarationSnapshot, StableKey, VectorMemory,
};
pub struct Fixture {
allocation: Box<dyn Fn() -> RuntimeMemory<VectorMemory>>,
}
impl Fixture {
#[must_use]
pub fn new(key: &str) -> Self {
let key = StableKey::parse(key).expect("invalid fixture allocation key");
let (namespace, _) = key.as_str().rsplit_once('.').expect("versioned stable key");
let grants = AllocationGrants::new(vec![
MemoryAuthority::new("fixture", format!("{namespace}.")).unwrap(),
])
.unwrap();
let declarations = SealedDeclarationSnapshot::new(vec![
MemoryRequest::new("fixture", key.as_str()).unwrap(),
])
.unwrap();
let backing = VectorMemory::default();
Self::with_allocation(move || {
let mut runtime = MemoryRuntime::new(backing.clone())
.expect("drop the previous database before reopening its backing");
runtime
.bootstrap(&declarations, &grants, &GenericAllocationPolicy)
.expect("fixture storage bootstrap");
runtime.open_memory(&key).expect("fixture allocation")
})
}
#[must_use]
pub fn with_allocation(allocation: impl Fn() -> RuntimeMemory<VectorMemory> + 'static) -> Self {
drop(allocation());
Self {
allocation: Box::new(allocation),
}
}
pub fn create(
&self,
schema: Schema,
incarnation: [u8; 16],
) -> Result<Database<VectorMemory>, Error> {
Database::create((self.allocation)(), schema, incarnation)
}
pub fn open(&self, schema: Schema) -> Result<Database<VectorMemory>, Error> {
Database::open((self.allocation)(), schema)
}
}