-
Notifications
You must be signed in to change notification settings - Fork 2
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat: sqlx migrations in test hooks #16
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,4 @@ | ||
DROP DATABASE RATINGS; | ||
DROP USER IF EXISTS service; | ||
REVOKE USAGE, CREATE ON SCHEMA public FROM migration_user; | ||
DROP USER IF EXISTS migration_user; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
CREATE USER migration_user WITH PASSWORD 'strongpassword'; | ||
CREATE USER service WITH PASSWORD 'covfefe!1'; | ||
CREATE DATABASE ratings; | ||
-- /c ratings; | ||
GRANT CONNECT ON DATABASE ratings TO migration_user; | ||
GRANT USAGE, CREATE ON SCHEMA public TO migration_user; |
Empty file.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,9 @@ | ||
REVOKE ALL PRIVILEGES ON TABLE users FROM service; | ||
REVOKE USAGE, SELECT ON SEQUENCE users_id_seq FROM service; | ||
REVOKE ALL PRIVILEGES ON TABLE votes FROM service; | ||
REVOKE USAGE, SELECT ON SEQUENCE votes_id_seq FROM service; | ||
REVOKE CONNECT ON DATABASE ratings FROM service; | ||
|
||
DROP TABLE IF EXISTS votes; | ||
DROP TABLE IF EXISTS users; | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
use std::error::Error; | ||
use std::fmt::{Debug, Formatter}; | ||
use std::sync::Arc; | ||
|
||
use sqlx::{postgres::PgPoolOptions, PgPool}; | ||
|
||
const MIGRATIONS_PATH: &str = "sql/migrations"; | ||
|
||
#[derive(Clone)] | ||
pub struct Migrator { | ||
pub pool: Arc<PgPool>, | ||
} | ||
|
||
#[allow(dead_code)] | ||
impl Migrator { | ||
pub async fn new(uri: &str) -> Result<Migrator, Box<dyn Error>> { | ||
let pool = PgPoolOptions::new().max_connections(1).connect(uri).await?; | ||
let pool = Arc::new(pool); | ||
Ok(Migrator { pool }) | ||
} | ||
|
||
pub async fn run(&self) -> Result<(), sqlx::Error> { | ||
let m = sqlx::migrate::Migrator::new(std::path::Path::new(MIGRATIONS_PATH)).await?; | ||
|
||
m.run(&mut self.pool.acquire().await?).await?; | ||
Ok(()) | ||
} | ||
|
||
pub async fn revert(&self) -> Result<(), sqlx::Error> { | ||
let m = sqlx::migrate::Migrator::new(std::path::Path::new(MIGRATIONS_PATH)).await?; | ||
|
||
m.undo(&mut self.pool.acquire().await?, 1).await?; | ||
|
||
Ok(()) | ||
} | ||
} | ||
|
||
impl Debug for Migrator { | ||
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { | ||
f.write_str("Migrator { migrations_pool }") | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,6 +1,8 @@ | ||
pub mod config; | ||
pub mod infrastructure; | ||
pub mod jwt; | ||
pub mod migrator; | ||
|
||
pub use config::Config; | ||
pub use infrastructure::Infrastructure; | ||
pub use migrator::Migrator; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,32 @@ | ||
use std::sync::Arc; | ||
use std::sync::{Arc, Once}; | ||
|
||
use once_cell::sync::Lazy; | ||
use ratings::utils::Migrator; | ||
use tokio::sync::Mutex; | ||
|
||
static INITIALIZATION_FLAG: Lazy<Arc<Mutex<bool>>> = Lazy::new(|| Arc::new(Mutex::new(false))); | ||
|
||
pub async fn before_all() { | ||
let mutex = Arc::clone(&*INITIALIZATION_FLAG); | ||
let mut initialised = mutex.lock().await; | ||
|
||
if !*initialised { | ||
*initialised = true; | ||
static INIT: Once = Once::new(); | ||
static TEST_COUNTER: Lazy<Arc<Mutex<i32>>> = Lazy::new(|| Arc::new(Mutex::new(0))); | ||
|
||
pub async fn before_all(migrator: Migrator) { | ||
INIT.call_once(|| { | ||
tracing_subscriber::fmt().init(); | ||
}); | ||
if let Err(e) = migrator.run().await { | ||
panic!("{}", e) | ||
} | ||
|
||
let counter = Arc::clone(&*TEST_COUNTER); | ||
let mut test_counter = counter.lock().await; | ||
*test_counter += 1; | ||
} | ||
|
||
pub async fn after_all() {} | ||
pub async fn after_all(migrator: Migrator) { | ||
let counter = Arc::clone(&*TEST_COUNTER); | ||
let mut test_counter = counter.lock().await; | ||
*test_counter -= 1; | ||
if *test_counter == 0 { | ||
if let Err(e) = migrator.revert().await { | ||
panic!("{}", e) | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,12 +1,13 @@ | ||
use std::future::Future; | ||
|
||
use crate::helpers::hooks::{after_all, before_all}; | ||
use ratings::utils::Migrator; | ||
|
||
pub async fn with_lifecycle<F>(f: F) | ||
pub async fn with_lifecycle<F>(f: F, migrator: Migrator) | ||
where | ||
F: Future<Output = ()>, | ||
{ | ||
before_all().await; | ||
before_all(migrator.clone()).await; | ||
f.await; | ||
after_all().await; | ||
after_all(migrator.clone()).await; | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,42 +1,50 @@ | ||
use ratings::utils::Config; | ||
use ratings::utils::{Config, Migrator}; | ||
use tonic::Code; | ||
|
||
use super::super::helpers::{client_user::UserClient, with_lifecycle::with_lifecycle}; | ||
|
||
#[tokio::test] | ||
async fn blank() -> Result<(), Box<dyn std::error::Error>> { | ||
let config = Config::load()?; | ||
let migrator = Migrator::new(&config.migration_postgres_uri).await?; | ||
|
||
with_lifecycle(async { | ||
let id = ""; | ||
let client = UserClient::new(&config.socket()); | ||
with_lifecycle( | ||
async { | ||
let id = ""; | ||
let client = UserClient::new(&config.socket()); | ||
|
||
match client.register(id).await { | ||
Ok(response) => panic!("expected Err but got Ok: {response:?}"), | ||
Err(status) => { | ||
assert_eq!(status.code(), Code::InvalidArgument) | ||
match client.register(id).await { | ||
Ok(response) => panic!("expected Err but got Ok: {response:?}"), | ||
Err(status) => { | ||
assert_eq!(status.code(), Code::InvalidArgument) | ||
} | ||
} | ||
} | ||
}) | ||
}, | ||
migrator, | ||
) | ||
.await; | ||
Ok(()) | ||
} | ||
|
||
#[tokio::test] | ||
async fn wrong_length() -> Result<(), Box<dyn std::error::Error>> { | ||
let config = Config::load()?; | ||
let migrator = Migrator::new(&config.migration_postgres_uri).await?; | ||
|
||
with_lifecycle(async { | ||
let client_hash = "foobarbazbun"; | ||
let client = UserClient::new(&config.socket()); | ||
with_lifecycle( | ||
async { | ||
let client_hash = "foobarbazbun"; | ||
let client = UserClient::new(&config.socket()); | ||
|
||
match client.register(client_hash).await { | ||
Ok(response) => panic!("expected Err but got Ok: {response:?}"), | ||
Err(status) => { | ||
assert_eq!(status.code(), Code::InvalidArgument) | ||
match client.register(client_hash).await { | ||
Ok(response) => panic!("expected Err but got Ok: {response:?}"), | ||
Err(status) => { | ||
assert_eq!(status.code(), Code::InvalidArgument) | ||
} | ||
} | ||
} | ||
}) | ||
}, | ||
migrator, | ||
) | ||
.await; | ||
Ok(()) | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I assume this means that clippy doesn't consider code invoked from
/tests/
for this lint?I think for now, we should opt to #[allow(lint_xyz)] to reduce noise. We can remove these allows as / when they're no longer needed. WDYT?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Yes, its strange. It's right that it isn't used in the bin module, but it is exposed by the lib, and used in tests. I'll tag them for now.