Class: Soaspec::RestHandler
- Inherits:
-
ExchangeHandler
- Object
- ExchangeHandler
- Soaspec::RestHandler
- 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
-
#api_username ⇒ Object
User used in making API calls.
Attributes inherited from ExchangeHandler
Instance Method Summary collapse
-
#base_url_value ⇒ Object
Set through following method.
-
#convert_to_pascal_case(key) ⇒ Object
Convert snakecase to PascalCase.
-
#extract_hash(response) ⇒ Hash
Convert XML or JSON response into a Hash.
-
#found?(response) ⇒ Boolean
@@return [Boolean] Whether the request found the desired value or not.
-
#include_in_body?(response, expected) ⇒ Boolean
Whether response body includes String.
-
#include_key?(response, expected) ⇒ Boolean
Whether response body contains expected key.
-
#include_value?(response, expected) ⇒ Boolean
Whether response contains expected value.
-
#init_merge_options ⇒ Object
Initialize value of merged options.
-
#initialize(name = self.class.to_s, options = {}) ⇒ RestHandler
constructor
Setup object to handle communicating with a particular SOAP WSDL.
-
#json_path_values_for(response, path, attribute: nil) ⇒ Enumerable
List of values matching JSON path.
-
#make_request(override_parameters) ⇒ Object
Used in together with Exchange request that passes such override parameters.
-
#mandatory_elements ⇒ Array
Override this to specify elements that must be present in the response Will be used in ‘success_scenarios’ shared examples.
-
#mandatory_xpath_values ⇒ Hash
Override this to specify xpath results that must be present in the response Will be used in ‘success_scenarios’ shared examples.
-
#parse_headers ⇒ Hash
Perform ERB on each header value.
-
#pascal_keys? ⇒ Boolean
Whether to convert each key in the request to PascalCase It will also auto convert simple XPath, JSONPath where ‘//’ or ‘..’ not specified.
-
#response_body(response, format: :hash) ⇒ Object
Generic body to be displayed in error messages.
-
#rest_client_headers ⇒ Object
Headers used in RestClient.
-
#rest_resource_options ⇒ Hash
Add values to here when extending this class to have default REST options.
-
#root_attributes ⇒ Object
Attributes set at the root XML element of SOAP request.
-
#status_code_for(response) ⇒ Integer
HTTP Status code for response.
-
#to_hash(response) ⇒ Hash
Hash representing response body.
-
#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.
-
#values_from_path(response, path, attribute: nil) ⇒ Enumerable
List of values returned from path.
-
#xpath_elements_for(response: nil, xpath: nil, attribute: nil) ⇒ Enumerable
Returns the value at the provided xpath.
Methods included from RestAccessors
base_url, headers, oauth2, oauth2_file, pascal_keys
Methods inherited from ExchangeHandler
#convert_to_lower?, #default_hash=, #elements, #expected_mandatory_elements, #expected_mandatory_json_values, #expected_mandatory_xpath_values, #set_remove_key, #store, #strip_namespaces?, #to_s, #use
Methods included from HandlerAccessors
#attribute, #convert_to_lower, #element, #mandatory_json_values, #strip_namespaces
Constructor Details
#initialize(name = self.class.to_s, options = {}) ⇒ RestHandler
Setup object to handle communicating with a particular SOAP WSDL
48 49 50 51 52 53 54 55 56 57 58 59 60 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 48 def initialize(name = self.class.to_s, = {}) raise "Base URL not set! Please set in class with 'base_url' method" unless base_url_value @default_hash = {} if name.is_a?(Hash) && == {} # If name is not set = name name = self.class.to_s end super set_remove_key(, :api_username) set_remove_key(, :default_hash) set_remove_key(, :template_name) = end |
Instance Attribute Details
#api_username ⇒ Object
User used in making API calls
19 20 21 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 19 def api_username @api_username end |
Instance Method Details
#base_url_value ⇒ Object
Set through following method. Base URL in REST requests.
22 23 24 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 22 def base_url_value nil end |
#convert_to_pascal_case(key) ⇒ Object
Convert snakecase to PascalCase
63 64 65 66 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 63 def convert_to_pascal_case(key) return key if /[[:upper:]]/ =~ key[0] # If first character already capital, don't do conversion key.split('_').map(&:capitalize).join end |
#extract_hash(response) ⇒ Hash
Convert XML or JSON response into a Hash
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 136 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
@@return [Boolean] Whether the request found the desired value or not
129 130 131 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 129 def found?(response) status_code_for(response) != 404 end |
#include_in_body?(response, expected) ⇒ Boolean
124 125 126 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 124 def include_in_body?(response, expected) response.body.include? expected end |
#include_key?(response, expected) ⇒ Boolean
158 159 160 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 158 def include_key?(response, expected) value_from_path(response, expected) end |
#include_value?(response, expected) ⇒ Boolean
153 154 155 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 153 def include_value?(response, expected) extract_hash(response).include_value? expected end |
#init_merge_options ⇒ Object
Initialize value of merged options
76 77 78 79 80 81 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 76 def = [:headers] ||= {} [:headers].merge! parse_headers .merge() end |
#json_path_values_for(response, path, attribute: nil) ⇒ Enumerable
208 209 210 211 212 213 214 215 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 208 def json_path_values_for(response, path, attribute: nil) raise 'JSON does not support attributes' if attribute if path[0] != '$' path = convert_to_pascal_case(path) if pascal_keys? path = '$..' + path end JsonPath.on(response.body, path) end |
#make_request(override_parameters) ⇒ Object
Used in together with Exchange request that passes such override parameters
89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 89 def make_request(override_parameters) ||= test_values = override_parameters test_values[:params] ||= {} test_values[:method] ||= :post test_values[:suburl] = test_values[:suburl].to_s if test_values[:suburl] test_values[:params][:params] = test_values[:q] if test_values[:q] # Use q for query parameters. Nested :params is ugly and long # In order for ERB to be calculated at correct time, the first time request is made, the resource should be created @resource ||= RestClient::Resource.new(ERB.new(base_url_value).result(binding), ) @resource_used = test_values[:suburl] ? @resource[test_values[:suburl]] : @resource begin response = case test_values[:method] when :post, :patch, :put Soaspec::SpecLogger.info("request body: #{post_data(test_values)}") @resource_used.send(test_values[:method].to_s, post_data(test_values), test_values[:params]) else # :get, :delete @resource_used.send(test_values[:method].to_s, test_values[:params]) end rescue RestClient::ExceptionWithResponse => e response = e.response end Soaspec::SpecLogger.info('response_headers: ' + response.headers.to_s) Soaspec::SpecLogger.info('response_body: ' + response.to_s) response end |
#mandatory_elements ⇒ Array
Override this to specify elements that must be present in the response Will be used in ‘success_scenarios’ shared examples
170 171 172 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 170 def mandatory_elements [] end |
#mandatory_xpath_values ⇒ Hash
Override this to specify xpath results that must be present in the response Will be used in ‘success_scenarios’ shared examples
177 178 179 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 177 def mandatory_xpath_values {} end |
#parse_headers ⇒ Hash
Perform ERB on each header value
42 43 44 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 42 def parse_headers Hash[rest_client_headers.map { |k, header| [k, ERB.new(header).result(binding)] }] end |
#pascal_keys? ⇒ Boolean
Whether to convert each key in the request to PascalCase It will also auto convert simple XPath, JSONPath where ‘//’ or ‘..’ not specified
71 72 73 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 71 def pascal_keys? false end |
#response_body(response, format: :hash) ⇒ Object
119 120 121 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 119 def response_body(response, format: :hash) extract_hash response end |
#rest_client_headers ⇒ Object
Headers used in RestClient
27 28 29 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 27 def rest_client_headers {} end |
#rest_resource_options ⇒ Hash
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
35 36 37 38 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 35 def { } end |
#root_attributes ⇒ Object
Attributes set at the root XML element of SOAP request
182 183 184 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 182 def root_attributes nil end |
#status_code_for(response) ⇒ Integer
163 164 165 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 163 def status_code_for(response) response.code end |
#to_hash(response) ⇒ Hash
259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 259 def to_hash(response) case Interpreter.response_type_for(response) when :xml parser = Nori.new(strip_namespaces: strip_namespaces?, convert_tags_to: ->(tag) { tag.snakecase.to_sym }) parser.parse(response.body.to_s) when :json JSON.parse(response.body.to_s) else raise "Unable to interpret type of #{response.body}" end 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
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 223 def value_from_path(response, path, attribute: nil) path = path.to_s case Interpreter.response_type_for(response) when :xml result = xpath_elements_for(response: response, xpath: path, attribute: attribute).first raise NoElementAtPath, "No value at Xpath '#{path}'" unless result return result.inner_text if attribute.nil? return result.attributes[attribute].inner_text when :json paths_to_check = path.split(',') matching_values = paths_to_check.collect do |path_to_check| json_path_values_for(response, path_to_check, attribute: attribute) end.reject(&:empty?) raise NoElementAtPath, "Path '#{path}' not found in '#{response.body}'" if matching_values.empty? matching_values.first.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 |
#values_from_path(response, path, attribute: nil) ⇒ Enumerable
246 247 248 249 250 251 252 253 254 255 256 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 246 def values_from_path(response, path, attribute: nil) path = path.to_s case Interpreter.response_type_for(response) when :xml xpath_elements_for(response: response, xpath: path, attribute: attribute).map(&:inner_text) when :json json_path_values_for(response, path, attribute: attribute) else raise "Unable to interpret type of #{response.body}" end end |
#xpath_elements_for(response: nil, xpath: nil, attribute: nil) ⇒ Enumerable
Returns the value at the provided xpath
190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 |
# File 'lib/soaspec/exchange_handlers/rest_handler.rb', line 190 def xpath_elements_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 xpath = "//*[@#{attribute}]" unless attribute.nil? if xpath[0] != '/' xpath = convert_to_pascal_case(xpath) if pascal_keys? xpath = '//' + xpath end temp_doc = Nokogiri.parse(response.body).dup if strip_namespaces? && !xpath.include?(':') temp_doc.remove_namespaces! temp_doc.xpath(xpath) else temp_doc.xpath(xpath, temp_doc.collect_namespaces) end end |