commit baeb77af99dc3315304814e40f85465e090018ed
parent 29b1e8ce589976ae81985cdc2fe0cf31115be07e
Author: Greg Heartsfield <scsibug@imap.cc>
Date: Sat, 17 Sep 2022 14:36:05 -0500
test: dynamically find open port for test relay
Diffstat:
4 files changed, 35 insertions(+), 6 deletions(-)
diff --git a/Cargo.lock b/Cargo.lock
@@ -976,6 +976,7 @@ checksum = "38bf9645c8b145698bb0b18a4637dcacbc421ea49bef2317e4fd8065a387cf21"
name = "nostr-rs-relay"
version = "0.6.2"
dependencies = [
+ "anyhow",
"bitcoin_hashes",
"config",
"console-subscriber",
diff --git a/Cargo.toml b/Cargo.toml
@@ -31,3 +31,6 @@ hyper-tls = "0.5"
http = { version = "0.2" }
parse_duration = "2"
rand = "0.8"
+
+[dev-dependencies]
+anyhow = "1"
diff --git a/tests/common/mod.rs b/tests/common/mod.rs
@@ -1,29 +1,52 @@
+use anyhow::Result;
use log::*;
use nostr_rs_relay::config;
use nostr_rs_relay::server::start_server;
+use std::net::TcpListener;
use std::sync::mpsc as syncmpsc;
use std::sync::mpsc::{Receiver as MpscReceiver, Sender as MpscSender};
use std::thread;
use std::thread::JoinHandle;
pub struct Relay {
+ pub port: u16,
pub handle: JoinHandle<()>,
pub shutdown_tx: MpscSender<()>,
}
-pub fn start_relay(port: u16) -> Relay {
+pub fn start_relay() -> Result<Relay> {
let _ = env_logger::try_init();
info!("Starting up from main");
// replace default settings
let mut settings = config::Settings::default();
- settings.database.in_memory = true;
+ // identify open port
+ let port = get_available_port().unwrap();
+ info!("Starting relay on port {}", port);
+ // bind to local interface only
+ settings.network.address = "127.0.0.1".to_owned();
settings.network.port = port;
+ // create an in-memory DB with multiple readers
+ settings.database.in_memory = true;
+ settings.database.min_conn = 4;
+ settings.database.max_conn = 8;
let (shutdown_tx, shutdown_rx): (MpscSender<()>, MpscReceiver<()>) = syncmpsc::channel();
let handle = thread::spawn(|| {
let _ = start_server(settings, shutdown_rx);
});
- return Relay {
+ return Ok(Relay {
+ port,
handle,
shutdown_tx,
- };
+ });
+}
+
+// from https://elliotekj.com/posts/2017/07/25/find-available-tcp-port-rust/
+fn get_available_port() -> Option<u16> {
+ (4000..20000).find(|port| port_is_available(*port))
+}
+fn port_is_available(port: u16) -> bool {
+ match TcpListener::bind(("127.0.0.1", port)) {
+ Ok(_) => true,
+ Err(_) => false,
+ }
}
diff --git a/tests/integration_test.rs b/tests/integration_test.rs
@@ -1,11 +1,12 @@
+use anyhow::Result;
use std::thread;
use std::time::Duration;
mod common;
#[test]
-fn startup() {
- let relay = common::start_relay(8080);
+fn startup() -> Result<()> {
+ let relay = common::start_relay()?;
// just make sure we can startup and shut down.
// if we send a shutdown message before the server is listening,
// we will get a SendError. Keep sending until someone is
@@ -24,4 +25,5 @@ fn startup() {
// wait for relay to shutdown
let thread_join = relay.handle.join();
assert!(thread_join.is_ok());
+ Ok(())
}