fabrica

hanna/fabrica

2370 bytes
Raw
1// This Source Code Form is subject to the terms of the Mozilla Public
2// License, v. 2.0. If a copy of the MPL was not distributed with this
3// file, You can obtain one at https://mozilla.org/MPL/2.0/.
4
5//! Shared test scaffolding: a temp data directory with a SQLite database and a
6//! matching config file, so command handlers run end-to-end with no external
7//! services.
8
9#![allow(clippy::unwrap_used, clippy::expect_used)]
10
11use std::path::Path;
12
13use store::{NewUser, Store};
14use tempfile::TempDir;
15
16/// A throwaway environment for a CLI command test.
17pub(crate) struct Env {
18 _dir: TempDir,
19 config_path: std::path::PathBuf,
20 db_url: String,
21}
22
23/// Build a temp data dir with a config pointing at a fresh SQLite database.
24pub(crate) fn env() -> Env {
25 let dir = tempfile::tempdir().unwrap();
26 let repos = dir.path().join("repos");
27 let db = dir.path().join("fabrica.db");
28 let db_url = format!("sqlite://{}", db.display());
29 let config_path = dir.path().join("fabrica.toml");
30 let toml = format!(
31 "[storage]\ndata_dir = {:?}\nrepo_dir = {:?}\n\n[database]\nurl = {:?}\n",
32 dir.path().display(),
33 repos.display(),
34 db_url,
35 );
36 std::fs::write(&config_path, toml).unwrap();
37 Env {
38 _dir: dir,
39 config_path,
40 db_url,
41 }
42}
43
44impl Env {
45 /// The `--config` path the handlers accept. The `Option` is intrinsic to the
46 /// handler signature, not incidental.
47 #[allow(clippy::unnecessary_wraps)]
48 pub(crate) fn path(&self) -> Option<&Path> {
49 Some(self.config_path.as_path())
50 }
51
52 /// A store connected to the same database the handlers use.
53 pub(crate) async fn store(&self) -> Store {
54 Store::connect(&self.db_url, 1).await.unwrap()
55 }
56
57 /// Create a user directly and return its id, for tests that need one to exist.
58 pub(crate) async fn make_user(&self, name: &str) -> String {
59 let store = self.store().await;
60 store.migrate().await.unwrap();
61 store
62 .create_user(NewUser {
63 username: name.to_string(),
64 email: format!("{name}@example.com"),
65 display_name: None,
66 password_hash: None,
67 is_admin: false,
68 must_change_password: false,
69 })
70 .await
71 .unwrap()
72 .id
73 }
74}