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