axum_test

Struct 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.

// Build your request
let request = server.get(&"/user")
    .add_header("x-custom-header", "example.com")
    .content_type("application/yaml");

// await request to execute
let response = request.await;

You will receive a TestResponse.

TestRequest::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 json_from_file<P>(self, path: P) -> Self
where P: AsRef<Path>,

Sends a payload as a Json request, with the contents coming from a file.

Source

pub fn yaml<Y>(self, body: &Y) -> Self
where Y: ?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 yaml_from_file<P>(self, path: P) -> Self
where P: AsRef<Path>,

Available on crate feature yaml only.

Sends a payload as a Yaml request, with the contents coming from a file.

Source

pub fn msgpack<M>(self, body: &M) -> Self
where M: ?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 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 text_from_file<P>(self, path: P) -> Self
where P: AsRef<Path>,

Sends a payload as plain text, with the contents coming from a file.

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 bytes_from_file<P>(self, path: P) -> Self
where P: AsRef<Path>,

Reads the contents of the file as raw bytes, and sends it within the request.

The content type is left unchanged, and no parsing of the file is done.

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 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<N, V>(self, name: N, value: V) -> Self

Adds a header to be sent with this request.

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

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

let response = server.get(&"/my-end-point")
    .add_header("x-custom-header", "custom-value")
    .add_header(http::header::CONTENT_LENGTH, 12345)
    .add_header(http::header::HOST, "example.com")
    .await;
Source

pub fn authorization<T>(self, authorization_header: T) -> Self
where T: AsRef<str>,

Adds an ‘AUTHORIZATION’ HTTP header to the request, with no internal formatting of what is given.

Source

pub fn authorization_bearer<T>(self, authorization_bearer_token: T) -> Self
where T: Display,

Adds an ‘AUTHORIZATION’ HTTP header to the request, in the ‘Bearer {token}’ format.

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

Source§

type Output = TestResponse

The output that the future will produce on completion.
Source§

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>

Source§

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> FutureExt for T

Source§

fn with_context(self, otel_cx: Context) -> WithContext<Self>

Attaches the provided Context to this type, returning a WithContext wrapper. Read more
Source§

fn with_current_context(self) -> WithContext<Self>

Attaches the current Context to this type, returning a WithContext 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> IntoRequest<T> for T

Source§

fn into_request(self) -> Request<T>

Wrap the input message T in a tonic::Request
Source§

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

Source§

fn fg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the foreground set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like red() and green(), which have the same functionality but are pithier.

§Example

Set foreground color to white using fg():

use yansi::{Paint, Color};

painted.fg(Color::White);

Set foreground color to white using white().

use yansi::Paint;

painted.white();
Source§

fn primary(&self) -> Painted<&T>

Returns self with the fg() set to Color::Primary.

§Example
println!("{}", value.primary());
Source§

fn fixed(&self, color: u8) -> Painted<&T>

Returns self with the fg() set to Color::Fixed.

§Example
println!("{}", value.fixed(color));
Source§

fn rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the fg() set to Color::Rgb.

§Example
println!("{}", value.rgb(r, g, b));
Source§

fn black(&self) -> Painted<&T>

Returns self with the fg() set to Color::Black.

§Example
println!("{}", value.black());
Source§

fn red(&self) -> Painted<&T>

Returns self with the fg() set to Color::Red.

§Example
println!("{}", value.red());
Source§

fn green(&self) -> Painted<&T>

Returns self with the fg() set to Color::Green.

§Example
println!("{}", value.green());
Source§

fn yellow(&self) -> Painted<&T>

Returns self with the fg() set to Color::Yellow.

§Example
println!("{}", value.yellow());
Source§

fn blue(&self) -> Painted<&T>

Returns self with the fg() set to Color::Blue.

§Example
println!("{}", value.blue());
Source§

fn magenta(&self) -> Painted<&T>

Returns self with the fg() set to Color::Magenta.

§Example
println!("{}", value.magenta());
Source§

fn cyan(&self) -> Painted<&T>

Returns self with the fg() set to Color::Cyan.

§Example
println!("{}", value.cyan());
Source§

fn white(&self) -> Painted<&T>

Returns self with the fg() set to Color::White.

§Example
println!("{}", value.white());
Source§

