pub struct ResponseTemplate { /* private fields */ }
Expand description

The blueprint for the response returned by a MockServer when a Mock matches on an incoming request.

Implementations§

source§

impl ResponseTemplate

source

pub fn new<S>(s: S) -> Self

Start building a ResponseTemplate specifying the status code of the response.

source

pub fn append_header<K, V>(self, key: K, value: V) -> Self

Append a header value to list of headers with key as header name.

Unlike insert_header, this function will not override the contents of a header:

  • if there are no header values with key as header name, it will insert one;
  • if there are already some values with key as header name, it will append to the existing list.
source

pub fn insert_header<K, V>(self, key: K, value: V) -> Self

Insert a header value with key as header name.

This function will override the contents of a header:

  • if there are no header values with key as header name, it will insert one;
  • if there are already some values with key as header name, it will drop them and start a new list of header values, containing only value.
§Example:
use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;

#[async_std::main]
async fn main() {
    // Arrange
    let mock_server = MockServer::start().await;
    let correlation_id = "1311db4f-fe65-4cb2-b514-1bb47f781aa7";
    let template = ResponseTemplate::new(200).insert_header(
        "X-Correlation-ID",
        correlation_id
    );
    Mock::given(method("GET"))
        .respond_with(template)
        .mount(&mock_server)
        .await;

    // Act
    let res = surf::get(&mock_server.uri())
        .await
        .unwrap();

    // Assert
    assert_eq!(res.header("X-Correlation-ID").unwrap().as_str(), correlation_id);
}
source

pub fn set_body_bytes<B>(self, body: B) -> Self
where B: TryInto<Vec<u8>>, <B as TryInto<Vec<u8>>>::Error: Debug,

Set the response body with bytes.

It sets “Content-Type” to “application/octet-stream”.

To set a body with bytes but a different “Content-Type” set_body_raw can be used.

source

pub fn set_body_json<B: Serialize>(self, body: B) -> Self

Set the response body from a JSON-serializable value.

It sets “Content-Type” to “application/json”.

source

pub fn set_body_string<T>(self, body: T) -> Self
where T: TryInto<String>, <T as TryInto<String>>::Error: Debug,

Set the response body to a string.

It sets “Content-Type” to “text/plain”.

source

pub fn set_body_raw<B>(self, body: B, mime: &str) -> Self
where B: TryInto<Vec<u8>>, <B as TryInto<Vec<u8>>>::Error: Debug,

Set a raw response body. The mime type needs to be set because the raw body could be of any type.

§Example:
use surf::http::mime;
use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;

mod external {
    // This could be a method of a struct that is
    // implemented in another crate and the struct
    // does not implement Serialize.
    pub fn body() -> Vec<u8>{
        r#"{"hello": "world"}"#.as_bytes().to_owned()
    }
}

#[async_std::main]
async fn main() {
    // Arrange
    let mock_server = MockServer::start().await;
    let template = ResponseTemplate::new(200).set_body_raw(
        external::body(),
        "application/json"
    );
    Mock::given(method("GET"))
        .respond_with(template)
        .mount(&mock_server)
        .await;

    // Act
    let mut res = surf::get(&mock_server.uri())
        .await
        .unwrap();
    let body = res.body_string()
        .await
        .unwrap();

    // Assert
    assert_eq!(body, r#"{"hello": "world"}"#);
    assert_eq!(res.content_type(), Some(mime::JSON));
}
source

pub fn set_delay(self, delay: Duration) -> Self

By default the MockServer tries to fulfill incoming requests as fast as possible.

You can use set_delay to introduce an artificial delay to simulate the behaviour of a real server with a non-negligible latency.

In particular, you can use it to test the behaviour of your timeout policies.

§Example:
use wiremock::{MockServer, Mock, ResponseTemplate};
use wiremock::matchers::method;
use std::time::Duration;
use async_std::prelude::FutureExt;

#[async_std::main]
async fn main() {
    // Arrange
    let mock_server = MockServer::start().await;
    let delay = Duration::from_secs(1);
    let template = ResponseTemplate::new(200).set_delay(delay);
    Mock::given(method("GET"))
        .respond_with(template)
        .mount(&mock_server)
        .await;

    // Act
    let mut res = async_std::future::timeout(
        // Shorter than the response delay!
        delay / 3,
        surf::get(&mock_server.uri())
    )
    .await;

    // Assert - Timeout error!
    assert!(res.is_err());
}

Trait Implementations§

source§

impl Clone for ResponseTemplate

source§

fn clone(&self) -> ResponseTemplate

Returns a copy of the value. Read more
1.0.0 · source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
source§

impl Debug for ResponseTemplate

source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
source§

impl Respond for ResponseTemplate

A ResponseTemplate is the simplest Respond implementation: it returns a clone of itself no matter what the incoming request contains!

source§

fn respond(&self, _request: &Request) -> ResponseTemplate

Given a reference to a Request return a ResponseTemplate that will be used by the MockServer as blueprint for the response returned to the client.

Auto Trait Implementations§

Blanket Implementations§

source§

impl<T> Any for T
where T: 'static + ?Sized,

source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
source§

impl<T> Borrow<T> for T
where T: ?Sized,

source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
source§

impl<T> From<T> for T

source§

fn from(t: T) -> T

Returns the argument unchanged.

§

impl<T> Instrument for T

§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided [Span], returning an Instrumented wrapper. Read more
§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
source§

impl<T, U> Into<U> for T
where U: From<T>,

source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

source§

impl<T> ToOwned for T
where T: Clone,

§

type Owned = T

The resulting type after obtaining ownership.
source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

§

type Error = Infallible

The type returned in the event of a conversion error.
source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

§

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

The type returned in the event of a conversion error.
source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
§

impl<T> WithSubscriber for T

§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a [WithDispatch] wrapper. Read more
§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a [WithDispatch] wrapper. Read more