pub struct QueryExpectation { /* private fields */ }Expand description
Pending untyped expectation, created by MockDb::expect_query or
MockDb::expect_statement.
For raw SQL, and statements whose results do not map to an entity. Narrow
the statements it accepts with the matching methods, then complete it with
a result: rows (returning_rows,
returning_with), an exec result
(rows_affected,
last_insert_id, exec_with),
or returning_error. Forgetting the result is a
compiler warning.
Implementations§
Source§impl QueryExpectation
impl QueryExpectation
Sourcepub fn matching<Q: QueryTrait>(self, query: Q) -> Self
pub fn matching<Q: QueryTrait>(self, query: Q) -> Self
Accept only the statement that query builds: the same SQL, and the
same bound values.
This is the most precise matcher, and the most robust one: the expected statement comes from the same query builder as the code under test, so a renamed column or a value of the wrong type is a compile error, and no SQL is written by hand. The query is built for the mock’s backend.
Some SeaORM methods add a LIMIT to the query they send:
find_by_id(1).one(db) sends … WHERE "id" = $1 LIMIT $2, which
matching(find_by_id(1)) rejects. To expect such a query, use
matching_ignoring_limit. When a
statement only differs by its LIMIT or OFFSET, the failure message
suggests it.
use sea_orm::{ColumnTrait, DbBackend, EntityTrait, QueryFilter};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
let query = || cake::Entity::find().filter(cake::Column::Name.contains("choc"));
mock.expect_select::<cake::Entity>().matching(query()).returning::<cake::Model>([]);
let db = mock.connection().await;
assert!(query().all(&db).await.unwrap().is_empty());Sourcepub fn matching_ignoring_limit<Q: QueryTrait>(self, query: Q) -> Self
pub fn matching_ignoring_limit<Q: QueryTrait>(self, query: Q) -> Self
Like matching, but ignores LIMIT and OFFSET, and
the values bound to them, in both statements.
.one() adds a LIMIT, and paginators add both. This lets the expected
query be written as the code under test builds it:
expected find_by_id(1) SELECT … WHERE "id" = $1 [1]
sent find_by_id(1).one(db) SELECT … WHERE "id" = $1 LIMIT $2 [1, 1]
compared SELECT … WHERE "id" = $1 [1]use sea_orm::{DbBackend, EntityTrait};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock
.expect_select::<cake::Entity>()
.matching_ignoring_limit(cake::Entity::find_by_id(1))
.returning([cake::Model { id: 1, name: "Chocolate".into(), bakery_id: None }]);
let db = mock.connection().await;
let found = cake::Entity::find_by_id(1).one(&db).await.unwrap();
assert_eq!(found.unwrap().name, "Chocolate");Sourcepub fn matching_query<S: StatementBuilder>(self, query: &S) -> Self
pub fn matching_query<S: StatementBuilder>(self, query: &S) -> Self
Like matching, for a statement built with
sea_query (Query::select(), …) rather than with SeaORM’s entities.
The statement is built for the mock’s backend, so that the test does not
have to name the backend again: on a Postgres mock,
matching_query(&query) is the same as
matching_statement(DbBackend::Postgres.build(&query)).
use sea_orm::{ConnectionTrait, DbBackend, sea_query::{Expr, ExprTrait, Query}};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
let query = Query::select().column("name").from("cake").and_where(Expr::col("id").eq(1)).to_owned();
mock.expect_query().matching_query(&query).returning_rows(Vec::<std::collections::BTreeMap<String, sea_orm::Value>>::new());
let db = mock.connection().await;
assert!(db.query_one(&query).await.unwrap().is_none());Sourcepub fn matching_statement(self, stmt: Statement) -> Self
pub fn matching_statement(self, stmt: Statement) -> Self
Accept only stmt: the same SQL, ignoring formatting, and the same
bound values.
For statements that are already built, such as raw Statements. Prefer
matching for SeaORM queries, and
matching_query for sea_query statements:
both build the statement for the mock’s backend.
use sea_orm::{ConnectionTrait, DbBackend, Statement};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
let stmt = || Statement::from_sql_and_values(DbBackend::Postgres, r#"DELETE FROM "cake" WHERE "id" = $1"#, [1.into()]);
mock.expect_statement().matching_statement(stmt()).rows_affected(1);
let db = mock.connection().await;
assert_eq!(db.execute_raw(stmt()).await.unwrap().rows_affected(), 1);Sourcepub fn sql(self, sql: impl Into<String>) -> Self
pub fn sql(self, sql: impl Into<String>) -> Self
Accept statements whose SQL is sql, ignoring formatting: SELECT * FROM t (on two lines) matches SELECT * FROM t. Only the whitespace
between tokens is ignored: string literals, quoted identifiers and
comments must be identical.
Bound values are not checked: add with_args for
them. For statements built by SeaORM, prefer
matching, as the SQL SeaORM generates may change
between versions.
use std::collections::BTreeMap;
use sea_orm::{ConnectionTrait, DbBackend, Statement, Value};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock.expect_query().sql("SELECT 1 AS one").returning_rows([BTreeMap::from([("one", Value::from(1))])]);
let db = mock.connection().await;
let row = db.query_one_raw(Statement::from_string(DbBackend::Postgres, "SELECT 1 AS one")).await.unwrap();
assert_eq!(row.unwrap().try_get::<i32>("", "one").unwrap(), 1);Sourcepub fn sql_regex(self, pattern: &str) -> Self
pub fn sql_regex(self, pattern: &str) -> Self
Accept statements whose SQL matches the regular expression pattern,
anywhere in the SQL unless the pattern is anchored with ^ or $. The
SQL is matched exactly as it was sent, formatting included.
Useful when only part of a statement matters, or when part of the
statement varies, such as the IN (…) lists that loaders generate.
§Panics
If pattern is not a valid regular expression.
use sea_orm::{DbBackend, EntityTrait, QueryOrder};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock.expect_select::<cake::Entity>().sql_regex(r#"ORDER BY "cake"\."name" (ASC|DESC)"#).returning::<cake::Model>([]);
let db = mock.connection().await;
cake::Entity::find().order_by_desc(cake::Column::Name).all(&db).await.unwrap();Sourcepub fn sql_contains(self, needle: impl Into<String>) -> Self
pub fn sql_contains(self, needle: impl Into<String>) -> Self
Accept statements whose SQL contains needle, ignoring formatting as
sql does: sql_contains(r#"ORDER BY "name""#) matches
SELECT … ORDER BY "name" ASC.
The simplest way to check one part of a statement. Chain several matchers to check several parts: a statement must satisfy all of them.
use sea_orm::{ColumnTrait, DbBackend, EntityTrait, QueryFilter, QueryOrder};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock
.expect_select::<cake::Entity>()
.sql_contains(r#"WHERE "cake"."bakery_id" = $1"#)
.sql_contains("ORDER BY")
.with_args((3,))
.returning::<cake::Model>([]);
let db = mock.connection().await;
cake::Entity::find()
.filter(cake::Column::BakeryId.eq(3))
.order_by_asc(cake::Column::Id)
.all(&db)
.await
.unwrap();Sourcepub fn sql_fn(
self,
predicate: impl Fn(&Statement) -> bool + Send + Sync + 'static,
) -> Self
pub fn sql_fn( self, predicate: impl Fn(&Statement) -> bool + Send + Sync + 'static, ) -> Self
Accept statements for which predicate returns true.
For conditions no other matcher expresses. The predicate sees the
whole Statement: SQL, bound values and backend.
use sea_orm::{DbBackend, EntityTrait};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock
.expect_select::<cake::Entity>()
.sql_fn(|stmt| !stmt.sql.contains("LIMIT"))
.returning::<cake::Model>([]);
let db = mock.connection().await;
cake::Entity::find().all(&db).await.unwrap();Sourcepub fn with_args(self, args: impl IntoArgs) -> Self
pub fn with_args(self, args: impl IntoArgs) -> Self
Accept only statements whose bound values match args, one by one and
in order. The statement must have exactly as many values.
args is a tuple, or a Vec, with one entry per value:
- a plain value matches an equal value:
(1, "Lemon"); Anymatches any value:(Any, "Lemon");Arg::matchingruns a custom check.
Integers compare by value, whatever their width: 1 is bound as an
i32, but matches the 1 of a BigInt column. Other values must have
the same type: a String does not match a Char, nor an f32 an
f64.
Values are checked independently of the SQL, which makes this a good
companion to the sql* matchers.
use sea_orm::{ColumnTrait, DbBackend, EntityTrait, QueryFilter, Value, sea_query::Expr};
use leadline::{Any, Arg, MockDb};
let mock = MockDb::new(DbBackend::Postgres);
mock
.expect_update::<cake::Entity>()
.with_args(("Lemon", Arg::matching(|v| matches!(v, Value::Int(Some(id)) if *id > 10))))
.rows_affected(1);
mock.expect_delete::<cake::Entity>().with_args((Any,)).rows_affected(1);
let db = mock.connection().await;
cake::Entity::update_many()
.col_expr(cake::Column::Name, Expr::value("Lemon"))
.filter(cake::Column::Id.eq(42))
.exec(&db)
.await
.unwrap();
cake::Entity::delete_by_id(7).exec(&db).await.unwrap();Sourcepub fn times(self, n: usize) -> Self
pub fn times(self, n: usize) -> Self
Expect this statement exactly n times, or up to n times when the
expectation is also maybe. The default is once.
This saves declaring the same expectation several times, for
instance for a loop. Every call gets the same result, unless it is
computed by a closure (returning_with, exec_with).
use sea_orm::{DbBackend, EntityTrait};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock.expect_delete::<cake::Entity>().times(3).rows_affected(1);
let db = mock.connection().await;
for id in 1..=3 {
cake::Entity::delete_by_id(id).exec(&db).await.unwrap();
}Sourcepub fn maybe(self) -> Self
pub fn maybe(self) -> Self
Make this expectation optional: it may be met up to its
times (once by default), or not at all.
For statements the code may or may not send, such as a lookup skipped
when a cache is warm. In an ordered mock, an optional expectation is
skipped as soon as a later one matches, and cannot be met afterwards:
with an optional SELECT expected before a DELETE, receiving the
DELETE first skips the SELECT for good.
use sea_orm::{DbBackend, EntityTrait};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock.expect_select::<cake::Entity>().maybe().returning::<cake::Model>([]);
mock.expect_delete::<cake::Entity>().rows_affected(1);
let db = mock.connection().await;
// The SELECT is never sent: the expectation is skipped.
cake::Entity::delete_by_id(1).exec(&db).await.unwrap();Sourcepub fn returning_error(self, err: DbErr)
pub fn returning_error(self, err: DbErr)
Complete the expectation by failing the statement with err.
For testing how the code under test handles database errors: constraint violations, lost connections, and so on.
use sea_orm::{DbBackend, DbErr, EntityTrait};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock
.expect_delete::<cake::Entity>()
.returning_error(DbErr::Custom("foreign key violation".into()));
let db = mock.connection().await;
let err = cake::Entity::delete_by_id(1).exec(&db).await.unwrap_err();
assert!(err.to_string().contains("foreign key violation"));Sourcepub fn returning_rows<R: IntoMockRow>(self, rows: impl IntoIterator<Item = R>)
pub fn returning_rows<R: IntoMockRow>(self, rows: impl IntoIterator<Item = R>)
Complete the expectation by returning these rows: BTreeMap<String, Value>s
spelling out every column, or models.
An empty result needs a type: Vec::<BTreeMap<String, Value>>::new().
use std::collections::BTreeMap;
use sea_orm::{ConnectionTrait, DbBackend, Statement, Value};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock
.expect_query()
.sql_contains("COUNT(*)")
.returning_rows([BTreeMap::from([("count", Value::BigInt(Some(12)))])]);
let db = mock.connection().await;
let stmt = Statement::from_string(DbBackend::Postgres, r#"SELECT COUNT(*) AS "count" FROM "cake""#);
let row = db.query_one_raw(stmt).await.unwrap().unwrap();
assert_eq!(row.try_get::<i64>("", "count").unwrap(), 12);Sourcepub fn returning_with<R, F>(self, f: F)
pub fn returning_with<R, F>(self, f: F)
Complete the expectation by computing the returned rows from the incoming
statement. Returning an Err fails the statement with it.
use std::collections::BTreeMap;
use sea_orm::{ConnectionTrait, DbBackend, Statement, Value};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock.expect_query().returning_with(|stmt| Ok(vec![BTreeMap::from([("sql", Value::from(stmt.sql.clone()))])]));
let db = mock.connection().await;
let row = db.query_one_raw(Statement::from_string(DbBackend::Postgres, "SELECT 1")).await.unwrap().unwrap();
assert_eq!(row.try_get::<String>("", "sql").unwrap(), "SELECT 1");Sourcepub fn rows_affected(self, n: u64) -> QueryResponse
pub fn rows_affected(self, n: u64) -> QueryResponse
Complete the expectation by reporting n affected rows. The returned
QueryResponse can also report a last inserted ID.
use sea_orm::{ConnectionTrait, DbBackend};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock.expect_statement().sql_contains("TRUNCATE").rows_affected(0);
let db = mock.connection().await;
db.execute_unprepared(r#"TRUNCATE "cake""#).await.unwrap();Sourcepub fn last_insert_id(self, id: u64) -> QueryResponse
pub fn last_insert_id(self, id: u64) -> QueryResponse
Complete the expectation by reporting id as the last inserted ID.
Unlike ExecExpectation::last_insert_id, this knows no entity: it only
sets the exec result, and returns no row to a statement with a RETURNING
clause. To answer such a statement, use
returning_rows.
use sea_orm::{ConnectionTrait, DbBackend};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::MySql);
mock.expect_statement().last_insert_id(5).rows_affected(1);
let db = mock.connection().await;
let res = db.execute_unprepared("INSERT INTO `cake` (`name`) VALUES ('Lemon')").await.unwrap();
assert_eq!(res.last_insert_id(), 5);Sourcepub fn exec_with<F>(self, f: F)
pub fn exec_with<F>(self, f: F)
Complete the expectation by computing the exec result from the incoming
statement. Returning an Err fails the statement with it.
use sea_orm::{ConnectionTrait, DbBackend, ProxyExecResult};
use leadline::MockDb;
let mock = MockDb::new(DbBackend::Postgres);
mock.expect_statement().exec_with(|stmt| Ok(ProxyExecResult::new(0, stmt.sql.len() as u64)));
let db = mock.connection().await;
let res = db.execute_unprepared("VACUUM").await.unwrap();
assert_eq!(res.rows_affected(), 6);Auto Trait Implementations§
impl Freeze for QueryExpectation
impl RefUnwindSafe for QueryExpectation
impl Send for QueryExpectation
impl Sync for QueryExpectation
impl Unpin for QueryExpectation
impl UnsafeUnpin for QueryExpectation
impl UnwindSafe for QueryExpectation
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Source§impl<T> Instrument for T
impl<T> Instrument for T
Source§fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
fn instrument(self, span: Span) -> Instrumented<Self> ⓘ
Source§fn in_current_span(self) -> Instrumented<Self> ⓘ
fn in_current_span(self) -> Instrumented<Self> ⓘ
Source§impl<T> IntoEither for T
impl<T> IntoEither for T
Source§fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
fn into_either(self, into_left: bool) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left is true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read moreSource§fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
fn into_either_with<F>(self, into_left: F) -> Either<Self, Self> ⓘ
self into a Left variant of Either<Self, Self>
if into_left(&self) returns true.
Converts self into a Right variant of Either<Self, Self>
otherwise. Read more