use std::fmt::Write as _;
use std::future::{Future, IntoFuture};
use std::panic::Location;
use std::pin::Pin;
use serde::Serialize;
use serde_json::{Map, Value};
use crate::Application;
use crate::db::identifier::{is_identifier_path, quote};
use crate::db::sqlx::AssertSqlSafe;
use crate::db::{AnyConnection, DatabaseManager, Driver};
use crate::model::Model;
use crate::numeric::Decimal;
const SHOWN_ROWS: usize = 5;
pub trait InteractsWithDatabase {
#[track_caller]
fn seed<S, F>(&self, seeder: S) -> impl Future<Output = ()> + Send + 'static
where
S: FnOnce() -> F + Send + 'static,
F: Future<Output = crate::Result<()>> + Send + 'static;
#[track_caller]
fn assert_database_has(&self, table: &str, columns: impl Serialize) -> DatabaseAssertion;
#[track_caller]
fn assert_database_missing(&self, table: &str, columns: impl Serialize) -> DatabaseAssertion;
#[track_caller]
fn assert_database_count(&self, table: &str, count: u64) -> DatabaseAssertion;
#[track_caller]
fn assert_database_empty(&self, table: &str) -> DatabaseAssertion {
self.assert_database_count(table, 0)
}
#[track_caller]
fn assert_model_exists<M: Model>(&self, model: &M) -> DatabaseAssertion;
#[track_caller]
fn assert_model_missing<M: Model>(&self, model: &M) -> DatabaseAssertion;
}
impl InteractsWithDatabase for Application {
#[track_caller]
fn seed<S, F>(&self, seeder: S) -> impl Future<Output = ()> + Send + 'static
where
S: FnOnce() -> F + Send + 'static,
F: Future<Output = crate::Result<()>> + Send + 'static,
{
let application = self.clone();
let location = Location::caller();
async move {
let seeded = application
.scope(async move || crate::db::seeders::seed_test(&crate::db::manager(), Box::pin(seeder())).await)
.await;
if let Err(error) = seeded {
panic!("seeding the test's database failed: {error:#}\n\nat {location}");
}
}
}
#[track_caller]
fn assert_database_has(&self, table: &str, columns: impl Serialize) -> DatabaseAssertion {
DatabaseAssertion::new(self, table, Expectation::Has(column_values(columns)))
}
#[track_caller]
fn assert_database_missing(&self, table: &str, columns: impl Serialize) -> DatabaseAssertion {
DatabaseAssertion::new(self, table, Expectation::Missing(column_values(columns)))
}
#[track_caller]
fn assert_database_count(&self, table: &str, count: u64) -> DatabaseAssertion {
DatabaseAssertion::new(self, table, Expectation::Count(count))
}
#[track_caller]
fn assert_model_exists<M: Model>(&self, model: &M) -> DatabaseAssertion {
DatabaseAssertion::of_model(self, model, Expectation::Has)
}
#[track_caller]
fn assert_model_missing<M: Model>(&self, model: &M) -> DatabaseAssertion {
DatabaseAssertion::of_model(self, model, Expectation::Missing)
}
}
#[derive(Debug)]
#[must_use = "a database assertion does nothing unless awaited"]
pub struct DatabaseAssertion {
application: Application,
connection: Option<String>,
table: String,
expectation: Expectation,
location: &'static Location<'static>,
}
#[derive(Debug)]
enum Expectation {
Has(Map<String, Value>),
Missing(Map<String, Value>),
Count(u64),
}
type Row = Vec<Option<String>>;
impl DatabaseAssertion {
#[track_caller]
fn new(application: &Application, table: &str, expectation: Expectation) -> Self {
assert!(
is_identifier_path(table),
"`{table}` isn't a table name; use letters, digits and underscores, optionally after a schema, as in `reporting.users`"
);
Self {
application: application.clone(),
connection: None,
table: table.to_owned(),
expectation,
location: Location::caller(),
}
}
#[track_caller]
fn of_model<M: Model>(
application: &Application,
model: &M,
expectation: fn(Map<String, Value>) -> Expectation,
) -> Self {
let key = serde_json::to_value(M::META.key.get(model)).expect("a model's key serializes");
let columns = Map::from_iter([(M::META.key.name().to_owned(), key)]);
let assertion = Self::new(application, M::META.table, expectation(columns));
match connection_of(model) {
Some(connection) => assertion.connection(connection),
None => assertion,
}
}
pub fn connection(mut self, name: impl Into<String>) -> Self {
self.connection = Some(name.into());
self
}
async fn check(self) {
let manager = self.application.resolve::<DatabaseManager>().await;
let connection = match &self.connection {
Some(name) => manager.connection(name),
None => manager.default_connection(),
};
let connection = connection.unwrap_or_else(|error| self.fail(format_args!("{error}")));
match &self.expectation {
Expectation::Count(expected) => {
let actual = self.count(&connection).await;
if actual != *expected {
let wanted = match expected {
0 => "to be empty".to_owned(),
_ => format!("to have {}", row_count(*expected)),
};
self.fail(format_args!(
"expected {} {wanted}, but it has {}",
self.describe(),
row_count(actual)
));
}
}
Expectation::Has(columns) => {
let mut found = self.rows(&connection, columns).await;
if !found.iter().any(|row| matching(row, columns) == columns.len()) {
found.sort_by_key(|row| std::cmp::Reverse(matching(row, columns)));
self.fail(format_args!(
"expected {} to have a row matching {}, but {}",
self.describe(),
Value::Object(columns.clone()),
closest(&found, columns)
));
}
}
Expectation::Missing(columns) => {
let found = self.rows(&connection, columns).await;
let matches = found
.iter()
.filter(|row| matching(row, columns) == columns.len())
.count();
if matches > 0 {
self.fail(format_args!(
"expected {} to have no row matching {}, but it has {} matching",
self.describe(),
Value::Object(columns.clone()),
row_count(matches as u64)
));
}
}
}
}
async fn count(&self, connection: &AnyConnection) -> u64 {
connection
.table(self.table.as_str())
.use_write_connection()
.count()
.await
.unwrap_or_else(|error| self.unreadable(&error))
}
async fn rows(&self, connection: &AnyConnection, columns: &Map<String, Value>) -> Vec<Row> {
let driver = connection.driver();
let text = match driver {
Driver::MySql | Driver::MariaDb => "CHAR",
_ => "TEXT",
};
let selected = match columns.is_empty() {
true => "1".to_owned(),
false => columns
.keys()
.map(|column| format!("CAST({} AS {text})", quote(driver, column)))
.collect::<Vec<_>>()
.join(", "),
};
let sql = format!("SELECT {selected} FROM {}", quote(driver, &self.table));
let found = connection
.query(AssertSqlSafe(sql))
.use_write_connection()
.select()
.await
.unwrap_or_else(|error| self.unreadable(&error));
found
.iter()
.map(|row| {
(0..columns.len())
.map(|index| row.try_get::<Option<String>>(index))
.collect::<crate::Result<Row>>()
.unwrap_or_else(|error| self.unreadable(&error))
})
.collect()
}
fn describe(&self) -> String {
match &self.connection {
Some(connection) => format!("the `{}` table on the `{connection}` connection", self.table),
None => format!("the `{}` table", self.table),
}
}
fn unreadable(&self, error: &crate::Error) -> ! {
self.fail(format_args!("{} couldn't be read: {error}", self.describe()))
}
fn fail(&self, message: std::fmt::Arguments<'_>) -> ! {
panic!("{message}\n\nat {}", self.location)
}
}
impl IntoFuture for DatabaseAssertion {
type Output = ();
type IntoFuture = Pin<Box<dyn Future<Output = ()> + Send>>;
fn into_future(self) -> Self::IntoFuture {
Box::pin(self.check())
}
}
#[track_caller]
fn column_values(columns: impl Serialize) -> Map<String, Value> {
let columns = match serde_json::to_value(columns) {
Ok(Value::Object(columns)) => columns,
Ok(other) => panic!("the columns should be an object, such as `json!({{ \"id\": 1 }})`, not `{other}`"),
Err(error) => panic!("the columns couldn't be serialized: {error}"),
};
for column in columns.keys() {
assert!(
is_identifier_path(column) && !column.contains('.'),
"`{column}` isn't a column name; use letters, digits and underscores"
);
}
columns
}
fn connection_of<M: Model>(model: &M) -> Option<String> {
model.__connection().name().or(M::META.connection).map(str::to_owned)
}
fn matching(row: &[Option<String>], columns: &Map<String, Value>) -> usize {
columns
.values()
.zip(row)
.filter(|(expected, actual)| equals(expected, actual.as_deref()))
.count()
}
fn equals(expected: &Value, actual: Option<&str>) -> bool {
let Some(actual) = actual else {
return expected.is_null();
};
match expected {
Value::Null => false,
Value::String(expected) => expected == actual,
Value::Bool(expected) => boolean(actual) == Some(*expected),
Value::Number(expected) => {
let expected = expected.to_string().parse::<Decimal>();
let actual = actual.parse::<Decimal>();
matches!((expected, actual), (Ok(expected), Ok(actual)) if expected == actual)
}
Value::Array(_) | Value::Object(_) => {
serde_json::from_str::<Value>(actual).is_ok_and(|actual| actual == *expected)
}
}
}
fn boolean(text: &str) -> Option<bool> {
match text {
"1" | "t" | "true" => Some(true),
"0" | "f" | "false" => Some(false),
_ => None,
}
}
fn closest(found: &[Row], columns: &Map<String, Value>) -> String {
if found.is_empty() {
return "the table is empty".to_owned();
}
let mut description = match found.len() {
1 => "its only row is:".to_owned(),
count => format!("it has {count} rows, closest first:"),
};
for row in found.iter().take(SHOWN_ROWS) {
let shown: Map<String, Value> = columns
.iter()
.zip(row)
.map(|((column, expected), actual)| (column.clone(), shown(expected, actual.as_deref())))
.collect();
let _ = write!(description, "\n{}", Value::Object(shown));
}
if found.len() > SHOWN_ROWS {
let _ = write!(
description,
"\nand {} more",
row_count((found.len() - SHOWN_ROWS) as u64)
);
}
description
}
fn shown(expected: &Value, actual: Option<&str>) -> Value {
let Some(actual) = actual else {
return Value::Null;
};
let typed = match expected {
Value::Number(_) => serde_json::from_str::<serde_json::Number>(actual)
.ok()
.map(Value::Number),
Value::Bool(_) => boolean(actual).map(Value::Bool),
Value::Array(_) | Value::Object(_) => serde_json::from_str(actual).ok(),
Value::Null | Value::String(_) => None,
};
typed.unwrap_or_else(|| Value::String(actual.to_owned()))
}
fn row_count(count: u64) -> String {
match count {
1 => "1 row".to_owned(),
count => format!("{count} rows"),
}
}