Skip to main content

MockServerClient

Struct MockServerClient 

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

A blocking client for the MockServer control-plane REST API.

Created via ClientBuilder. All methods are synchronous.

Implementations§

Source§

impl MockServerClient

Source

pub fn upsert(&self, expectations: &[Expectation]) -> Result<Vec<Expectation>>

Create one or more expectations on the server.

Returns the created expectations as echoed by the server.

Source

pub fn upsert_raw(&self, expectations: Value) -> Result<Value>

Create one or more expectations from raw JSON values.

This is the lower-level counterpart to upsert for expectation shapes that the typed Expectation model does not (yet) cover — notably the httpLlmResponse action and conversation scenario fields produced by the crate::llm builders, and the Velocity/JSON-RPC expectations produced by the crate::mcp builder.

The expectations value should be a JSON object (single expectation) or a JSON array of expectation objects. Returns the raw JSON the server echoes back (or the submitted value if the server returns an empty body).

Source

pub fn openapi( &self, expectation: &OpenApiExpectation, ) -> Result<Vec<Expectation>>

Register expectations from an OpenAPI/Swagger specification.

Sends a PUT /mockserver/openapi with the given OpenApiExpectation. MockServer parses the spec and creates request matchers and example responses for the selected operations (or every operation when none are specified). Returns the created expectations as echoed by the server.

§Example
use mockserver_client::{ClientBuilder, OpenApiExpectation};

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.openapi(
    &OpenApiExpectation::new("https://example.com/petstore.yaml")
        .operation("listPets", "200"),
).unwrap();
Source

pub fn when(&self, request: HttpRequest) -> ForwardChainExpectation<'_>

Begin building an expectation with the fluent when(...).respond(...) API.

§Example
use mockserver_client::{ClientBuilder, HttpRequest, HttpResponse};

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.when(HttpRequest::new().method("GET").path("/foo"))
    .respond(HttpResponse::new().status_code(200).body("bar"))
    .unwrap();
Source

pub fn verify( &self, request: HttpRequest, times: VerificationTimes, ) -> Result<()>

Verify that a request was received the specified number of times.

Returns Ok(()) if verification passes, or Err(Error::VerificationFailure) with the server’s failure message.

Source

pub fn verify_request_and_response( &self, request: HttpRequest, response: HttpResponse, times: VerificationTimes, ) -> Result<()>

Verify that a request/response pair was received the specified number of times.

Both the request matcher and the response matcher must match for a recorded exchange to count. The response matcher uses the same HttpResponse type as expectations — the server matches against the recorded response’s status code, headers, and body.

Source

pub fn verify_response( &self, response: HttpResponse, times: VerificationTimes, ) -> Result<()>

Verify that a response (regardless of request) was returned the specified number of times.

The httpRequest field is omitted from the JSON so the server matches any request.

Source

pub fn verify_zero_interactions(&self) -> Result<()>

Verify that no requests at all were received by the server.

Thin wrapper over verify: matches any request (an empty matcher) with exactly(0) times. Returns Ok(()) if the server received no requests, or Err(Error::VerificationFailure) otherwise.

Source

pub fn verify_raw(&self, verification: &Verification) -> Result<()>

Send a fully constructed Verification to the server.

This is the most flexible form — callers can set every field, including maximum_number_of_request_to_return_in_verification_failure.

Source

pub fn verify_sequence(&self, requests: Vec<HttpRequest>) -> Result<()>

Verify that requests were received in the given order.

Source

pub fn verify_sequence_with_responses( &self, requests: Vec<HttpRequest>, responses: Vec<HttpResponse>, ) -> Result<()>

Verify that request/response pairs were received in the given order.

responses is index-aligned with requests — each entry constrains the response that must have been returned for the corresponding request.

Source

pub fn verify_sequence_raw( &self, verification: &VerificationSequence, ) -> Result<()>

Send a fully constructed VerificationSequence to the server.

Source

pub fn clear( &self, request: Option<&HttpRequest>, clear_type: Option<ClearType>, ) -> Result<()>

Clear expectations and/or logs matching the given request.

