Skip to main content

ic_testkit/pic/
baseline.rs

1use super::{
2    CanisterSnapshotTarget, ControllerSnapshotError, ControllerSnapshots, PocketIcInstance,
3    PocketIcSnapshotExt, SnapshotRestoreFunding,
4};
5use candid::Principal;
6use pocket_ic::PocketIc;
7
8/// One owned PocketIC instance/server record with snapshots and caller metadata.
9///
10/// The value contains no synchronization. A [`super::PocketIcBaselineRecipe`]
11/// can own it as its fixture in a [`super::CachedPocketIcBaselinePool`].
12pub struct CachedPocketIcBaseline<T> {
13    instance: PocketIcInstance<PocketIc>,
14    snapshots: ControllerSnapshots,
15    metadata: T,
16}
17
18impl<T> CachedPocketIcBaseline<T> {
19    /// Capture a cached baseline with an explicit sender for every canister.
20    ///
21    /// Capture is ordered and transactional as documented by
22    /// [`PocketIcSnapshotExt::capture_snapshots`]. No sender fallback is performed.
23    pub fn capture<I>(
24        instance: PocketIcInstance<PocketIc>,
25        targets: I,
26        metadata: T,
27    ) -> Result<Self, ControllerSnapshotError>
28    where
29        I: IntoIterator<Item = CanisterSnapshotTarget>,
30    {
31        let snapshots = instance.instance.capture_snapshots(targets)?;
32        Ok(Self {
33            instance,
34            snapshots,
35            metadata,
36        })
37    }
38
39    /// Restore with exactly the captured senders and selected cycle funding.
40    pub fn restore(&self, funding: SnapshotRestoreFunding) -> Result<(), ControllerSnapshotError> {
41        self.instance
42            .instance
43            .restore_snapshots(&self.snapshots, funding)
44    }
45
46    /// Borrow the owned PocketIC instance behind this cached baseline.
47    #[must_use]
48    pub const fn pocket_ic(&self) -> &PocketIc {
49        &self.instance.instance
50    }
51
52    /// Return the number of canisters captured by this baseline.
53    #[must_use]
54    pub fn snapshot_count(&self) -> usize {
55        self.snapshots.len()
56    }
57
58    /// Iterate over captured canister ids in deterministic principal order.
59    pub fn snapshot_canister_ids(&self) -> impl Iterator<Item = Principal> + '_ {
60        self.snapshots.canister_ids()
61    }
62
63    /// Borrow the captured metadata associated with this cached baseline.
64    #[must_use]
65    pub const fn metadata(&self) -> &T {
66        &self.metadata
67    }
68
69    /// Mutably borrow the captured metadata associated with this cached baseline.
70    #[must_use]
71    pub const fn metadata_mut(&mut self) -> &mut T {
72        &mut self.metadata
73    }
74}