This however was a bit annoying in unit tests. These tests are not executed against a real database, I am mocking the MongoDbDao instead. When using a pymongo.cursor.Cursor, the only thing I am doing in production code is iteration over the results or checking if there were any results using the count function. So here is what I came up with for the unit test.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class LoanApp(tornado.web.Application): | |
def __init__(self, dao = MongoDbDao()): | |
self.dao = dao | |
... | |
class AdminHandler(tornado.web.RequestHandler): | |
def get(self, *args, **kwargs): | |
articles = self.application.dao.load_all_articles() | |
self.render("admin/index.html", articles=articles) # articles.count() used in template | |
class LoanAppTest(AsyncHTTPTestCase): | |
def get_app(self): | |
self.mongo_db_dao = mock() # mockito | |
return LoanApp(self.mongo_db_dao) | |
def test_admin_home(self): | |
when(self.mongo_db_dao).load_all_articles().thenReturn(MockCursor([])) | |
self.http_client.fetch(self.get_url('/admin'), self.stop) | |
response = self.wait() | |
self.assertEqual(200, response.code) | |
verify(self.mongo_db_dao, times=1).load_all_articles() | |
class MockCursor(UserList): | |
def count(self, with_limit_and_skip=False): | |
""" | |
Mimics the Cursors count method | |
""" | |
return len(self) |
This is basically a UserList that has the count function of the pymongo.cursor.Cursor added to it (not really using the with_limit_and_skip argument at the moment). I found this to be easier than creating a stub with Mockito every time I want to return a Cursor that can be iterated or checked for it's size.