diff options
author | Ilion Beyst <ilion.beyst@gmail.com> | 2021-12-18 15:39:05 +0100 |
---|---|---|
committer | Ilion Beyst <ilion.beyst@gmail.com> | 2021-12-18 15:39:05 +0100 |
commit | 2dbb085008f68ed56675cf23ea6e1c89af632ea9 (patch) | |
tree | 44f025664d0188ed854b5edb35da285dc997980c /backend/tests/util | |
parent | 6aa72b3c8717f32e62c772aeed327d3cd9a6fa65 (diff) | |
download | planetwars.dev-2dbb085008f68ed56675cf23ea6e1c89af632ea9.tar.xz planetwars.dev-2dbb085008f68ed56675cf23ea6e1c89af632ea9.zip |
use async closures for tests
Diffstat (limited to 'backend/tests/util')
-rw-r--r-- | backend/tests/util/mod.rs | 39 |
1 files changed, 39 insertions, 0 deletions
diff --git a/backend/tests/util/mod.rs b/backend/tests/util/mod.rs new file mode 100644 index 0000000..3502ddb --- /dev/null +++ b/backend/tests/util/mod.rs @@ -0,0 +1,39 @@ +use std::future::Future; + +use diesel::RunQueryDsl; +use mozaic4_backend::DbConn; +use rocket::local::asynchronous::Client; + +// We use a lock to synchronize between tests so DB operations don't collide. +// For now. In the future, we'll have a nice way to run each test in a DB +// transaction so we can regain concurrency. +static DB_LOCK: parking_lot::Mutex<()> = parking_lot::const_mutex(()); + +async fn reset_db(db: &DbConn) { + db.run(|conn| { + diesel::sql_query("TRUNCATE TABLE users, sessions") + .execute(conn) + .expect("drop all tables"); + }) + .await +} + +pub async fn run_test<F, R>(test_closure: F) +where + F: FnOnce(Client, DbConn) -> R, + R: Future<Output = ()>, +{ + let _lock = DB_LOCK.lock(); + + let client = Client::untracked(mozaic4_backend::rocket()) + .await + .expect("failed to create test client"); + let db = mozaic4_backend::DbConn::get_one(client.rocket()) + .await + .expect("failed to get db connection"); + + // make sure we start with a clean DB + reset_db(&db).await; + + test_closure(client, db).await; +} |