Lines
96.55 %
Functions
100 %
Branches
//! `start_server --database` boots against that URL, not `DATABASE_URL`.
//!
//! The URL source is process-global, so this binary holds a single test.
use cli_core::start_server;
use server::db::{DBError, admin_database_url, get_connection, use_url};
use sqlx::postgres::PgConnectOptions;
use sqlx::{ConnectOptions, Connection, PgConnection};
#[tokio::test]
async fn database_flag_selects_the_server_database() -> anyhow::Result<()> {
let admin: PgConnectOptions = std::env::var("DATABASE_URL")?.parse()?;
let name = format!("start_url_{}", uuid::Uuid::new_v4().simple());
let mut admin_conn = PgConnection::connect_with(&admin).await?;
sqlx::raw_sql(sqlx::AssertSqlSafe(format!("CREATE DATABASE {name}")))
.execute(&mut admin_conn)
.await?;
let url = admin.database(&name).to_url_lossy().to_string();
let outcome = boot_and_probe(&url, &name).await;
// The server pool is still open; FORCE drops its connections.
sqlx::raw_sql(sqlx::AssertSqlSafe(format!(
"DROP DATABASE {name} WITH (FORCE)"
)))
outcome
}
async fn boot_and_probe(url: &str, name: &str) -> anyhow::Result<()> {
start_server(Some(url.to_owned()), None).await?;
// ensure! rather than assert!, so a failure still reaches the caller's DROP.
anyhow::ensure!(admin_database_url()? == url, "server resolved another URL");
let mut conn = get_connection().await?;
let connected: String = sqlx::query_scalar("SELECT current_database()")
.fetch_one(&mut *conn)
anyhow::ensure!(connected == name, "pool connected to {connected}");
anyhow::ensure!(
matches!(use_url(url.to_owned()), Err(DBError::UrlAlreadyResolved)),
"a second use_url was accepted"
);
Ok(())