Struct httpmock::Then

source ·
pub struct Then { /* private fields */ }
Expand description

A type that allows the specification of HTTP response values.

Implementations§

source§

impl Then

source

pub fn status(self, status: u16) -> Self

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

  • status - The status code.
Example:
use httpmock::prelude::*;

// Arrange
let server = MockServer::start();

let m = server.mock(|when, then|{
    when.path("/hello");
    then.status(200);
});

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

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

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

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

  • body - The response body content.
Example:
use httpmock::prelude::*;
use isahc::{prelude::*, ResponseExt};

// Arrange
let server = MockServer::start();

let m = server.mock(|when, then| {
    when.path("/hello");
    then.status(200)
        .body("ohi!");
});

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

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

pub fn body_from_file<S: Into<String>>(self, resource_file_path: S) -> Self

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

  • body - The response body content.
Example:
use httpmock::prelude::*;
use isahc::{prelude::*, ResponseExt};

// Arrange
let server = MockServer::start();

let m = server.mock(|when, then|{
    when.path("/hello");
    then.status(200)
        .body_from_file("tests/resources/simple_body.txt");
});

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

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

pub fn json_body<V: Into<Value>>(self, body: V) -> Self

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::prelude::*;
use serde_json::{Value, json};
use isahc::ResponseExt;
use isahc::prelude::*;

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

let m = server.mock(|when, then|{
    when.path("/user");
    then.status(200)
        .header("content-type", "application/json")
        .json_body(json!({ "name": "Hans" }));
});

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

pub fn json_body_obj<T>(self, body: &T) -> Self
where T: Serialize,

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::prelude::*;
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 = server.mock(|when, then| {
    when.path("/user");
    then.status(200)
        .header("content-type", "application/json")
        .json_body_obj(&TestUser {
            name: String::from("Hans"),
        });
});

// 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(), 200);
assert_eq!(user.name, "Hans");
source

pub fn header<SK: Into<String>, SV: Into<String>>( self, name: SK, value: SV ) -> Self

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::prelude::*;
use serde_json::Value;
use isahc::ResponseExt;

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

let m = server.mock(|when, then|{
    when.path("/");
    then.status(200)
        .header("Expires", "Wed, 21 Oct 2050 07:28:00 GMT");
});

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

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

pub fn delay<D: Into<Duration>>(self, duration: D) -> Self

Sets a duration that will delay the mock server response.

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

let _ = env_logger::try_init();
let start_time = SystemTime::now();
let three_seconds = Duration::from_secs(3);
let server = MockServer::start();

let mock = server.mock(|when, then| {
    when.path("/delay");
    then.status(200)
        .delay(three_seconds);
});

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

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

pub fn and(self, func: fn(_: Then) -> Then) -> Self

A semantic convenience for applying multiple operations on a given Then instance via an discrete encapsulating function.

Example:
use hyper::http;use httpmock::Then;
// Assuming an encapsulating function like:

fn ok_json_with_delay(then: Then) -> Then {
    then.status(http::StatusCode::OK.as_u16())
        .header("content-type", "application/json")
        .delay(Duration::from_secs_f32(0.5))
}

// It can be applied without breaking the usual `Then`
// semantic style. Meaning instead of:
ok_json_with_delay(then.header("general-vibe", "not great my guy"))

// the `and` method can be used to preserve the
// legibility of the method chain:
 then.header("general-vibe", "much better")
     .and(ok_json_with_delay)

// is still intuitively legible as "{when some criteria},
// then set the 'general-vibe' header to 'much better'
// *and* the status code to 200 (ok), the 'content-type'
// header to 'application/json' and return it with a delay
// of 0.50 seconds".

Auto Trait Implementations§

§

impl !RefUnwindSafe for Then

§

impl !Send for Then

§

impl !Sync for Then

§

impl Unpin for Then

§

impl !UnwindSafe for Then

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.

source§

impl<T> Instrument for T

source§

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

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

fn in_current_span(self) -> Instrumented<Self>

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

impl<T> Instrument for T

source§

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

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

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, 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.
source§

impl<T> WithSubscriber for T

source§

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
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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

impl<T> WithSubscriber for T

source§

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
source§

fn with_current_subscriber(self) -> WithDispatch<Self>

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