#![allow(clippy::unwrap_used)]
#![allow(clippy::expect_used)]
#![allow(clippy::panic)]
#![allow(clippy::indexing_slicing)]
#![allow(dead_code)]
use anyhow::Result;
use secrecy::SecretString;
use sqlx::PgPool;
use std::env;
#[must_use]
pub fn metric_value_to_i64(value: f64) -> i64 {
assert!(
value.is_finite(),
"metric values must be finite, got {value}"
);
let rounded = value.round();
let as_string = format!("{rounded:.0}");
as_string
.parse::<i64>()
.unwrap_or_else(|_| panic!("metric value {value} does not fit in i64"))
}
pub fn get_test_dsn() -> String {
let dsn = env::var("PG_EXPORTER_DSN")
.unwrap_or_else(|_| "postgresql://postgres:postgres@localhost:5432/postgres".to_string());
if !dsn.contains("localhost") && !dsn.contains("127.0.0.1") && !dsn.contains("::1") {
eprintln!("WARNING: PG_EXPORTER_DSN points to a remote database!");
eprintln!("DSN: {}", dsn.replace(char::is_alphanumeric, "*"));
eprintln!("Tests should run against localhost only.");
eprintln!("Use: just test (handles this automatically)");
eprintln!(
"Or: PG_EXPORTER_DSN='postgresql://postgres:postgres@localhost:5432/postgres' cargo test"
);
panic!("Refusing to run tests against remote database. Use localhost.");
}
dsn
}
pub async fn create_test_pool() -> Result<PgPool> {
let dsn = get_test_dsn();
let pool = PgPool::connect(&dsn).await?;
Ok(pool)
}
pub fn get_test_dsn_secret() -> SecretString {
SecretString::from(get_test_dsn())
}
pub fn get_available_port() -> u16 {
use std::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").expect("Failed to bind to random port");
let port = listener
.local_addr()
.expect("Failed to get local addr")
.port();
assert!(port > 1024, "Assigned port {port} should be > 1024");
port
}
pub async fn wait_for_server(port: u16, max_attempts: u32) -> bool {
use tokio::time::{Duration, sleep};
for attempt in 1..=max_attempts {
if tokio::net::TcpStream::connect(format!("localhost:{port}"))
.await
.is_ok()
{
return true;
}
if attempt % 10 == 0 {
eprintln!("Still waiting for server on port {port} (attempt {attempt}/{max_attempts})");
}
sleep(Duration::from_millis(100)).await;
}
eprintln!("Failed to connect to server on port {port} after {max_attempts} attempts");
false
}
pub fn get_test_url(port: u16) -> String {
format!("http://localhost:{port}")
}