tests + fixes for using nil _id's

This commit is contained in:
Mike Dirolf 2009-12-08 17:51:32 -05:00
parent a9bb31e392
commit d268595584
3 changed files with 24 additions and 2 deletions

View File

@ -175,7 +175,8 @@ module Mongo
# will be raised on an error. Checking for safety requires an extra
# round-trip to the database
def save(to_save, options={})
if id = to_save[:_id] || to_save['_id']
if to_save.has_key?(:_id) || to_save.has_key?('_id')
id = to_save[:_id] || to_save['_id']
update({:_id => id}, to_save, :upsert => true, :safe => options.delete(:safe))
id
else

View File

@ -44,7 +44,7 @@ module Mongo
# Adds a primary key to the given document if needed.
def self.create_pk(doc)
doc[:_id] || doc['_id'] ? doc : doc.merge!(:_id => self.new)
doc.has_key?(:_id) || doc.has_key?('_id') ? doc : doc.merge!(:_id => self.new)
end
# +data+ is an array of bytes. If nil, a new id will be generated.

View File

@ -53,6 +53,27 @@ class TestCollection < Test::Unit::TestCase
assert_equal 5, @@db.collection("test.foo").find_one()["x"]
end
def test_nil_id
assert_equal 5, @@test.insert({"_id" => 5, "foo" => "bar"}, {:safe => true})
assert_equal 5, @@test.save({"_id" => 5, "foo" => "baz"}, {:safe => true})
assert_equal nil, @@test.find_one("foo" => "bar")
assert_equal "baz", @@test.find_one(:_id => 5)["foo"]
assert_raise OperationFailure do
@@test.insert({"_id" => 5, "foo" => "bar"}, {:safe => true})
end
assert_equal nil, @@test.insert({"_id" => nil, "foo" => "bar"}, {:safe => true})
assert_equal nil, @@test.save({"_id" => nil, "foo" => "baz"}, {:safe => true})
assert_equal nil, @@test.find_one("foo" => "bar")
assert_equal "baz", @@test.find_one(:_id => nil)["foo"]
assert_raise OperationFailure do
@@test.insert({"_id" => nil, "foo" => "bar"}, {:safe => true})
end
assert_raise OperationFailure do
@@test.insert({:_id => nil, "foo" => "bar"}, {:safe => true})
end
end
if @@version > "1.1"
def test_distinct
@@test.remove