Struct axum_test::TestResponse

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

The TestResponse is the result of a request created using a TestServer. The TestServer builds a TestRequest, which when awaited, will produce the response.

use ::axum::Json;
use ::axum::routing::Router;
use ::axum::routing::get;
use ::serde::Deserialize;
use ::serde::Serialize;

use ::axum_test::TestServer;

let app = Router::new()
    .route(&"/test", get(|| async { "hello!" }));

let server = TestServer::new(app)?;

// This builds a `TestResponse`
let response = server.get(&"/todo").await;

§Extracting Response

The functions TestResponse::json(), TestResponse::text(), and TestResponse::form(), allow you to extract the underlying response content in different formats.

let todo_response = server.get(&"/todo")
        .await
        .json::<Todo>();

let response_as_raw_text = server.get(&"/todo")
        .await
        .text();

TestResponse::as_bytes() and TestResponse::into_bytes(), offer the underlying raw bytes to allow custom decoding.

Full code examples can be found within their documentation.

§Assertions

The result of a response can also be asserted using the many assertion functions.

use ::axum::Json;
use ::axum::routing::Router;
use ::axum::routing::get;
use ::serde::Deserialize;
use ::serde::Serialize;

use ::axum_test::TestServer;

let app = Router::new()
    .route(&"/test", get(|| async { "hello!" }));

let server = TestServer::new(app)?;

let response = server.get(&"/todo").await;

// These assertions will panic if they are not fulfilled by the response.
response.assert_status_ok();
response.assert_text("hello!");

Implementations§

source§

impl TestResponse

source

pub fn text(&self) -> String

Returns the underlying response, extracted as a UTF-8 string.

§Example
use ::axum::Json;
use ::axum::routing::Router;
use ::axum::routing::get;
use ::serde_json::json;
use ::serde_json::Value;

use ::axum_test::TestServer;

async fn route_get_todo() -> Json<Value> {
    Json(json!({
        "description": "buy milk",
    }))
}

let app = Router::new()
    .route(&"/todo", get(route_get_todo));

let server = TestServer::new(app)?;
let response = server.get(&"/todo").await;

// Extract the response as a string on it's own.
let raw_text = response.text();
source

pub fn json<T>(&self) -> T

Deserializes the response, as Json, into the type given.

If deserialization fails then this will panic.

§Example
use ::axum::Json;
use ::axum::routing::Router;
use ::axum::routing::get;
use ::serde::Deserialize;
use ::serde::Serialize;

use ::axum_test::TestServer;

#[derive(Serialize, Deserialize, Debug)]
struct Todo {
    description: String,
}

async fn route_get_todo() -> Json<Todo> {
    Json(Todo {
        description: "buy milk".to_string(),
    })
}

let app = Router::new()
    .route(&"/todo", get(route_get_todo));

let server = TestServer::new(app)?;
let response = server.get(&"/todo").await;

// Extract the response as a `Todo` item.
let todo = response.json::<Todo>();
source

pub fn yaml<T>(&self) -> T

Available on crate feature yaml only.

Deserializes the response, as Yaml, into the type given.

If deserialization fails then this will panic.

§Example
use ::axum::routing::Router;
use ::axum::routing::get;
use ::axum_yaml::Yaml;
use ::serde::Deserialize;
use ::serde::Serialize;

use ::axum_test::TestServer;

#[derive(Serialize, Deserialize, Debug)]
struct Todo {
    description: String,
}

async fn route_get_todo() -> Yaml<Todo> {
    Yaml(Todo {
        description: "buy milk".to_string(),
    })
}

let app = Router::new()
    .route(&"/todo", get(route_get_todo));

let server = TestServer::new(app)?;
let response = server.get(&"/todo").await;

// Extract the response as a `Todo` item.
let todo = response.yaml::<Todo>();
source

pub fn msgpack<T>(&self) -> T

Available on crate feature msgpack only.

Deserializes the response, as MsgPack, into the type given.

If deserialization fails then this will panic.

§Example
use ::axum::routing::Router;
use ::axum::routing::get;
use ::axum_msgpack::MsgPack;
use ::serde::Deserialize;
use ::serde::Serialize;

use ::axum_test::TestServer;

#[derive(Serialize, Deserialize, Debug)]
struct Todo {
    description: String,
}

async fn route_get_todo() -> MsgPack<Todo> {
    MsgPack(Todo {
        description: "buy milk".to_string(),
    })
}

let app = Router::new()
    .route(&"/todo", get(route_get_todo));

let server = TestServer::new(app)?;
let response = server.get(&"/todo").await;

// Extract the response as a `Todo` item.
let todo = response.msgpack::<Todo>();
source

pub fn form<T>(&self) -> T

Deserializes the response, as an urlencoded Form, into the type given.

If deserialization fails then this will panic.

§Example
use ::axum::Form;
use ::axum::routing::Router;
use ::axum::routing::get;
use ::serde::Deserialize;
use ::serde::Serialize;

