Struct axum_test::TestRequest

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

A TestRequest is for building and executing a HTTP request to the TestServer.

§Building

Requests are created by the TestServer, using it’s builder functions. They correspond to the appropriate HTTP method: TestServer::get(), TestServer::post(), etc.

See there for documentation.

§Customising

The TestRequest allows the caller to fill in the rest of the request to be sent to the server. Including the headers, the body, cookies, and the content type, using the relevant functions.

The TestRequest struct provides a number of methods to set up the request, such as json, text, bytes, expect_failure, content_type, etc.

§Sending

Once fully configured you send the request by awaiting the request object.

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

You will receive a TestResponse.

TestRequest::do_save_cookies() and TestRequest::do_not_save_cookies() methods allow you to set the request to save cookies to the TestServer, for reuse on any future requests.

This behaviour is off by default, and can be changed for all TestRequests when building the TestServer. By building it with a TestServerConfig where save_cookies is set to true.

§Expecting Failure and Success

When making a request you can mark it to expect a response within, or outside, of the 2xx range of HTTP status codes.

If the response returns a status code different to what is expected, then it will panic.

This is useful when making multiple requests within a test. As it can find issues earlier than later.

See the TestRequest::expect_failure(), and TestRequest::expect_success().

Implementations§

source§

impl TestRequest

source

pub fn json<J>(self, body: &J) -> Self
where J: ?Sized + Serialize,

Set the body of the request to send up data as Json, and changes the content type to application/json.

source

pub fn msgpack<J>(self, body: &J) -> Self
where J: ?Sized + Serialize,

Available on crate feature msgpack only.

Set the body of the request to send up data as MsgPack, and changes the content type to application/msgpack.

source

pub fn yaml<J>(self, body: &J) -> Self
where J: ?Sized + Serialize,

Available on crate feature yaml only.

Set the body of the request to send up data as Yaml, and changes the content type to application/yaml.

source

pub fn form<F>(self, body: &F) -> Self
where F: ?Sized + Serialize,

Sets the body of the request, with the content type of ‘application/x-www-form-urlencoded’.

source

pub fn multipart(self, multipart: MultipartForm) -> Self

For sending multipart forms. The payload is built using MultipartForm and Part.

This will be sent with the content type of ‘multipart/form-data’.

§Simple example
use ::axum::Router;
use ::axum_test::TestServer;
use ::axum_test::multipart::MultipartForm;

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

let multipart_form = MultipartForm::new()
    .add_text("name", "Joe")
    .add_text("animals", "foxes");

let response = server.post(&"/my-form")
    .multipart(multipart_form)
    .await;
§Sending byte parts
use ::axum::Router;
use ::axum_test::TestServer;
use ::axum_test::multipart::MultipartForm;
use ::axum_test::multipart::Part;

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

let image_bytes = include_bytes!("../README.md");
let image_part = Part::bytes(image_bytes.as_slice())
    .file_name(&"README.md")
    .mime_type(&"text/markdown");

let multipart_form = MultipartForm::new()
    .add_part("file", image_part);

let response = server.post(&"/my-form")
    .multipart(multipart_form)
    .await;
source

pub fn text<T>(self, raw_text: T) -> Self
where T: Display,

Set raw text as the body of the request, and sets the content type to text/plain.

source

pub fn bytes(self, body_bytes: Bytes) -> Self

Set raw bytes as the body of the request.

The content type is left unchanged.

source

pub fn content_type(self, content_type: &str) -> Self

Set the content type to use for this request in the header.

Adds a Cookie to be sent with this request.

source

pub fn add_cookies(self, cookies: CookieJar) -> Self

Adds many cookies to be used with this request.

source

pub fn clear_cookies(self) -> Self

Clears all cookies used internally within this Request, including any that came from the TestServer.

source

pub fn do_save_cookies(self) -> Self

Any cookies returned will be saved to the TestServer that created this, which will continue to use those cookies on future requests.

source

