Skip to content

Commit 61f67c9

Browse files
committed
Make KeywordArgs fail if unexpected keys are passed in
1 parent fc98f41 commit 61f67c9

File tree

3 files changed

+26
-3
lines changed

3 files changed

+26
-3
lines changed

lib/contracts/builtin_contracts.rb

+4-3
Original file line numberDiff line numberDiff line change
@@ -385,9 +385,10 @@ def initialize(options)
385385
end
386386

387387
def valid?(hash)
388-
options.all? do |key, contract|
389-
Optional._valid?(hash, key, contract)
390-
end
388+
(hash.keys - options.keys == []) &&
389+
options.all? do |key, contract|
390+
Optional._valid?(hash, key, contract)
391+
end
391392
end
392393

393394
def to_s

spec/builtin_contracts_spec.rb

+18
Original file line numberDiff line numberDiff line change
@@ -332,6 +332,24 @@
332332
end
333333
end
334334

335+
describe "KeywordArgs:" do
336+
it "should pass for exact correct input" do
337+
expect { @o.person_keywordargs(:name => "calvin", :age => 10) }.to_not raise_error
338+
end
339+
340+
it "should fail if some keys don't have contracts" do
341+
expect { @o.person_keywordargs(:name => "calvin", :age => 10, :foo => "bar") }.to raise_error(ContractError)
342+
end
343+
344+
it "should fail if a key with a contract on it isn't provided" do
345+
expect { @o.person_keywordargs(:name => "calvin") }.to raise_error(ContractError)
346+
end
347+
348+
it "should fail for incorrect input" do
349+
expect { @o.person_keywordargs(:name => 50, :age => 10) }.to raise_error(ContractError)
350+
end
351+
end
352+
335353
describe "Optional:" do
336354
it "can't be used outside of KeywordArgs" do
337355
expect do

spec/fixtures/fixtures.rb

+4
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,10 @@ def hash_complex_contracts(data)
113113
def nested_hash_complex_contracts(data)
114114
end
115115

116+
Contract KeywordArgs[:name => String, :age => Fixnum] => nil
117+
def person_keywordargs(data)
118+
end
119+
116120
Contract [Or[TrueClass, FalseClass]] => nil
117121
def array_complex_contracts(data)
118122
end

0 commit comments

Comments
 (0)