Skip to content

Commit

Permalink
Refactoring to avoid RequestPattern being coupled with JSON or XML pa…
Browse files Browse the repository at this point in the history
…rser specific parsing exceptions.
  • Loading branch information
bblimke committed Sep 18, 2024
1 parent 4a8a513 commit 8db8b02
Show file tree
Hide file tree
Showing 7 changed files with 114 additions and 80 deletions.
4 changes: 2 additions & 2 deletions lib/webmock.rb
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

require 'addressable/uri'
require 'addressable/template'
require 'crack/xml'

require_relative 'webmock/deprecation'
require_relative 'webmock/version'
Expand All @@ -17,7 +16,8 @@
require_relative 'webmock/util/hash_counter'
require_relative 'webmock/util/hash_keys_stringifier'
require_relative 'webmock/util/values_stringifier'
require_relative 'webmock/util/json'
require_relative 'webmock/util/parsers/json'
require_relative 'webmock/util/parsers/xml'
require_relative 'webmock/util/version_checker'
require_relative 'webmock/util/hash_validator'

Expand Down
7 changes: 4 additions & 3 deletions lib/webmock/request_pattern.rb
Original file line number Diff line number Diff line change
Expand Up @@ -303,13 +303,14 @@ def to_s
def body_as_hash(body, content_type)
case body_format(content_type)
when :json then
WebMock::Util::JSON.parse(body)
WebMock::Util::Parsers::JSON.parse(body)
when :xml then
Crack::XML.parse(body)
WebMock::Util::Parsers::XML.parse(body)
else
WebMock::Util::QueryMapper.query_to_values(body, notation: Config.instance.query_values_notation)
end
rescue Psych::SyntaxError, REXML::ParseException
rescue WebMock::Util::Parsers::ParseError
nil
end

def body_format(content_type)
Expand Down
69 changes: 0 additions & 69 deletions lib/webmock/util/json.rb

This file was deleted.

72 changes: 72 additions & 0 deletions lib/webmock/util/parsers/json.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
# frozen_string_literal: true

# This is a copy of https://github.com/jnunemaker/crack/blob/master/lib/crack/json.rb
# with date parsing removed
# Copyright (c) 2004-2008 David Heinemeier Hansson
# Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

require_relative "parse_error"

module WebMock
module Util
module Parsers
class JSON
def self.parse(json)
yaml = unescape(convert_json_to_yaml(json))
YAML.load(yaml)
rescue ArgumentError, Psych::SyntaxError => e
raise ParseError, "Invalid JSON string: #{yaml}, Error: #{e.inspect}"
end

protected

def self.unescape(str)
str.gsub(/\\u([0-9a-f]{4})/) { [$1.hex].pack("U") }
end

# Ensure that ":" and "," are always followed by a space
def self.convert_json_to_yaml(json) #:nodoc:
scanner, quoting, marks, times = StringScanner.new(json), false, [], []
while scanner.scan_until(/(\\['"]|['":,\\]|\\.)/)
case char = scanner[1]
when '"', "'"
if !quoting
quoting = char
elsif quoting == char
quoting = false
end
when ":",","
marks << scanner.pos - 1 unless quoting
when "\\"
scanner.skip(/\\/)
end
end

if marks.empty?
json.gsub(/\\\//, '/')
else
left_pos = [-1].push(*marks)
right_pos = marks << json.bytesize
output = []

left_pos.each_with_index do |left, i|
if json.respond_to?(:byteslice)
output << json.byteslice(left.succ..right_pos[i])
else
output << json[left.succ..right_pos[i]]
end
end

output = output * " "

times.each { |i| output[i-1] = ' ' }
output.gsub!(/\\\//, '/')
output
end
end
end
end
end
end
7 changes: 7 additions & 0 deletions lib/webmock/util/parsers/parse_error.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module WebMock
module Util
module Parsers
class ParseError < StandardError; end
end
end
end
16 changes: 16 additions & 0 deletions lib/webmock/util/parsers/xml.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
require_relative "parse_error"
require "crack/xml"

module WebMock
module Util
module Parsers
class XML
def self.parse(xml)
::Crack::XML.parse(xml)
rescue ::REXML::ParseException => e
raise ParseError, "Invalid XML string: #{xml}, Error: #{e.inspect}"
end
end
end
end
end
Original file line number Diff line number Diff line change
@@ -1,31 +1,38 @@
# encoding: utf-8
require 'spec_helper'

describe WebMock::Util::JSON do
describe WebMock::Util::Parsers::JSON do
describe ".parse" do
it "should parse json without parsing dates" do
expect(WebMock::Util::JSON.parse("\"a\":\"2011-01-01\"")).to eq(
expect(described_class.parse("\"a\":\"2011-01-01\"")).to eq(
{"a" => "2011-01-01"}
)
end

it "can parse json with multibyte characters" do
expect(WebMock::Util::JSON.parse(
expect(described_class.parse(
"{\"name\":\"山田太郎\"\,\"job\":\"会社員\"}"
)).to eq({"name" => "山田太郎", "job" => "会社員"})
end

it "rescues ArgumentError's from YAML.load" do
allow(YAML).to receive(:load).and_raise(ArgumentError)
expect {
WebMock::Util::JSON.parse("Bad JSON")
}.to raise_error WebMock::Util::JSON::ParseError
described_class.parse("Bad JSON")
}.to raise_error WebMock::Util::Parsers::ParseError
end

it "rescues Psych::SyntaxError's from YAML.load" do
allow(YAML).to receive(:load).and_raise(Psych::SyntaxError)
expect {
described_class.parse("Bad JSON")
}.to raise_error WebMock::Util::Parsers::ParseError
end
end

describe ".convert_json_to_yaml" do
it "parses multibyte characters" do
expect(WebMock::Util::JSON.convert_json_to_yaml(
expect(described_class.convert_json_to_yaml(
"{\"name\":\"山田太郎\"\,\"job\":\"会社員\"}"
)).to eq "{\"name\": \"山田太郎\", \"job\": \"会社員\"}"
end
Expand Down

0 comments on commit 8db8b02

Please sign in to comment.