Struct httpmock::Then[][src]

pub struct Then { /* fields omitted */ }

A type that allows the specification of HTTP response values.

Implementations

impl Then[src]

pub fn 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 = 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);

pub fn 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 = 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!");

pub fn body_from_file<S: Into<String>>(self, body: S) -> 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 = 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!");

pub fn json_body<V: Into<Value>>(self, value: 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 = 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");

pub fn 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 = 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");

pub fn 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 = 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);

pub fn 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;
use isahc::{prelude::*, ResponseExt};

let _ = env_logger::try_init();

let server = MockServer::start();

let redirect_mock = server.mock(|when, then|{
    when.path("/redirectPath");
    then.temporary_redirect("http://www.google.com");
});

// 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 permanent_redirect<S: Into<String>>(self, redirect_url: S) -> Self[src]

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;
use isahc::{prelude::*, ResponseExt};
let _ = env_logger::try_init();

let server = MockServer::start();

let redirect_mock = server.mock(|when, then|{
    when.path("/redirectPath");
    then.permanent_redirect("http://www.google.com");
});

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

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

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]