Skip to content

Commit b470b85

Browse files
test(testkit): let a host HTTP server listen on a chosen port
Signed-off-by: Matthew Grossman <mgrossman@nvidia.com>
1 parent a7e7bb9 commit b470b85

5 files changed

Lines changed: 101 additions & 15 deletions

File tree

‎tests/support/README.md‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ hooks and crate test settings.
3939

4040
When a test must listen on an address the environment picked, because the
4141
gateway or another service is configured to call it, the environment
42-
publishes it as `OPENSHELL_TEST_<SERVICE>_LISTEN` and the test binds it. The
43-
test never picks the address itself. Tests that bind the same address can't
42+
publishes it as `OPENSHELL_TEST_<SERVICE>_LISTEN` and the test binds it, for
43+
example with `HttpRecorder::builder().port(port)` from `host-server-support`.
44+
The test never picks the address itself. Tests that bind the same address can't
4445
run at the same time.

‎tests/support/host-server/src/http.rs‎

Lines changed: 84 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -173,14 +173,23 @@ impl HttpRecorder {
173173
pub async fn serve(
174174
handler: impl Fn(&Request) -> Response + Send + Sync + 'static,
175175
) -> Result<Self> {
176-
Self::listen(None, handler).await
176+
Self::builder().serve(handler).await
177+
}
178+
179+
/// A recorder on a chosen port or with TLS, such as on a port the
180+
/// environment published:
181+
///
182+
/// ```ignore
183+
/// let upstream = HttpRecorder::builder().port(port).tls(&identity).start("ok").await?;
184+
/// ```
185+
pub fn builder() -> HttpRecorderBuilder {
186+
HttpRecorderBuilder::default()
177187
}
178188

179189
/// Answer every request over TLS with `200` and `body`, presenting
180190
/// `identity`'s certificate.
181191
pub async fn start_tls(identity: &Identity, body: impl Into<String>) -> Result<Self> {
182-
let body = body.into();
183-
Self::serve_tls(identity, move |_| Response::text(body.clone())).await
192+
Self::builder().tls(identity).start(body).await
184193
}
185194

186195
/// Answer every request over TLS with `handler`'s response, presenting
@@ -190,14 +199,15 @@ impl HttpRecorder {
190199
identity: &Identity,
191200
handler: impl Fn(&Request) -> Response + Send + Sync + 'static,
192201
) -> Result<Self> {
193-
Self::listen(Some(identity.acceptor()?), handler).await
202+
Self::builder().tls(identity).serve(handler).await
194203
}
195204

196205
async fn listen(
206+
port: u16,
197207
tls: Option<TlsAcceptor>,
198208
handler: impl Fn(&Request) -> Response + Send + Sync + 'static,
199209
) -> Result<Self> {
200-
let (listener, port) = bind().await?;
210+
let (listener, port) = bind(port).await?;
201211
let handler: Arc<Handler> = Arc::new(handler);
202212
let requests = Arc::new(Mutex::new(Vec::new()));
203213
let connections = Arc::new(AtomicUsize::new(0));
@@ -266,6 +276,47 @@ impl HttpRecorder {
266276
}
267277
}
268278

279+
/// Options for an [`HttpRecorder`], from [`HttpRecorder::builder`].
280+
#[derive(Debug, Default)]
281+
pub struct HttpRecorderBuilder {
282+
port: u16,
283+
tls: Option<Identity>,
284+
}
285+
286+
impl HttpRecorderBuilder {
287+
/// Listen on `port` instead of a random free one. Fails to start if
288+
/// something already listens there.
289+
#[must_use]
290+
pub fn port(mut self, port: u16) -> Self {
291+
self.port = port;
292+
self
293+
}
294+
295+
/// Serve TLS, presenting `identity`'s certificate. A connection that
296+
/// fails the TLS handshake counts in
297+
/// [`connections`](HttpRecorder::connections) but records no request.
298+
#[must_use]
299+
pub fn tls(mut self, identity: &Identity) -> Self {
300+
self.tls = Some(identity.clone());
301+
self
302+
}
303+
304+
/// Answer every request with `200` and `body`.
305+
pub async fn start(self, body: impl Into<String>) -> Result<HttpRecorder> {
306+
let body = body.into();
307+
self.serve(move |_| Response::text(body.clone())).await
308+
}
309+
310+
/// Answer every request with `handler`'s response.
311+
pub async fn serve(
312+
self,
313+
handler: impl Fn(&Request) -> Response + Send + Sync + 'static,
314+
) -> Result<HttpRecorder> {
315+
let tls = self.tls.as_ref().map(Identity::acceptor).transpose()?;
316+
HttpRecorder::listen(self.port, tls, handler).await
317+
}
318+
}
319+
269320
impl Drop for HttpRecorder {
270321
fn drop(&mut self) {
271322
self.task.abort();
@@ -442,6 +493,34 @@ mod tests {
442493
);
443494
}
444495

496+
#[tokio::test]
497+
async fn http_recorder_listens_on_a_chosen_port() {
498+
let port = crate::free_port().await.unwrap();
499+
let recorder = HttpRecorder::builder()
500+
.port(port)
501+
.start("fixed")
502+
.await
503+
.unwrap();
504+
assert_eq!(recorder.port, port);
505+
let mut stream = connect(port).await;
506+
stream
507+
.write_all(b"GET / HTTP/1.1\r\nHost: test\r\n\r\n")
508+
.await
509+
.unwrap();
510+
assert!(read_to_end(&mut stream).await.ends_with("fixed"));
511+
512+
let error = HttpRecorder::builder()
513+
.port(port)
514+
.start("taken")
515+
.await
516+
.err()
517+
.unwrap();
518+
assert!(
519+
error.to_string().contains(&format!("port {port}")),
520+
"{error}"
521+
);
522+
}
523+
445524
#[tokio::test]
446525
async fn http_recorder_keeps_a_connection_alive_until_the_request_closes_it() {
447526
let recorder =

‎tests/support/host-server/src/lib.rs‎

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,8 @@
1212
//!
1313
//! - [`HttpRecorder`] answers HTTP requests with a fixed body or a handler's
1414
//! [`Response`], and records each parsed [`Request`]. It serves HTTPS with
15-
//! a certificate from a [`TestCa`].
15+
//! a certificate from a [`TestCa`], and listens on a random free port unless
16+
//! [`HttpRecorder::builder`] names one.
1617
//! - [`WebSocketRecorder`] completes the WebSocket handshake and records the
1718
//! frames that arrive.
1819
//! - [`TcpServer`] records raw bytes, and echoes them or answers once the
@@ -30,7 +31,7 @@ use std::time::Duration;
3031
use testkit::{Result, ResultExt as _};
3132
use tokio::net::TcpListener;
3233

33-
pub use http::{HttpRecorder, Request, Response};
34+
pub use http::{HttpRecorder, HttpRecorderBuilder, Request, Response};
3435
pub use tcp::{TcpServer, exchange};
3536
pub use tls::{ADDITIONAL_CA_CERT_ENV, ADDITIONAL_CA_KEY_ENV, Identity, TestCa};
3637
pub use websocket::{TEXT_REPLY, WebSocketRecorder};
@@ -43,10 +44,15 @@ const WAIT_INTERVAL: Duration = Duration::from_millis(100);
4344
const READ_TIMEOUT: Duration = Duration::from_secs(10);
4445
const MAX_REQUEST: usize = 1024 * 1024;
4546

46-
async fn bind() -> Result<(TcpListener, u16)> {
47-
let listener = TcpListener::bind(("0.0.0.0", 0))
47+
/// Listen on every host address at `port`, or at a random free port for 0.
48+
async fn bind(port: u16) -> Result<(TcpListener, u16)> {
49+
let listener = TcpListener::bind(("0.0.0.0", port))
4850
.await
49-
.context("bind a host server")?;
51+
.context(if port == 0 {
52+
"bind a host server".to_string()
53+
} else {
54+
format!("bind a host server on port {port}")
55+
})?;
5056
let port = listener
5157
.local_addr()
5258
.context("read the host server's address")?
@@ -56,7 +62,7 @@ async fn bind() -> Result<(TcpListener, u16)> {
5662

5763
/// A port that nothing on the test host listened on when this returned.
5864
pub async fn free_port() -> Result<u16> {
59-
let (_listener, port) = bind().await?;
65+
let (_listener, port) = bind(0).await?;
6066
Ok(port)
6167
}
6268

‎tests/support/host-server/src/tcp.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ impl TcpServer {
4545
}
4646

4747
async fn start(mode: Mode) -> Result<Self> {
48-
let (listener, port) = bind().await?;
48+
let (listener, port) = bind(0).await?;
4949
let received = Arc::new(Mutex::new(Vec::new()));
5050
let connections = Arc::new(AtomicUsize::new(0));
5151
let task_received = Arc::clone(&received);

‎tests/support/host-server/src/websocket.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@ struct WebSocketState {
3434

3535
impl WebSocketRecorder {
3636
pub async fn start() -> Result<Self> {
37-
let (listener, port) = bind().await?;
37+
let (listener, port) = bind(0).await?;
3838
let state = Arc::new(WebSocketState::default());
3939
let task_state = Arc::clone(&state);
4040
let task = tokio::spawn(async move {

0 commit comments

Comments
 (0)