Class: Soaspec::RestHandler

Inherits:
ExchangeHandler show all
Extended by:
RestAccessors
Defined in:
lib/soaspec/exchange_handlers/rest_handler.rb

Overview

Wraps around Savon client defining default values dependent on the soap request

Instance Attribute Summary collapse

Attributes inherited from ExchangeHandler

#template_name

Instance Method Summary collapse

Methods included from RestAccessors

base_url, headers, oauth2, oauth2_file

Methods inherited from ExchangeHandler

#default_hash=, #elements, #expected_mandatory_elements, #expected_mandatory_json_values, #expected_mandatory_xpath_values, #set_remove_key, #store, #to_s, #use

Methods included from HandlerAccessors

#attribute, #element, #mandatory_json_values

Constructor Details

#initialize(name = self.class.to_s, options = {}) ⇒ RestHandler

Setup object to handle communicating with a particular SOAP WSDL

Parameters:

  • options (Hash) (defaults to: {})

    Options defining SOAP request. WSDL, authentication



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 128

def initialize(name = self.class.to_s, options = {})
  raise "Base URL not set! Please set in class with 'base_url' method" unless base_url_value
  @default_hash = {}
  if name.is_a?(Hash) && options == {} # If name is not set
    options = name
    name = self.class.to_s
  end
  super
  set_remove_key(options, :default_hash)
  merged_options = rest_resource_options
  merged_options[:headers] ||= {}
  merged_options[:headers].merge! rest_client_headers
  merged_options.merge!(options)
  @resource = RestClient::Resource.new(base_url_value, merged_options) # @resource[url_extension].get
end

Instance Attribute Details

#clientObject

Savon client used to make SOAP calls



103
104
105
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 103

def client
  @client
end

#operationObject

SOAP Operation to use by default



105
106
107
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 105

def operation
  @operation
end

Instance Method Details

#base_url_valueObject

Set through following method. Base URL in REST requests.



108
109
110
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 108

def base_url_value
  nil
end

#extract_hash(response) ⇒ Hash

Convert XML or JSON response into a Hash

Parameters:

  • response (String)

    Response as a String (either in XML or JSON)

Returns:



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 192

def extract_hash(response)
  raise ArgumentError("Empty Body. Can't assert on it") if response.body.empty?
  case Interpreter.response_type_for response
  when :json
    converted = JSON.parse(response.body)
    return converted.transform_keys_to_symbols if converted.is_a? Hash
    return converted.map!(&:transform_keys_to_symbols) if converted.is_a? Array
    raise 'Incorrect Type prodcued ' + converted.class
  when :xml
    parser = Nori.new(convert_tags_to: lambda { |tag| tag.snakecase.to_sym })
    parser.parse(response.body)
  else
    raise "Neither XML nor JSON detected. It is #{type}. Don't know how to parse It is #{response.body}"
  end
end

#found?(response) ⇒ Boolean

Whether the request found the desired value or not

Returns:

  • (Boolean)


185
186
187
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 185

def found?(response)
  status_code_for(response) != 404
end

#include_in_body?(response, expected) ⇒ Boolean

Returns:

  • (Boolean)


180
181
182
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 180

def include_in_body?(response, expected)
  response.body.include? expected
end

#include_key?(response, expected) ⇒ Boolean

Returns Whether response body contains expected key.

Returns:

  • (Boolean)

    Whether response body contains expected key



214
215
216
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 214

def include_key?(response, expected)
  value_from_path(response, expected)
end

#include_value?(response, expected) ⇒ Boolean

Returns Whether response contains expected value.

Returns:

  • (Boolean)

    Whether response contains expected value



209
210
211
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 209

def include_value?(response, expected)
  extract_hash(response).include_value? expected
end

#make_request(override_parameters) ⇒ Object

Used in together with Exchange request that passes such override parameters

Parameters:

  • override_parameters (Hash)

    Params to characterize REST request



149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 149

def make_request(override_parameters)
  test_values = override_parameters
  test_values[:params] ||= {}
  test_values[:suburl] = test_values[:suburl].to_s if test_values[:suburl]

  @resource_used = test_values[:suburl] ? @resource[test_values[:suburl]] : @resource

  begin
  response = case test_values[:method]
             when :post, :patch, :put
               unless test_values[:payload]
                 test_values[:payload] = JSON.generate(@default_hash.merge(test_values[:body])).to_s if test_values[:body]
               end
               @resource_used.send(test_values[:method].to_s, test_values[:payload], test_values[:params])
             else
               @resource_used.send(test_values[:method].to_s, test_values[:params])
             end
  rescue RestClient::ExceptionWithResponse => e
    response = e.response
  end
  Soaspec::SpecLogger.add_to('response_headers: ' + response.headers.to_s)
  Soaspec::SpecLogger.add_to('response_body: ' + response.to_s)
  response
