Module: MockServer

Defined in:
lib/mockserver/client.rb,
lib/mockserver/errors.rb,
lib/mockserver/models.rb,
lib/mockserver/version.rb,
lib/mockserver/websocket_client.rb,
lib/mockserver/forward_chain_expectation.rb

Defined Under Namespace

Classes: AfterAction, BinaryResponse, Body, CallbackError, Client, ConnectionError, ConnectionOptions, CrudExpectationsDefinition, Delay, DelayDistribution, DnsRecord, DnsResponse, Error, Expectation, ExpectationId, ExpectationStep, ForwardChainExpectation, GraphQLBody, GrpcBidiResponse, GrpcBidiRule, GrpcStreamMessage, GrpcStreamResponse, HttpChaosProfile, HttpClassCallback, HttpError, HttpForward, HttpObjectCallback, HttpOverrideForwardedRequest, HttpRequest, HttpRequestAndHttpResponse, HttpResponse, HttpSseResponse, HttpTemplate, HttpWebSocketResponse, JsonRpcBody, KeyToMultiValue, OpenAPIDefinition, OpenAPIExpectation, Ports, SocketAddress, SseEvent, TimeToLive, Times, Verification, VerificationError, VerificationSequence, VerificationTimes, WebSocketClient, WebSocketError, WebSocketMessage

Constant Summary collapse

FIELD_MAP =

Explicit mapping from Ruby snake_case field names to the camelCase keys expected by the MockServer JSON protocol.

{
  'status_code'                    => 'statusCode',
  'reason_phrase'                  => 'reasonPhrase',
  'keep_alive'                     => 'keepAlive',
  'respond_before_body'            => 'respondBeforeBody',
  'query_string_parameters'        => 'queryStringParameters',
  'path_parameters'                => 'pathParameters',
  'socket_address'                 => 'socketAddress',
  'time_unit'                      => 'timeUnit',
  'time_to_live'                   => 'timeToLive',
  'remaining_times'                => 'remainingTimes',
  'close_socket'                   => 'closeSocket',
  'close_socket_delay'             => 'closeSocketDelay',
  'suppress_content_length_header' => 'suppressContentLengthHeader',
  'content_length_header_override' => 'contentLengthHeaderOverride',
  'suppress_connection_header'     => 'suppressConnectionHeader',
  'keep_alive_override'            => 'keepAliveOverride',
  'connection_options'             => 'connectionOptions',
  'callback_class'                 => 'callbackClass',
  'client_id'                      => 'clientId',
  'response_callback'              => 'responseCallback',
  'drop_connection'                => 'dropConnection',
  'response_bytes'                 => 'responseBytes',
  'http_request'                   => 'httpRequest',
  'http_response'                  => 'httpResponse',
  'http_response_template'         => 'httpResponseTemplate',
  'http_response_class_callback'   => 'httpResponseClassCallback',
  'http_response_object_callback'  => 'httpResponseObjectCallback',
  'http_forward'                   => 'httpForward',
  'http_forward_template'          => 'httpForwardTemplate',
  'http_forward_class_callback'    => 'httpForwardClassCallback',
  'http_forward_object_callback'   => 'httpForwardObjectCallback',
  'http_override_forwarded_request' => 'httpOverrideForwardedRequest',
  'http_error'                     => 'httpError',
  'http_sse_response'              => 'httpSseResponse',
  'http_websocket_response'        => 'httpWebSocketResponse',
  'template_type'                  => 'templateType',
  'base64_bytes'                   => 'base64Bytes',
  'not_body'                       => 'not',
  'content_type'                   => 'contentType',
  'at_least'                       => 'atLeast',
  'at_most'                        => 'atMost',
  'expectation_id'                 => 'expectationId',
  'expectation_ids'                => 'expectationIds',
  'http_requests'                  => 'httpRequests',
  'spec_url_or_payload'            => 'specUrlOrPayload',
  'operations_and_responses'       => 'operationsAndResponses',
  'operation_id'                   => 'operationId',
  'request_modifier'               => 'requestModifier',
  'response_modifier'              => 'responseModifier',
  'maximum_number_of_request_to_return_in_verification_failure' => 'maximumNumberOfRequestToReturnInVerificationFailure',
  'base_path'                      => 'basePath',
  'id_field'                       => 'idField',
  'id_strategy'                    => 'idStrategy',
  'initial_data'                   => 'initialData',
  'error_status'                   => 'errorStatus',
  'error_probability'              => 'errorProbability',
  'drop_connection_probability'    => 'dropConnectionProbability',
  'retry_after'                    => 'retryAfter',
  'succeed_first'                  => 'succeedFirst',
  'fail_request_count'             => 'failRequestCount',
  'outage_after_millis'            => 'outageAfterMillis',
  'outage_duration_millis'         => 'outageDurationMillis',
  'truncate_body_at_fraction'      => 'truncateBodyAtFraction',
  'malformed_body'                 => 'malformedBody',
  'slow_response_chunk_size'       => 'slowResponseChunkSize',
  'slow_response_chunk_delay'      => 'slowResponseChunkDelay',
  'quota_name'                     => 'quotaName',
  'quota_limit'                    => 'quotaLimit',
  'quota_window_millis'            => 'quotaWindowMillis',
  'quota_error_status'             => 'quotaErrorStatus',
  'degradation_ramp_millis'        => 'degradationRampMillis',
  'http_class_callback'            => 'httpClassCallback',
  'http_object_callback'           => 'httpObjectCallback',
  'failure_policy'                 => 'failurePolicy'
}.freeze
REVERSE_FIELD_MAP =
FIELD_MAP.invert.freeze
BODY_TYPES =

