Skip to main content

APIClient

Struct APIClient 

Source
pub struct APIClient { /* private fields */ }
Expand description

Test client for making API requests

§Example

use reinhardt_testkit::APIClient;
use http::StatusCode;
use serde_json::json;

let client = APIClient::with_base_url("http://localhost:8080");
let credentials = json!({"username": "user", "password": "pass"});
client.post("/auth/login", &credentials, "json").await?;
let response = client.get("/api/users/").await?;
assert_eq!(response.status(), StatusCode::OK);

Implementations§

Source§

impl APIClient

Source

pub fn new() -> Self

Create a new API client

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
assert_eq!(client.base_url(), "http://testserver");
Source

pub fn with_base_url(base_url: impl Into<String>) -> Self

Create a client with a custom base URL

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::with_base_url("https://api.example.com");
assert_eq!(client.base_url(), "https://api.example.com");
Source

pub fn from_handler(handler: impl HttpHandler + 'static) -> Self

Create a test client that dispatches requests directly to a reinhardt Handler without TCP.

The Handler runs the full middleware stack in-process. Sets base_url to "http://testserver" and injects a default Origin header for OriginGuardMiddleware compatibility.

§Panics

Panics if called outside a tokio runtime.

§Examples
use reinhardt_testkit::APIClient;

// let router = build_routes(scope).into_server();
// let client = APIClient::from_handler(router);
// let resp = client.get("/api/health/").await.unwrap();
Source

pub fn builder() -> APIClientBuilder

Create a builder for customizing the client configuration

§Examples
use reinhardt_testkit::client::APIClient;
use std::time::Duration;

let client = APIClient::builder()
    .base_url("http://localhost:8080")
    .timeout(Duration::from_secs(30))
    .build();
Source

pub fn base_url(&self) -> &str

Get the base URL of this client.

Source

pub fn set_handler<F>(&mut self, handler: F)
where F: Fn(Request<Full<Bytes>>) -> Response<Full<Bytes>> + Send + Sync + 'static,

Set a request handler for testing

§Examples
use reinhardt_testkit::client::APIClient;
use http::{Request, Response, StatusCode};
use http_body_util::Full;
use bytes::Bytes;

let mut client = APIClient::new();
client.set_handler(|_req| {
    Response::builder()
        .status(StatusCode::OK)
        .body(Full::new(Bytes::from("test")))
        .unwrap()
});
Source

pub async fn set_header( &self, name: impl AsRef<str>, value: impl AsRef<str>, ) -> ClientResult<()>

Set a default header for all requests

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
client.set_header("User-Agent", "TestClient/1.0").await.unwrap();
Source

pub async fn force_authenticate(&self, user: Option<Value>)

👎Deprecated since 0.1.0-rc.16:

use client.auth().session() or client.auth().jwt() instead

Force authenticate as a user (for testing)

§Examples
use reinhardt_testkit::client::APIClient;
use serde_json::json;

let client = APIClient::new();
let user = json!({"id": 1, "username": "testuser"});
client.force_authenticate(Some(user)).await;
Source

pub async fn credentials( &self, username: &str, password: &str, ) -> ClientResult<()>

Set credentials for Basic Authentication

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
client.credentials("username", "password").await.unwrap();
Source

pub async fn clear_auth(&self) -> ClientResult<()>

Clear authentication and cookies

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
client.clear_auth().await.unwrap();

Set a cookie that will be sent with subsequent requests.

§Panics

Panics if name contains = or ;, or if value contains ;.

Remove a specific cookie.

Source

pub async fn logout(&self) -> ClientResult<()>

Clear all authentication state (session cookies, auth headers, stored user).

This is the replacement for force_authenticate(None).

Source

pub fn auth(&self) -> AuthBuilder<'_>

Start building an auth configuration for this client.

§Examples
client.auth()
    .session(&user, &session_store)
    .with_staff(true)
    .apply().await?;
Source

pub async fn cleanup(&self)

Clean up all client state for teardown

This method performs a complete cleanup of the client state including:

  • Clearing authentication
  • Clearing cookies
  • Clearing default headers

This is typically called during test teardown to ensure clean state between tests.

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
client.set_header("X-Custom", "value").await.unwrap();
client.cleanup().await;
// All state is now cleared
Source

pub async fn get(&self, path: &str) -> ClientResult<TestResponse>

Make a GET request

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
Source

pub async fn post<T: Serialize>( &self, path: &str, data: &T, format: &str, ) -> ClientResult<TestResponse>

Make a POST request

§Examples
use reinhardt_testkit::client::APIClient;
use serde_json::json;

let client = APIClient::new();
let data = json!({"name": "test"});
Source

pub async fn put<T: Serialize>( &self, path: &str, data: &T, format: &str, ) -> ClientResult<TestResponse>

Make a PUT request

§Examples
use reinhardt_testkit::client::APIClient;
use serde_json::json;

let client = APIClient::new();
let data = json!({"name": "updated"});
Source

pub async fn patch<T: Serialize>( &self, path: &str, data: &T, format: &str, ) -> ClientResult<TestResponse>

Make a PATCH request

§Examples
use reinhardt_testkit::client::APIClient;
use serde_json::json;

let client = APIClient::new();
let data = json!({"name": "partial_update"});
Source

pub async fn delete(&self, path: &str) -> ClientResult<TestResponse>

Make a DELETE request

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
Source

pub async fn head(&self, path: &str) -> ClientResult<TestResponse>

Make a HEAD request

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
Source

pub async fn options(&self, path: &str) -> ClientResult<TestResponse>

Make an OPTIONS request

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::new();
Source

pub async fn get_with_headers( &self, path: &str, headers: &[(&str, &str)], ) -> ClientResult<TestResponse>

Make a GET request with additional per-request headers

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::with_base_url("http://localhost:8080");
// let response = client.get_with_headers("/api/data", &[("Accept", "application/json")]).await;
Source

pub async fn post_raw_with_headers( &self, path: &str, body: &[u8], content_type: &str, headers: &[(&str, &str)], ) -> ClientResult<TestResponse>

Make a POST request with raw body and additional per-request headers

Unlike post(), this method allows setting a raw body without automatic serialization.

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::with_base_url("http://localhost:8080");
// let response = client.post_raw_with_headers(
//     "/api/echo",
//     b"{\"test\":\"data\"}",
//     "application/json",
//     &[("X-Custom-Header", "value")]
// ).await;
Source

pub async fn post_raw( &self, path: &str, body: &[u8], content_type: &str, ) -> ClientResult<TestResponse>

Make a POST request with raw body

Unlike post(), this method allows setting a raw body without automatic serialization.

§Examples
use reinhardt_testkit::client::APIClient;

let client = APIClient::with_base_url("http://localhost:8080");
// let response = client.post_raw("/api/echo", b"{\"test\":\"data\"}", "application/json").await;

Trait Implementations§

Source§

impl Default for APIClient

Source§

fn default() -> Self

Returns the “default value” for a type. 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> Any for T
where T: Any,

Source§

fn into_any(self: Box<T>) -> Box<dyn Any>

Source§

fn into_any_rc(self: Rc<T>) -> Rc<dyn Any>

Source§

fn type_name(&self) -> &'static str

Source§

impl<T> AnySync for T
where T: Any + Send + Sync,

Source§

fn into_any_arc(self: Arc<T>) -> Arc<dyn Any + Send + Sync>

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

Source§

fn into_either(self, into_left: bool) -> Either<Self, Self>

Converts self into a Left variant of Either<Self, Self> if into_left is true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

fn into_either_with<F>(self, into_left: F) -> Either<Self, Self>
where F: FnOnce(&Self) -> bool,

Converts self into a Left variant of Either<Self, Self> if into_left(&self) returns true. Converts self into a Right variant of Either<Self, Self> otherwise. Read more
Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
Source§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
Source§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow only if self and other return Action::Follow. Read more
Source§

fn or<P, B, E>(self, other: P) -> Or<T, P>
where T: Policy<B, E>, P: Policy<B, E>,

Create a new Policy that returns Action::Follow if either self or other returns Action::Follow. Read more
Source§

impl<R, P> ReadPrimitive<R> for P
where R: Read + ReadEndian<P>, P: Default,

Source§

fn read_from_little_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_little_endian().
Source§

fn read_from_big_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_big_endian().
Source§

fn read_from_native_endian(read: &mut R) -> Result<Self, Error>

Read this value from the supplied reader. Same as ReadEndian::read_from_native_endian().
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