Skip to main content

coven/
test_utils.rs

1//! Installations for application tests: an isolated in-memory keychain and
2//! a network the test drives, with the production store graph.
3
4use super::Coven;
5use crate::*;
6use coven_crypto::custody::{Keychain, KeyringCustody, StoreKeychain};
7use coven_foundation::files::{FileBudget, StoreDirectories};
8use coven_foundation::network_watch::{NetworkSource, TestNetwork};
9use std::path::{Path, PathBuf};
10use std::sync::Arc;
11
12#[cfg(test)]
13#[path = "test_utils_tests.rs"]
14mod tests;
15
16impl Coven {
17    /// An installation for a test: its stores under `app_dir`, a keychain
18    /// with no device-only entries and none of the person's entries, isolated
19    /// from the OS and other tests, and a usable network that isn't metered,
20    /// which the test drives. A new one simulates another device; keep one to
21    /// test reopening.
22    pub fn in_memory(app_dir: PathBuf) -> Self {
23        Self::in_memory_reporting_to(app_dir, crate::task::HeardBugs::shared())
24    }
25
26    /// `in_memory`, whose bugs in work nobody waits for go to `bugs`, for a
27    /// test that hears them (E15).
28    pub fn in_memory_reporting_to(app_dir: PathBuf, bugs: crate::task::BugSinkRef) -> Self {
29        Self::testing(app_dir, Keychain::in_memory("coven-test").expect("valid service name"), bugs)
30    }
31
32    /// `in_memory`, whose bugs go to `bugs` and whose places for open files
33    /// are `files`, the budget an app's test shares with the library's own
34    /// reads of files.
35    pub fn in_memory_sharing(
36        app_dir: PathBuf,
37        bugs: crate::task::BugSinkRef,
38        files: FileBudget,
39    ) -> Self {
40        Self {
41            files,
42            ..Self::testing(
43                app_dir,
44                Keychain::in_memory("coven-test").expect("valid service name"),
45                bugs,
46            )
47        }
48    }
49
50    /// An installation, as `in_memory` makes, whose keychain's device-only
51    /// entries are the ones `save_device_keychain` saved at `path`: the same
52    /// device again, which opens the stores it had, as a test reopens a kept
53    /// copy of a store in another process. Its person entries start empty.
54    pub fn in_memory_with_saved_keychain(app_dir: PathBuf, path: &Path) -> Result<Self, KeyError> {
55        Ok(Self::testing(
56            app_dir,
57            Keychain::in_memory_with_saved_device_entries("coven-test", path)?,
58            crate::task::HeardBugs::shared(),
59        ))
60    }
61
62    /// An installation on an Android phone: its person entries behave as
63    /// Block Store keeps them, this phone's own, with Block Store's limits
64    /// (§13.1).
65    pub fn with_block_store(app_dir: PathBuf) -> Self {
66        Self::testing(
67            app_dir,
68            Keychain::in_memory_block_store("coven-test").expect("valid service name"),
69            crate::task::HeardBugs::shared(),
70        )
71    }
72
73    /// An installation for a test with the keychain `keychain`, such as one
74    /// failing on cue.
75    #[cfg(test)]
76    pub(crate) fn with_keychain(app_dir: PathBuf, keychain: Arc<Keychain>) -> Self {
77        Self::testing(app_dir, keychain, crate::task::HeardBugs::shared())
78    }
79
80    /// An installation for a test with the keychain `keychain`, whose bugs
81    /// in work nobody waits for go to `bugs` (E15).
82    #[cfg(test)]
83    pub(crate) fn with_keychain_reporting_to(
84        app_dir: PathBuf,
85        keychain: Arc<Keychain>,
86        bugs: crate::task::BugSinkRef,
87    ) -> Self {
88        Self::testing(app_dir, keychain, bugs)
89    }
90
91    /// The app directory's stores, for a test that begins a bootstrap or a
92    /// replacement itself.
93    #[cfg(test)]
94    pub(crate) fn directories(&self) -> &StoreDirectories {
95        &self.directories
96    }
97
98    fn testing(app_dir: PathBuf, keychain: Arc<Keychain>, bugs: crate::task::BugSinkRef) -> Self {
99        Self {
100            directories: StoreDirectories::new(app_dir, bugs),
101            keychain,
102            network: NetworkSource::Test(TestNetwork::new(true, false)),
103            // Another device is another process: each installation made for a
104            // test has places of its own.
105            files: FileBudget::for_test(),
106        }
107    }
108
109    /// Another device of the same person, its stores under `app_dir`: an
110    /// installation with its own empty device-only keychain. With iCloud
111    /// Keychain it shares this one's person entries, as iCloud Keychain
112    /// carries a restore code and S3 key between the person's devices; with
113    /// Block Store it has its own, empty.
114    pub fn another_device(&self, app_dir: PathBuf) -> Self {
115        Self::testing(app_dir, self.keychain.another_device(), self.directories.bugs().clone())
116    }
117
118    /// A new phone set up from this one by direct transfer, its stores under
119    /// `app_dir`: nothing of this phone's own, and a copy of its Block Store
120    /// entries (§13.1). Requires `with_block_store`.
121    pub fn set_up_new_device(&self, app_dir: PathBuf) -> Self {
122        Self::testing(app_dir, self.keychain.set_up_new_device(), self.directories.bugs().clone())
123    }
124
125    /// A new phone set up from this phone's last cloud backup, its stores
126    /// under `app_dir`: the Block Store entries that backup holds (§13.1).
127    /// Requires `with_block_store`.
128    pub fn restore_new_device_from_cloud(&self, app_dir: PathBuf) -> Self {
129        Self::testing(
130            app_dir,
131            self.keychain.restore_new_device_from_cloud(),
132            self.directories.bugs().clone(),
133        )
134    }
135
136    /// Google's periodic cloud backup of this phone's Block Store: the entries
137    /// stored while end-to-end encryption was available. Requires
138    /// `with_block_store`.
139    pub fn back_up_to_cloud(&self) {
140        self.keychain.back_up_to_cloud();
141    }
142
143    /// Whether this phone's cloud backup would be end-to-end encrypted: it
144    /// has a screen lock. Requires `with_block_store`.
145    pub fn set_end_to_end_encryption(&self, available: bool) {
146        self.keychain.set_end_to_end_encryption(available);
147    }
148
149    /// Create through the production builder, then close for a reopening fixture.
150    pub async fn create_closed_store(
151        &self,
152        name: &str,
153        ids: IdSourceRef,
154    ) -> Result<StoreDir, StoreCreationError> {
155        let handle = self
156            .builder()
157            .id_source(ids)
158            .synced_tables(Vec::new())
159            .migrations(Vec::new())
160            .create_store(name, "Test device", "Ana", |_| "Private".into(), &[], |_, _| Ok(()))
161            .await?;
162        let directory = self.store_dir(&handle.store_id());
163        handle.close().await?;
164        Ok(directory)
165    }
166
167    /// Publish a directory fixture without a database or member custody.
168    pub fn create_store_dir(
169        &self,
170        id: StoreId,
171        ids: &dyn IdSource,
172    ) -> Result<StoreDir, crate::DirectoryCreationError> {
173        self.directories.create_store_dir(id, ids)
174    }
175
176    /// Change the network this installation's test drives.
177    fn drive_network(&self, change: impl FnOnce(&TestNetwork)) {
178        match &self.network {
179            NetworkSource::Test(network) => change(network),
180            NetworkSource::Platform | NetworkSource::Refused(_) => {
181                panic!("an installation made for a test drives its network")
182            }
183        }
184    }
185
186    /// The device moves to another usable network: a network report, as
187    /// the platform's would make (api.md E5).
188    pub fn join_network(&self, metered: bool) {
189        self.drive_network(|network| network.join(metered));
190    }
191
192    /// The device loses its network: no report.
193    pub fn lose_network(&self) {
194        self.drive_network(TestNetwork::lose);
195    }
196
197    /// The platform fails to say what the device's network is: coven can't
198    /// tell, and calls it metered, until the test says again.
199    pub fn network_cannot_tell(&self) {
200        self.drive_network(TestNetwork::cannot_tell);
201    }
202
203    /// The device's network turns metered or unmetered: no report.
204    pub fn set_network_metered(&self, metered: bool) {
205        self.drive_network(|network| network.set_metered(metered));
206    }
207
208    /// Seed the simulated OS custody as if this installation had opened keys.
209    pub fn keep_store_keys(
210        &self,
211        directory: &StoreDir,
212        keys: &StoreKeyring,
213    ) -> Result<(), KeyError> {
214        let keychain = Arc::new(StoreKeychain::new(self.keychain.clone(), directory.id()));
215        Custody::<StoreKeyring>::persist(&KeyringCustody::new(keychain), keys)
216    }
217
218    /// Save this installation's device-only keychain entries at `path`,
219    /// replacing what is there: each store's device id, store keys and
220    /// member keys, which `in_memory_with_saved_keychain` loads. The
221    /// person's entries stay out.
222    pub fn save_device_keychain(&self, path: &Path) -> Result<(), KeyError> {
223        self.keychain.save_device_entries(path)
224    }
225
226    /// Delete this installation's storage credentials for `store`, as the
227    /// person deleting the keychain entry by hand does. The recorded location
228    /// stays: a handle opened afterwards reports no storage set up on this
229    /// device, and setup connects that location again.
230    pub fn lose_storage_credentials(&self, store: StoreId) -> Result<(), KeyError> {
231        StoreKeychain::new(self.keychain.clone(), store).delete_storage_credentials()
232    }
233
234    /// This installation's custody for one store, to read what it holds.
235    #[cfg(test)]
236    pub(crate) fn store_keychain(&self, store: StoreId) -> StoreKeychain {
237        StoreKeychain::new(self.keychain.clone(), store)
238    }
239
240    /// The person's entries for one store, as this installation sees them.
241    #[cfg(test)]
242    pub(crate) fn person_entries(&self, store: StoreId) -> coven_crypto::custody::PersonEntries {
243        coven_crypto::custody::PersonEntries::new(self.keychain.clone(), store)
244    }
245
246    /// While `refuse` holds, refuse this installation's calls on person entries only.
247    #[cfg(test)]
248    pub(crate) fn refuse_person_entry_operations(&self, refuse: bool) {
249        self.keychain.refuse_person_entry_operations(refuse);
250    }
251
252    /// The stores listed, every one readable; an unreadable entry fails the test.
253    #[cfg(test)]
254    pub(crate) async fn readable_stores(&self) -> Vec<StoreInfo> {
255        self.stores()
256            .await
257            .unwrap()
258            .into_iter()
259            .map(|listed| match listed {
260                ListedStore::Readable(info) => info,
261                ListedStore::Unreadable { id, reason } => {
262                    panic!("store {id} is listed as unreadable: {reason}")
263                }
264            })
265            .collect()
266    }
267
268    /// Refuse the next keychain operation before changing any stored value.
269    pub fn fail_next_keychain_operation(&self) {
270        self.keychain.fail_next_operation();
271    }
272
273    #[cfg(test)]
274    pub(crate) fn fail_keychain_operations_after(&self, successes: &[usize]) {
275        self.keychain.fail_operations_after(successes);
276    }
277}