require_relative 'exchange_handler' require_relative '../hash_methods' require_relative '../not_found_errors' require_relative '../accessors' require_relative '../interpreter' require 'json' require 'nori' module Soaspec # Accessors specific to REST handler module RestAccessors # Defines method 'base_url_value' containing base URL used in REST requests # @param [String] url Base Url to use in REST requests. Suburl is appended to this def base_url(url) define_method('base_url_value') do url end end end # Wraps around Savon client defining default values dependent on the soap request class RestHandler < ExchangeHandler extend Soaspec::RestAccessors extend Soaspec::Accessors # Savon client used to make SOAP calls attr_accessor :client # SOAP Operation to use by default attr_accessor :operation # Set through following method. Base URL in REST requests. def base_url_value nil end # Add values to here when extending this class to have default REST options. # See rest client resource at https://github.com/rest-client/rest-client for details # @return [Hash] Options adding to & overriding defaults def rest_resource_options { } end # Setup object to handle communicating with a particular SOAP WSDL # @param [Hash] specific_options Options defining SOAP request. WSDL, authentication def initialize(name, specific_options = {}) raise "Base URL not set! Please set in class with 'base_url' method" unless base_url_value options = rest_resource_options options.merge!(specific_options) @resource = RestClient::Resource.new(base_url_value, options) # @resource[url_extension].get super end # Used in together with Exchange request that passes such override parameters # @param [Hash] override_parameters Params to characterize REST request # @param_value [params] Extra parameters (E.g. headers) # @param_value [suburl] URL appended to base_url of clss # @param_value [method] REST method (get, post, etc) 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 unless test_values[:payload] test_values[:payload] = JSON.generate(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) response end # @param [Hash] format Format of expected result. Ignored for this # @return [Object] Generic body to be displayed in error messages def response_body(response, format: :hash) extract_hash response end def include_in_body?(response, expected) response.body.include? expected end # Whether the request found the desired value or not def found?(response) status_code_for(response) != 404 end # Convert XML or JSON response into a Hash # @param [String] response Response as a String (either in XML or JSON) # @return [Hash] 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 JSON.parse(response.body).transform_keys_to_symbols 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 # @return [Boolean] Whether response contains expected value def include_value?(response, expected) extract_hash(response).include_value? expected end # @return [Boolean] Whether response body contains expected key def include_key?(response, expected) extract_hash(response).include_key? expected end # @return [Integer] HTTP Status code for response def status_code_for(response) response.code end # Override this to specify elements that must be present in the response # Will be used in 'success_scenarios' shared examples # @return [Array] Array of symbols specifying element names def mandatory_elements [] end # Override this to specify xpath results that must be present in the response # Will be used in 'success_scenarios' shared examples # @return [Hash] Hash of 'xpath' => 'expected value' pairs def mandatory_xpath_values {} end # Attributes set at the root XML element of SOAP request def root_attributes nil end # Returns the value at the provided xpath # @param [Exchange] exchange # @param [String] xpath # @return [String] Value inside element found through Xpath def xpath_value_for(exchange: nil, xpath: nil) raise ArgumentError unless exchange && xpath response = exchange.response raise "Can't perform XPATH if response is not XML" unless Interpreter.response_type_for(response) == :xml result = if Soaspec::Environment.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 NoElementAtXpath, "No value at Xpath '#{xpath}'" unless result result.inner_text end # Based on a exchange, return the value at the provided xpath # If the path does not begin with a '/', a '//' is added to it # @param [Exchange] exchange # @param [Object] path Xpath or other path identifying how to find element # @return [String] Value at Xpath def value_from_path(exchange, path) case Interpreter.response_type_for(exchange.response) when :xml path = '//' + path if path[0] != '/' xpath_value_for(exchange: exchange, xpath: path) when :json hash = extract_hash exchange.response value = hash.dig(*path) raise NoElementInHash, "Element in #{hash} not found with path '#{path}'" unless value value else raise 'Unrecognised response message. Neither xml nor json detected' end end end end