nom-nom-nix-gc/tests/db.rs
2023-11-27 12:09:26 +01:00

75 lines
2.4 KiB
Rust

use std::{process::{Command, Child}, env::temp_dir, path::PathBuf, fs::remove_dir_all, fs::read_dir, time::Duration};
use nom_nom_gc::models::{Configuration, AppState, User};
use tokio::time::sleep;
use uuid::Uuid;
use anyhow::Result;
struct TestDB {
path: PathBuf,
pid: Child,
db_name: String,
port: u16
}
async fn setup_db() -> Result<TestDB> {
let mut dbdir = temp_dir();
let dir_uuid = Uuid::new_v4();
let db_name = "nom-nom-integration-test".to_string();
let port: u16 = 12345;
dbdir.push(dir_uuid.to_string());
let dbdir_str = dbdir.to_str().unwrap();
Command::new("initdb")
.arg(&dbdir)
.spawn()?
.wait()?;
let db_proc_handle = Command::new("postgres")
.args(["-D", dbdir_str, "-c", &format!("unix_socket_directories={}", dbdir_str), "-c", "listen_addresses=", "-c", &format!("port={}", &port.to_string())])
.spawn()?;
sleep(Duration::from_secs(1)).await;
Command::new("createdb")
.args([ "-h", dbdir_str, "-p", &port.to_string(), &db_name])
.spawn()?
.wait()?;
Ok(TestDB{ path: dbdir, pid: db_proc_handle, db_name, port })
}
fn teardown_db(mut db: TestDB) -> Result <()> {
println!("Stopping postgres");
db.pid.kill()?;
remove_dir_all(db.path)?;
Ok(())
}
#[tokio::test]
async fn test_db() {
let mdb = setup_db().await;
let db = mdb.expect("setup db");
let mut dbpath = db.path.to_str().unwrap().to_string();
dbpath.push('/');
let conf = Configuration {
url: "http://localhost:9000".to_string(),
db_port: Some(db.port),
db_host: Some(dbpath),
db_name: db.db_name.clone()
};
println!("Listing dir:");
let postgres_content = read_dir(&db.path).unwrap();
for file in postgres_content {
println!("{}", file.unwrap().path().display());
}
let state = AppState::new(conf);
let migrations_res = state.run_migrations().await;
let test_user = User { user_name: "test-user".to_owned() };
let uuid = state.generate_registration_link(test_user.clone()).await.expect("should generate registration uuid for test user");
let usr2 = state.retrieve_registration_link(uuid).await.expect("should retrieve user from reg uuid");
let usr2 = usr2.expect("should retrieve user from reg uuid");
assert_eq!(test_user.user_name, usr2.user_name);
teardown_db(db).expect("Failed to teardown DB.");
migrations_res.expect("migrations should not fail");
}