Skip to content

Commit c408bcc

Browse files
smt116egonSchiele
authored andcommitted
Fix StrictHash contract for extra keys (#254)
* Fix StrictHash contract for extra keys `Contracts::StrictHash` didn't complain about extra entries in a given hash. This was because of the missing assertion for keys. Specs hadn't caught this case because `age` key had a wrong type anyway. Compare keys for contract and a given hash and return false if they are equal. * Do not use a second lookup for the contract in StrictHash assertion `all?` iterator already provides contract for the `valid?` check. Use it instead of accessing `contract_hash` again.
1 parent 8e6d4ee commit c408bcc

File tree

2 files changed

+4
-3
lines changed

2 files changed

+4
-3
lines changed

lib/contracts/builtin_contracts.rb

+3-2
Original file line numberDiff line numberDiff line change
@@ -405,9 +405,10 @@ def initialize(contract_hash)
405405

406406
def valid?(arg)
407407
return false unless arg.is_a?(Hash)
408+
return false unless arg.keys.sort.eql?(contract_hash.keys.sort)
408409

409-
contract_hash.all? do |key, _v|
410-
contract_hash.key?(key) && Contract.valid?(arg[key], contract_hash[key])
410+
contract_hash.all? do |key, contract|
411+
contract_hash.key?(key) && Contract.valid?(arg[key], contract)
411412
end
412413
end
413414
end

spec/builtin_contracts_spec.rb

+1-1
Original file line numberDiff line numberDiff line change
@@ -448,7 +448,7 @@ def something(hash)
448448

449449
context "when given an input with extra keys" do
450450
it "raises an error" do
451-
fails { @o.strict_person(:name => "calvin", :age => "10", :soft => true) }
451+
fails { @o.strict_person(:name => "calvin", :age => 10, :soft => true) }
452452
end
453453
end
454454

0 commit comments

Comments
 (0)