pub fn do_not_save_cookies(self) -> Self

Cookies returned by this will not be saved to the TestServer. For use by future requests.

This is the default behaviour. You can change that default in TestServerConfig.

source

pub fn add_query_param<V>(self, key: &str, value: V) -> Self
where V: Serialize,

Adds query parameters to be sent with this request.

source

pub fn add_query_params<V>(self, query_params: V) -> Self
where V: Serialize,

Adds the structure given as query parameters for this request.

This is designed to take a list of parameters, or a body of parameters, and then serializes them into the parameters of the request.

§Sending a body of parameters using json!
use ::axum::Router;
use ::axum_test::TestServer;
use ::serde_json::json;

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

let response = server.get(&"/my-end-point")
    .add_query_params(json!({
        "username": "Brian",
        "age": 20
    }))
    .await;
§Sending a body of parameters with Serde
use ::axum::Router;
use ::axum_test::TestServer;
use ::serde::Deserialize;
use ::serde::Serialize;

#[derive(Serialize, Deserialize)]
struct UserQueryParams {
    username: String,
    age: u32,
}

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

let response = server.get(&"/my-end-point")
    .add_query_params(UserQueryParams {
        username: "Brian".to_string(),
        age: 20
    })
    .await;
§Sending a list of parameters
use ::axum::Router;
use ::axum_test::TestServer;

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

let response = server.get(&"/my-end-point")
    .add_query_params(&[
        ("username", "Brian"),
        ("age", "20"),
    ])
    .await;
source

pub fn add_raw_query_param(self, query_param: &str) -> Self

Adds a query param onto the end of the request, with no urlencoding of any kind.

This exists to allow custom query parameters, such as for the many versions of query param arrays.

use ::axum::Router;
use ::axum_test::TestServer;

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

let response = server.get(&"/my-end-point")
    .add_raw_query_param(&"my-flag")
    .add_raw_query_param(&"array[]=123")
    .add_raw_query_param(&"filter[value]=some-value")
    .await;
source

pub fn clear_query_params(self) -> Self

Clears all query params set, including any that came from the TestServer.

source

pub fn add_header<'c>(self, name: HeaderName, value: HeaderValue) -> Self

Adds a header to be sent with this request.

source

pub fn clear_headers(self) -> Self

Clears all headers set.

source

pub fn scheme(self, scheme: &str) -> Self

Sets the scheme to use when making the request. i.e. http or https. The default scheme is ‘http’.

use ::axum::Router;
use ::axum_test::TestServer;

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

let response = server
    .get(&"/my-end-point")
    .scheme(&"https")
    .await;
source

pub fn expect_success(self) -> Self

Marks that this request is expected to always return a HTTP status code within the 2xx range (200 to 299).

If a code outside of that range is returned, then this will panic.

use ::axum::Json;
use ::axum::routing::Router;
use ::axum::routing::put;
use ::serde_json::json;

use ::axum_test::TestServer;

let app = Router::new()
    .route(&"/todo", put(|| async { unimplemented!() }));

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

// If this doesn't return a value in the 2xx range,
// then it will panic.
server.put(&"/todo")
    .expect_success()
    .json(&json!({
        "task": "buy milk",
    }))
    .await;
source

pub fn expect_failure(self) -> Self

Marks that this request is expected to return a HTTP status code outside of the 2xx range.

If a code within the 2xx range is returned, then this will panic.

Trait Implementations§

source§

impl Debug for TestRequest

source§

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

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

impl IntoFuture for TestRequest

§

type Output = TestResponse

The output that the future will produce on completion.
§

type IntoFuture = AutoFuture<TestResponse>

Which kind of future are we turning this into?
source§

fn into_future(self) -> Self::IntoFuture

Creates a future from a value. Read more
source§

impl TryFrom<TestRequest> for Request<Body>

§

type Error = Error

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

fn try_from(test_request: TestRequest) -> Result<Request<Body>>

Performs the conversion.

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> 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<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,