PYTHON-2466 Make pymongo client, database and collection objects hashable. (#533)

This commit is contained in:
Pascal Corpet 2020-12-17 04:44:56 +01:00 committed by GitHub
parent eb5bd9c858
commit 733ab2527b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 19 additions and 0 deletions

View File

@ -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`.

View File

@ -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)

View File

@ -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."""

View File

@ -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,),

View File

@ -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.

View File

@ -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"])