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, Body, CallbackError, Client, ConnectionError, ConnectionOptions, CrudExpectationsDefinition, Delay, DelayDistribution, Error, Expectation, ExpectationId, ForwardChainExpectation, GraphQLBody, 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'
}.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 =
'6.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.



124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
# File 'lib/mockserver/models.rb', line 124

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.



150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
# File 'lib/mockserver/models.rb', line 150

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.



88
89
90
91
92
# File 'lib/mockserver/models.rb', line 88

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.



112
113
114
115
116
117
118
119
120
121
# File 'lib/mockserver/models.rb', line 112

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.



143
144
145
146
147
# File 'lib/mockserver/models.rb', line 143

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.



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

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.



95
96
97
# File 'lib/mockserver/models.rb', line 95

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.



80
81
82
83
84
85
# File 'lib/mockserver/models.rb', line 80

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