college/Summer-2024/CS-3443/LakeWatch/LakeWatchAPI/tests/api/helpers.rs

43 lines
1.2 KiB
Rust

use lakewatch::configuration::get_configuration;
use sqlx::PgPool;
use uuid::Uuid;
pub struct TestApp {
pub socket_addr: std::net::SocketAddr,
}
impl TestApp {
pub async fn spawn(db_pool: &PgPool) -> Self {
let config = {
let mut c = get_configuration().expect("Failed to get configuration!");
c.db.name = Uuid::new_v4().to_string();
c.app.port = 0;
c.app.host = "127.0.0.1".to_string();
c
};
let listener = tokio::net::TcpListener::bind(&config.app.connection_string())
.await
.expect("Failed to bind random port!");
let socket_addr = lakewatch::startup::Application::run(listener, db_pool.clone(), false)
.await
.expect("Failed to run API!");
Self { socket_addr }
}
pub fn url(&self, path: &str) -> String {
let address = format!(
"http://{}:{}",
self.socket_addr.ip(),
self.socket_addr.port()
);
if path.starts_with('/') {
format!("{}{}", address, path)
} else {
format!("{}/{}", address, path)
}
}
}