Class: MockServer::Client
- Inherits:
-
Object
- Object
- MockServer::Client
- Defined in:
- lib/mockserver/client.rb
Overview
Synchronous MockServer client.
Provides the full MockServer REST API plus a fluent builder DSL and WebSocket-based object callback support.
Constant Summary collapse
- HTTP_TIMEOUT =
seconds, matching Python client
60- MODE_SIMULATE =
Valid operating modes (parallels
org.mockserver.mock.MockMode). 'SIMULATE'- MODE_SPY =
'SPY'- MODE_CAPTURE =
'CAPTURE'
Instance Method Summary collapse
-
#add_breakpoint(matcher, phases, request_handler: nil, response_handler: nil, stream_frame_handler: nil) ⇒ String
Register a breakpoint matcher with callback handlers.
-
#add_request_and_response_breakpoint(matcher, request_handler, response_handler) ⇒ String
Convenience: register a REQUEST+RESPONSE breakpoint.
-
#add_request_breakpoint(matcher, request_handler) ⇒ String
Convenience: register a REQUEST-only breakpoint.
-
#advance_clock(duration_millis) ⇒ Hash
Advance the frozen clock by
duration_millismilliseconds. -
#bind(*ports) ⇒ Array<Integer>
Bind additional ports.
-
#clear(request = nil, type: nil) ⇒ nil
Clear expectations and/or logs.
-
#clear_breakpoint_matchers ⇒ Hash
Clear all registered breakpoint matchers.
-
#clear_by_id(expectation_id, type: nil) ⇒ nil
Clear by expectation ID.
-
#clear_drift ⇒ nil
Clear all recorded mock drift (PUT /mockserver/drift/clear).
-
#clear_grpc_descriptors ⇒ nil
Clear all uploaded gRPC descriptor sets and registered services.
-
#clear_load_scenarios ⇒ Hash
Clear all registered load scenarios.
-
#clear_service_chaos ⇒ Hash
Clear all service-scoped chaos profiles.
-
#clock_status ⇒ Hash
Query the current clock status.
-
#close ⇒ nil
Close all WebSocket connections.
-
#delete_file(name) ⇒ nil
Delete a stored file (PUT /mockserver/files/delete).
-
#delete_load_scenario(name) ⇒ Hash
Remove a single registered load scenario by name.
-
#freeze_clock(instant = nil) ⇒ Hash
Freeze the server clock at the given ISO-8601 instant.
-
#generate_load_scenario_from_openapi(name, spec_url_or_payload, target: nil, profile: nil) ⇒ Hash
Generate (and register) a load scenario from an OpenAPI specification.
-
#generate_load_scenario_from_recording(name, mode: nil, request_filter: nil, target: nil, max_steps: nil) ⇒ Hash
Generate (and register) a load scenario from recorded proxy traffic.
-
#get_load_scenario(name) ⇒ Hash
Fetch a single registered load scenario by name.
-
#get_load_scenario_report(name, format = nil) ⇒ Hash, String
Fetch the end-of-run summary report for a load scenario run.
-
#has_started?(attempts: 10, timeout: 0.5) ⇒ Boolean
(also: #has_started)
Check if MockServer has started.
-
#import_har(har_json) ⇒ Array<Expectation>
Import a HAR document as expectations (PUT /mockserver/import?format=har).
-
#import_postman_collection(collection_json) ⇒ Array<Expectation>
Import a Postman collection as expectations (PUT /mockserver/import?format=postman).
-
#initialize(host, port, context_path: '', secure: false, ca_cert_path: nil, tls_verify: true) ⇒ Client
constructor
A new instance of Client.
-
#list_breakpoint_matchers ⇒ Hash
List all registered breakpoint matchers.
-
#list_files ⇒ Array<String>
List the names of all stored files (PUT /mockserver/files/list).
-
#load_scenario(scenario) ⇒ Hash
Register (load) a scenario into the registry without running it.
-
#load_scenarios ⇒ Hash
List all registered load scenarios.
-
#mock_with_callback(request, callback, times: nil, time_to_live: nil) ⇒ Array<Expectation>
Register a response callback via WebSocket.
-
#mock_with_forward_callback(request, forward_callback, response_callback = nil, times: nil, time_to_live: nil) ⇒ Array<Expectation>
Register a forward callback via WebSocket.
-
#open_api_expectation(expectation) ⇒ nil
Create an OpenAPI expectation.
-
#pact_export(consumer: nil, provider: nil) ⇒ String
Export the active expectations as a Pact v3 contract (PUT /mockserver/pact?consumer=&provider=).
-
#pact_import(json) ⇒ String
Import a Pact v3 contract as expectations (PUT /mockserver/pact/import).
-
#pact_verify(json) ⇒ String
Verify a Pact v3 contract against the active expectations (PUT /mockserver/pact/verify).
-
#remove_breakpoint_matcher(breakpoint_id) ⇒ Hash
Remove a breakpoint matcher by id.
-
#remove_service_chaos(host) ⇒ Hash
Remove the service-scoped chaos profile registered for
host. -
#reset ⇒ nil
Reset all expectations and logs.
-
#reset_clock ⇒ Hash
Reset the server clock to real wall-clock time.
-
#retrieve_active_expectations(request: nil) ⇒ Array<Expectation>
Retrieve active expectations.
-
#retrieve_configuration ⇒ String
Read the effective live configuration (GET /mockserver/configuration).
-
#retrieve_drift ⇒ Hash
Retrieve the recorded mock drift report (GET /mockserver/drift).
-
#retrieve_expectations_as_code(format: 'java', request: nil) ⇒ String
Retrieve the active expectations as MockServer SDK setup code (the builder code that recreates the expectations) in the requested language.
-
#retrieve_file(name) ⇒ String
Retrieve a file's raw content (PUT /mockserver/files/retrieve).
-
#retrieve_grpc_services ⇒ Array<Hash>
Retrieve the gRPC services registered from uploaded descriptor sets.
-
#retrieve_log_messages(request: nil) ⇒ Array<String>
Retrieve log messages.
-
#retrieve_metrics ⇒ Hash
Retrieve the JSON metric counter snapshot (PUT /mockserver/retrieve?type=METRICS).
-
#retrieve_mode ⇒ Hash
Read the current operating mode (GET /mockserver/mode).
-
#retrieve_recorded_expectations(request: nil) ⇒ Array<Expectation>
Retrieve recorded expectations.
-
#retrieve_recorded_expectations_as_code(format: 'java', request: nil) ⇒ String
Retrieve the recorded (proxied) request/response pairs as MockServer SDK setup code in the requested language.
-
#retrieve_recorded_requests(request: nil) ⇒ Array<HttpRequest>
Retrieve recorded requests.
-
#retrieve_recorded_requests_and_responses(request: nil) ⇒ Array<HttpRequestAndHttpResponse>
Retrieve recorded requests and responses.
-
#run_load_scenario(scenario) ⇒ Hash
Convenience: register a scenario then immediately start it.
-
#scenario(name) ⇒ ScenarioHandle
Return a handle to the named stateful scenario, wrapping the
/mockserver/scenario/{name}control-plane endpoints. -
#scenario_request(method, path, body = nil) ⇒ Object
private
Issue a control-plane scenario request, parsing the JSON response and raising Error on any >= 400 status.
-
#scenarios ⇒ Array<ScenarioState>
List every known scenario and its current state.
-
#scrape_metrics ⇒ String
Scrape the Prometheus exposition text (GET /mockserver/metrics).
-
#service_chaos_status ⇒ Hash
Query the current service-scoped chaos registrations.
-
#set_mode(mode) ⇒ Hash
Set the high-level operating mode (PUT /mockserver/mode?mode=
). -
#set_service_chaos(host, chaos, ttl_millis = nil) ⇒ Hash
Register a service-scoped HTTP chaos profile for an upstream host.
-
#start_chaos_experiment(experiment) ⇒ Hash
Start a scheduled multi-stage chaos experiment (PUT /mockserver/chaosExperiment).
-
#start_load_scenarios(names) ⇒ Hash
Start one or more registered scenarios.
-
#stop ⇒ nil
Stop the MockServer instance.
-
#stop_load_scenarios(names = nil) ⇒ Hash
Stop running scenarios.
-
#store_file(name, content) ⇒ Hash
Store a file in the in-memory file store (PUT /mockserver/files/store).
-
#update_configuration(config_json) ⇒ String
Update the live configuration (PUT /mockserver/configuration).
-
#upload_grpc_descriptor(descriptor_bytes) ⇒ nil
Upload a compiled protobuf descriptor set so gRPC requests can be matched.
-
#upsert(*expectations) ⇒ Array<Expectation>
Create or update expectations.
-
#verify(request = nil, times: nil, response: nil) ⇒ nil
Verify that a request (and optionally a response) was received.
-
#verify_sequence(*requests, responses: nil) ⇒ nil
Verify that requests were received in sequence.
-
#verify_slo(criteria) ⇒ Hash
Evaluate a set of service-level objectives (SLOs) over a window (PUT /mockserver/verifySLO).
-
#verify_zero_interactions ⇒ nil
Verify zero interactions.
-
#when(request, times: nil, time_to_live: nil, priority: nil) ⇒ ForwardChainExpectation
Begin building an expectation via the fluent API.
-
#wsdl_expectation(wsdl) ⇒ Array<Expectation>
Generate expectations from a WSDL document (PUT /mockserver/wsdl).
Constructor Details
#initialize(host, port, context_path: '', secure: false, ca_cert_path: nil, tls_verify: true) ⇒ Client
Returns a new instance of Client.
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/mockserver/client.rb', line 37 def initialize(host, port, context_path: '', secure: false, ca_cert_path: nil, tls_verify: true) @host = host @port = port @context_path = context_path @secure = secure @ca_cert_path = ca_cert_path @tls_verify = tls_verify @websocket_clients = [] @websocket_mutex = Mutex.new scheme = secure ? 'https' : 'http' ctx_path = '' if context_path && !context_path.empty? ctx_path = context_path.start_with?('/') ? context_path : "/#{context_path}" end @base_url = "#{scheme}://#{host}:#{port}#{ctx_path}" if block_given? begin yield self ensure close end end end |
Instance Method Details
#add_breakpoint(matcher, phases, request_handler: nil, response_handler: nil, stream_frame_handler: nil) ⇒ String
Register a breakpoint matcher with callback handlers. The callback WebSocket is opened lazily and reused.
1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 |
# File 'lib/mockserver/client.rb', line 1294 def add_breakpoint(matcher, phases, request_handler: nil, response_handler: nil, stream_frame_handler: nil) raise ArgumentError, 'add_breakpoint requires a non-nil matcher' if matcher.nil? raise ArgumentError, 'add_breakpoint requires a non-empty phases array' if phases.nil? || phases.empty? ws_client = ensure_breakpoint_websocket client_id = ws_client.client_id body = JSON.generate({ 'httpRequest' => matcher.to_h, 'phases' => phases, 'clientId' => client_id }) status, response_body = request('PUT', '/mockserver/breakpoint/matcher', body) if status >= 400 raise Error, "Failed to register breakpoint matcher (status=#{status}): #{response_body}" end parsed = response_body && !response_body.empty? ? JSON.parse(response_body) : {} breakpoint_id = parsed['id'] raise Error, 'Server did not return a breakpoint id' unless breakpoint_id # Install per-breakpoint-id handlers ws_client.set_breakpoint_request_handler(breakpoint_id, request_handler) if request_handler ws_client.set_breakpoint_response_handler(breakpoint_id, response_handler) if response_handler ws_client.set_breakpoint_stream_frame_handler(breakpoint_id, stream_frame_handler) if stream_frame_handler breakpoint_id end |
#add_request_and_response_breakpoint(matcher, request_handler, response_handler) ⇒ String
Convenience: register a REQUEST+RESPONSE breakpoint.
1338 1339 1340 1341 1342 |
# File 'lib/mockserver/client.rb', line 1338 def add_request_and_response_breakpoint(matcher, request_handler, response_handler) add_breakpoint(matcher, %w[REQUEST RESPONSE], request_handler: request_handler, response_handler: response_handler) end |
#add_request_breakpoint(matcher, request_handler) ⇒ String
Convenience: register a REQUEST-only breakpoint.
1329 1330 1331 |
# File 'lib/mockserver/client.rb', line 1329 def add_request_breakpoint(matcher, request_handler) add_breakpoint(matcher, ['REQUEST'], request_handler: request_handler) end |
#advance_clock(duration_millis) ⇒ Hash
Advance the frozen clock by duration_millis milliseconds.
174 175 176 177 178 179 180 181 182 |
# File 'lib/mockserver/client.rb', line 174 def advance_clock(duration_millis) body = JSON.generate({ 'action' => 'advance', 'durationMillis' => duration_millis }) status, response_body = request('PUT', '/mockserver/clock', body) if status >= 400 raise Error, "Failed to advance clock (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#bind(*ports) ⇒ Array<Integer>
Bind additional ports.
1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 |
# File 'lib/mockserver/client.rb', line 1217 def bind(*ports) body = JSON.generate(Ports.new(ports: ports.flatten).to_h) status, response_body = request('PUT', '/mockserver/bind', body) if status >= 400 raise Error, "Failed to bind ports (status=#{status}): #{response_body}" end if response_body && !response_body.empty? parsed = JSON.parse(response_body) return Ports.from_hash(parsed).ports end [] end |
#clear(request = nil, type: nil) ⇒ nil
Clear expectations and/or logs.
106 107 108 109 110 111 112 113 114 115 116 117 118 |
# File 'lib/mockserver/client.rb', line 106 def clear(request = nil, type: nil) query_params = {} query_params['type'] = type if type body = request ? JSON.generate(request.to_h) : '' status, response_body = do_request( 'PUT', '/mockserver/clear', body, query_params.empty? ? nil : query_params ) if status >= 400 raise Error, "Failed to clear (status=#{status}): #{response_body}" end nil end |
#clear_breakpoint_matchers ⇒ Hash
Clear all registered breakpoint matchers.
1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 |
# File 'lib/mockserver/client.rb', line 1379 def clear_breakpoint_matchers status, response_body = request('PUT', '/mockserver/breakpoint/matcher/clear') if status >= 400 raise Error, "Failed to clear breakpoint matchers (status=#{status}): #{response_body}" end # Clear client-side handlers @websocket_mutex.synchronize do @websocket_clients.each do |ws| ws.clear_breakpoint_handlers if ws.respond_to?(:clear_breakpoint_handlers) end end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#clear_by_id(expectation_id, type: nil) ⇒ nil
Clear by expectation ID.
124 125 126 127 128 129 130 131 132 133 134 135 136 |
# File 'lib/mockserver/client.rb', line 124 def clear_by_id(expectation_id, type: nil) query_params = {} query_params['type'] = type if type body = JSON.generate({ 'id' => expectation_id }) status, response_body = do_request( 'PUT', '/mockserver/clear', body, query_params.empty? ? nil : query_params ) if status >= 400 raise Error, "Failed to clear by id (status=#{status}): #{response_body}" end nil end |
#clear_drift ⇒ nil
Clear all recorded mock drift (PUT /mockserver/drift/clear).
305 306 307 308 309 310 311 312 |
# File 'lib/mockserver/client.rb', line 305 def clear_drift status, response_body = request('PUT', '/mockserver/drift/clear') if status >= 400 raise Error, "Failed to clear drift (status=#{status}): #{response_body}" end nil end |
#clear_grpc_descriptors ⇒ nil
Clear all uploaded gRPC descriptor sets and registered services.
1013 1014 1015 1016 1017 1018 1019 1020 |
# File 'lib/mockserver/client.rb', line 1013 def clear_grpc_descriptors status, response_body = request('PUT', '/mockserver/grpc/clear') if status >= 400 raise Error, "Failed to clear gRPC descriptors (status=#{status}): #{response_body}" end nil end |
#clear_load_scenarios ⇒ Hash
Clear all registered load scenarios.
689 690 691 692 693 694 695 696 |
# File 'lib/mockserver/client.rb', line 689 def clear_load_scenarios status, response_body = request('DELETE', '/mockserver/loadScenario') if status >= 400 raise Error, "Failed to clear load scenarios (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#clear_service_chaos ⇒ Hash
Clear all service-scoped chaos profiles.
588 589 590 591 592 593 594 595 596 |
# File 'lib/mockserver/client.rb', line 588 def clear_service_chaos body = JSON.generate({ 'clear' => true }) status, response_body = request('PUT', '/mockserver/serviceChaos', body) if status >= 400 raise Error, "Failed to clear service chaos (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#clock_status ⇒ Hash
Query the current clock status.
198 199 200 201 202 203 204 205 |
# File 'lib/mockserver/client.rb', line 198 def clock_status status, response_body = request('GET', '/mockserver/clock') if status >= 400 raise Error, "Failed to get clock status (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#close ⇒ nil
Close all WebSocket connections.
1439 1440 1441 1442 1443 1444 1445 |
# File 'lib/mockserver/client.rb', line 1439 def close @websocket_mutex.synchronize do @websocket_clients.each(&:close) @websocket_clients.clear end nil end |
#delete_file(name) ⇒ nil
Delete a stored file (PUT /mockserver/files/delete).
An unknown file yields a 404 which raises an Error.
447 448 449 450 451 452 453 454 455 456 457 458 |
# File 'lib/mockserver/client.rb', line 447 def delete_file(name) body = JSON.generate({ 'name' => name }) status, response_body = request('PUT', '/mockserver/files/delete', body) if status == 404 raise Error, "File not found (status=404): #{name}" end if status >= 400 raise Error, "Failed to delete file (status=#{status}): #{response_body}" end nil end |
#delete_load_scenario(name) ⇒ Hash
Remove a single registered load scenario by name.
677 678 679 680 681 682 683 684 |
# File 'lib/mockserver/client.rb', line 677 def delete_load_scenario(name) status, response_body = request('DELETE', "/mockserver/loadScenario/#{encode_path_segment(name)}") if status >= 400 raise Error, "Failed to delete load scenario (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#freeze_clock(instant = nil) ⇒ Hash
Freeze the server clock at the given ISO-8601 instant.
If instant is nil, the clock freezes at the current real time.
159 160 161 162 163 164 165 166 167 168 169 |
# File 'lib/mockserver/client.rb', line 159 def freeze_clock(instant = nil) payload = { 'action' => 'freeze' } payload['instant'] = instant if instant body = JSON.generate(payload) status, response_body = request('PUT', '/mockserver/clock', body) if status >= 400 raise Error, "Failed to freeze clock (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#generate_load_scenario_from_openapi(name, spec_url_or_payload, target: nil, profile: nil) ⇒ Hash
Generate (and register) a load scenario from an OpenAPI specification.
Produces an editable scenario - one step per OpenAPI operation - and loads
it into the registry under name in the LOADED state; it generates no
traffic and is allowed even when load generation is disabled.
813 814 815 816 817 818 819 820 821 822 823 824 |
# File 'lib/mockserver/client.rb', line 813 def generate_load_scenario_from_openapi(name, spec_url_or_payload, target: nil, profile: nil) payload = { 'name' => name, 'specUrlOrPayload' => spec_url_or_payload } payload['target'] = target if target payload['profile'] = profile.respond_to?(:to_h) ? profile.to_h : profile if profile body = JSON.generate(payload) status, response_body = request('PUT', '/mockserver/loadScenario/generateFromOpenAPI', body) if status >= 400 raise Error, "Failed to generate load scenario from OpenAPI (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#generate_load_scenario_from_recording(name, mode: nil, request_filter: nil, target: nil, max_steps: nil) ⇒ Hash
Generate (and register) a load scenario from recorded proxy traffic.
Converts requests previously recorded by MockServer in proxy/recording mode
into an editable scenario and loads it into the registry under name in the
LOADED state; it generates no traffic and is allowed even when load
generation is disabled.
841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 |
# File 'lib/mockserver/client.rb', line 841 def generate_load_scenario_from_recording(name, mode: nil, request_filter: nil, target: nil, max_steps: nil) payload = { 'name' => name } payload['mode'] = mode if mode payload['requestFilter'] = request_filter.respond_to?(:to_h) ? request_filter.to_h : request_filter if request_filter payload['target'] = target if target payload['maxSteps'] = max_steps if max_steps body = JSON.generate(payload) status, response_body = request('PUT', '/mockserver/loadScenario/generateFromRecording', body) if status >= 400 raise Error, "Failed to generate load scenario from recording (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#get_load_scenario(name) ⇒ Hash
Fetch a single registered load scenario by name.
661 662 663 664 665 666 667 668 669 670 671 |
# File 'lib/mockserver/client.rb', line 661 def get_load_scenario(name) status, response_body = request('GET', "/mockserver/loadScenario/#{encode_path_segment(name)}") if status == 404 raise Error, "Load scenario not found (status=404): #{name}" end if status >= 400 raise Error, "Failed to get load scenario (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#get_load_scenario_report(name, format = nil) ⇒ Hash, String
Fetch the end-of-run summary report for a load scenario run.
Returns the report derived from the run's status snapshot (live while
running, or the retained terminal snapshot once finished). With no format
(or any value other than "junit") the JSON report is parsed and returned
as a Hash carrying counts, latency percentiles, the threshold verdict and
per-threshold results. With format: "junit" the raw JUnit-XML
<testsuite> document is returned as a String so a load run becomes a
first-class CI test artifact.
779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 |
# File 'lib/mockserver/client.rb', line 779 def get_load_scenario_report(name, format = nil) query_params = {} query_params['format'] = format if format status, response_body = do_request( 'GET', "/mockserver/loadScenario/#{encode_path_segment(name)}/report", nil, query_params.empty? ? nil : query_params ) if status == 404 raise Error, "Load scenario report not found (status=404): #{name}" end if status >= 400 raise Error, "Failed to get load scenario report (status=#{status}): #{response_body}" end return response_body if format == 'junit' response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#has_started?(attempts: 10, timeout: 0.5) ⇒ Boolean Also known as: has_started
Check if MockServer has started.
1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 |
# File 'lib/mockserver/client.rb', line 1246 def has_started?(attempts: 10, timeout: 0.5) attempts.times do |i| begin status, = request('PUT', '/mockserver/status') return true if status == 200 rescue ConnectionError # not yet started end sleep(timeout) if i < attempts - 1 end false end |
#import_har(har_json) ⇒ Array<Expectation>
Import a HAR document as expectations (PUT /mockserver/import?format=har).
469 470 471 |
# File 'lib/mockserver/client.rb', line 469 def import_har(har_json) import_document(har_json, 'har') end |
#import_postman_collection(collection_json) ⇒ Array<Expectation>
Import a Postman collection as expectations (PUT /mockserver/import?format=postman).
479 480 481 |
# File 'lib/mockserver/client.rb', line 479 def import_postman_collection(collection_json) import_document(collection_json, 'postman') end |
#list_breakpoint_matchers ⇒ Hash
List all registered breakpoint matchers.
1346 1347 1348 1349 1350 1351 1352 1353 |
# File 'lib/mockserver/client.rb', line 1346 def list_breakpoint_matchers status, response_body = request('GET', '/mockserver/breakpoint/matchers') if status >= 400 raise Error, "Failed to list breakpoint matchers (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#list_files ⇒ Array<String>
List the names of all stored files (PUT /mockserver/files/list).
428 429 430 431 432 433 434 435 436 437 438 439 |
# File 'lib/mockserver/client.rb', line 428 def list_files status, response_body = request('PUT', '/mockserver/files/list') if status >= 400 raise Error, "Failed to list files (status=#{status}): #{response_body}" end if response_body && !response_body.empty? parsed = JSON.parse(response_body) return parsed if parsed.is_a?(Array) end [] end |
#load_scenario(scenario) ⇒ Hash
Register (load) a scenario into the registry without running it.
scenario may be a LoadScenario model (which responds to to_h) or a
plain Hash already shaped to the LoadScenario JSON contract. It must
carry a unique name. Registering is permitted even when load generation
is disabled on the server.
632 633 634 635 636 637 638 639 640 641 |
# File 'lib/mockserver/client.rb', line 632 def load_scenario(scenario) payload = scenario.respond_to?(:to_h) ? scenario.to_h : scenario body = JSON.generate(payload) status, response_body = request('PUT', '/mockserver/loadScenario', body) if status >= 400 raise Error, "Failed to register load scenario (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#load_scenarios ⇒ Hash
List all registered load scenarios.
647 648 649 650 651 652 653 654 |
# File 'lib/mockserver/client.rb', line 647 def load_scenarios status, response_body = request('GET', '/mockserver/loadScenario') if status >= 400 raise Error, "Failed to list load scenarios (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#mock_with_callback(request, callback, times: nil, time_to_live: nil) ⇒ Array<Expectation>
Register a response callback via WebSocket.
1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 |
# File 'lib/mockserver/client.rb', line 1405 def mock_with_callback(request, callback, times: nil, time_to_live: nil) client_id = register_websocket_callback('response', callback) expectation = Expectation.new( http_request: request, http_response_object_callback: HttpObjectCallback.new(client_id: client_id), times: times, time_to_live: time_to_live ) upsert(expectation) end |
#mock_with_forward_callback(request, forward_callback, response_callback = nil, times: nil, time_to_live: nil) ⇒ Array<Expectation>
Register a forward callback via WebSocket.
1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 |
# File 'lib/mockserver/client.rb', line 1423 def mock_with_forward_callback(request, forward_callback, response_callback = nil, times: nil, time_to_live: nil) client_id = register_websocket_callback('forward', forward_callback, response_callback) obj_callback = HttpObjectCallback.new(client_id: client_id) obj_callback.response_callback = true if response_callback expectation = Expectation.new( http_request: request, http_forward_object_callback: obj_callback, times: times, time_to_live: time_to_live ) upsert(expectation) end |
#open_api_expectation(expectation) ⇒ nil
Create an OpenAPI expectation.
92 93 94 95 96 97 98 99 100 |
# File 'lib/mockserver/client.rb', line 92 def open_api_expectation(expectation) body = JSON.generate(expectation.to_h) status, response_body = request('PUT', '/mockserver/openapi', body) if status >= 400 raise Error, "Failed to create OpenAPI expectation (status=#{status}): #{response_body}" end nil end |
#pact_export(consumer: nil, provider: nil) ⇒ String
Export the active expectations as a Pact v3 contract (PUT /mockserver/pact?consumer=&provider=).
A query param is only added when its value is non-blank; otherwise the server defaults are used.
345 346 347 348 349 350 351 352 353 354 355 356 357 |
# File 'lib/mockserver/client.rb', line 345 def pact_export(consumer: nil, provider: nil) query_params = {} query_params['consumer'] = consumer if consumer && !consumer.to_s.empty? query_params['provider'] = provider if provider && !provider.to_s.empty? status, response_body = do_request( 'PUT', '/mockserver/pact', nil, query_params.empty? ? nil : query_params ) if status >= 400 raise Error, "Failed to export pact (status=#{status}): #{response_body}" end response_body || '' end |
#pact_import(json) ⇒ String
Import a Pact v3 contract as expectations (PUT /mockserver/pact/import).
323 324 325 326 327 328 329 330 331 332 333 334 |
# File 'lib/mockserver/client.rb', line 323 def pact_import(json) if json.nil? || json.to_s.strip.empty? raise ArgumentError, 'pact JSON must not be empty' end status, response_body = request('PUT', '/mockserver/pact/import', json.to_s) if status >= 400 raise Error, "Failed to import pact (status=#{status}): #{response_body}" end response_body || '' end |
#pact_verify(json) ⇒ String
Verify a Pact v3 contract against the active expectations (PUT /mockserver/pact/verify).
The server encodes the verdict in the HTTP status: 202 when every interaction matches (PASS), 406 when verification fails (FAIL). Both carry the verification report JSON, which is returned verbatim in both cases (a FAIL does not raise) so callers can inspect the report.
370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 |
# File 'lib/mockserver/client.rb', line 370 def pact_verify(json) if json.nil? || json.to_s.strip.empty? raise ArgumentError, 'pact JSON must not be empty' end status, response_body = request('PUT', '/mockserver/pact/verify', json.to_s) if status == 202 || status == 406 return response_body || '' end if status >= 400 raise Error, "Failed to verify pact (status=#{status}): #{response_body}" end response_body || '' end |
#remove_breakpoint_matcher(breakpoint_id) ⇒ Hash
Remove a breakpoint matcher by id.
1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 |
# File 'lib/mockserver/client.rb', line 1358 def remove_breakpoint_matcher(breakpoint_id) raise ArgumentError, 'remove_breakpoint_matcher requires a non-empty id' if breakpoint_id.nil? || breakpoint_id.empty? body = JSON.generate({ 'id' => breakpoint_id }) status, response_body = request('PUT', '/mockserver/breakpoint/matcher/remove', body) if status >= 400 raise Error, "Failed to remove breakpoint matcher (status=#{status}): #{response_body}" end # Remove client-side handlers @websocket_mutex.synchronize do @websocket_clients.each do |ws| ws.remove_breakpoint_handlers(breakpoint_id) if ws.respond_to?(:remove_breakpoint_handlers) end end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#remove_service_chaos(host) ⇒ Hash
Remove the service-scoped chaos profile registered for host.
576 577 578 579 580 581 582 583 584 |
# File 'lib/mockserver/client.rb', line 576 def remove_service_chaos(host) body = JSON.generate({ 'host' => host, 'remove' => true }) status, response_body = request('PUT', '/mockserver/serviceChaos', body) if status >= 400 raise Error, "Failed to remove service chaos (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#reset ⇒ nil
Reset all expectations and logs.
140 141 142 143 144 145 146 147 148 149 |
# File 'lib/mockserver/client.rb', line 140 def reset status, response_body = request('PUT', '/mockserver/reset') if status >= 400 raise Error, "Failed to reset (status=#{status}): #{response_body}" end nil ensure close end |
#reset_clock ⇒ Hash
Reset the server clock to real wall-clock time.
186 187 188 189 190 191 192 193 194 |
# File 'lib/mockserver/client.rb', line 186 def reset_clock body = JSON.generate({ 'action' => 'reset' }) status, response_body = request('PUT', '/mockserver/clock', body) if status >= 400 raise Error, "Failed to reset clock (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#retrieve_active_expectations(request: nil) ⇒ Array<Expectation>
Retrieve active expectations.
1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 |
# File 'lib/mockserver/client.rb', line 1095 def retrieve_active_expectations(request: nil) body = request ? JSON.generate(request.to_h) : '' status, response_body = do_request( 'PUT', '/mockserver/retrieve', body, { 'type' => 'ACTIVE_EXPECTATIONS', 'format' => 'JSON' } ) if status >= 400 raise Error, "Failed to retrieve active expectations (status=#{status}): #{response_body}" end if response_body && !response_body.empty? parsed = JSON.parse(response_body) return parsed.map { |e| Expectation.from_hash(e) } if parsed.is_a?(Array) end [] end |
#retrieve_configuration ⇒ String
Read the effective live configuration (GET /mockserver/configuration).
255 256 257 258 259 260 261 262 |
# File 'lib/mockserver/client.rb', line 255 def retrieve_configuration status, response_body = request('GET', '/mockserver/configuration') if status >= 400 raise Error, "Failed to retrieve configuration (status=#{status}): #{response_body}" end response_body || '' end |
#retrieve_drift ⇒ Hash
Retrieve the recorded mock drift report (GET /mockserver/drift).
Returns the parsed report, a Hash of the form
{ "count" => <n>, "drifts" => [ ... ] }, where each entry describes a
difference detected between a mock's configured response and the live
upstream response for the same request. When no drift has been recorded an
empty Hash is returned.
294 295 296 297 298 299 300 301 |
# File 'lib/mockserver/client.rb', line 294 def retrieve_drift status, response_body = request('GET', '/mockserver/drift') if status >= 400 raise Error, "Failed to retrieve drift (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#retrieve_expectations_as_code(format: 'java', request: nil) ⇒ String
Retrieve the active expectations as MockServer SDK setup code (the builder code that recreates the expectations) in the requested language.
1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 |
# File 'lib/mockserver/client.rb', line 1138 def retrieve_expectations_as_code(format: 'java', request: nil) body = request ? JSON.generate(request.to_h) : '' status, response_body = do_request( 'PUT', '/mockserver/retrieve', body, { 'type' => 'ACTIVE_EXPECTATIONS', 'format' => format.to_s.upcase } ) if status >= 400 raise Error, "Failed to retrieve expectations as code (status=#{status}): #{response_body}" end response_body || '' end |
#retrieve_file(name) ⇒ String
Retrieve a file's raw content (PUT /mockserver/files/retrieve).
Returns the raw 200 body verbatim. An unknown file yields a 404 which raises an Error (there is no null-on-404 fallback).
412 413 414 415 416 417 418 419 420 421 422 423 |
# File 'lib/mockserver/client.rb', line 412 def retrieve_file(name) body = JSON.generate({ 'name' => name }) status, response_body = request('PUT', '/mockserver/files/retrieve', body) if status == 404 raise Error, "File not found (status=404): #{name}" end if status >= 400 raise Error, "Failed to retrieve file (status=#{status}): #{response_body}" end response_body || '' end |
#retrieve_grpc_services ⇒ Array<Hash>
Retrieve the gRPC services registered from uploaded descriptor sets.
Returns an array of service hashes, each with a "name" and a list of
"methods" (+"name"+, "inputType", "outputType", "clientStreaming",
"serverStreaming").
998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 |
# File 'lib/mockserver/client.rb', line 998 def retrieve_grpc_services status, response_body = request('PUT', '/mockserver/grpc/services') if status >= 400 raise Error, "Failed to retrieve gRPC services (status=#{status}): #{response_body}" end if response_body && !response_body.empty? parsed = JSON.parse(response_body) return parsed if parsed.is_a?(Array) end [] end |
#retrieve_log_messages(request: nil) ⇒ Array<String>
Retrieve log messages.
1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 |
# File 'lib/mockserver/client.rb', line 1193 def (request: nil) body = request ? JSON.generate(request.to_h) : '' status, response_body = do_request( 'PUT', '/mockserver/retrieve', body, { 'type' => 'LOGS' } ) if status >= 400 raise Error, "Failed to retrieve log messages (status=#{status}): #{response_body}" end if response_body && !response_body.empty? begin parsed = JSON.parse(response_body) return parsed if parsed.is_a?(Array) rescue JSON::ParserError return response_body.split("------------------------------------\n") end end [] end |
#retrieve_metrics ⇒ Hash
Retrieve the JSON metric counter snapshot (PUT /mockserver/retrieve?type=METRICS).
Returns a Hash mapping each metric name to its long value. When metrics are disabled on the server the snapshot is an empty Hash.
218 219 220 221 222 223 224 225 226 227 |
# File 'lib/mockserver/client.rb', line 218 def retrieve_metrics status, response_body = do_request( 'PUT', '/mockserver/retrieve', '', { 'type' => 'METRICS' } ) if status >= 400 raise Error, "Failed to retrieve metrics (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#retrieve_mode ⇒ Hash
Read the current operating mode (GET /mockserver/mode).
518 519 520 521 522 523 524 525 |
# File 'lib/mockserver/client.rb', line 518 def retrieve_mode status, response_body = request('GET', '/mockserver/mode') if status >= 400 raise Error, "Failed to retrieve mode (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#retrieve_recorded_expectations(request: nil) ⇒ Array<Expectation>
Retrieve recorded expectations.
1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 |
# File 'lib/mockserver/client.rb', line 1115 def retrieve_recorded_expectations(request: nil) body = request ? JSON.generate(request.to_h) : '' status, response_body = do_request( 'PUT', '/mockserver/retrieve', body, { 'type' => 'RECORDED_EXPECTATIONS', 'format' => 'JSON' } ) if status >= 400 raise Error, "Failed to retrieve recorded expectations (status=#{status}): #{response_body}" end if response_body && !response_body.empty? parsed = JSON.parse(response_body) return parsed.map { |e| Expectation.from_hash(e) } if parsed.is_a?(Array) end [] end |
#retrieve_recorded_expectations_as_code(format: 'java', request: nil) ⇒ String
Retrieve the recorded (proxied) request/response pairs as MockServer SDK setup code in the requested language.
1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 |
# File 'lib/mockserver/client.rb', line 1157 def retrieve_recorded_expectations_as_code(format: 'java', request: nil) body = request ? JSON.generate(request.to_h) : '' status, response_body = do_request( 'PUT', '/mockserver/retrieve', body, { 'type' => 'RECORDED_EXPECTATIONS', 'format' => format.to_s.upcase } ) if status >= 400 raise Error, "Failed to retrieve recorded expectations as code (status=#{status}): #{response_body}" end response_body || '' end |
#retrieve_recorded_requests(request: nil) ⇒ Array<HttpRequest>
Retrieve recorded requests.
1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 |
# File 'lib/mockserver/client.rb', line 1075 def retrieve_recorded_requests(request: nil) body = request ? JSON.generate(request.to_h) : '' status, response_body = do_request( 'PUT', '/mockserver/retrieve', body, { 'type' => 'REQUESTS', 'format' => 'JSON' } ) if status >= 400 raise Error, "Failed to retrieve recorded requests (status=#{status}): #{response_body}" end if response_body && !response_body.empty? parsed = JSON.parse(response_body) return parsed.map { |r| HttpRequest.from_hash(r) } if parsed.is_a?(Array) end [] end |
#retrieve_recorded_requests_and_responses(request: nil) ⇒ Array<HttpRequestAndHttpResponse>
Retrieve recorded requests and responses.
1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 |
# File 'lib/mockserver/client.rb', line 1173 def retrieve_recorded_requests_and_responses(request: nil) body = request ? JSON.generate(request.to_h) : '' status, response_body = do_request( 'PUT', '/mockserver/retrieve', body, { 'type' => 'REQUEST_RESPONSES', 'format' => 'JSON' } ) if status >= 400 raise Error, "Failed to retrieve request/responses (status=#{status}): #{response_body}" end if response_body && !response_body.empty? parsed = JSON.parse(response_body) return parsed.map { |rr| HttpRequestAndHttpResponse.from_hash(rr) } if parsed.is_a?(Array) end [] end |
#run_load_scenario(scenario) ⇒ Hash
Convenience: register a scenario then immediately start it.
Equivalent to calling #load_scenario followed by #start_load_scenarios
for the scenario's name. Requires loadGenerationEnabled on the server for
the start step.
754 755 756 757 758 759 760 761 762 763 |
# File 'lib/mockserver/client.rb', line 754 def run_load_scenario(scenario) payload = scenario.respond_to?(:to_h) ? scenario.to_h : scenario name = payload.respond_to?(:[]) ? (payload['name'] || payload[:name]) : nil if name.nil? || name.to_s.empty? raise ArgumentError, 'scenario must carry a non-empty name to run' end load_scenario(payload) start_load_scenarios(name) end |
#scenario(name) ⇒ ScenarioHandle
Return a handle to the named stateful scenario, wrapping the
/mockserver/scenario/{name} control-plane endpoints.
937 938 939 |
# File 'lib/mockserver/client.rb', line 937 def scenario(name) ScenarioHandle.new(self, name) end |
#scenario_request(method, path, body = nil) ⇒ Object
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Issue a control-plane scenario request, parsing the JSON response and
raising Error on any >= 400 status. Reuses the same transport
(+request+) as the other /mockserver/... control endpoints.
954 955 956 957 958 959 960 961 |
# File 'lib/mockserver/client.rb', line 954 def scenario_request(method, path, body = nil) status, response_body = request(method, path, body) if status >= 400 raise Error, "Scenario request failed (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#scenarios ⇒ Array<ScenarioState>
List every known scenario and its current state.
944 945 946 947 948 |
# File 'lib/mockserver/client.rb', line 944 def scenarios result = scenario_request('GET', '/mockserver/scenario') list = result.is_a?(Hash) ? (result['scenarios'] || []) : [] list.map { |s| ScenarioState.from_hash(s) } end |
#scrape_metrics ⇒ String
Scrape the Prometheus exposition text (GET /mockserver/metrics).
Returns the raw Prometheus/OpenMetrics exposition text. When metrics are disabled on the server this endpoint returns 404 and an Error is raised.
235 236 237 238 239 240 241 242 243 244 245 246 |
# File 'lib/mockserver/client.rb', line 235 def scrape_metrics status, response_body = request('GET', '/mockserver/metrics') if status == 404 raise Error, 'Failed to scrape metrics (status=404): metrics are disabled ' \ '(set metricsEnabled=true on the server to enable them)' end if status >= 400 raise Error, "Failed to scrape metrics (status=#{status}): #{response_body}" end response_body || '' end |
#service_chaos_status ⇒ Hash
Query the current service-scoped chaos registrations.
600 601 602 603 604 605 606 607 |
# File 'lib/mockserver/client.rb', line 600 def service_chaos_status status, response_body = request('GET', '/mockserver/serviceChaos') if status >= 400 raise Error, "Failed to get service chaos (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#set_mode(mode) ⇒ Hash
Set the high-level operating mode (PUT /mockserver/mode?mode=
mode may be a Symbol or String (case-insensitive), one of
+:simulate+/+:spy+/+:capture+ (or the MODE_SIMULATE, MODE_SPY,
MODE_CAPTURE constants). Setting the mode also flips the
proxy-on-no-match behaviour on the server.
502 503 504 505 506 507 508 509 510 511 512 |
# File 'lib/mockserver/client.rb', line 502 def set_mode(mode) mode_value = mode.to_s.upcase status, response_body = do_request( 'PUT', '/mockserver/mode', nil, { 'mode' => mode_value } ) if status >= 400 raise Error, "Failed to set mode (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#set_service_chaos(host, chaos, ttl_millis = nil) ⇒ Hash
Register a service-scoped HTTP chaos profile for an upstream host. The profile
is applied to every matched forward expectation to that host that does not
define its own chaos (an expectation's own chaos always wins). The host is
matched case-insensitively, ignoring any :port.
561 562 563 564 565 566 567 568 569 570 571 |
# File 'lib/mockserver/client.rb', line 561 def set_service_chaos(host, chaos, ttl_millis = nil) payload = { 'host' => host, 'chaos' => chaos.to_h } payload['ttlMillis'] = ttl_millis unless ttl_millis.nil? body = JSON.generate(payload) status, response_body = request('PUT', '/mockserver/serviceChaos', body) if status >= 400 raise Error, "Failed to set service chaos (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#start_chaos_experiment(experiment) ⇒ Hash
Start a scheduled multi-stage chaos experiment (PUT /mockserver/chaosExperiment).
The experiment is an ordered sequence of stages, each applying service-scoped chaos profiles to one or more hosts for a duration; stages progress automatically. Only one experiment may be active at a time; starting a new one stops the previous one.
experiment may be any Hash already shaped to the ChaosExperiment JSON
contract (+name+, loop, +stages+[+profiles+{host:
profile}]) or an object that responds to to_h.
914 915 916 917 918 919 920 921 922 923 924 925 926 |
# File 'lib/mockserver/client.rb', line 914 def start_chaos_experiment(experiment) payload = experiment.respond_to?(:to_h) ? experiment.to_h : experiment body = JSON.generate(payload) status, response_body = request('PUT', '/mockserver/chaosExperiment', body) if status == 403 raise Error, 'Chaos experiment rejected (status=403): chaos is disabled on the server' end if status >= 400 raise Error, "Failed to start chaos experiment (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#start_load_scenarios(names) ⇒ Hash
Start one or more registered scenarios.
names may be a single scenario name (String) or an Array of names; it is
always sent as { "names" => [...] }. Honours each scenario's
startDelayMillis. Requires loadGenerationEnabled on the server; a 403
response raises a clear error explaining the feature is disabled.
708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 |
# File 'lib/mockserver/client.rb', line 708 def start_load_scenarios(names) payload = { 'names' => Array(names) } body = JSON.generate(payload) status, response_body = request('PUT', '/mockserver/loadScenario/start', body) if status == 403 raise Error, 'Load scenario start rejected (status=403): load generation is disabled ' \ '(set loadGenerationEnabled=true on the server to enable it)' end if status == 404 raise Error, "Load scenario not found (status=404): #{response_body}" end if status >= 400 raise Error, "Failed to start load scenarios (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#stop ⇒ nil
Stop the MockServer instance.
1233 1234 1235 1236 1237 1238 1239 1240 |
# File 'lib/mockserver/client.rb', line 1233 def stop request('PUT', '/mockserver/stop') nil rescue ConnectionError nil ensure close end |
#stop_load_scenarios(names = nil) ⇒ Hash
Stop running scenarios.
names may be:
* a single scenario name (String) -> { "names" => ["a"] }
* an Array of names -> { "names" => ["a", "b"] }
* nil (the default) -> empty body, which stops all running scenarios
736 737 738 739 740 741 742 743 744 |
# File 'lib/mockserver/client.rb', line 736 def stop_load_scenarios(names = nil) body = names.nil? ? nil : JSON.generate({ 'names' => Array(names) }) status, response_body = request('PUT', '/mockserver/loadScenario/stop', body) if status >= 400 raise Error, "Failed to stop load scenarios (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#store_file(name, content) ⇒ Hash
Store a file in the in-memory file store (PUT /mockserver/files/store).
395 396 397 398 399 400 401 402 403 |
# File 'lib/mockserver/client.rb', line 395 def store_file(name, content) body = JSON.generate({ 'name' => name, 'content' => content }) status, response_body = request('PUT', '/mockserver/files/store', body) if status >= 400 raise Error, "Failed to store file (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#update_configuration(config_json) ⇒ String
Update the live configuration (PUT /mockserver/configuration).
config_json is a ConfigurationDTO JSON document; only the fields present
are applied (partial update). A nil value is sent as an empty body.
271 272 273 274 275 276 277 278 279 |
# File 'lib/mockserver/client.rb', line 271 def update_configuration(config_json) body = config_json.nil? ? '' : config_json.to_s status, response_body = request('PUT', '/mockserver/configuration', body) if status >= 400 raise Error, "Failed to update configuration (status=#{status}): #{response_body}" end response_body || '' end |
#upload_grpc_descriptor(descriptor_bytes) ⇒ nil
Upload a compiled protobuf descriptor set so gRPC requests can be matched.
descriptor_bytes 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 (NOT base64-encoded).
975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 |
# File 'lib/mockserver/client.rb', line 975 def upload_grpc_descriptor(descriptor_bytes) if descriptor_bytes.nil? || descriptor_bytes.empty? raise ArgumentError, 'descriptor bytes must not be empty' end status, response_body = request( 'PUT', '/mockserver/grpc/descriptors', descriptor_bytes, content_type: 'application/octet-stream' ) if status >= 400 raise Error, "Failed to upload gRPC descriptor (status=#{status}): #{response_body}" end nil end |
#upsert(*expectations) ⇒ Array<Expectation>
Create or update expectations.
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 |
# File 'lib/mockserver/client.rb', line 71 def upsert(*expectations) body = JSON.generate(expectations.map(&:to_h)) status, response_body = request('PUT', '/mockserver/expectation', body) if status == 400 raise Error, "Invalid expectation: #{response_body}" end if status >= 400 raise Error, "Failed to upsert expectations (status=#{status}): #{response_body}" end if response_body && !response_body.empty? parsed = JSON.parse(response_body) return parsed.map { |e| Expectation.from_hash(e) } if parsed.is_a?(Array) end expectations.to_a end |
#verify(request = nil, times: nil, response: nil) ⇒ nil
Verify that a request (and optionally a response) was received.
1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 |
# File 'lib/mockserver/client.rb', line 1028 def verify(request = nil, times: nil, response: nil) verification = Verification.new(http_request: request, http_response: response, times: times) body = JSON.generate(verification.to_h) status, response_body = do_request('PUT', '/mockserver/verify', body) if status == 406 raise VerificationError, response_body end if status >= 400 raise Error, "Failed to verify (status=#{status}): #{response_body}" end nil end |
#verify_sequence(*requests, responses: nil) ⇒ nil
Verify that requests were received in sequence.
1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 |
# File 'lib/mockserver/client.rb', line 1048 def verify_sequence(*requests, responses: nil) verification = VerificationSequence.new( http_requests: requests.empty? ? nil : requests.to_a, http_responses: responses ) body = JSON.generate(verification.to_h) status, response_body = request('PUT', '/mockserver/verifySequence', body) if status == 406 raise VerificationError, response_body end if status >= 400 raise Error, "Failed to verify sequence (status=#{status}): #{response_body}" end nil end |
#verify_slo(criteria) ⇒ Hash
Evaluate a set of service-level objectives (SLOs) over a window (PUT /mockserver/verifySLO).
The server encodes the verdict in the HTTP status: 200 for PASS or
INCONCLUSIVE, 406 for FAIL, 400 for malformed criteria or when SLO tracking
is disabled (+sloTrackingEnabled=false+). The decoded verdict Hash carries
the overall result and the per-objective objectiveResults so callers can
inspect why an SLO failed.
criteria may be any Hash already shaped to the SloCriteria JSON contract
(+name+, window, minimumSampleCount, upstreamHosts,
+objectives+[+comparator+, +threshold+, +scope+]) or an object that
responds to to_h.
880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 |
# File 'lib/mockserver/client.rb', line 880 def verify_slo(criteria) payload = criteria.respond_to?(:to_h) ? criteria.to_h : criteria body = JSON.generate(payload) status, response_body = request('PUT', '/mockserver/verifySLO', body) if status == 406 raise VerificationError, (response_body && !response_body.empty? ? response_body : 'SLO verdict: FAIL') end if status == 400 raise Error, 'Invalid SLO criteria (or SLO tracking disabled — set ' \ "sloTrackingEnabled=true on the server): #{response_body}" end if status >= 400 raise Error, "Failed to verify SLO (status=#{status}): #{response_body}" end response_body && !response_body.empty? ? JSON.parse(response_body) : {} end |
#verify_zero_interactions ⇒ nil
Verify zero interactions.
1068 1069 1070 |
# File 'lib/mockserver/client.rb', line 1068 def verify_zero_interactions verify(HttpRequest.new, times: VerificationTimes.new(at_most: 0)) end |
#when(request, times: nil, time_to_live: nil, priority: nil) ⇒ ForwardChainExpectation
Begin building an expectation via the fluent API.
1271 1272 1273 1274 1275 1276 1277 1278 1279 |
# File 'lib/mockserver/client.rb', line 1271 def when(request, times: nil, time_to_live: nil, priority: nil) expectation = Expectation.new( http_request: request, times: times, time_to_live: time_to_live, priority: priority ) ForwardChainExpectation.new(self, expectation) end |
#wsdl_expectation(wsdl) ⇒ Array<Expectation>
Generate expectations from a WSDL document (PUT /mockserver/wsdl).
The WSDL XML is sent as the raw request body with an XML content type.
538 539 540 541 542 543 544 545 546 547 548 549 550 551 |
# File 'lib/mockserver/client.rb', line 538 def wsdl_expectation(wsdl) if wsdl.nil? || wsdl.to_s.strip.empty? raise ArgumentError, 'WSDL must not be empty' end status, response_body = request( 'PUT', '/mockserver/wsdl', wsdl.to_s, content_type: 'application/xml' ) if status >= 400 raise Error, "Failed to generate WSDL expectations (status=#{status}): #{response_body}" end expectations_from_response(response_body) end |