Struct httpmock::Mock[][src]

pub struct Mock { /* fields omitted */ }
👎 Deprecated since 0.5.0:

Please use newer API (see: https://github.com/alexliesenfeld/httpmock/blob/master/CHANGELOG.md#version-050)

The Mock structure holds a definition for a request/response scenario that can be used to configure a MockServer.

This structure provides methods starting with expect in their name to define requirements for HTTP requests that the server will respond to. On the other hand, methods starting with return in their name define what data the mock server will put into the corresponding HTTP response.

Because of this naming scheme, this structure is said to privide access to the “expect/return” API of httpmock.

Example

// Arrange
use httpmock::{MockServer, Mock};

let server = MockServer::start();

let mock = Mock::new()
    .expect_path_contains("/search")
    .expect_query_param("query", "metallica")
    .return_status(202)
    .create_on(&server);

// Act: Send the HTTP request
let response = isahc::get(server.url("/search?query=metallica")).unwrap();

// Assert
mock.assert();
assert_eq!(response.status(), 202);

Observe how Mock::create_on is used to create a mock object on the server. After the call completes, the mock server will start serving HTTP requests as specified in the Mock instance.

The Mock::create_on method also returns a mock reference that identifies the mock object on the server. It can be used to fetch related information from the server, such as the number of times the mock was served (see MockRef::hits). You can also use it to explicitly delete the mock object from the server (see MockRef::delete).

Implementations

impl Mock[src]

pub fn new() -> Self[src]

Creates a new mock that automatically returns HTTP status code 200 if hit by an HTTP call.

pub fn expect_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 = Mock::new()
    .expect_path("/test")
    .return_status(200)
    .create_on(&server);

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

mock.assert();

pub fn expect_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 = Mock::new()
    .expect_path_contains("es")
    .return_status(200)
    .create_on(&server);

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

mock.assert();

pub fn expect_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 = Mock::new()
    .expect_path_matches(Regex::new("le$").unwrap())
    .return_status(200)
    .create_on(&server);

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

mock.assert();

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

Sets the expected HTTP method.

  • method - The HTTP method.

Example

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

let server = MockServer::start();
let mock = Mock::new()
    .expect_method(GET)
    .return_status(200)
    .create_on(&server);

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

mock.assert();

pub fn expect_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::*, Request};

let server = MockServer::start();
let mock = Mock::new()
    .expect_header("Authorization", "token 1234567890")
    .return_status(200)
    .create_on(&server);

Request::post(&format!("http://{}/test", server.address()))
    .header("Authorization", "token 1234567890")
    .body(())
    .unwrap()
    .send()
    .unwrap();

mock.assert();

pub fn expect_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::*, Request};

let server = MockServer::start();
let mock = Mock::new()
    .expect_header_exists("Authorization")
    .return_status(200)
    .create_on(&server);

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.

Example

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

let server = MockServer::start();
let mock = Mock::new()
    .expect_cookie("SESSIONID", "1234567890")
    .return_status(200)
    .create_on(&server);

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

Example

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

let server = MockServer::start();
let mock = Mock::new()
    .expect_cookie_exists("SESSIONID")
    .return_status(200)
    .create_on(&server);

Request::post(&format!("http://{}/test", server.address()))
    .header("Cookie", "TRACK=12345; SESSIONID=1234567890; CONSENT=1")
    .body(())
    .unwrap()
    .send()
    .unwrap();

mock.assert();

pub fn expect_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::*, Request};

let server = MockServer::start();
let mock = Mock::new()
    .expect_body("The Great Gatsby")
    .return_status(200)
    .create_on(&server);

Request::post(&format!("http://{}/test", server.address()))
    .body("The Great Gatsby")
    .unwrap()
    .send()
    .unwrap();

mock.assert();

pub fn expect_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::*, 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 = Mock::new()
    .expect_method(POST)
    .expect_path("/users")
    .expect_header("Content-Type", "application/json")
    .expect_json_body_obj(&TestUser {
        name: String::from("Fred"),
    })
    .return_status(201)
    .create_on(&server);