If request is None, clears everything of the specified type.

Source

pub fn clear_by_id( &self, expectation_id: impl Into<String>, clear_type: Option<ClearType>, ) -> Result<()>

Clear expectations by expectation ID.

Source

pub fn reset(&self) -> Result<()>

Reset all expectations and recorded requests.

Source

pub fn retrieve_recorded_requests( &self, request: Option<&HttpRequest>, ) -> Result<Vec<HttpRequest>>

Retrieve recorded requests matching the optional filter.

Source

pub fn retrieve_active_expectations( &self, request: Option<&HttpRequest>, ) -> Result<Vec<Expectation>>

Retrieve active expectations matching the optional filter.

Source

pub fn retrieve_recorded_expectations( &self, request: Option<&HttpRequest>, ) -> Result<Vec<Expectation>>

Retrieve recorded expectations matching the optional filter.

Source

pub fn retrieve_expectations_as_code( &self, format: RetrieveFormat, request: Option<&HttpRequest>, ) -> Result<String>

Retrieve the active expectations as MockServer SDK setup code (the builder code that recreates the expectations) in the requested language.

format must be one of the code-generation variants of RetrieveFormat (e.g. RetrieveFormat::Java, RetrieveFormat::Rust). The generated code is returned as a string.

Source

pub fn retrieve_recorded_expectations_as_code( &self, format: RetrieveFormat, request: Option<&HttpRequest>, ) -> Result<String>

Retrieve the recorded (proxied) request/response pairs as MockServer SDK setup code in the requested language.

format must be one of the code-generation variants of RetrieveFormat. The generated code is returned as a string.

Source

pub fn retrieve_log_messages( &self, request: Option<&HttpRequest>, ) -> Result<Vec<String>>

Retrieve log messages matching the optional filter.

Source

pub fn retrieve_request_responses( &self, request: Option<&HttpRequest>, ) -> Result<Vec<Value>>

Retrieve recorded request/response pairs.

Source

pub fn status(&self) -> Result<Ports>

Query the server’s listening ports.

Source

pub fn bind(&self, ports: &[u16]) -> Result<Ports>

Bind additional listening ports.

Source

pub fn has_started(&self, attempts: u32, timeout_ms: u64) -> bool

Check if the MockServer has started (polls with retries).

Source

pub fn add_breakpoint( &self, matcher: HttpRequest, phases: &[&str], request_handler: Option<BreakpointRequestHandler>, response_handler: Option<BreakpointResponseHandler>, stream_frame_handler: Option<BreakpointStreamFrameHandler>, ) -> Result<String>

Register a breakpoint matcher with the given phases and handlers. Returns the server-assigned breakpoint id.

Source

pub fn add_request_breakpoint( &self, matcher: HttpRequest, handler: BreakpointRequestHandler, ) -> Result<String>

Convenience: register a REQUEST-only breakpoint.

Source

pub fn add_request_response_breakpoint( &self, matcher: HttpRequest, request_handler: BreakpointRequestHandler, response_handler: BreakpointResponseHandler, ) -> Result<String>

Convenience: register a REQUEST + RESPONSE breakpoint.

Source

pub fn add_stream_breakpoint( &self, matcher: HttpRequest, phases: &[&str], handler: BreakpointStreamFrameHandler, ) -> Result<String>

Convenience: register a streaming-phase breakpoint.

Source

pub fn list_breakpoint_matchers(&self) -> Result<BreakpointMatcherList>

List all registered breakpoint matchers.

Source

pub fn remove_breakpoint_matcher(&self, id: impl Into<String>) -> Result<()>

Remove a breakpoint matcher by id.

Source

pub fn clear_breakpoint_matchers(&self) -> Result<()>

Remove all registered breakpoint matchers.

Source

pub fn close_breakpoint_websocket(&self)

Close the breakpoint callback WebSocket connection.

Source

pub fn mock_with_callback<F>( &self, matcher: HttpRequest, handler: F, ) -> Result<Vec<Expectation>>
where F: Fn(HttpRequest) -> HttpResponse + Send + 'static,

