Skip to main content

capy_testing/
boot.rs

1use crate::TestApp;
2use capy_core::{AppConfig, AppContext, AppError, Result};
3use sea_orm::{ConnectionTrait, DatabaseConnection};
4use std::{future::Future, net::SocketAddr, sync::Arc};
5
6/// Adapter implemented by Capy's normal App builder, not a separate test router.
7pub trait TestApplication: Sized {
8    /// Resolve the application's configuration without opening a database.
9    fn test_config(&self) -> Result<AppConfig>;
10
11    /// Apply the application's own migrations and construct its normal router/services.
12    fn boot_test(
13        self,
14        context: AppContext,
15        migrate: bool,
16    ) -> impl Future<Output = Result<TestApp>> + Send;
17
18    /// Explicitly replace outbound mail with real-rendering capture before boot.
19    /// Dependencies captured by custom handlers remain application-owned.
20    #[cfg(feature = "mail")]
21    fn capture_test_mail(self, _config: &AppConfig) -> Result<(Self, crate::TestMailer)> {
22        Err(AppError::Configuration(
23            "This application adapter does not support mail capture.".into(),
24        ))
25    }
26}
27
28/// Databases provisioned by the test harness. No application database URL is used implicitly.
29#[derive(Clone, Default)]
30pub enum TestDatabase {
31    /// A fresh in-memory SQLite database, isolated even between concurrent tests.
32    #[default]
33    Sqlite,
34    /// Create a uniquely named disposable database using this administrator URL.
35    /// The user needs CREATEDB permission. Cleanup drops only the generated database.
36    Postgres(String),
37}
38
39impl std::fmt::Debug for TestDatabase {
40    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
41        f.write_str(match self {
42            Self::Sqlite => "Sqlite",
43            Self::Postgres(_) => "Postgres([REDACTED])",
44        })
45    }
46}
47
48/// Test setup using the real application factory's App value.
49pub struct TestAppBuilder<A> {
50    application: A,
51    config: Option<AppConfig>,
52    database: TestDatabase,
53    migrate: bool,
54    peer: SocketAddr,
55    #[cfg(feature = "mail")]
56    capture_mail: bool,
57}
58
59impl<A: TestApplication> TestAppBuilder<A> {
60    pub(crate) fn new(application: A) -> Self {
61        Self {
62            application,
63            config: None,
64            database: TestDatabase::Sqlite,
65            migrate: true,
66            peer: ([127, 0, 0, 1], 12345).into(),
67            #[cfg(feature = "mail")]
68            capture_mail: false,
69        }
70    }
71
72    /// Select a fresh SQLite or uniquely provisioned PostgreSQL database.
73    pub fn database(mut self, database: TestDatabase) -> Self {
74        self.database = database;
75        self
76    }
77
78    /// Override typed settings; environment and database are replaced by isolated test values.
79    /// Auth, throttling, proxy and password settings retain their real behavior.
80    pub fn config(mut self, config: AppConfig) -> Self {
81        self.config = Some(config);
82        self
83    }
84
85    /// Apply the normal application's migrations (enabled by default).
86    pub fn migrate(mut self) -> Self {
87        self.migrate = true;
88        self
89    }
90
91    /// Deliberately skip migrations, for testing missing-schema behavior.
92    pub fn without_migrations(mut self) -> Self {
93        self.migrate = false;
94        self
95    }
96
97    /// Use this socket peer for requests, including automatic CSRF bootstrap.
98    pub fn peer_addr(mut self, peer: SocketAddr) -> Self {
99        self.peer = peer;
100        self
101    }
102
103    /// Replace the App mail service and built-in mail job with an in-memory capture.
104    /// Custom job/listener captures are not rewritten; inject their dependencies in the factory.
105    #[cfg(feature = "mail")]
106    pub fn capture_mail(mut self) -> Self {
107        self.capture_mail = true;
108        self
109    }
110
111    /// Provision the isolated database, migrate and build the real application router.
112    pub async fn boot(self) -> Result<TestApp> {
113        let mut config = match self.config {
114            Some(config) => config,
115            None => self.application.test_config()?,
116        };
117        config.app.environment = "test".into();
118        // Validate against an isolated URL before provisioning any database.
119        config.database.url = "sqlite::memory:".into();
120        config.validate()?;
121        #[cfg(feature = "mail")]
122        let (application, mail) = if self.capture_mail {
123            let (app, capture) = self.application.capture_test_mail(&config)?;
124            (app, Some(capture))
125        } else {
126            (self.application, None)
127        };
128        #[cfg(not(feature = "mail"))]
129        let application = self.application;
130        let database = Arc::new(DatabaseGuard::provision(self.database, &mut config).await?);
131        let context = AppContext {
132            db: database.db.clone(),
133            config: Arc::new(config),
134        };
135        match application.boot_test(context, self.migrate).await {
136            Ok(mut app) => {
137                app.database = Some(database);
138                app.peer = self.peer;
139                #[cfg(feature = "mail")]
140                if let Some(mail) = mail {
141                    app.mail = Some(mail);
142                }
143                Ok(app)
144            }
145            Err(error) => {
146                // Preserve the original boot error; Drop retries cleanup if it fails.
147                let _ = database.cleanup().await;
148                Err(error)
149            }
150        }
151    }
152}
153
154pub(crate) struct DatabaseGuard {
155    db: DatabaseConnection,
156    admin: Option<(DatabaseConnection, String)>,
157    cleaned: tokio::sync::Mutex<bool>,
158}
159
160impl DatabaseGuard {
161    async fn provision(database: TestDatabase, config: &mut AppConfig) -> Result<Self> {
162        let admin = match database {
163            TestDatabase::Sqlite => {
164                config.database.url = "sqlite::memory:".into();
165                config.database.max_connections = 1;
166                config.database.min_connections = 1;
167                None
168            }
169            TestDatabase::Postgres(admin_url) => {
170                let mut url = url::Url::parse(&admin_url).map_err(|_| {
171                    AppError::Configuration(
172                        "Invalid test PostgreSQL administrator URL (redacted).".into(),
173                    )
174                })?;
175                if !matches!(url.scheme(), "postgres" | "postgresql") {
176                    return Err(AppError::Configuration(
177                        "TestDatabase::Postgres requires a PostgreSQL URL.".into(),
178                    ));
179                }
180                let mut settings = config.database.clone();
181                settings.url = admin_url;
182                settings.max_connections = 1;
183                settings.min_connections = 1;
184                let admin = capy_db::connect(&settings).await?;
185                let name = format!("capy_test_{}", uuid::Uuid::new_v4().simple());
186                // Identifier is generated exclusively from a fixed prefix and UUID hex.
187                admin
188                    .execute_unprepared(&format!("CREATE DATABASE {name}"))
189                    .await?;
190                url.set_path(&format!("/{name}"));
191                // SQLx applies query parameters after the URL path. Retaining
192                // dbname would silently connect to the administrator database.
193                let query: Vec<_> = url
194                    .query_pairs()
195                    .filter(|(key, _)| key != "dbname")
196                    .map(|pair| (pair.0.into_owned(), pair.1.into_owned()))
197                    .collect();
198                url.set_query(None);
199                if !query.is_empty() {
200                    url.query_pairs_mut().extend_pairs(query);
201                }
202                config.database.url = url.into();
203                Some((admin, name))
204            }
205        };
206        match capy_db::connect(&config.database).await {
207            Ok(db) => {
208                let guard = Self {
209                    db,
210                    admin,
211                    cleaned: tokio::sync::Mutex::new(false),
212                };
213                if let Some((_, name)) = &guard.admin {
214                    let verified: Result<bool> = async {
215                        let row = guard
216                            .db
217                            .query_one(sea_orm::Statement::from_string(
218                                sea_orm::DbBackend::Postgres,
219                                "SELECT current_database() AS name",
220                            ))
221                            .await?
222                            .ok_or_else(|| {
223                                AppError::Configuration(
224                                    "Test database identity was not returned.".into(),
225                                )
226                            })?;
227                        Ok(row.try_get::<String>("", "name")? == *name)
228                    }
229                    .await;
230                    if !matches!(verified, Ok(true)) {
231                        let _ = guard.cleanup().await;
232                        return Err(AppError::Configuration(
233                            "Could not verify isolated test database; refused to run migrations."
234                                .into(),
235                        ));
236                    }
237                }
238                Ok(guard)
239            }
240            Err(error) => {
241                if let Some((admin, name)) = admin {
242                    let _ = admin
243                        .execute_unprepared(&format!("DROP DATABASE {name}"))
244                        .await;
245                    let _ = admin.close().await;
246                }
247                Err(error)
248            }
249        }
250    }
251
252    pub(crate) async fn cleanup(&self) -> Result<()> {
253        let mut cleaned = self.cleaned.lock().await;
254        if !*cleaned {
255            self.db.clone().close().await?;
256            if let Some((admin, name)) = &self.admin {
257                admin
258                    .execute_unprepared(&format!("DROP DATABASE IF EXISTS {name}"))
259                    .await?;
260                admin.clone().close().await?;
261            }
262            *cleaned = true;
263        }
264        Ok(())
265    }
266}
267
268impl Drop for DatabaseGuard {
269    fn drop(&mut self) {
270        if *self.cleaned.get_mut() {
271            return;
272        }
273        if let Ok(runtime) = tokio::runtime::Handle::try_current() {
274            let db = self.db.clone();
275            let admin = self.admin.clone();
276            runtime.spawn(async move {
277                let _ = db.close().await;
278                if let Some((admin, name)) = admin {
279                    let _ = admin
280                        .execute_unprepared(&format!("DROP DATABASE IF EXISTS {name}"))
281                        .await;
282                    let _ = admin.close().await;
283                }
284            });
285        }
286    }
287}