Known Body type strings used to distinguish Body objects from plain hashes during deserialization.

Set.new(%w[
  STRING JSON REGEX XML BINARY JSON_SCHEMA JSON_PATH XPATH XML_SCHEMA JSON_RPC GRAPHQL
]).freeze
RequestDefinition =

Alias matching the Python client

HttpRequest
VERSION =
'7.0.0'
WEB_SOCKET_CORRELATION_ID_HEADER_NAME =
'WebSocketCorrelationId'
CLIENT_REGISTRATION_ID_HEADER =
'X-CLIENT-REGISTRATION-ID'
WEBSOCKET_PATH =
'/_mockserver_callback_websocket'
TYPE_HTTP_REQUEST =
'org.mockserver.model.HttpRequest'
TYPE_HTTP_RESPONSE =
'org.mockserver.model.HttpResponse'
TYPE_HTTP_REQUEST_AND_RESPONSE =
'org.mockserver.model.HttpRequestAndHttpResponse'
TYPE_CLIENT_ID_DTO =
'org.mockserver.serialization.model.WebSocketClientIdDTO'
TYPE_ERROR_DTO =
'org.mockserver.serialization.model.WebSocketErrorDTO'
MAX_RECONNECT_ATTEMPTS =
3
REGISTRATION_TIMEOUT =
10

Class Method Summary collapse

Class Method Details

.add_correlation_id_header(message, correlation_id) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/mockserver/websocket_client.rb', line 35

def self.add_correlation_id_header(message, correlation_id)
  message.headers ||= []
  message.headers.each do |header|
    if header.name == WEB_SOCKET_CORRELATION_ID_HEADER_NAME
      header.values = [correlation_id]
      return message
    end
  end
  message.headers << KeyToMultiValue.new(
    name: WEB_SOCKET_CORRELATION_ID_HEADER_NAME,
    values: [correlation_id]
  )
  message
end

.build_error_message(error_msg, correlation_id) ⇒ Object



57
58
59
60
61
62
63
64
65
# File 'lib/mockserver/websocket_client.rb', line 57

def self.build_error_message(error_msg, correlation_id)
  JSON.generate({
    'type'  => TYPE_ERROR_DTO,
    'value' => JSON.generate({
      'message' => error_msg,
      'webSocketCorrelationId' => correlation_id
    })
  })
end

.build_ws_message(type_name, value_dict) ⇒ Object



50
51
52
53
54
55
# File 'lib/mockserver/websocket_client.rb', line 50