// Act: Send the request and deserialize the response to JSON
let mut response = Request::post(&format!("http://{}/users", 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(), 201);

pub fn expect_json_body<V: Into<Value>>(self, body: 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::*, Request};

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

let m = Mock::new()
    .expect_method(POST)
    .expect_path("/users")
    .expect_header("Content-Type", "application/json")
    .expect_json_body(json!({ "name": "Hans" }))
    .return_status(201)
    .create_on(&server);

// Act: Send the request and deserialize the response to JSON
let mut response = Request::post(&format!("http://{}/users", 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 expect_json_body_partial<S: Into<String>>(self, partial_body: 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 = Mock::new()
    .expect_json_body_partial(r#"
        {
            "child" : {
                "target_attribute" : "Example"
            }
         }
    "#)
    .return_status(202)
    .create_on(&server);

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 expect_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::*, Request};

// Arrange
let _ = env_logger::try_init();

let server = MockServer::start();

let m = Mock::new()
    .expect_method(POST)
    .expect_path("/books")
    .expect_body_contains("Ring")
    .return_status(201)
    .create_on(&server);

// Act: Send the request and deserialize the response to JSON
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 expect_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::*, Request};
use httpmock::Method::POST;
use httpmock::{MockServer, Mock, Regex};

// Arrange
let _ = env_logger::try_init();

let server = MockServer::start();

let m = Mock::new()
    .expect_method(POST)
    .expect_path("/books")
    .expect_body_matches(Regex::new("Fellowship").unwrap())
    .return_status(201)
    .create_on(&server);

// Act: Send the request and deserialize the response to JSON
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 expect_query_param<S: Into<String>>(self, name: S, value: S) -> Self[src]

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::{MockServer, Mock};

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

let m = Mock::new()
    .expect_query_param("query", "Metallica")
    .return_status(200)
    .create_on(&server);

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

// Assert
m.assert();

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

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::{MockServer, Mock};

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

let m = Mock::new()
    .expect_query_param_exists("query")
    .return_status(200)
    .create_on(&server);

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

// Assert
m.assert();

pub fn expect_match(self, request_matcher: MockMatcherFunction) -> Self[src]

Sets a custom function that will evaluate if an HTTP request matches custom matching rules. Attention: This will NOT work in standalone mock server (search the docs for “Standalone” to get more information on the standalone mode).

  • request_matcher - The matcher function.

Example:

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

// Arrange
let server = MockServer::start();
let m = Mock::new()
    .expect_match(|req: &HttpMockRequest| {
        req.path.ends_with("st")
    })
    .return_status(200)
    .create_on(&server);

// Act
let response = isahc::get(server.url("/test")).unwrap();

// Assert
m.assert();
assert_eq!(response.status(), 200);

pub fn return_status(self, status: u16) -> Self[src]

Sets the HTTP response code that will be returned by the mock server.

  • status - The status code.

Example:

use httpmock::{MockServer, Mock};

// Arrange
let server = MockServer::start();
let m = Mock::new()
    .expect_path("/hello")
    .return_status(200)
    .create_on(&server);

// Act
let response = isahc::get(server.url("/hello")).unwrap();

// Assert
m.assert();
assert_eq!(response.status(), 200);

pub fn return_body(self, body: impl AsRef<[u8]>) -> Self[src]

Sets the HTTP response body that will be returned by the mock server.

  • body - The response body content.

Example:

use httpmock::{MockServer, Mock};
use isahc::{prelude::*, ResponseExt};

// Arrange
let server = MockServer::start();
let m = Mock::new()
    .expect_path("/hello")
    .return_status(200)
    .return_body("ohi!")
    .create_on(&server);

// Act
let mut response = isahc::get(server.url("/hello")).unwrap();

// Assert
m.assert();
assert_eq!(response.status(), 200);
assert_eq!(response.text().unwrap(), "ohi!");

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

Sets the HTTP response body that will be returned by the mock server.

  • resource_file_path - The file path to the file with the response body content. The file path can either be absolute or relative to the project root directory.

Example:

use httpmock::{MockServer, Mock};
use isahc::{prelude::*, ResponseExt};

// Arrange
let server = MockServer::start();
let m = Mock::new()
    .expect_path("/hello")
    .return_status(200)
    .return_body_from_file("tests/resources/simple_body.txt")
    .create_on(&server);

// Act
let mut response = isahc::get(server.url("/hello")).unwrap();

// Assert
m.assert();
assert_eq!(response.status(), 200);
assert_eq!(response.text().unwrap(), "ohi!");

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

Sets the JSON body for the HTTP response that will be returned by the mock server.

The provided JSON object needs to be both, a deserializable and serializable serde object.

Note that this method does not set the “Content-Type” header automatically, so you need to provide one yourself!

  • body - The HTTP response body the mock server will return in the form of a serde_json::Value object.

Example

You can use this method conveniently as follows:

use httpmock::{MockServer, Mock};
use serde_json::{Value, json};
use isahc::ResponseExt;
use isahc::prelude::*;

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

let m = Mock::new()
    .expect_path("/user")
    .return_status(200)
    .return_header("Content-Type", "application/json")
    .return_json_body(json!({ "name": "Hans" }))
    .create_on(&server);

// Act
let mut response = isahc::get(server.url("/user")).unwrap();

let user: Value =
    serde_json::from_str(&response.text().unwrap()).expect("cannot deserialize JSON");

// Assert
m.assert();
assert_eq!(response.status(), 200);
assert_eq!(user.as_object().unwrap().get("name").unwrap(), "Hans");

pub fn return_json_body_obj<T>(self, body: &T) -> Self where
    T: Serialize
[src]

Sets the JSON body that will be returned by the mock server. 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 isahc::{prelude::*, ResponseExt};

// This is a temporary type that we will use for this example
#[derive(serde::Serialize, serde::Deserialize)]
struct TestUser {
    name: String,
}

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

let m = Mock::new()
    .expect_path("/user")
    .return_status(201)
    .return_header("Content-Type", "application/json")
    .return_json_body_obj(&TestUser {
        name: String::from("Hans"),
    })
    .create_on(&server);

// Act
let mut response = isahc::get(server.url("/user")).unwrap();

let user: TestUser =
    serde_json::from_str(&response.text().unwrap()).unwrap();

// Assert
m.assert();
assert_eq!(response.status(), 201);
assert_eq!(user.name, "Hans");

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

Sets an HTTP header that the mock server will return.

  • name - The name of the header.
  • value - The value of the header.

Example

You can use this method conveniently as follows:

// Arrange
use httpmock::{MockServer, Mock};
use serde_json::Value;
use isahc::ResponseExt;

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

let m = Mock::new()
    .return_status(200)
    .return_header("Expires", "Wed, 21 Oct 2050 07:28:00 GMT")
    .create_on(&server);

// Act
let mut response = isahc::get(server.url("/")).unwrap();

// Assert
m.assert();
assert_eq!(response.status(), 200);

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

👎 Deprecated since 0.5.6:

Please use desired response code and headers instead

Sets the HTTP response up to return a permanent redirect.

In detail, this method will add the following information to the HTTP response:

  • A “Location” header with the provided URL as its value.
  • Status code will be set to 301 (if no other status code was set before).
  • The response body will be set to “Moved Permanently” (if no other body was set before).

Further information: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections and https://tools.ietf.org/html/rfc2616#section-10.3.8.

  • redirect_url - THe URL to redirect to.

Example

// Arrange
use httpmock::{MockServer, Mock};
use isahc::{prelude::*, ResponseExt};

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

let redirect_mock = Mock::new()
    .expect_path("/redirectPath")
    .return_permanent_redirect("http://www.google.com")
    .create_on(&server);

// Act: Send the HTTP request with an HTTP client that DOES NOT FOLLOW redirects automatically!
let mut response = isahc::get(server.url("/redirectPath")).unwrap();
let body = response.text().unwrap();

// Assert
assert_eq!(redirect_mock.hits(), 1);

// Attention!: Note that all of these values are automatically added to the response
// (see details in mock builder method documentation).
assert_eq!(response.status(), 301);
assert_eq!(body, "Moved Permanently");
assert_eq!(response.headers().get("Location").unwrap().to_str().unwrap(), "http://www.google.com");

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

👎 Deprecated since 0.5.6:

Please use desired response code and headers instead

Sets the HTTP response up to return a temporary redirect.

In detail, this method will add the following information to the HTTP response:

  • A “Location” header with the provided URL as its value.
  • Status code will be set to 302 (if no other status code was set before).
  • The response body will be set to “Found” (if no other body was set before).

Further information: https://developer.mozilla.org/en-US/docs/Web/HTTP/Redirections and https://tools.ietf.org/html/rfc2616#section-10.3.8.

  • redirect_url - THe URL to redirect to.

Example

// Arrange
use httpmock::{MockServer, Mock};
use isahc::{prelude::*, ResponseExt};

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

let redirect_mock = Mock::new()
    .expect_path("/redirectPath")
    .return_temporary_redirect("http://www.google.com")
    .create_on(&server);

// Act: Send the HTTP request with an HTTP client that DOES NOT FOLLOW redirects automatically!

let mut response = isahc::get(server.url("/redirectPath")).unwrap();
let body = response.text().unwrap();

// Assert
assert_eq!(redirect_mock.hits(), 1);

// Attention!: Note that all of these values are automatically added to the response
// (see details in mock builder method documentation).
assert_eq!(response.status(), 302);
assert_eq!(body, "Found");
assert_eq!(response.headers().get("Location").unwrap().to_str().unwrap(), "http://www.google.com");

pub fn return_with_delay<D: Into<Duration>>(self, duration: D) -> Self[src]

Sets a duration that will delay the mock server response.

  • duration - The delay.
// Arrange
use std::time::{SystemTime, Duration};
use httpmock::{MockServer, Mock};

let _ = env_logger::try_init();
let start_time = SystemTime::now();
let delay = Duration::from_secs(3);

let server = MockServer::start();

let mock = Mock::new()
    .expect_path("/delay")
    .return_with_delay(delay)
    .create_on(&server);

// Act
let response = isahc::get(server.url("/delay")).unwrap();

// Assert
mock.assert();
assert_eq!(start_time.elapsed().unwrap() > delay, true);

pub fn create_on<'a>(self, server: &'a MockServer) -> MockRef<'a>[src]

This method creates the mock object at the MockServer. It returns a MockRef object representing the reference of the created mock at the server. Only after the call of this method completes, the mock server will start serving HTTP requests as specified in the Mock instance.

// Arrange
use httpmock::{MockServer, Mock};

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

let mock = Mock::new()
    .return_status(200)
    .create_on(&server);

// Act
let response = isahc::get(server.url("/delay")).unwrap();

// Assert
mock.assert();

Panics

This method will panic if there is a problem communicating with the server.

pub async fn create_on_async<'a>(self, server: &'a MockServer) -> MockRef<'a>[src]

This method creates the mock object at the MockServer. It returns a MockRef object representing the reference of the created mock at the server. Only after the call of this method completes, the mock server will start serving HTTP requests as specified in the Mock instance.

async_std::task::block_on(async {
    use std::time::{SystemTime, Duration};
    use httpmock::{MockServer, Mock};
    use tokio_test::block_on;
    let _ = env_logger::try_init();

    // Arrange
    let server = MockServer::start_async().await;

    let mock = Mock::new()
        .return_status(200)
        .create_on_async(&server)
        .await;

    // Act
    let response = isahc::get_async(server.url("/delay")).await.unwrap();

    // Assert
    mock.assert_async().await;
});

Panics

This method will panic if there is a problem communicating with the server.

Trait Implementations

impl Default for Mock[src]

Auto Trait Implementations

impl RefUnwindSafe for Mock

impl Send for Mock

impl Sync for Mock

impl Unpin for Mock

impl UnwindSafe for Mock

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]