Skip to main content

FakeHandler

Struct FakeHandler 

Source
pub struct FakeHandler { /* private fields */ }
Available on crate features test-util only.
Expand description

Simulates HTTP responses for testing without making actual network requests.

The FakeHandler lets you easily mock HTTP client behavior by providing predefined responses or custom response logic. Available with the test-util feature enabled.

§Examples

Return a fixed status code:

use http::StatusCode;
use http_extensions::FakeHandler;

// All requests to this client will return 404 Not Found
let handler = FakeHandler::from(StatusCode::NOT_FOUND);

Return a sequence of responses:

use http::StatusCode;
use http_extensions::FakeHandler;

let handler = FakeHandler::from(vec![
    StatusCode::OK,
    StatusCode::BAD_REQUEST,
    StatusCode::INTERNAL_SERVER_ERROR,
]);

// First request → 200 OK
// Second request → 400 Bad Request
// Third request → 500 Internal Server Error
// Fourth request → Error (all responses consumed)

Create dynamic responses based on the request:

use http::StatusCode;
use http_extensions::{FakeHandler, HttpResponseBuilder};

let handler = FakeHandler::from_fn(|request| {
    if request.uri().path() == "/api/users" {
        HttpResponseBuilder::new_fake()
            .status(StatusCode::OK)
            .text(r#"{"users": []}"#)
            .build()
    } else {
        HttpResponseBuilder::new_fake()
            .status(StatusCode::NOT_FOUND)
            .text("Resource not found")
            .build()
    }
});

§Working with HttpResponseBuilder

Use HttpResponseBuilder::new_fake to generate tailored test responses with a fluent API. This is especially useful with FakeHandler::from_fn to create responses that react to request data:

Implementations§

Source§

impl FakeHandler

Source

pub fn from_fn<H>(handler: H) -> Self
where H: Fn(HttpRequest) -> Result<HttpResponse> + 'static + Send + Sync,

Creates a handler from a synchronous request handler function.

Takes a function that processes requests synchronously and wraps it into an async handler internally.

§Examples
use http::StatusCode;
use http_extensions::{FakeHandler, HttpResponseBuilder};

let handler = FakeHandler::from_fn(|request| {
    HttpResponseBuilder::new_fake()
        .status(StatusCode::OK)
        .text("Hello World")
        .build()
});
Source

pub fn from_error_fn( error: impl Fn(HttpRequest) -> HttpError + Send + Sync + 'static, ) -> Self

Creates a handler that always returns HTTP error.

§Examples
use http_extensions::{FakeHandler, HttpError, HttpRequest};

let handler = FakeHandler::from_error_fn(|_request: HttpRequest| {
    HttpError::validation("simulated error")
});
Source

pub fn from_async_fn<H, F>(handler: H) -> Self
where H: Fn(HttpRequest) -> F + 'static + Send + Sync, F: Future<Output = Result<HttpResponse>> + Send + 'static,

Creates a handler from an asynchronous function.

Useful for complex async scenarios like simulating network delays or other asynchronous behavior in your tests.

§Examples
use http::StatusCode;
use http_extensions::{FakeHandler, HttpResponseBuilder};

let handler = FakeHandler::from_async_fn(|request| async move {
    // Simulate network delay
    tokio::time::sleep(std::time::Duration::from_millis(50)).await;

    HttpResponseBuilder::new_fake()
        .status(StatusCode::OK)
        .text("Response after delay")
        .build()
});
Source

pub fn from_status_codes<T>(codes: T) -> Self
where T: IntoIterator<Item = StatusCode>,

Creates a handler that returns a sequence of status codes.

Returns empty-body responses with the given status codes in order. When the sequence is exhausted, further requests will error.

§Examples
use http::StatusCode;
use http_extensions::FakeHandler;

let handler = FakeHandler::from_status_codes([
    StatusCode::OK,
    StatusCode::BAD_REQUEST,
    StatusCode::INTERNAL_SERVER_ERROR,
]);
§Errors

After all responses are consumed, further requests will return a validation error.

Source

pub fn from_responses<T>(responses: T) -> Self
where T: IntoIterator<Item = HttpResponse>,

Creates a handler that returns predefined HTTP responses in sequence.

Takes full HttpResponse objects and returns them in order. When the sequence is exhausted, further requests return an error.

§Examples
use http::StatusCode;
use http_extensions::{FakeHandler, HttpResponseBuilder};

let responses = vec![
    HttpResponseBuilder::new_fake()
        .status(StatusCode::OK)
        .text("Success response")
        .build()
        .unwrap(),
    HttpResponseBuilder::new_fake()
        .status(StatusCode::NOT_FOUND)
        .text("Not found")
        .build()
        .unwrap(),
];

let handler = FakeHandler::from_responses(responses);
§Errors

After all responses are consumed, requests will fail with “all responses used by fake handler are already consumed”.

Source

pub fn never_completes() -> Self

Creates a handler that never completes requests.

Useful for testing timeout handling in your code.

Trait Implementations§

Source§

impl AsRef<HttpBodyBuilder> for FakeHandler

Source§

fn as_ref(&self) -> &HttpBodyBuilder

Converts this type into a shared reference of the (usually inferred) input type.
Source§

impl Clone for FakeHandler

Source§

fn clone(&self) -> FakeHandler

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for FakeHandler

Source§

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

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

impl Default for FakeHandler

Creates a default FakeHandler that returns 200 OK responses.

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl From<Response<HttpBody>> for FakeHandler

Create a FakeHandler from a single HTTP response.

The response body must be buffered to be reused for multiple requests. If the body is not buffered, an error will be returned when the handler tries to reuse it.

Source§

fn from(value: HttpResponse) -> Self

Converts to this type from the input type.
Source§

impl From<StatusCode> for FakeHandler

Create a FakeHandler from a single status code.

Source§

fn from(value: StatusCode) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<Response<HttpBody>>> for FakeHandler

Create a FakeHandler from a vector of HTTP responses.

Source§

fn from(value: Vec<HttpResponse>) -> Self

Converts to this type from the input type.
Source§

impl From<Vec<StatusCode>> for FakeHandler

Create a FakeHandler from a vector of status codes.

Source§

fn from(value: Vec<StatusCode>) -> Self

Converts to this type from the input type.
Source§

impl Service<Request<HttpBody>> for FakeHandler

Source§

type Out = Result<Response<HttpBody>, HttpError>

The output type returned by this service.
Source§

fn execute(&self, input: HttpRequest) -> impl Future<Output = Self::Out> + Send

Processes the input and returns the output. Read more
Source§

impl ThreadAware for FakeHandler

Source§

fn relocate(&mut self, _source: Option<Affinity>, _destination: Affinity)

Relocate this value in place to the destination affinity. Read more

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> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> HttpRequestBuilderExt for T

Source§

fn request_builder(&self) -> HttpRequestBuilder<'_, T>

Creates a new HTTP request builder associated with this handler.
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<S> RequestHandler for S

Source§

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

Source§

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

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.