Skip to content

Commit

Permalink
[tests] Use pid to ensure unique port #909 (#910)
Browse files Browse the repository at this point in the history
* Update config.rs

* Update integration.rs
  • Loading branch information
michaelvlach authored Dec 22, 2023
1 parent 952f5e4 commit 35bef94
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 14 deletions.
31 changes: 31 additions & 0 deletions agdb_server/src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,3 +31,34 @@ pub(crate) fn new() -> ServerResult<Config> {

Ok(Config::new(config))
}

#[cfg(test)]
mod tests {
use super::*;
use crate::config;
use std::path::Path;

struct TestFile {}

impl TestFile {
fn new() -> Self {
let _ = std::fs::remove_file(CONFIG_FILE);
Self {}
}
}

impl Drop for TestFile {
fn drop(&mut self) {
let _ = std::fs::remove_file(CONFIG_FILE);
}
}

#[test]
fn default_values() {
let _test_file = TestFile::new();
assert!(!Path::new(CONFIG_FILE).exists());
let _config = config::new().unwrap();
assert!(Path::new(CONFIG_FILE).exists());
let _config = config::new().unwrap();
}
}
26 changes: 12 additions & 14 deletions agdb_server/tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -93,26 +93,24 @@ pub struct ServerUser {

impl TestServer {
pub async fn new() -> anyhow::Result<Self> {
let port = PORT.fetch_add(1, Ordering::Relaxed);
let port = PORT.fetch_add(1, Ordering::Relaxed) + std::process::id() as u16;
let dir = format!("{BINARY}.{port}.test");
let data_dir = format!("{dir}/{SERVER_DATA_DIR}");

Self::remove_dir_if_exists(&dir)?;
std::fs::create_dir(&dir)?;

if port != DEFAULT_PORT {
let mut config = HashMap::<&str, serde_yaml::Value>::new();
config.insert("host", HOST.into());
config.insert("port", port.into());
config.insert("admin", ADMIN.into());
config.insert("data_dir", SERVER_DATA_DIR.into());

let file = std::fs::File::options()
.create_new(true)
.write(true)
.open(Path::new(&dir).join(CONFIG_FILE))?;
serde_yaml::to_writer(file, &config)?;
}
let mut config = HashMap::<&str, serde_yaml::Value>::new();
config.insert("host", HOST.into());
config.insert("port", port.into());
config.insert("admin", ADMIN.into());
config.insert("data_dir", SERVER_DATA_DIR.into());

let file = std::fs::File::options()
.create_new(true)
.write(true)
.open(Path::new(&dir).join(CONFIG_FILE))?;
serde_yaml::to_writer(file, &config)?;

let process = Command::cargo_bin(BINARY)?.current_dir(&dir).spawn()?;
let client = reqwest::Client::new();
Expand Down

0 comments on commit 35bef94

Please sign in to comment.