pub struct When { /* private fields */ }
Expand description
A type that allows the specification of HTTP request values.
Implementations§
source§impl When
impl When
sourcepub fn any_request(self) -> Self
pub fn any_request(self) -> Self
Sets the mock server to respond to any incoming request.
Example
use httpmock::prelude::*;
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.any_request();
then.status(200);
});
isahc::get(server.url("/anyPath")).unwrap();
mock.assert();
sourcepub fn path<S: Into<String>>(self, path: S) -> Self
pub fn path<S: Into<String>>(self, path: S) -> Self
Sets the expected URL path.
path
- The URL path.
Example
use httpmock::prelude::*;
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.path("/test");
then.status(200);
});
isahc::get(server.url("/test")).unwrap();
mock.assert();
sourcepub fn path_contains<S: Into<String>>(self, substring: S) -> Self
pub fn path_contains<S: Into<String>>(self, substring: S) -> Self
Sets an substring that the URL path needs to contain.
substring
- The substring to match against.
Example
use httpmock::prelude::*;
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.path_contains("es");
then.status(200);
});
isahc::get(server.url("/test")).unwrap();
mock.assert();
sourcepub fn path_matches<R: Into<Regex>>(self, regex: R) -> Self
pub fn path_matches<R: Into<Regex>>(self, regex: R) -> Self
Sets a regex that the URL path needs to match.
regex
- The regex to match against.
Example
use httpmock::prelude::*;
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.path_matches(Regex::new("le$").unwrap());
then.status(200);
});
isahc::get(server.url("/example")).unwrap();
mock.assert();
sourcepub fn query_param<SK: Into<String>, SV: Into<String>>(
self,
name: SK,
value: SV
) -> Self
pub fn query_param<SK: Into<String>, SV: Into<String>>( self, name: SK, value: SV ) -> Self
Sets a query parameter that needs to be provided.
Attention!: The request query keys and values are implicitly allowed, but is not required to be urlencoded! The value you pass here, however, must be in plain text (i.e. not encoded)!
name
- The query parameter name that will matched against.value
- The value parameter name that will matched against.
// Arrange
use isahc::get;
use httpmock::prelude::*;
let _ = env_logger::try_init();
let server = MockServer::start();
let m = server.mock(|when, then|{
when.query_param("query", "Metallica is cool");
then.status(200);
});
// Act
get(server.url("/search?query=Metallica+is+cool")).unwrap();
// Assert
m.assert();
sourcepub fn query_param_exists<S: Into<String>>(self, name: S) -> Self
pub fn query_param_exists<S: Into<String>>(self, name: S) -> Self
Sets a query parameter that needs to exist in an HTTP request.
Attention!: The request query key is implicitly allowed, but is not required to be urlencoded! The value you pass here, however, must be in plain text (i.e. not encoded)!
name
- The query parameter name that will matched against.
// Arrange
use isahc::get;
use httpmock::prelude::*;
let _ = env_logger::try_init();
let server = MockServer::start();
let m = server.mock(|when, then| {
when.query_param_exists("query");
then.status(200);
});
// Act
get(server.url("/search?query=Metallica")).unwrap();
// Assert
m.assert();
sourcepub fn x_www_form_urlencoded_tuple<SK: Into<String>, SV: Into<String>>(
self,
key: SK,
value: SV
) -> Self
pub fn x_www_form_urlencoded_tuple<SK: Into<String>, SV: Into<String>>( self, key: SK, value: SV ) -> Self
Sets a requirement for a tuple in an x-www-form-urlencoded request body. Please refer to https://url.spec.whatwg.org/#application/x-www-form-urlencoded for more information.
use httpmock::prelude::*;
use isahc::{prelude::*, Request};
// Arrange
let server = MockServer::start();
let m = server.mock(|when, then| {
when.method(POST)
.path("/example")
.header("content-type", "application/x-www-form-urlencoded")
.x_www_form_urlencoded_tuple("name", "Peter Griffin")
.x_www_form_urlencoded_tuple("town", "Quahog");
then.status(202);
});
let response = Request::post(server.url("/example"))
.header("content-type", "application/x-www-form-urlencoded")
.body("name=Peter%20Griffin&town=Quahog")
.unwrap()
.send()
.unwrap();
// Assert
m.assert();
assert_eq!(response.status(), 202);
sourcepub fn x_www_form_urlencoded_key_exists<S: Into<String>>(self, key: S) -> Self
pub fn x_www_form_urlencoded_key_exists<S: Into<String>>(self, key: S) -> Self
Sets a requirement for a tuple key in an x-www-form-urlencoded request body. Please refer to https://url.spec.whatwg.org/#application/x-www-form-urlencoded for more information.
use httpmock::prelude::*;
use isahc::{prelude::*, Request};
// Arrange
let server = MockServer::start();
let m = server.mock(|when, then| {
when.method(POST)
.path("/example")
.header("content-type", "application/x-www-form-urlencoded")
.x_www_form_urlencoded_key_exists("name")
.x_www_form_urlencoded_key_exists("town");
then.status(202);
});
let response = Request::post(server.url("/example"))
.header("content-type", "application/x-www-form-urlencoded")
.body("name=Peter%20Griffin&town=Quahog")
.unwrap()
.send()
.unwrap();
// Assert
m.assert();
assert_eq!(response.status(), 202);
sourcepub fn body<S: Into<String>>(self, body: S) -> Self
pub fn body<S: Into<String>>(self, body: S) -> Self
Sets the required HTTP request body content.
body
- The required HTTP request body.
Example
use httpmock::prelude::*;
use isahc::{prelude::*, Request};
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.body("The Great Gatsby");
then.status(200);
});
Request::post(&format!("http://{}/test", server.address()))
.body("The Great Gatsby")
.unwrap()
.send()
.unwrap();
mock.assert();
sourcepub fn body_matches<R: Into<Regex>>(self, regex: R) -> Self
pub fn body_matches<R: Into<Regex>>(self, regex: R) -> Self
Sets a Regex for the expected HTTP body.
regex
- The regex that the HTTP request body will matched against.
use isahc::{prelude::*, Request};
use httpmock::prelude::*;
// Arrange
let _ = env_logger::try_init();
let server = MockServer::start();
let m = server.mock(|when, then|{
when.method(POST)
.path("/books")
.body_matches(Regex::new("Fellowship").unwrap());
then.status(201);
});
// Act: Send the request
let response = Request::post(server.url("/books"))
.body("The Fellowship of the Ring")
.unwrap()
.send()
.unwrap();
// Assert
m.assert();
assert_eq!(response.status(), 201);
sourcepub fn body_contains<S: Into<String>>(self, substring: S) -> Self
pub fn body_contains<S: Into<String>>(self, substring: S) -> Self
Sets the expected HTTP body substring.
substring
- The substring that will matched against.
use httpmock::prelude::*;
use isahc::{prelude::*, Request};
// Arrange
let _ = env_logger::try_init();
let server = MockServer::start();
let m = server.mock(|when, then|{
when.path("/books")
.body_contains("Ring");
then.status(201);
});
// Act: Send the request
let response = Request::post(server.url("/books"))
.body("The Fellowship of the Ring")
.unwrap()
.send()
.unwrap();
// Assert
m.assert();
assert_eq!(response.status(), 201);
sourcepub fn json_body<V: Into<Value>>(self, value: V) -> Self
pub fn json_body<V: Into<Value>>(self, value: V) -> Self
Sets the expected JSON body. This method expects a serde_json::Value that will be serialized/deserialized to/from a JSON string.
Note that this method does not set the content-type
header automatically, so you
need to provide one yourself!
body
- The HTTP body object that will be serialized to JSON using serde.
use httpmock::prelude::*;
use serde_json::json;
use isahc::{prelude::*, Request};
// Arrange
let _ = env_logger::try_init();
let server = MockServer::start();
let m = server.mock(|when, then|{
when.path("/user")
.header("content-type", "application/json")
.json_body(json!({ "name": "Hans" }));
then.status(201);
});
// Act: Send the request and deserialize the response to JSON
let mut response = Request::post(&format!("http://{}/user", server.address()))
.header("content-type", "application/json")
.body(json!({ "name": "Hans" }).to_string())
.unwrap()
.send()
.unwrap();
// Assert
m.assert();
assert_eq!(response.status(), 201);
sourcepub fn json_body_obj<'a, T>(self, body: &T) -> Selfwhere
T: Serialize + Deserialize<'a>,
pub fn json_body_obj<'a, T>(self, body: &T) -> Selfwhere
T: Serialize + Deserialize<'a>,
Sets the expected JSON body. This method expects a serializable serde object that will be serialized/deserialized to/from a JSON string.
Note that this method does not set the “content-type” header automatically, so you need to provide one yourself!
body
- The HTTP body object that will be serialized to JSON using serde.
use httpmock::prelude::*;
use serde_json::json;
use isahc::{prelude::*, Request};
// This is a temporary type that we will use for this test
#[derive(serde::Serialize, serde::Deserialize)]
struct TestUser {
name: String,
}
// Arrange
let _ = env_logger::try_init();
let server = MockServer::start();
let m = server.mock(|when, then|{
when.path("/user")
.header("content-type", "application/json")
.json_body_obj(&TestUser {
name: String::from("Fred"),
});
then.status(200);
});
// Act: Send the request and deserialize the response to JSON
let mut response = Request::post(&format!("http://{}/user", server.address()))
.header("content-type", "application/json")
.body(json!(&TestUser {
name: "Fred".to_string()
}).to_string())
.unwrap()
.send()
.unwrap();
// Assert
m.assert();
assert_eq!(response.status(), 200);
sourcepub fn json_body_partial<S: Into<String>>(self, partial: S) -> Self
pub fn json_body_partial<S: Into<String>>(self, partial: S) -> Self
Sets the expected partial JSON body.
Attention: The partial string needs to be a valid JSON string. It must contain the full object hierarchy from the original JSON object but can leave out irrelevant attributes (see example).
Note that this method does not set the content-type
header automatically, so you
need to provide one yourself!
String format and attribute order are irrelevant.
partial_body
- The HTTP body object that will be serialized to JSON using serde.
Example
Suppose your application sends the following JSON request body:
{
"parent_attribute" : "Some parent data goes here",
"child" : {
"target_attribute" : "Example",
"other_attribute" : "Another value"
}
}
If we only want to verify that target_attribute
has value Example
without the need
to provide a full JSON object, we can use this method as follows:
use httpmock::prelude::*;
let server = MockServer::start();
let mut mock = server.mock(|when, then|{
when.json_body_partial(r#"
{
"child" : {
"target_attribute" : "Example"
}
}
"#);
then.status(200);
});
Please note that the JSON partial contains the full object hierarchy, i.e. it needs to start
from the root! It leaves out irrelevant attributes, however (parent_attribute
and child.other_attribute
).
sourcepub fn header<SK: Into<String>, SV: Into<String>>(
self,
name: SK,
value: SV
) -> Self
pub fn header<SK: Into<String>, SV: Into<String>>( self, name: SK, value: SV ) -> Self
Sets the expected HTTP header.
name
- The HTTP header name (header names are case-insensitive by RFC 2616).value
- The header value.
Example
use httpmock::prelude::*;
use isahc::{prelude::*, Request};
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.header("Authorization", "token 1234567890");
then.status(200);
});
Request::post(&format!("http://{}/test", server.address()))
.header("Authorization", "token 1234567890")
.body(())
.unwrap()
.send()
.unwrap();
mock.assert();
sourcepub fn header_exists<S: Into<String>>(self, name: S) -> Self
pub fn header_exists<S: Into<String>>(self, name: S) -> Self
Sets the requirement that the HTTP request needs to contain a specific header (value is unchecked, refer to Mock::expect_header).
name
- The HTTP header name (header names are case-insensitive by RFC 2616).
Example
use httpmock::prelude::*;
use isahc::{prelude::*, Request};
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.header_exists("Authorization");
then.status(200);
});
Request::post(&format!("http://{}/test", server.address()))
.header("Authorization", "token 1234567890")
.body(())
.unwrap()
.send()
.unwrap();
mock.assert();
Sets the cookie that needs to exist in the HTTP request. Cookie parsing follows RFC-6265. Attention: Cookie names are case-sensitive.
name
- The cookie name.value
- The expected cookie value.
Note: This function is only available when the
cookies
feature is enabled. It is enabled by default.
Example
use httpmock::prelude::*;
use isahc::{prelude::*, Request};
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.cookie("SESSIONID", "1234567890");
then.status(200);
});
Request::post(&format!("http://{}/test", server.address()))
.header("Cookie", "TRACK=12345; SESSIONID=1234567890; CONSENT=1")
.body(())
.unwrap()
.send()
.unwrap();
mock.assert();
Sets the cookie that needs to exist in the HTTP request. Cookie parsing follows RFC-6265. Attention: Cookie names are case-sensitive.
name
- The cookie name
Note: This function is only available when the
cookies
feature is enabled. It is enabled by default.
Example
use httpmock::prelude::*;
use isahc::{prelude::*, Request};
let server = MockServer::start();
let mock = server.mock(|when, then|{
when.cookie_exists("SESSIONID");
then.status(200);
});
Request::post(&format!("http://{}/test", server.address()))
.header("Cookie", "TRACK=12345; SESSIONID=1234567890; CONSENT=1")
.body(())
.unwrap()
.send()
.unwrap();
mock.assert();
sourcepub fn matches(self, matcher: fn(_: &HttpMockRequest) -> bool) -> Self
pub fn matches(self, matcher: fn(_: &HttpMockRequest) -> bool) -> Self
Sets a custom matcher for expected HTTP request. If this function returns true, the request is considered a match and the mock server will respond to the request (given all other criteria are also met).
matcher
- The matcher function.
Example:
use httpmock::prelude::*;
// Arrange
let server = MockServer::start();
let m = server.mock(|when, then|{
when.matches(|req: &HttpMockRequest| {
req.path.contains("es")
});
then.status(200);
});
// Act: Send the HTTP request
let response = isahc::get(server.url("/test")).unwrap();
// Assert
m.assert();
assert_eq!(response.status(), 200);
sourcepub fn and(self, func: fn(_: When) -> When) -> Self
pub fn and(self, func: fn(_: When) -> When) -> Self
A semantic convenience for applying multiple operations
on a given When
instance via an discrete encapsulating
function.
Example:
// Assuming an encapsulating function like:
fn is_authorized_json_post_request(when: When) -> When {
when.method(httpmock::Method::POST)
.header("authorization", "SOME API KEY")
.header("content-type", "application/json")
}
// It can be applied without breaking the usual `When`
// semantic style. Meaning instead of:
is_authorized_json_post_request(when.json_body_partial(r#"{"key": "value"}"#))
// the `and` method can be used to preserve the
// legibility of the method chain:
when.query_param("some-param", "some-value")
.and(is_authorized_json_post_request)
.json_body_partial(r#"{"key": "value"}"#)
// is still intuitively legible as "when some query
// parameter equals "some-value", the request is an
// authorized POST request, and the request body
// is the literal JSON object `{"key": "value"}`.