use std::{
error::Error,
fmt,
sync::{Arc, Mutex, MutexGuard},
};
use sea_orm::{Database, DatabaseConnection, DbBackend, DbErr, EntityTrait, ProxyDatabaseTrait, ProxyExecResult, ProxyRow, Statement};
use crate::{
builders::{ExecExpectation, QueryExpectation, SelectExpectation, TransactionExpectation},
classify::{StmtKind, classify},
expectation::{Expectation, Label, Response, Spec, describe},
parse::{Parsed, parse},
};
#[derive(Default)]
pub(crate) struct State {
pub expectations: Vec<Expectation>,
pub unordered: bool,
pub strict_transactions: bool,
pub failures: Vec<String>,
pub log: Vec<Statement>,
revision: usize,
checked: Option<usize>,
}
impl State {
fn candidates(&self) -> Vec<Candidate> {
self
.expectations
.iter()
.enumerate()
.filter(|(_, e)| !e.exhausted())
.map(|(idx, e)| Candidate {
idx,
spec: e.spec.clone(),
calls: e.calls,
min: e.min,
max: e.max,
})
.collect()
}
fn fail(&mut self, kind: StmtKind, stmt: &Statement, reason: &str) -> String {
let message = format!("unexpected {kind} {}: {reason}", describe(stmt));
self.failures.push(message.clone());
message
}
fn report(&self) -> Result<(), MockError> {
let mut problems = self.failures.clone();
problems.extend(self.expectations.iter().filter_map(|e| {
if !e.has_result() {
Some(format!("expectation has no result: {}", e.label()))
} else if !e.satisfied() {
Some(format!("expectation not met: {}", e.label()))
} else {
None
}
}));
if problems.is_empty() { Ok(()) } else { Err(MockError(problems)) }
}
}
#[derive(Clone)]
pub struct MockDb {
pub(crate) backend: DbBackend,
pub(crate) state: Arc<Mutex<State>>,
_drop_check: Arc<DropCheck>,
}
impl MockDb {
pub fn new(backend: DbBackend) -> Self {
let state = Arc::<Mutex<State>>::default();
Self {
backend,
_drop_check: Arc::new(DropCheck { state: state.clone() }),
state,
}
}
pub fn unordered(&self) -> Self {
self.lock().unordered = true;
self.clone()
}
pub fn strict_transactions(&self) -> Self {
self.lock().strict_transactions = true;
self.clone()
}
pub async fn connection(&self) -> DatabaseConnection {
let handler: Box<dyn ProxyDatabaseTrait> = Box::new(Handler {
state: self.state.clone(),
backend: self.backend,
});
Database::connect_proxy(self.backend, Arc::new(handler)).await.expect("could not create proxy connection")
}
pub fn expect_select<E: EntityTrait>(&self) -> SelectExpectation<E> {
SelectExpectation::new(self.push_entity::<E>(StmtKind::Select), self.backend)
}
pub fn expect_insert<E: EntityTrait>(&self) -> ExecExpectation<E> {
ExecExpectation::new(self.push_entity::<E>(StmtKind::Insert), self.backend)
}
pub fn expect_update<E: EntityTrait>(&self) -> ExecExpectation<E> {
ExecExpectation::new(self.push_entity::<E>(StmtKind::Update), self.backend)
}
pub fn expect_delete<E: EntityTrait>(&self) -> ExecExpectation<E> {
ExecExpectation::new(self.push_entity::<E>(StmtKind::Delete), self.backend)
}
pub fn expect_query(&self) -> QueryExpectation {
QueryExpectation::new(self.push(Expectation::new(Some(StmtKind::Select))), self.backend)
}
pub fn expect_statement(&self) -> QueryExpectation {
QueryExpectation::new(self.push(Expectation::new(None)), self.backend)
}
pub fn expect_begin(&self) -> TransactionExpectation {
TransactionExpectation::new(self.push(Expectation::new(Some(StmtKind::Begin))))
}
pub fn expect_commit(&self) -> TransactionExpectation {
TransactionExpectation::new(self.push(Expectation::new(Some(StmtKind::Commit))))
}
pub fn expect_rollback(&self) -> TransactionExpectation {
TransactionExpectation::new(self.push(Expectation::new(Some(StmtKind::Rollback))))
}
pub fn statements(&self) -> Vec<Statement> {
self.lock().log.clone()
}
pub fn check(&self) -> Result<(), MockError> {
let mut state = self.lock();
state.checked = Some(state.revision);
state.report()
}
#[track_caller]
pub fn verify(&self) {
if let Err(err) = self.check() {
panic!("{err}");
}
}
fn push_entity<E: EntityTrait>(&self, kind: StmtKind) -> ExpectationRef {
let mut expectation = Expectation::new(Some(kind));
expectation.spec_mut().table = Some(E::default().table_name().to_string());
self.push(expectation)
}
fn push(&self, expectation: Expectation) -> ExpectationRef {
let mut state = self.lock();
state.revision += 1;
state.expectations.push(expectation);
ExpectationRef {
state: self.state.clone(),
index: state.expectations.len() - 1,
}
}
fn lock(&self) -> MutexGuard<'_, State> {
lock(&self.state)
}
}
pub(crate) struct ExpectationRef {
state: Arc<Mutex<State>>,
index: usize,
}
impl ExpectationRef {
pub fn update(&self, f: impl FnOnce(&mut Expectation)) {
let mut state = lock(&self.state);
state.revision += 1;
f(&mut state.expectations[self.index]);
}
}
struct DropCheck {
state: Arc<Mutex<State>>,
}
impl Drop for DropCheck {
fn drop(&mut self) {
if std::thread::panicking() {
return;
}
let state = lock(&self.state);
if state.checked == Some(state.revision) {
return;
}
if let Err(err) = state.report() {
drop(state);
panic!("{err}");
}
}
}
#[derive(Debug)]
pub struct MockError(Vec<String>);
impl MockError {
pub fn problems(&self) -> &[String] {
&self.0
}
}
impl fmt::Display for MockError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
writeln!(f, "leadline: {} problem(s):", self.0.len())?;
for problem in &self.0 {
writeln!(f, " - {problem}")?;
}
Ok(())
}
}
impl Error for MockError {}
#[derive(Debug)]
struct Handler {
state: Arc<Mutex<State>>,
backend: DbBackend,
}
impl fmt::Debug for State {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("State").field("expectations", &self.expectations.len()).finish_non_exhaustive()
}
}
impl Handler {
fn respond<T>(&self, stmt: Statement, reads_rows: bool, respond: impl FnOnce(&Selected, &Statement, Option<&Parsed>) -> Result<T, DbErr>, unscripted: T) -> Result<T, DbErr> {
let parsed = parse(&stmt);
let kind = parsed.as_ref().map_or_else(|| classify(&stmt.sql), |parsed| parsed.kind);
match self.select(kind, &stmt, parsed.as_ref()) {
Ok(Some(selected)) if reads_rows && matches!(kind, StmtKind::Insert | StmtKind::Update | StmtKind::Delete) && !selected.response.has_rows() => {
let fix = match (selected.table.is_some(), kind) {
(true, StmtKind::Insert) => "`.returning(..)`, `.last_insert_id(..)` or `.last_insert_key(..)`",
(true, _) => "`.returning(..)` (`.returning::<Model>([])` for none)",
(false, _) => "`.returning_rows(..)` (an empty list for none)",
};
let reason = format!("it reads the written rows back (`RETURNING` on this backend), but its expectation has no rows to return: complete it with {fix}");
let message = lock(&self.state).fail(kind, &stmt, &reason);
unexpected(message)
}
Ok(Some(selected)) => respond(&selected, &stmt, parsed.as_ref()),
Ok(None) => Ok(unscripted),
Err(message) => unexpected(message),
}
}
fn transaction(&self, kind: StmtKind) {
let stmt = Statement::from_string(self.backend, kind.to_string());
if let Err(message) = self.select(kind, &stmt, None) {
let _ = unexpected::<()>(message);
}
}
fn select(&self, kind: StmtKind, stmt: &Statement, parsed: Option<&Parsed>) -> Result<Option<Selected>, String> {
let unchecked_transaction = {
let mut state = lock(&self.state);
state.revision += 1;
state.log.push(stmt.clone());
kind.is_transaction() && !state.strict_transactions && !state.expectations.iter().any(|e| e.spec.is_transaction())
};
loop {
let (candidates, total, unordered, revision) = {
let state = lock(&self.state);
(state.candidates(), state.expectations.len(), state.unordered, state.revision)
};
let choice = if unordered {
choose_unordered(&candidates, total, kind, stmt, parsed)
} else {
choose_ordered(&candidates, total, kind, stmt, parsed)
};
let mut state = lock(&self.state);
if state.revision != revision {
continue;
}
let (idx, skipped) = match choice {
Ok(choice) => choice,
Err(_) if unchecked_transaction => return Ok(None),
Err(reason) => return Err(state.fail(kind, stmt, &reason)),
};
if !state.expectations[idx].has_result() {
let reason = format!("it matches {}, which has no result", state.expectations[idx].label());
return Err(state.fail(kind, stmt, &reason));
}
for idx in skipped {
state.expectations[idx].close();
}
state.revision += 1;
let expectation = &mut state.expectations[idx];
expectation.calls += 1;
return Ok(Some(Selected {
response: expectation.response.clone(),
table: expectation.spec.table.clone(),
}));
}
}
}
struct Selected {
response: Arc<Response>,
table: Option<String>,
}
struct Candidate {
idx: usize,
spec: Arc<Spec>,
calls: usize,
min: usize,
max: usize,
}
impl Candidate {
fn satisfied(&self) -> bool {
self.calls >= self.min
}
fn label(&self) -> Label<'_> {
Label {
spec: &self.spec,
calls: self.calls,
min: self.min,
max: self.max,
}
}
}
fn choose_unordered(candidates: &[Candidate], total: usize, kind: StmtKind, stmt: &Statement, parsed: Option<&Parsed>) -> Result<(usize, Vec<usize>), String> {
let mut mismatches = Vec::new();
for candidate in candidates {
match candidate.spec.check(kind, stmt, parsed) {
Ok(()) => return Ok((candidate.idx, Vec::new())),
Err(reason) => mismatches.push(format!("{}: {reason}", candidate.label())),
}
}
Err(no_match(total, &mismatches, "pending"))
}
fn choose_ordered(candidates: &[Candidate], total: usize, kind: StmtKind, stmt: &Statement, parsed: Option<&Parsed>) -> Result<(usize, Vec<usize>), String> {
let mut skipped = Vec::new();
let mut mismatches = Vec::new();
for candidate in candidates {
match candidate.spec.check(kind, stmt, parsed) {
Ok(()) => return Ok((candidate.idx, skipped)),
Err(reason) if candidate.satisfied() => {
skipped.push(candidate.idx);
mismatches.push(format!("{}: {reason}", candidate.label()));
}
Err(reason) => return Err(format!("next expectation is {}, but {reason}", candidate.label())),
}
}
Err(no_match(total, &mismatches, "remaining optional"))
}
fn no_match(total: usize, mismatches: &[String], candidates: &str) -> String {
if total == 0 {
return "no expectation was set".to_string();
}
if mismatches.is_empty() {
return "every expectation was already consumed".to_string();
}
let mut message = format!("none of the {candidates} expectations matches it:");
for mismatch in mismatches {
message.push_str(&format!("\n - {mismatch}"));
}
message
}
fn unexpected<T>(message: String) -> Result<T, DbErr> {
if !std::thread::panicking() {
panic!("leadline: {message}");
}
Err(DbErr::Custom(format!("leadline: {message}")))
}
#[async_trait::async_trait]
impl ProxyDatabaseTrait for Handler {
async fn query(&self, stmt: Statement) -> Result<Vec<ProxyRow>, DbErr> {
self.respond(stmt, true, |selected, stmt, parsed| selected.response.query(selected.table.as_deref(), stmt, parsed), Vec::new())
}
async fn execute(&self, stmt: Statement) -> Result<ProxyExecResult, DbErr> {
self.respond(stmt, false, |selected, stmt, _| selected.response.exec(stmt), ProxyExecResult::default())
}
async fn begin(&self) {
self.transaction(StmtKind::Begin);
}
async fn commit(&self) {
self.transaction(StmtKind::Commit);
}
async fn rollback(&self) {
self.transaction(StmtKind::Rollback);
}
fn start_rollback(&self) {
self.transaction(StmtKind::Rollback);
}
}
fn lock(state: &Mutex<State>) -> MutexGuard<'_, State> {
state.lock().unwrap_or_else(|poisoned| poisoned.into_inner())
}