Register an expectation whose response is produced by a Rust closure invoked over the callback WebSocket (an httpResponseObjectCallback).

When a request matches matcher, MockServer pushes it to this client over the shared callback WebSocket; handler receives the HttpRequest and returns the HttpResponse to send back. The closure runs on the client’s background WebSocket-read thread, so it must be Send + 'static.

The callback WebSocket is shared with breakpoints — only one socket is opened per client. There is a single object-response handler per client; calling this again replaces it. Narrow which requests reach the closure with the matcher.

§Example
use mockserver_client::{ClientBuilder, HttpRequest, HttpResponse};

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.mock_with_callback(
    HttpRequest::new().method("GET").path("/echo"),
    |req| {
        HttpResponse::new()
            .status_code(200)
            .body(format!("you asked for {}", req.path.unwrap_or_default()))
    },
).unwrap();
Source

pub fn upload_grpc_descriptor(&self, descriptor: &[u8]) -> Result<()>

Upload a compiled protobuf descriptor set so gRPC requests can be matched.

descriptor must be the raw bytes of a FileDescriptorSet (e.g. the output of protoc --descriptor_set_out=... --include_imports). The bytes are sent verbatim as application/octet-stream — they are not base64-encoded. Sends a PUT /mockserver/grpc/descriptors; the server responds 201 Created on success.

§Example
use mockserver_client::ClientBuilder;

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
let descriptor_set: Vec<u8> = std::fs::read("greeter.desc").unwrap();
client.upload_grpc_descriptor(&descriptor_set).unwrap();
Source

pub fn retrieve_grpc_services(&self) -> Result<Vec<GrpcService>>

Retrieve the gRPC services registered from uploaded descriptor sets.

Sends a PUT /mockserver/grpc/services and returns the parsed list of GrpcServices, each with its GrpcMethods.

Source

pub fn clear_grpc_descriptors(&self) -> Result<()>

Clear all uploaded gRPC descriptor sets and registered services.

Sends a PUT /mockserver/grpc/clear; the server responds 200 OK.

Source

pub fn scenario(&self, name: &str) -> Scenario<'_>

Obtain a handle for inspecting and driving a named scenario state-machine.

The returned Scenario borrows the client and issues control-plane requests against /mockserver/scenario/{name}.

§Example
use mockserver_client::ClientBuilder;

let client = ClientBuilder::new("localhost", 1080).build().unwrap();
client.scenario("Deploy").set("Deploying").unwrap();
client.scenario("Deploy").set_timed("Deploying", 5000, "Deployed").unwrap();
client.scenario("Deploy").trigger("Failed").unwrap();
let state = client.scenario("Deploy").state().unwrap();
assert_eq!(state, "Failed");
Source

pub fn scenarios(&self) -> Result<Vec<ScenarioState>>

List every known scenario and its current state.

Sends a GET /mockserver/scenario and returns the parsed list of ScenarioStates.

Source

pub fn load_scenario(&self, scenario: &LoadScenario) -> Result<Value>

Register (load) a load scenario in the registry without running it.

Sends a PUT /mockserver/loadScenario with the given LoadScenario. The scenario’s name is the unique registry key used later by start_load_scenarios / stop_load_scenarios and the per-scenario fetch/delete endpoints.

Registering is always allowed — even when load generation is disabled on the server — so this does not surface Error::FeatureDisabled. Returns the raw JSON the server echoes ({"name":..,"state":"LOADED"}).

Source

pub fn load_scenarios(&self) -> Result<Value>

List every registered load scenario.

Sends a GET /mockserver/loadScenario and returns the raw JSON ({"scenarios":[{"name":..,"state":..,"definition":..,"status":..?}]}).

Source

pub fn get_load_scenario(&self, name: impl AsRef<str>) -> Result<Value>

Fetch a single registered load scenario by name.

Sends a GET /mockserver/loadScenario/{name}. Returns Error::NotFound when no scenario with that name is registered.

Source

pub fn delete_load_scenario(&self, name: impl AsRef<str>) -> Result<Value>

Remove a single registered load scenario by name.