use ::axum_test::TestServer;

#[derive(Serialize, Deserialize, Debug)]
struct Todo {
    description: String,
}

async fn route_get_todo() -> Form<Todo> {
    Form(Todo {
        description: "buy milk".to_string(),
    })
}

let app = Router::new()
    .route(&"/todo", get(route_get_todo));

let server = TestServer::new(app)?;
let response = server.get(&"/todo").await;

// Extract the response as a `Todo` item.
let todo = response.form::<Todo>();
source

pub fn as_bytes<'a>(&'a self) -> &'a Bytes

Returns the raw underlying response as Bytes.

source

pub fn into_bytes<'a>(self) -> Bytes

Consumes this returning the underlying Bytes in the response.

source

pub fn status_code(&self) -> StatusCode

The status_code of the response.

source

pub fn request_url(&self) -> Url

The full URL that was used to produce this response.

source

pub fn maybe_header<N>(&self, header_name: N) -> Option<HeaderValue>
where N: AsHeaderName,

Finds a header with the given name. If there are multiple headers with the same name, then only the first HeaderValue will be returned.

None is returned when no header was found.

source

pub fn headers<'a>(&'a self) -> &'a HeaderMap<HeaderValue>

Returns the headers returned from the response.

source

pub fn header<N>(&self, header_name: N) -> HeaderValue
where N: AsHeaderName + Display + Clone,

Finds a header with the given name. If there are multiple headers with the same name, then only the first will be returned.

If no header is found, then this will panic.

source

pub fn iter_headers<'a>( &'a self ) -> impl Iterator<Item = (&'a HeaderName, &'a HeaderValue)>

Iterates over all of the headers contained in the response.

source

pub fn iter_headers_by_name<'a, N>( &'a self, header_name: N ) -> impl Iterator<Item = &'a HeaderValue>
where N: AsHeaderName,

Iterates over all of the headers for a specific name, contained in the response.

Finds a Cookie with the given name. If there are multiple matching cookies, then only the first will be returned.

None is returned if no Cookie is found.

source

pub fn cookie(&self, cookie_name: &str) -> Cookie<'static>

Finds a Cookie with the given name. If there are multiple matching cookies, then only the first will be returned.

If no Cookie is found, then this will panic.

source

pub fn cookies(&self) -> CookieJar

Returns all of the cookies contained in the response, within a CookieJar object.

See the cookie crate for details.

source

pub fn iter_cookies<'a>(&'a self) -> impl Iterator<Item = Cookie<'a>>

Iterate over all of the cookies in the response.

source

pub fn assert_text<C>(&self, other: C)
where C: AsRef<str>,

This performs an assertion comparing the whole body of the response, against the text provided.

source

pub fn assert_json<T>(&self, other: &T)

Deserializes the contents of the request as Json, and asserts it matches the value given.

If other does not match, or the response is not Json, then this will panic.

source

pub fn assert_yaml<T>(&self, other: &T)

Available on crate feature yaml only.

Deserializes the contents of the request as Yaml, and asserts it matches the value given.

If other does not match, or the response is not Yaml, then this will panic.

source

pub fn assert_msgpack<T>(&self, other: &T)

Available on crate feature msgpack only.

Deserializes the contents of the request as MsgPack, and asserts it matches the value given.

If other does not match, or the response is not MsgPack, then this will panic.

source

pub fn assert_form<T>(&self, other: &T)

Deserializes the contents of the request as an url encoded form, and asserts it matches the value given.

If other does not match, or the response cannot be deserialized, then this will panic.

source

pub fn assert_status_success(&self)

Assert that the status code is within the 2xx range. i.e. The range from 200-299.

source

pub fn assert_status_failure(&self)

Assert that the status code is outside the 2xx range. i.e. A status code less than 200, or 300 or more.

source

pub fn assert_status_bad_request(&self)

Assert the response status code is 400.

source

pub fn assert_status_not_found(&self)

Assert the response status code is 404.

source

pub fn assert_status_unauthorized(&self)

Assert the response status code is 401.

source

pub fn assert_status_forbidden(&self)

Assert the response status code is 403.

source

pub fn assert_status_ok(&self)

Assert the response status code is 200.

source

pub fn assert_status_not_ok(&self)

Assert the response status code is not 200.

source

pub fn assert_status(&self, expected_status_code: StatusCode)

Assert the response status code matches the one given.

source

pub fn assert_not_status(&self, expected_status_code: StatusCode)

Assert the response status code does not match the one given.

Trait Implementations§

source§

impl Clone for TestResponse

source§

fn clone(&self) -> TestResponse

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 TestResponse

source§

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

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

impl From<TestResponse> for Bytes

source§

fn from(response: TestResponse) -> Self

Converts to this type from the input type.

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.

source§

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

source§

fn from_ref(input: &T) -> T

Converts to this type from a reference to the input type.
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> 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.
source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

source§

fn vzip(self) -> V

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<A, B, T> HttpServerConnExec<A, B> for T
where B: Body,