agoragames/chai — Issue #1: Nest expectations on return values
Author: kesor
Created: 2011-12-23 01:22:52+00:00
State: open

In python-mock library, return_value can be used to chain expectations (as it is also a mock), example:

def test_mongo_db_api_connects_to_mongo(self):
with mock.patch('pymongo.Connection') as mock_conn:
stub_cursor = "whatever"
mock_conn.return_value.__getitem__ = mock.MagicMock()
mock_conn.return_value.__getitem__.return_value.__getitem__.return_value = stub_cursor

api = MongoDbApi(database_name='dbname', collection_name='collection')
self.assertEquals(api.cursor, stub_cursor)

mock_conn.assert_called_with({'host':'localhost'})
mock_conn.return_value.__getitem__.assert_called_with('dbname')
mock_conn.return_value.__getitem__.return_value.__getitem__.assert_called_with('collection')

would be nice if something similar was available in chai, maybe like this:

def test_mongo_db_api_connects_to_mongo(self):
stub_cursor = stub("whatever")
expect(pymongo.Connection).args({'host':'localhost'}).\
return_value.expect('__getitem__').args('dbname').\
return_value.expect('__getitem__').args('collection').\
returns( stub_cursor )
api = MongoDbApi(database_name='dbname', collection_name='collection')
assert_equals(api.cursor, stub_cursor)

It does behave a bit different though, since the object that receives the method now has an .expect() method which is different from how Chai usually sets expectations on objects, but on other hand it looks so cool! :)