def self.build_ws_message(type_name, value_dict)
  JSON.generate({
    'type'  => type_name,
    'value' => JSON.generate(value_dict)
  })
end

.clean_context_path(context_path) ⇒ 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.



68
69
70
71
72
73
# File 'lib/mockserver/websocket_client.rb', line 68

def self.clean_context_path(context_path)
  return '' if context_path.nil? || context_path.empty?
  return "/#{context_path}" unless context_path.start_with?('/')

  context_path
end

.deserialize_body(data) ⇒ 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.



144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
# File 'lib/mockserver/models.rb', line 144

def self.deserialize_body(data)
  return nil if data.nil?
  return data if data.is_a?(String)

  if data.is_a?(Hash)
    if data['type'] == 'JSON_RPC'
      return JsonRpcBody.from_hash(data)
    end
    if data['type'] == 'GRAPHQL'
      return GraphQLBody.from_hash(data)
    end
    return Body.from_hash(data) if BODY_TYPES.include?(data['type'])

    return data
  end
  data
end

.deserialize_key_multi_values(data) ⇒ 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.



170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
# File 'lib/mockserver/models.rb', line 170

def self.deserialize_key_multi_values(data)
  return nil if data.nil?

  if data.is_a?(Hash)
    return data.map { |k, v| KeyToMultiValue.new(name: k, values: v.is_a?(Array) ? v : [v]) }
  end

  data.map do |item|
    if item.is_a?(Hash)
      KeyToMultiValue.from_hash(item)
    elsif item.is_a?(String)
      KeyToMultiValue.new(name: item, values: [])
    else
      KeyToMultiValue.from_hash(item)
    end
  end
end

.extract_correlation_id(request) ⇒ Object



24
25
26
27
28
29
30
31
32
33
# File 'lib/mockserver/websocket_client.rb', line 24

def self.extract_correlation_id(request)
  return nil if request.headers.nil?

  request.headers.each do |header|
    if header.name == WEB_SOCKET_CORRELATION_ID_HEADER_NAME
      return header.values.first if header.values && !header.values.empty?
    end
  end
  nil
end

.from_camel(camel_str) ⇒ 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.



108
109
110
111
112
# File 'lib/mockserver/models.rb', line 108

def self.from_camel(camel_str)
  return REVERSE_FIELD_MAP[camel_str] if REVERSE_FIELD_MAP.key?(camel_str)

  camel_str.gsub(/([A-Z])/) { "_#{$1.downcase}" }
end

.serialize_body(body) ⇒ 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.



132
133
134
135
136
137
138
139
140
141
# File 'lib/mockserver/models.rb', line 132

def self.serialize_body(body)
  return nil if body.nil?
  return body if body.is_a?(String)
  return body if body.is_a?(Hash)
  return body.to_h if body.is_a?(Body)
  return body.to_h if body.is_a?(JsonRpcBody)
  return body.to_h if body.is_a?(GraphQLBody)

  body
end

.serialize_key_multi_values(items) ⇒ 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.



163
164
165
166
167
# File 'lib/mockserver/models.rb', line 163

def self.serialize_key_multi_values(items)
  return nil if items.nil?

  items.map(&:to_h)
end

.serialize_value(value) ⇒ 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.



120
121
122
123
124
125
126
127
128
129
# File 'lib/mockserver/models.rb', line 120

def self.serialize_value(value)
  case value
  when ->(v) { v.respond_to?(:to_h) && v.class.ancestors.any? { |a| a.to_s.start_with?('MockServer::') } }
    value.to_h
  when Array
    value.map { |item| serialize_value(item) }
  else
    value
  end
end

.strip_none(hash) ⇒ 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.



115
116
117
# File 'lib/mockserver/models.rb', line 115

def self.strip_none(hash)
  hash.reject { |_k, v| v.nil? }
end

.to_camel(snake_str) ⇒ 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.



100
101
102
103
104
105
# File 'lib/mockserver/models.rb', line 100

def self.to_camel(snake_str)
  return FIELD_MAP[snake_str] if FIELD_MAP.key?(snake_str)

  parts = snake_str.split('_')
  parts[0] + parts[1..].map(&:capitalize).join
end