use std::{
error::Error,
fmt,
panic::Location,
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, Response},
parse::{Parsed, parse},
problem::{Mismatch, Problem, Reason},
render,
};
#[derive(Default)]
pub(crate) struct State {
pub expectations: Vec<Expectation>,
pub unordered: bool,
pub strict_transactions: bool,
pub failures: Vec<Problem>,
pub log: Vec<Statement>,
revision: usize,
checked: Option<usize>,
}
impl State {
fn candidates(&self) -> Vec<(usize, Expectation)> {
self.expectations.iter().enumerate().filter(|(_, e)| !e.exhausted()).map(|(idx, e)| (idx, e.clone())).collect()
}
fn fail(&mut self, kind: StmtKind, stmt: &Statement, reason: Reason) -> Box<Problem> {
let problem = Problem::Unexpected { kind, stmt: stmt.clone(), reason };
self.failures.push(problem.clone());
Box::new(problem)
}
fn report(&self) -> Result<(), MockError> {
let mut problems = self.failures.clone();
problems.extend(self.expectations.iter().filter_map(|e| {
if !e.has_result() {
Some(Problem::NoResult(e.declared()))
} else if !e.satisfied() {
Some(Problem::Unmet(e.declared()))
} else {
None
}
}));
if problems.is_empty() { Ok(()) } else { Err(MockError::new(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")
}
#[track_caller]
pub fn expect_select<E: EntityTrait>(&self) -> SelectExpectation<E> {
SelectExpectation::new(self.push_entity::<E>(StmtKind::Select), self.backend)
}
#[track_caller]
pub fn expect_insert<E: EntityTrait>(&self) -> ExecExpectation<E> {
ExecExpectation::new(self.push_entity::<E>(StmtKind::Insert), self.backend)
}
#[track_caller]
pub fn expect_update<E: EntityTrait>(&self) -> ExecExpectation<E> {
ExecExpectation::new(self.push_entity::<E>(StmtKind::Update), self.backend)
}
#[track_caller]
pub fn expect_delete<E: EntityTrait>(&self) -> ExecExpectation<E> {
ExecExpectation::new(self.push_entity::<E>(StmtKind::Delete), self.backend)
}
#[track_caller]
pub fn expect_query(&self) -> QueryExpectation {
QueryExpectation::new(self.push(Expectation::new(Some(StmtKind::Select), Location::caller())), self.backend)
}
#[track_caller]
pub fn expect_statement(&self) -> QueryExpectation {
QueryExpectation::new(self.push(Expectation::new(None, Location::caller())), self.backend)
}
#[track_caller]
pub fn expect_begin(&self) -> TransactionExpectation {
TransactionExpectation::new(self.push(Expectation::new(Some(StmtKind::Begin), Location::caller())))
}
#[track_caller]
pub fn expect_commit(&self) -> TransactionExpectation {
TransactionExpectation::new(self.push(Expectation::new(Some(StmtKind::Commit), Location::caller())))
}
#[track_caller]
pub fn expect_rollback(&self) -> TransactionExpectation {
TransactionExpectation::new(self.push(Expectation::new(Some(StmtKind::Rollback), Location::caller())))
}
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.report(render::colors()));
}
}
#[track_caller]
fn push_entity<E: EntityTrait>(&self, kind: StmtKind) -> ExpectationRef {
let mut expectation = Expectation::new(Some(kind), Location::caller());
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(crate) 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.report(render::colors()));
}
}
}
pub struct MockError {
pub(crate) problems: Vec<Problem>,
messages: Vec<String>,
}
impl MockError {
pub fn problems(&self) -> &[String] {
&self.messages
}
fn new(problems: Vec<Problem>) -> Self {
let messages = problems.iter().map(Problem::to_string).collect();
Self { problems, messages }
}
pub(crate) fn report(&self, colors: bool) -> String {
let count = self.problems.len();
let plural = if count == 1 { "" } else { "s" };
let mut report = format!("leadline: {count} problem{plural}:\n");
for problem in &self.problems {
report.push_str(&format!(" - {}\n", problem.headline()));
}
report.push('\n');
report.push_str(&render::render(&self.problems, colors));
report
}
}
impl fmt::Display for MockError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.report(false))
}
}
impl fmt::Debug for MockError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_tuple("MockError").field(&self.messages).finish()
}
}
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, answer: 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 problem = lock(&self.state).fail(kind, &stmt, Reason::MissingRows { fix });
Err(unexpected(problem))
}
Ok(Some(selected)) => answer(&selected, &stmt, parsed.as_ref()),
Ok(None) => Ok(unscripted),
Err(problem) => Err(unexpected(problem)),
}
}
fn transaction(&self, kind: StmtKind) {
let stmt = Statement::from_string(self.backend, kind.to_string());
if let Err(problem) = self.select(kind, &stmt, None) {
unexpected(problem);
}
}
fn select(&self, kind: StmtKind, stmt: &Statement, parsed: Option<&Parsed>) -> Result<Option<Selected>, Box<Problem>> {
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 = choose(&candidates, total, unordered, 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 = Reason::MatchedWithoutResult(state.expectations[idx].declared());
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>,
}
fn choose(candidates: &[(usize, Expectation)], total: usize, unordered: bool, kind: StmtKind, stmt: &Statement, parsed: Option<&Parsed>) -> Result<(usize, Vec<usize>), Reason> {
let mut skipped = Vec::new();
let mut rejections = Vec::new();
for (idx, candidate) in candidates {
match candidate.spec.check(kind, stmt, parsed) {
Ok(()) => return Ok((*idx, skipped)),
Err(mismatch) if unordered || candidate.satisfied() => {
if !unordered {
skipped.push(*idx);
}
rejections.push((candidate, mismatch));
}
Err(mismatch) => return Err(Reason::Next(candidate.rejection(mismatch))),
}
}
Err(no_match(total, rejections, if unordered { "pending" } else { "remaining optional" }))
}
fn no_match(total: usize, rejections: Vec<(&Expectation, Mismatch)>, candidates: &'static str) -> Reason {
if total == 0 {
Reason::NoExpectation
} else if rejections.is_empty() {
Reason::Consumed
} else {
let rejections = rejections.into_iter().map(|(candidate, mismatch)| candidate.rejection(mismatch)).collect();
Reason::NoneMatched { candidates, rejections }
}
}
fn unexpected(problem: Box<Problem>) -> DbErr {
if !std::thread::panicking() {
panic!("leadline: {}\n\n{}", problem.headline(), render::render(std::slice::from_ref(problem.as_ref()), render::colors()));
}
DbErr::Custom(format!("leadline: {problem}"))
}
#[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())
}