Skip to content

Commit a1738be

Browse files
author
Michael Kryukov
committed
feat: instances are now hashable (#44)
1 parent 6ac83c7 commit a1738be

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

mongomock_motor/__init__.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,9 @@ def __eq__(self, other):
192192
def __getattr__(self, name):
193193
return getattr(self.__collection, name)
194194

195+
def __hash__(self):
196+
return hash(self.__collection)
197+
195198
def find(self, *args, **kwargs) -> AsyncCursor:
196199
return AsyncCursor(self.__collection.find(*args, **kwargs))
197200

@@ -269,6 +272,9 @@ def __getattr__(self, name):
269272

270273
return self.get_collection(name)
271274

275+
def __hash__(self):
276+
return hash(self.__database)
277+
272278

273279
@masquerade_class('motor.motor_asyncio.AsyncIOMotorClient')
274280
@with_async_methods(
@@ -317,6 +323,9 @@ def __getattr__(self, name):
317323

318324
return self.get_database(name)
319325

326+
def __hash__(self):
327+
return hash(self.__client)
328+
320329

321330
@contextmanager
322331
def enabled_gridfs_integration():

tests/test_hashable.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
import pytest
2+
3+
from mongomock_motor import AsyncMongoMockClient
4+
5+
6+
@pytest.mark.anyio
7+
async def test_hashing_is_possible():
8+
hash(AsyncMongoMockClient())
9+
hash(AsyncMongoMockClient()['database'])
10+
hash(AsyncMongoMockClient()['database']['collection'])
11+
12+
13+
@pytest.mark.anyio
14+
async def test_hashing_is_stable():
15+
assert hash(AsyncMongoMockClient()) == hash(AsyncMongoMockClient())
16+
assert hash(AsyncMongoMockClient('localhost')) == hash(
17+
AsyncMongoMockClient('not.localhost')
18+
)
19+
assert hash(AsyncMongoMockClient()['database1']) == hash(
20+
AsyncMongoMockClient()['database1']
21+
)
22+
assert hash(AsyncMongoMockClient()['database1']) != hash(
23+
AsyncMongoMockClient()['database2']
24+
)

0 commit comments

Comments
 (0)