Skip to content

Commit

Permalink
Add networking/port test utils fn(s)
Browse files Browse the repository at this point in the history
  • Loading branch information
jbesraa committed Sep 30, 2024
1 parent 49bca60 commit b40240c
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
7 changes: 4 additions & 3 deletions roles/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions roles/tests-integration/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ edition = "2021"
bitcoind = "0.36.0"
flate2 = "1.0.32"
minreq = { version = "2.12.0", features = ["https"] }
once_cell = "1.20.0"
tar = "0.4.41"

[lib]
Expand Down
27 changes: 27 additions & 0 deletions roles/tests-integration/tests/common/mod.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
use bitcoind::{bitcoincore_rpc::RpcApi, BitcoinD, Conf};
use flate2::read::GzDecoder;
use once_cell::sync::Lazy;
use std::{
collections::HashSet,
env,
fs::{create_dir_all, File},
io::{BufReader, Read},
net::TcpListener,
path::{Path, PathBuf},
sync::Mutex,
};
use tar::Archive;

// prevents get_available_port from ever returning the same port twice
static UNIQUE_PORTS: Lazy<Mutex<HashSet<u16>>> = Lazy::new(|| Mutex::new(HashSet::new()));

const VERSION_TP: &str = "0.1.7";

fn download_bitcoind_tarball(download_url: &str) -> Vec<u8> {
Expand Down Expand Up @@ -148,3 +155,23 @@ impl TemplateProvider {
.unwrap();
}
}

pub fn is_port_open(address: std::net::SocketAddr) -> bool {
TcpListener::bind(address).is_err()
}

pub fn get_available_port() -> u16 {
let mut unique_ports = UNIQUE_PORTS.lock().unwrap();

loop {
let port = TcpListener::bind("127.0.0.1:0")
.unwrap()
.local_addr()
.unwrap()
.port();
if !unique_ports.contains(&port) {
unique_ports.insert(port);
return port;
}
}
}

0 comments on commit b40240c

Please sign in to comment.