[][src]Struct httpmock::When

pub struct When { /* fields omitted */ }

A type that allows the specification of HTTP request values.

Implementations

impl When[src]

pub fn any_request(self) -> Self[src]

Sets the mock server to respond to any incoming request.

Example

use httpmock::{Mock, MockServer};
use httpmock::Method::GET;
use regex::Regex;

let server = MockServer::start();

let mock = server.mock(|when, then|{
    when.any_request();
    then.status(200);
});

isahc::get(server.url("/anyPath")).unwrap();

mock.assert();

pub fn method<M: Into<Method>>(self, method: M) -> Self[src]

Sets the expected HTTP method.

  • method - The HTTP method (a Method or a String).

Example

use httpmock::{Mock, MockServer};
use httpmock::Method::GET;
use regex::Regex;

let server = MockServer::start();

let mock = server.mock(|when, then|{
    when.method(GET);
    then.status(200);
});

isahc::get(server.url("/")).unwrap();

mock.assert();

pub fn path<S: Into<String>>(self, path: S) -> Self[src]

Sets the expected URL path.

  • path - The URL path.

Example

use httpmock::{Mock, MockServer};

let server = MockServer::start();

let mock = server.mock(|when, then|{
    when.path_contains("/test");
    then.status(200);
});

isahc::get(server.url("/test")).unwrap();

mock.assert();

pub fn path_contains<S: Into<String>>(self, substring: S) -> Self[src]

Sets an substring that the URL path needs to contain.

  • substring - The substring to match against.

Example

use httpmock::{Mock, MockServer};

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();

pub fn path_matches<R: Into<Regex>>(self, regex: R) -> Self[src]

Sets a regex that the URL path needs to match.

  • regex - The regex to match against.

Example

use httpmock::{Mock, MockServer};
use regex::Regex;

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();

pub fn query_param<S: Into<String>>(self, name: S, value: S) -> Self[src]

Sets a query parameter that needs to be provided.

  • name - The query parameter name that will matched against.
  • value - The value parameter name that will matched against.
// Arrange
use isahc::get;
use httpmock::{MockServer, Mock};

let _ = env_logger::try_init();
let server = MockServer::start();

let m = server.mock(|when, then|{
    when.query_param("query", "Metallica");
    then.status(200);
});

// Act
get(server.url("/search?query=Metallica")).unwrap();

// Assert
m.assert();

pub fn query_param_exists<S: Into<String>>(self, name: S) -> Self[src]

Sets a query parameter that needs to exist in an HTTP request.

  • name - The query parameter name that will matched against.
// Arrange
use isahc::get;
use httpmock::{MockServer, Mock};

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();

pub fn body<S: Into<String>>(self, body: S) -> Self[src]

Sets the required HTTP request body content.

  • body - The required HTTP request body.

Example

use httpmock::{Mock, MockServer};
use httpmock::Method::GET;
use regex::Regex;
use isahc::prelude::*;

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();

pub fn body_matches<R: Into<Regex>>(self, regex: R) -> Self[src]

Sets a Regex for the expected HTTP body.

  • regex - The regex that the HTTP request body will matched against.
use isahc::prelude::*;
use httpmock::Method::POST;
use httpmock::{MockServer, Mock, Regex};

// 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);

pub fn body_contains<S: Into<String>>(self, substring: S) -> Self[src]

Sets the expected HTTP body substring.

  • substring - The substring that will matched against.
use httpmock::{MockServer, Mock, Regex};
use httpmock::Method::POST;
use isahc::prelude::*;

// 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);

pub fn json_body<V: Into<Value>>(self, value: V) -> Self[src]

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::{Mock, MockServer};
use httpmock::Method::POST;
use serde_json::json;
use isahc::prelude::*;

// 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);

pub fn json_body_obj<'a, T>(self, body: &T) -> Self where
    T: Serialize + Deserialize<'a>, 
[src]

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::{MockServer, Mock};
use httpmock::Method::POST;
use serde_json::json;
use isahc::prelude::*;

// 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);

pub fn json_body_partial<S: Into<String>>(self, partial: S) -> Self[src]

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 provive a full JSON object, we can use this method as follows:

use httpmock::{MockServer, Mock};

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 hierachy, i.e. it needs to start from the root! It leaves out irrelevant attributes, however (parent_attribute and child.other_attribute).

pub fn header<S: Into<String>>(self, name: S, value: S) -> Self[src]

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::{Mock, MockServer};
use httpmock::Method::GET;
use regex::Regex;
use isahc::prelude::*;

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();

pub fn header_exists<S: Into<String>>(self, name: S) -> Self[src]

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::{Mock, MockServer};
use httpmock::Method::GET;
use regex::Regex;
use isahc::prelude::*;

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();

pub fn cookie<S: Into<String>>(self, name: S, value: S) -> Self[src]

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.

Example

use httpmock::{Mock, MockServer};
use httpmock::Method::GET;
use regex::Regex;
use isahc::prelude::*;

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();

pub fn cookie_exists<S: Into<String>>(self, name: S) -> Self[src]

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

Example

use httpmock::{Mock, MockServer};
use httpmock::Method::GET;
use regex::Regex;
use isahc::prelude::*;

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();

pub fn matches(self, matcher: MockMatcherFunction) -> Self[src]

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).

  • request_matcher - The matcher function.

Example:

use httpmock::{MockServer, Mock, HttpMockRequest};

// 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);

Auto Trait Implementations

impl !RefUnwindSafe for When

impl !Send for When

impl !Sync for When

impl Unpin for When

impl !UnwindSafe for When

Blanket Implementations

impl<T> Any for T where
    T: 'static + ?Sized
[src]

impl<T> Borrow<T> for T where
    T: ?Sized
[src]

impl<T> BorrowMut<T> for T where
    T: ?Sized
[src]

impl<T> From<T> for T[src]

impl<T> Instrument for T[src]

impl<T> Instrument for T[src]

impl<T, U> Into<U> for T where
    U: From<T>, 
[src]

impl<T, U> TryFrom<U> for T where
    U: Into<T>, 
[src]

type Error = Infallible

The type returned in the event of a conversion error.

impl<T, U> TryInto<U> for T where
    U: TryFrom<T>, 
[src]

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.

impl<T> WithSubscriber for T[src]