capy-testing 0.10.0

In-process HTTP testing utilities for Capy applications.
Documentation
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;
                }
            });
        }
    }
}