Skip to content

Commit

Permalink
actix-test: allow the configuration of the TestServer address
Browse files Browse the repository at this point in the history
This is useful if you're running (say) Selenium tests against a running TestServer, and the Selenium workers are Docker containers elsewhere in the network.
Not a *particularly* common use case, perhaps, but one that I can attest happens every now and then.
  • Loading branch information
mpalmer committed May 5, 2024
1 parent babac13 commit 0afdb26
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 3 deletions.
1 change: 1 addition & 0 deletions actix-test/CHANGES.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## Unreleased

- Minimum supported Rust version (MSRV) is now 1.72.
- TestServer can now be told to listen on an interface other than `localhost`, via the `TestServerConfig::listen_address()` method.

## 0.1.3

Expand Down
16 changes: 13 additions & 3 deletions actix-test/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,7 @@ where
// run server in separate orphaned thread
thread::spawn(move || {
rt::System::new().block_on(async move {
let tcp = net::TcpListener::bind(("127.0.0.1", cfg.port)).unwrap();
let tcp = net::TcpListener::bind((cfg.listen_address.clone(), cfg.port)).unwrap();
let local_addr = tcp.local_addr().unwrap();
let factory = factory.clone();
let srv_cfg = cfg.clone();
Expand Down Expand Up @@ -459,6 +459,7 @@ pub struct TestServerConfig {
tp: HttpVer,
stream: StreamType,
client_request_timeout: Duration,
listen_address: String,
port: u16,
workers: usize,
}
Expand All @@ -476,6 +477,7 @@ impl TestServerConfig {
tp: HttpVer::Both,
stream: StreamType::Tcp,
client_request_timeout: Duration::from_secs(5),
listen_address: "localhost".to_string(),
port: 0,
workers: 1,
}
Expand Down Expand Up @@ -543,6 +545,14 @@ impl TestServerConfig {
self
}

/// Sets the address the server will listen on.
///
/// By default, only listens on `localhost`.
pub fn listen_address(mut self, addr: impl Into<String>) -> Self {
self.listen_address = addr.into();
self
}

/// Sets test server port.
///
/// By default, a random free port is determined by the OS.
Expand Down Expand Up @@ -584,9 +594,9 @@ impl TestServer {
let scheme = if self.tls { "https" } else { "http" };

if uri.starts_with('/') {
format!("{}://localhost:{}{}", scheme, self.addr.port(), uri)
format!("{}://{}{}", scheme, self.addr, uri)
} else {
format!("{}://localhost:{}/{}", scheme, self.addr.port(), uri)
format!("{}://{}/{}", scheme, self.addr, uri)
}
}

Expand Down

0 comments on commit 0afdb26

Please sign in to comment.