# frozen_string_literal: true require_relative 'exe_helpers' module Soaspec # Used for defining parameters for recording and asserting against # a baseline class Baseline include Soaspec::ExeHelpers @folder = File.join('config', 'baseline') # @return [Array] List of allowed formats ALLOWED_FORMATS = %i[raw hash].freeze # @return [Exchange] Exchange object to save/assert baseline for attr_accessor :exchange # @return [Symbol] Format in which baseline is stored. Either :raw or :hash attr_accessor :format # @return [String] Name of file including folders describing baseline attr_writer :description # @param [Exchange] exchange Exchange object to baseline response for # @param [Symbol] format Format of baseline def initialize(exchange, format) self.exchange = exchange self.format = format unless ALLOWED_FORMATS.include? format raise ArgumentError, "Expected format #{format} to be " \ "either #{ALLOWED_FORMATS}" end end # Compare baseline with expected result. This will create baseline # if not created # @return [Boolean] Whether response matches baseline def matches? if File.exist?(file) actual_content == read_baseline else create_file filename: file, content: content_to_save raise Soaspec::BaselineError, "Created baseline at #{file}. Inspect file to ensure it is correct and rerun to ensure baseline is stable" end end # Content to save as a baseline def content_to_save format == :raw ? exchange.pretty_response_body : YAML.dump(exchange.to_hash) end # @return [String, Hash] Actual response from API def actual_content if format == :hash exchange.to_hash elsif format == :raw exchange.pretty_response_body.strip else raise NotImplementedError, "Format #{format} is not #{ALLOWED_FORMATS}" end end # @return [String] Result of reading baseline def read_baseline format == :raw ? File.read(file).strip : YAML.load_file(file) end # @return [String] File where baseline is stored def file File.join(self.class.folder, exchange.exchange_handler.to_s.snakecase, "#{description}.#{format == :raw ? exchange.format : 'yml'}") end # @return [String] Name of file including folders describing baseline def description @description || exchange.request_parameters.description end class << self # @return [String] Folder where baselines are recorded and retrieved attr_accessor :folder end end end