Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

Already on GitHub? Sign in to your account

Allowing regex to be used for hash matching #81

Closed
wants to merge 1 commit into
from
Jump to file or symbol
Failed to load files and symbols.
+21 −4
Split
@@ -143,11 +143,11 @@ def matches?(body, content_type = "")
case BODY_FORMATS[content_type]
when :json then
- Crack::JSON.parse(body) == @pattern
+ matching_hashes?(Crack::JSON.parse(body), @pattern)
when :xml then
- Crack::XML.parse(body) == @pattern
+ matching_hashes?(Crack::XML.parse(body), @pattern)
else
- Addressable::URI.parse('?' + body).query_values == @pattern
+ matching_hashes?(Addressable::URI.parse('?' + body).query_values, @pattern)
end
else
empty_string?(@pattern) && empty_string?(body) ||
@@ -161,6 +161,18 @@ def to_s
end
private
+
+ def matching_hashes?(h1, h2)
+ return false if h1.size != h2.size
+ h1.each do |k, v|
+ if v.is_a?(Hash) && h2[k].is_a?(Hash)
+ return false unless matching_hashes?(v, h2[k])
+ else
+ return false unless h2[k] === v
+ end
+ end
+ true
+ end
def empty_string?(string)
string.nil? || string == ""
@@ -145,7 +145,7 @@ def match(request_signature)
WebMock::RequestPattern.new(:get, "www.example.com", :query => {"a" => ["b", "c"]}).
should_not match(WebMock::RequestSignature.new(:get, "www.example.com?x[]=b&a[]=c"))
end
-
+
it "should match for query params are the same as declared as string" do
WebMock::RequestPattern.new(:get, "www.example.com", :query => "a[]=b&a[]=c").
should match(WebMock::RequestSignature.new(:get, "www.example.com?a[]=b&a[]=c"))
@@ -223,6 +223,11 @@ def match(request_signature)
WebMock::RequestPattern.new(:post, 'www.example.com', :body => body_hash).
should_not match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'foo bar'))
end
+
+ it "should match when hash contains regex values" do
+ WebMock::RequestPattern.new(:post, "www.example.com", :body => {:a => /^\w{5}$/, :b => {:c => /^\d{3}$/}}).
+ should match(WebMock::RequestSignature.new(:post, "www.example.com", :body => 'a=abcde&b[c]=123'))
+ end
end