Skip to main content

HealthStatus

Enum HealthStatus 

Source
pub enum HealthStatus {
    Healthy,
    Unhealthy,
    Uncheckable,
}
Expand description

A trait for implementing test server abstractions for different web frameworks.

This trait provides a generic interface for launching and managing test servers for various web frameworks (e.g., Axum, Warp, actix-web). It allows the TestClient to work with any server implementation in a framework-agnostic way.

§Associated Types

  • Error: Error type that can occur during server operations

§Required Methods

  • launch: Starts the server with the provided TcpListener

§Optional Methods

  • is_healthy: Checks if the server is ready to accept requests
  • config: Provides configuration for the test framework

§Example

use clawspec_core::test_client::{TestServer, TestServerConfig, HealthStatus};
use std::net::TcpListener;
use std::time::Duration;

#[derive(Debug)]
struct ServerError;

impl std::fmt::Display for ServerError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Server error")
    }
}

impl std::error::Error for ServerError {}

#[derive(Debug)]
struct MyTestServer;

impl TestServer for MyTestServer {
    type Error = ServerError;

    async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
        // Convert to non-blocking for tokio compatibility
        listener.set_nonblocking(true).map_err(|_| ServerError)?;
        let tokio_listener = tokio::net::TcpListener::from_std(listener)
            .map_err(|_| ServerError)?;
         
        // Start your web server here
        // For example, with axum:
        // axum::serve(tokio_listener, app).await.map_err(|_| ServerError)?;
        Ok(())
    }

    async fn is_healthy(&self, client: &mut clawspec_core::ApiClient) -> Result<HealthStatus, Self::Error> {
        // Check if server is ready by making a health check request
        match client.get("/health").unwrap().await {
            Ok(_) => Ok(HealthStatus::Healthy),
            Err(_) => Ok(HealthStatus::Unhealthy),
        }
    }

    fn config(&self) -> TestServerConfig {
        TestServerConfig {
            api_client: Some(
                clawspec_core::ApiClient::builder()
                    .with_host("localhost")
                    .with_base_path("/api").unwrap()
            ),
            min_backoff_delay: Duration::from_millis(10),
            max_backoff_delay: Duration::from_secs(1),
            backoff_jitter: true,
            max_retry_attempts: 10,
        }
    }
}

§Framework Integration

§Framework Integration Example

use clawspec_core::test_client::{TestServer, TestServerConfig};
use std::net::TcpListener;

#[derive(Debug)]
struct WebFrameworkTestServer {
    // Your web framework's app/router would go here
    // For example: app: axum::Router, or app: warp::Filter, etc.
}

impl WebFrameworkTestServer {
    fn new(/* app: YourApp */) -> Self {
        Self { /* app */ }
    }
}

impl TestServer for WebFrameworkTestServer {
    type Error = std::io::Error; // or your custom error type

    async fn launch(&self, listener: TcpListener) -> Result<(), Self::Error> {
        listener.set_nonblocking(true)?;
        let tokio_listener = tokio::net::TcpListener::from_std(listener)?;
         
        // Start your web framework here:
        // For Axum: axum::serve(tokio_listener, self.app.clone()).await?;
        // For Warp: warp::serve(self.app.clone()).run_async(tokio_listener).await;
        // For actix-web: HttpServer::new(|| self.app.clone()).listen(tokio_listener)?.run().await?;
        Ok(())
    }
}

§Health Checking

The is_healthy method allows implementing custom health check logic:

  • Return Ok(HealthStatus::Healthy) if the server is ready to accept requests
  • Return Ok(HealthStatus::Unhealthy) if the server is not ready
  • Return Ok(HealthStatus::Uncheckable) to use the default TCP connection test
  • Return Err(Self::Error) if an error occurs during health checking

The TestClient will wait for the server to become healthy before returning success. Health check status returned by the is_healthy method.

This enum provides more explicit control over health checking behavior compared to the previous Option<bool> approach.

Variants§

§

Healthy

Server is healthy and ready to accept requests.

§

Unhealthy

Server is not healthy or not ready yet.

§

Uncheckable

Use the default TCP connection test to determine health. This is equivalent to the previous None return value.

Trait Implementations§

Source§

impl Clone for HealthStatus

Source§

fn clone(&self) -> HealthStatus

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 Copy for HealthStatus

Source§

impl Debug for HealthStatus

Source§

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

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

impl Eq for HealthStatus

Source§

impl PartialEq for HealthStatus

Source§

fn eq(&self, other: &HealthStatus) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more
Source§

impl StructuralPartialEq for HealthStatus

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<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

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<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Checks if this value is equivalent to the given key. Read more
Source§

impl<Q, K> Equivalent<K> for Q
where Q: Eq + ?Sized, K: Borrow<Q> + ?Sized,

Source§

fn equivalent(&self, key: &K) -> bool

Compare self to key and return true if they are equal.
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> PolicyExt for T
where T: ?Sized,

Source§

fn and<P, B, E>(self, other: P) -> And<T, P>
where T: Sized + 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: Sized + 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<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
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.
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