end

#mandatory_elementsArray

Override this to specify elements that must be present in the response Will be used in ‘success_scenarios’ shared examples

Returns:

  • (Array)

    Array of symbols specifying element names



226
227
228
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 226

def mandatory_elements
  []
end

#mandatory_xpath_valuesHash

Override this to specify xpath results that must be present in the response Will be used in ‘success_scenarios’ shared examples

Returns:

  • (Hash)

    Hash of ‘xpath’ => ‘expected value’ pairs



233
234
235
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 233

def mandatory_xpath_values
  {}
end

#response_body(response, format: :hash) ⇒ Object

Returns Generic body to be displayed in error messages.

Parameters:

  • format (Hash) (defaults to: :hash)

    Format of expected result. Ignored for this

Returns:

  • (Object)

    Generic body to be displayed in error messages



176
177
178
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 176

def response_body(response, format: :hash)
  extract_hash response
end

#rest_client_headersObject

Headers used in RestClient



113
114
115
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 113

def rest_client_headers
  {}
end

#rest_resource_optionsHash

Add values to here when extending this class to have default REST options. See rest client resource at github.com/rest-client/rest-client for details It’s easier to set headers via ‘headers’ accessor rather than here

Returns:

  • (Hash)

    Options adding to & overriding defaults



121
122
123
124
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 121

def rest_resource_options
  {
  }
end

#root_attributesObject

Attributes set at the root XML element of SOAP request



238
239
240
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 238

def root_attributes
  nil
end

#status_code_for(response) ⇒ Integer

Returns HTTP Status code for response.

Returns:

  • (Integer)

    HTTP Status code for response



219
220
221
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 219

def status_code_for(response)
  response.code
end

#value_from_path(response, path, attribute: nil) ⇒ String

Based on a exchange, return the value at the provided xpath If the path does not begin with a ‘/’, a ‘//’ is added to it

Parameters:

  • response (Response)
  • path (Object)

    Xpath, JSONPath or other path identifying how to find element

  • attribute (String) (defaults to: nil)

    Generic attribute to find. Will override path

Returns:

  • (String)

    Value at Xpath



268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 268

def value_from_path(response, path, attribute: nil)
  path = path.to_s

  case Interpreter.response_type_for(response)
  when :xml
    path = "//*[@#{attribute}]" unless attribute.nil?
    path = '//' + path if path[0] != '/'
    xpath_value_for(response: response, xpath: path, attribute: attribute)
  when :json
    raise 'JSON does not support attributes' if attribute
    path = '$..' + path if path[0] != '$'
    matching_values = JsonPath.on(response.body, path)
    raise NoElementAtPath, "Element in #{response.body} not found with path '#{path}'" if matching_values.empty?
    matching_values.first
  when :hash
    response.dig(path.split('.')) # Use path as Hash dig expression separating params via '.' TODO: Unit test
  else
    response.to_s[/path/] # Perform regular expression using path if not XML nor JSON TODO: Unit test
  end
end

#xpath_value_for(response: nil, xpath: nil, attribute: nil) ⇒ String

Returns the value at the provided xpath

Parameters:

  • response (RestClient::Response) (defaults to: nil)
  • xpath (String) (defaults to: nil)

Returns:

  • (String)

    Value inside element found through Xpath

Raises:

  • (ArgumentError)


246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 246

def xpath_value_for(response: nil, xpath: nil, attribute: nil)
  raise ArgumentError unless response && xpath
  raise "Can't perform XPATH if response is not XML" unless Interpreter.response_type_for(response) == :xml
  result =
    if Soaspec.strip_namespaces? && !xpath.include?(':')
      temp_doc = Nokogiri.parse response.body
      temp_doc.remove_namespaces!
      temp_doc.xpath(xpath).first
    else
      Nokogiri.parse(response.body).xpath(xpath).first
    end
  raise NoElementAtPath, "No value at Xpath '#{xpath}'" unless result
  return result.inner_text if attribute.nil?
  result.attributes[attribute].inner_text
end