PYTHON-2466 Make pymongo client, database and collection objects hashable. (#533)
This commit is contained in:
parent
eb5bd9c858
commit
733ab2527b
@ -303,6 +303,9 @@ class Collection(common.BaseObject):
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __hash__(self):
|
||||
return hash((self.__database, self.__name))
|
||||
|
||||
@property
|
||||
def full_name(self):
|
||||
"""The full name of this :class:`Collection`.
|
||||
|
||||
@ -272,6 +272,9 @@ class Database(common.BaseObject):
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __hash__(self):
|
||||
return hash((self.__client, self.__name))
|
||||
|
||||
def __repr__(self):
|
||||
return "Database(%r, %r)" % (self.__client, self.__name)
|
||||
|
||||
|
||||
@ -1509,6 +1509,9 @@ class MongoClient(common.BaseObject):
|
||||
def __ne__(self, other):
|
||||
return not self == other
|
||||
|
||||
def __hash__(self):
|
||||
return hash(self.address)
|
||||
|
||||
def _repr_helper(self):
|
||||
def option_repr(option, value):
|
||||
"""Fix options whose __repr__ isn't usable in a constructor."""
|
||||
|
||||
@ -627,6 +627,10 @@ class TestClient(IntegrationTest):
|
||||
# Explicitly test inequality
|
||||
self.assertFalse(client_context.client != c)
|
||||
|
||||
def test_hashable(self):
|
||||
c = connected(rs_or_single_client())
|
||||
self.assertIn(c, {client_context.client})
|
||||
|
||||
def test_host_w_port(self):
|
||||
with self.assertRaises(ValueError):
|
||||
connected(MongoClient("%s:1234567" % (client_context.host,),
|
||||
|
||||
@ -154,6 +154,9 @@ class TestCollection(IntegrationTest):
|
||||
self.assertEqual(self.db.test.mike, self.db["test.mike"])
|
||||
self.assertEqual(self.db.test["mike"], self.db["test.mike"])
|
||||
|
||||
def test_hashable(self):
|
||||
self.assertIn(self.db.test.mike, {self.db["test.mike"]})
|
||||
|
||||
@client_context.require_version_min(3, 3, 9)
|
||||
def test_create(self):
|
||||
# No Exception.
|
||||
|
||||
@ -126,6 +126,9 @@ class TestDatabase(IntegrationTest):
|
||||
self.assertFalse(Database(self.client, "test") !=
|
||||
Database(self.client, "test"))
|
||||
|
||||
def test_hashable(self):
|
||||
self.assertIn(self.client.test, {Database(self.client, "test")})
|
||||
|
||||
def test_get_coll(self):
|
||||
db = Database(self.client, "pymongo_test")
|
||||
self.assertEqual(db.test, db["test"])
|
||||
|
||||
Loading…
Reference in New Issue
Block a user