Request Matchers
This section describes matcher functions designed to target and match the TCP port in incoming HTTP requests.
These matchers are especially useful when using the proxy and record-and-playback features of httpmock
.
port
Specifies the expected port number for incoming requests to match.
This constraint is especially useful when working with proxy or forwarding rules, but it can also be used to serve mocks (e.g., when using a mock server as a proxy).
Parameters
port
: A value convertible tou16
, representing the expected port number.
Example
use httpmock::prelude::*;use reqwest::blocking::Client;
// Start a new mock serverlet server = MockServer::start();
// Configure a mock to respond to requests made to `github.com`// with a specific portserver.mock(|when, then| { when.port(80); // Specify the expected port then.body("This is a mock response");});
// Set up an HTTP client to use the mock server as a proxylet client = Client::builder() // Proxy all requests to the mock server .proxy(reqwest::Proxy::all(&server.base_url()).unwrap()) .build() .unwrap();
// Send a GET request to `github.com` on port 80.// The request will be sent to our mock server due to the HTTP client proxy settings.let response = client.get("http://github.com:80").send().unwrap();
// Validate that the mock server returned the expected responseassert_eq!(response.text().unwrap(), "This is a mock response");
Errors
- This function will panic if the port number cannot be converted to a valid
u16
value.
Returns
The updated When
instance to allow method chaining.
port_not
Specifies the port number that incoming requests must not match.
This constraint is especially useful when working with proxy or forwarding rules, but it can also be used to serve mocks (e.g., when using a mock server as a proxy).
To add multiple excluded ports, invoke this function multiple times.
Parameters
port
: A value convertible tou16
, representing the port number to be excluded.
Example
use httpmock::prelude::*;use reqwest::blocking::Client;
// Start a new mock serverlet server = MockServer::start();
// Configure a mock to respond to requests not using port 81server.mock(|when, then| { when.port_not(81); // Exclude requests on port 81 then.body("This is a mock response");});
// Set up an HTTP client to use the mock server as a proxylet client = Client::builder() .proxy(reqwest::Proxy::all(&server.base_url()).unwrap()) .build() .unwrap();
// Make a request to `github.com` on port 80, which will trigger// the mock responselet response = client.get("http://github.com:80").send().unwrap();
// Validate that the mock server returned the expected responseassert_eq!(response.text().unwrap(), "This is a mock response");
Errors
- This function will panic if the port number cannot be converted to a valid
u16
value.
Returns
The updated When
instance to enable method chaining.