RUBY-165 raise error if BSON.serialize is passed something other than a hash

This commit is contained in:
Kyle Banker 2010-08-24 14:01:24 -04:00
parent 78c194bcb4
commit 02a0c7c2dc
3 changed files with 20 additions and 1 deletions

View File

@ -562,8 +562,12 @@ static void write_doc(buffer_t buffer, VALUE hash, VALUE check_keys, VALUE move_
write_function(key, value, pack_extra(buffer, check_keys)); write_function(key, value, pack_extra(buffer, check_keys));
} }
} else { } else if (strcmp(rb_obj_classname(hash), "Hash") == 0) {
rb_hash_foreach(hash, write_function, pack_extra(buffer, check_keys)); rb_hash_foreach(hash, write_function, pack_extra(buffer, check_keys));
} else {
buffer_free(buffer);
char* cls = rb_obj_classname(hash);
rb_raise(InvalidDocument, "BSON.serialize takes a Hash but got a %s", cls);
} }
// write null byte and fill in length // write null byte and fill in length

View File

@ -89,6 +89,7 @@ module BSON
end end
def serialize(obj, check_keys=false, move_id=false) def serialize(obj, check_keys=false, move_id=false)
raise(InvalidDocument, "BSON.serialize takes a Hash but got a #{obj.class}") unless obj.is_a?(Hash)
raise "Document is null" unless obj raise "Document is null" unless obj
@buf.rewind @buf.rewind

View File

@ -22,6 +22,20 @@ class BSONTest < Test::Unit::TestCase
include BSON include BSON
def test_require_hash
assert_raise_error InvalidDocument, "takes a Hash" do
BSON.serialize('foo')
end
assert_raise_error InvalidDocument, "takes a Hash" do
BSON.serialize(Object.new)
end
assert_raise_error InvalidDocument, "takes a Hash" do
BSON.serialize(Set.new)
end
end
def test_read_bson_io_document def test_read_bson_io_document
doc = {'doc' => 'hello, world'} doc = {'doc' => 'hello, world'}
bson = BSON.serialize(doc) bson = BSON.serialize(doc)