Sends a DELETE /mockserver/loadScenario/{name}. Returns Error::NotFound when no scenario with that name is registered.

Source

pub fn clear_load_scenarios(&self) -> Result<Value>

Clear all registered load scenarios.

Sends a DELETE /mockserver/loadScenario. Idempotent.

Source

pub fn start_load_scenarios<S: AsRef<str>>(&self, names: &[S]) -> Result<Value>

Start one or more registered load scenarios by name.

Sends a PUT /mockserver/loadScenario/start with {"names":[...]}. Requires load generation to be enabled on the server — returns Error::FeatureDisabled on 403 (loadGenerationEnabled=false) — and Error::NotFound when a name is not registered. Honours each scenario’s startDelayMillis. Returns the raw JSON ({"started":[{"name":..,"state":..}],"status":..}).

Source

pub fn stop_load_scenarios<S: AsRef<str>>(&self, names: &[S]) -> Result<Value>

Stop running load scenarios.

Sends a PUT /mockserver/loadScenario/stop. When names is non-empty the body is {"names":[...]}; when it is empty (or &[]) the body is empty, which the server treats as “stop all”. Returns the raw JSON ({"stopped":[..],"status":..}).

Source

pub fn run_load_scenario(&self, scenario: &LoadScenario) -> Result<Value>

Convenience: register scenario then immediately start it by name.

Equivalent to load_scenario followed by start_load_scenarios with the scenario’s own name. Returns the JSON from the start call. Surfaces Error::FeatureDisabled from start when load generation is disabled.

Source

pub fn set_service_chaos( &self, host: impl Into<String>, profile: &HttpChaosProfile, ttl_millis: Option<u64>, ) -> Result<Value>

Register a service-scoped HTTP chaos profile for a downstream host.

Sends a PUT /mockserver/serviceChaos. ttl_millis, when supplied, sets an optional time-to-live after which the registration auto-reverts. Returns the raw JSON the server echoes.

Source

pub fn remove_service_chaos(&self, host: impl Into<String>) -> Result<Value>

Remove a single host’s service-scoped chaos profile.

Sends a PUT /mockserver/serviceChaos with {"host":..,"remove":true}.

Source

pub fn clear_service_chaos(&self) -> Result<Value>

Clear all service-scoped chaos.

Sends a PUT /mockserver/serviceChaos with {"clear":true}.

Source

pub fn verify_slo(&self, criteria: &SloCriteria) -> Result<SloVerdict>

Verify a set of service-level objectives over a window.

Sends a PUT /mockserver/verifySLO. The HTTP status encodes the verdict: 200 for PASS or INCONCLUSIVE, 406 for FAIL — both deserialize into a SloVerdict (inspect SloVerdict::result). A 400 (malformed criteria, or SLO tracking disabled) surfaces as Error::FeatureDisabled.

Returns Ok(SloVerdict) for both PASS/INCONCLUSIVE (200) and FAIL (406) so callers can branch on the verdict; transport/parse failures and 400 are returned as Err.

Source

pub fn set_preemption( &self, request: &PreemptionRequest, ) -> Result<PreemptionStatus>

Cordon and drain the server (preemption simulation).

Sends a PUT /mockserver/preemption with the given PreemptionRequest and returns the resulting PreemptionStatus.

Source

pub fn preemption_status(&self) -> Result<PreemptionStatus>

Retrieve the current preemption status.

Sends a GET /mockserver/preemption and returns the PreemptionStatus.

Source

pub fn clear_preemption(&self) -> Result<Value>

Uncordon the server (clear any active preemption simulation).

Sends a DELETE /mockserver/preemption. Idempotent — succeeds whether or not a simulation was active. Returns the raw JSON status.

Source

pub fn start_chaos_experiment( &self, experiment: &ChaosExperiment, ) -> Result<Value>

Start a scheduled multi-stage chaos experiment.

Sends a PUT /mockserver/chaosExperiment with the given ChaosExperiment. Only one experiment may be active at a time; starting a new one stops the previous one. Returns the raw JSON status ({"status":"started","name":..}).

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