fn bright_black(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightBlack.

§Example
println!("{}", value.bright_black());
Source§

fn bright_red(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightRed.

§Example
println!("{}", value.bright_red());
Source§

fn bright_green(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightGreen.

§Example
println!("{}", value.bright_green());
Source§

fn bright_yellow(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightYellow.

§Example
println!("{}", value.bright_yellow());
Source§

fn bright_blue(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightBlue.

§Example
println!("{}", value.bright_blue());
Source§

fn bright_magenta(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightMagenta.

§Example
println!("{}", value.bright_magenta());
Source§

fn bright_cyan(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightCyan.

§Example
println!("{}", value.bright_cyan());
Source§

fn bright_white(&self) -> Painted<&T>

Returns self with the fg() set to Color::BrightWhite.

§Example
println!("{}", value.bright_white());
Source§

fn bg(&self, value: Color) -> Painted<&T>

Returns a styled value derived from self with the background set to value.

This method should be used rarely. Instead, prefer to use color-specific builder methods like on_red() and on_green(), which have the same functionality but are pithier.

§Example

Set background color to red using fg():

use yansi::{Paint, Color};

painted.bg(Color::Red);

Set background color to red using on_red().

use yansi::Paint;

painted.on_red();
Source§

fn on_primary(&self) -> Painted<&T>

Returns self with the bg() set to Color::Primary.

§Example
println!("{}", value.on_primary());
Source§

fn on_fixed(&self, color: u8) -> Painted<&T>

Returns self with the bg() set to Color::Fixed.

§Example
println!("{}", value.on_fixed(color));
Source§

fn on_rgb(&self, r: u8, g: u8, b: u8) -> Painted<&T>

Returns self with the bg() set to Color::Rgb.

§Example
println!("{}", value.on_rgb(r, g, b));
Source§

fn on_black(&self) -> Painted<&T>

Returns self with the bg() set to Color::Black.

§Example
println!("{}", value.on_black());
Source§

fn on_red(&self) -> Painted<&T>

Returns self with the bg() set to Color::Red.

§Example
println!("{}", value.on_red());
Source§

fn on_green(&self) -> Painted<&T>

Returns self with the bg() set to Color::Green.

§Example
println!("{}", value.on_green());
Source§

fn on_yellow(&self) -> Painted<&T>

Returns self with the bg() set to Color::Yellow.

§Example
println!("{}", value.on_yellow());
Source§

fn on_blue(&self) -> Painted<&T>

Returns self with the bg() set to Color::Blue.

§Example
println!("{}", value.on_blue());
Source§

fn on_magenta(&self) -> Painted<&T>

Returns self with the bg() set to Color::Magenta.

§Example
println!("{}", value.on_magenta());
Source§

fn on_cyan(&self) -> Painted<&T>

Returns self with the bg() set to Color::Cyan.

§Example
println!("{}", value.on_cyan());
Source§

fn on_white(&self) -> Painted<&T>

Returns self with the bg() set to Color::White.

§Example
println!("{}", value.on_white());
Source§

fn on_bright_black(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightBlack.

§Example
println!("{}", value.on_bright_black());
Source§

fn on_bright_red(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightRed.

§Example
println!("{}", value.on_bright_red());
Source§

fn on_bright_green(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightGreen.

§Example
println!("{}", value.on_bright_green());
Source§

fn on_bright_yellow(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightYellow.

§Example
println!("{}", value.on_bright_yellow());
Source§

fn on_bright_blue(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightBlue.

§Example
println!("{}", value.on_bright_blue());
Source§

fn on_bright_magenta(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightMagenta.

§Example
println!("{}", value.on_bright_magenta());
Source§

fn on_bright_cyan(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightCyan.

§Example
println!("{}", value.on_bright_cyan());
Source§

fn on_bright_white(&self) -> Painted<&T>

Returns self with the bg() set to Color::BrightWhite.

§Example
println!("{}", value.on_bright_white());
Source§

fn attr(&self, value: Attribute) -> Painted<&T>

Enables the styling Attribute value.

This method should be used rarely. Instead, prefer to use attribute-specific builder methods like bold() and underline(), which have the same functionality but are pithier.

§Example

Make text bold using attr():

use yansi::{Paint, Attribute};

painted.attr(Attribute::Bold);

Make text bold using using bold().

use yansi::Paint;

painted.bold();
Source§

fn bold(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Bold.

§Example
println!("{}", value.bold());
Source§

fn dim(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Dim.

§Example
println!("{}", value.dim());
Source§

fn italic(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Italic.

§Example
println!("{}", value.italic());
Source§

fn underline(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Underline.

§Example
println!("{}", value.underline());

Returns self with the attr() set to Attribute::Blink.

§Example
println!("{}", value.blink());

Returns self with the attr() set to Attribute::RapidBlink.

§Example
println!("{}", value.rapid_blink());
Source§

fn invert(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Invert.

§Example
println!("{}", value.invert());
Source§

fn conceal(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Conceal.

§Example
println!("{}", value.conceal());
Source§

fn strike(&self) -> Painted<&T>

Returns self with the attr() set to Attribute::Strike.

§Example
println!("{}", value.strike());
Source§

fn quirk(&self, value: Quirk) -> Painted<&T>

Enables the yansi Quirk value.

This method should be used rarely. Instead, prefer to use quirk-specific builder methods like mask() and wrap(), which have the same functionality but are pithier.

§Example

Enable wrapping using .quirk():

use yansi::{Paint, Quirk};

painted.quirk(Quirk::Wrap);

Enable wrapping using wrap().

use yansi::Paint;

painted.wrap();
Source§

fn mask(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Mask.

§Example
println!("{}", value.mask());
Source§

fn wrap(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Wrap.

§Example
println!("{}", value.wrap());
Source§

fn linger(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Linger.

§Example
println!("{}", value.linger());
Source§

fn clear(&self) -> Painted<&T>

👎Deprecated since 1.0.1: renamed to resetting() due to conflicts with Vec::clear(). The clear() method will be removed in a future release.

Returns self with the quirk() set to Quirk::Clear.

§Example
println!("{}", value.clear());
Source§

fn resetting(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Resetting.

§Example
println!("{}", value.resetting());
Source§

fn bright(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::Bright.

§Example
println!("{}", value.bright());
Source§

fn on_bright(&self) -> Painted<&T>

Returns self with the quirk() set to Quirk::OnBright.

§Example
println!("{}", value.on_bright());
Source§

fn whenever(&self, value: Condition) -> Painted<&T>

Conditionally enable styling based on whether the Condition value applies. Replaces any previous condition.

See the crate level docs for more details.

§Example

Enable styling painted only when both stdout and stderr are TTYs:

use yansi::{Paint, Condition};

painted.red().on_yellow().whenever(Condition::STDOUTERR_ARE_TTY);
Source§

fn new(self) -> Painted<Self>
where Self: Sized,

Create a new Painted with a default Style. Read more
Source§

fn paint<S>(&self, style: S) -> Painted<&Self>
where S: Into<Style>,

Apply a style wholesale to self. Any previous style is replaced. Read more
Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

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

Source§

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

Source§

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<T> ErasedDestructor for T
where T: 'static,

Source§

impl<T> MaybeSendSync for T