Sha256: f25ac66d1fd96f6d636ffce3d7120cc521854586d6899dac7481a73082d1f4c8

Contents?: true

Size: 1.8 KB

Versions: 5

Compression:

Stored size: 1.8 KB

Contents

# frozen_string_literal: true

module Peddler
  # A custom matcher that can be used to record MWS interactions when
  # writing integration tests
  class VCRMatcher
    # @api private
    TRANSIENT_PARAMS = %w[
      Signature Timestamp StartDate CreatedAfter QueryStartDateTime
    ].freeze

    # @api private
    SELLER_PARAMS = %w[
      AWSAccessKeyId SellerId
    ].freeze

    class << self
      # @api private
      def call(*requests)
        new(*requests).compare
      end

      # @api private
      def ignored_params
        @ignored_params ||= TRANSIENT_PARAMS.dup
      end

      # Ignore seller specific attributes when recording
      # @return [void]
      def ignore_seller!
        ignored_params.concat(SELLER_PARAMS)
        ignored_params.uniq!
      end
    end

    # @api private
    attr_reader :requests

    # @api private
    def initialize(*requests)
      @requests = requests
    end

    # @api private
    def compare
      compare_uris && compare_bodies
    end

    private

    def compare_uris
      return false if hosts.reduce(:!=) || paths.reduce(:!=)
      return true if queries.all?(&:empty?)

      queries.reduce(:==)
    end

    def compare_bodies
      bodies.reduce(:==)
    end

    def extract_params(string)
      return {} unless string

      params = ::CGI.parse(string)
      self.class.ignored_params.each do |k|
        params.delete(k)
      end

      params
    end

    def uris
      requests.map { |r| URI.parse(r.uri) }
    end

    def hosts
      uris.map(&:host)
    end

    def paths
      uris.map(&:path)
    end

    def queries
      uris.map { |uri| extract_params(uri.query) }
    end

    def bodies
      if queries.all?(&:empty?)
        requests.map { |request| extract_params(request.body) }
      else
        requests.map(&:body)
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
peddler-2.1.1 lib/peddler/vcr_matcher.rb
peddler-2.1.0 lib/peddler/vcr_matcher.rb
peddler-2.0.4 lib/peddler/vcr_matcher.rb
peddler-2.0.3 lib/peddler/vcr_matcher.rb
peddler-2.0.0 lib/peddler/vcr_matcher.rb