diff options
author | Ilion Beyst <ilion.beyst@gmail.com> | 2021-12-29 19:56:31 +0100 |
---|---|---|
committer | Ilion Beyst <ilion.beyst@gmail.com> | 2021-12-29 19:56:31 +0100 |
commit | 3eeaab6cec70e7a06a99a1ac2662974f71064bee (patch) | |
tree | 9d5a2665ed32df41b2be131d5e27e8b321ce78a8 /backend/tests/util/mod.rs | |
parent | ee5af8d07625bfc7ad11b842b3941bb095aa6a6e (diff) | |
parent | 1fb4a5151bd8cfe6de4d8c19e2066a9281a0b61a (diff) | |
download | planetwars.dev-3eeaab6cec70e7a06a99a1ac2662974f71064bee.tar.xz planetwars.dev-3eeaab6cec70e7a06a99a1ac2662974f71064bee.zip |
Merge branch 'backend-server'
Diffstat (limited to 'backend/tests/util/mod.rs')
-rw-r--r-- | backend/tests/util/mod.rs | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/backend/tests/util/mod.rs b/backend/tests/util/mod.rs new file mode 100644 index 0000000..f34e9f3 --- /dev/null +++ b/backend/tests/util/mod.rs @@ -0,0 +1,59 @@ +use std::future::Future; + +use diesel::RunQueryDsl; +use mozaic4_backend::DbConn; +use rocket::{http::Header, 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( + r#" + TRUNCATE TABLE users, sessions, + bots, code_bundles"#, + ) + .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; +} + +pub struct BearerAuth { + token: String, +} + +impl BearerAuth { + pub fn new(token: String) -> Self { + Self { token } + } +} + +impl<'a> Into<Header<'a>> for BearerAuth { + fn into(self) -> Header<'a> { + Header::new("Authorization", format!("Bearer {}", self.token)) + } +} |