<commit_before>class ExpectationMatcher
  require 'result'
  require 'nokogiri'
  require 'JSON'

  def initialize(excludes=nil)
    @test_types = [:response_code, :response_body_format, :response_headers, :response_body]
    @excludes = excludes || []
  end

  # returns the available test types if this matcher class
  def test_types
    return @test_types
  end

  # dispatches incoming matching requests
  def check(method, response, testcase)
    self.send(method, response, testcase)
  end

  protected

  # matches the given response code
  def response_code(response, testcase)
    result = Result.new(testcase, response)
    if not testcase['response_expectation']['status_code'].to_s == response.code.to_s
      result.succeeded = false
      result.error_message = " expected response code --#{testcase['response_expectation']['status_code']}--\n got response code --#{response.code}--"
    end
    result
  end

  # checks the format of the given data of JSON conformity
  def response_body_format(response, testcase)
    result_struct = Struct.new(:succeeded, :error)
    results = result_struct.new(:succeeded => true, :error => nil)
    result = Result.new(testcase, response)
    if not valid_json?(response.body)
      result.succeeded = false
      result.error_message = "expected valid JSON in body\n got --#{response.body[1..400]}--"
    end
    result
  end

  # matches the given response header
  def response_headers(response, testcase)
    result = Result.new(testcase, response)

    testcase['response_expectation']['headers'].each_pair do |header_name, header_value|
      if is_regex?(header_value)
        if not (excluded?(header_name) or regex_matches?(header_value, response.headers[header_name]))
          result.succeeded = false
          result.error_message = " expected header identifier --#{header_name}-- to match regex --#{header_value}--\n got --#{response.headers[header_name]}--"
        end
      else
        if not (excluded?(header_name) or string_matches?(header_value, response.headers[header_name]))
          result.succeeded = false
          result.error_message = " expected header identifier --#{header_name}-- to match --#{header_value}--\n got --#{response.headers[header_name]}--"
        end
      end
    end unless (testcase['response_expectation']['headers'].nil? or testcase['response_expectation']['headers'].empty?)
    return result
  end

  # matches the given attributes and values against the ones from the response body
  def response_body(response, testcase)
    result = Result.new(testcase, response)

    expected_body_hash = testcase['response_expectation']['body']

    # in case we have no body expectation we simply return success
    return result if expected_body_hash.nil?

    # in case the response body is nil or damaged we return an error
    begin
      responded_body_hash = JSON.parse(response.body)
    rescue
      result = Result.new(testcase, response)
      result.succeeded = false
      result.error_message = " expected response to have a body\n got raw body --#{response.body}-- which is nil or an unparseable hash"
      return result
    end

    # else we build trees from both body structures...
    expectation_tree = Nokogiri::XML(expected_body_hash.to_xml({ :indent => 0 }))
    response_tree = Nokogiri::XML(responded_body_hash.to_xml({ :indent => 0 }))

    # retrieve all the leafs pathes and match the leafs values using xpath
    matcher_pathes_from(expectation_tree).each do |path|
      debugger if testcase['name'] == "Check users watchlist afterwards"
      expectation_node = expectation_tree.xpath(path).first
      response_node = response_tree.xpath(path).first

      # in some (not awesome) cases the root node occures as leaf, so we have to skip him here
      next if expectation_node.name == "hash"

      # return error if response body does not have the expected entry
      if response_node.nil?
        result.succeeded = false
        result.error_message = " expected body to have identifier --#{expectation_node.name}--\n got nil"
        return result
      end

      # last but not least try the regex or direct match and return errors in case of any<commit_msg>Extended expectation_matcher to be able to match the whole body against a regular expression. Signed-off-by: <NAME> <<EMAIL>><commit_after>class ExpectationMatcher
  require 'result'
  require 'nokogiri'
  require 'JSON'

  def initialize(excludes=nil)
    @test_types = [:response_code, :response_body_format, :response_headers, :response_body]
    @excludes = excludes || []
  end

  # returns the available test types if this matcher class
  def test_types
    return @test_types
  end

  # dispatches incoming matching requests
  def check(method, response, testcase)
    self.send(method, response, testcase)
  end

  protected

  # matches the given response code
  def response_code(response, testcase)
    result = Result.new(testcase, response)
    if not testcase['response_expectation']['status_code'].to_s == response.code.to_s
      result.succeeded = false
      result.error_message = " expected response code --#{testcase['response_expectation']['status_code']}--\n got response code --#{response.code}--"
    end
    result
  end

  # checks the format of the given data of JSON conformity
  def response_body_format(response, testcase)
    result_struct = Struct.new(:succeeded, :error)
    results = result_struct.new(:succeeded => true, :error => nil)
    result = Result.new(testcase, response)
    if not valid_json?(response.body)
      result.succeeded = false
      result.error_message = "expected valid JSON in body\n got --#{response.body[1..400]}--"
    end
    result
  end

  # matches the given response header
  def response_headers(response, testcase)
    result = Result.new(testcase, response)

    testcase['response_expectation']['headers'].each_pair do |header_name, header_value|
      if is_regex?(header_value)
        if not (excluded?(header_name) or regex_matches?(header_value, response.headers[header_name]))
          result.succeeded = false
          result.error_message = " expected header identifier --#{header_name}-- to match regex --#{header_value}--\n got --#{response.headers[header_name]}--"
        end
      else
        if not (excluded?(header_name) or string_matches?(header_value, response.headers[header_name]))
          result.succeeded = false
          result.error_message = " expected header identifier --#{header_name}-- to match --#{header_value}--\n got --#{response.headers[header_name]}--"
        end
      end
    end unless (testcase['response_expectation']['headers'].nil? or testcase['response_expectation']['headers'].empty?)
    return result
  end

  # matches the given attributes and values against the ones from the response body
  def response_body(response, testcase)
    result = Result.new(testcase, response)

    # special case: the whole body has to be matched via a regular expression
    if is_regex?(testcase['response_expectation']['body'])
      if not regex_matches?(testcase['response_expectation']['body'], response.body)
        result.succeeded = false
        result.error_message = " expected the whole body to match regex --#{testcase['response_expectation']['body']}--\n got --#{response.body}--"
      end
      return result
    end

    expected_body_hash = testcase['response_expectation']['body']

    # in case we have no body expectation we simply return success
    return result if expected_body_hash.nil?

    # in case the response body is nil or damaged we return an error
    begin
      responded_body_hash = JSON.parse(response.body)
    rescue
      result = Result.new(testcase, response)
      result.succeeded = false
      result.error_message = " expected response to have a body\n got raw body --#{response.body}-- which is nil or an unparseable hash"
      return result
    end

    # else we build trees from both body structures...
    expectation_tree = Nokogiri::XML(expected_body_hash.to_xml({ :indent => 0 }))
    response_tree = Nokogiri::XML(responded_body_hash.to_xml({ :indent => 0 }))

    # retrieve all the leafs pathes and match the leafs values using xpath
    matcher_pathes_from(expectation_tree).each do |path|
      expectation_node = expectation_tree.xpath(path).first
      response_node = response_tree.xpath(path).first

      debugger
      # in some (not awesome) cases the root node occures as leaf, so we have to skip him here
      next if expectation_node.name == "hash"

      # return error if response body does not have the expected entry
      if response_node.nil?
        result.succeeded = false
        result.error_message = " expected body to have identifier --#{expectation_node.name}--\n got nil"
        return result
      end

      # last but not least try the regex or direct match and return errors in case of any
{'fraction_non_alphanumeric': 0.09739091318038687, 'fraction_numerical': 0.001349527665317139, 'mean_word_length': 3.4936836786255685, 'pattern_counts': {'":': 0, '<': 6, '<?xml version=': 0, '>': 14, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 4}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '1652184', 'n_tokens_mistral': 2537, 'n_tokens_neox': 2485, 'n_words': 779}