Mocking in Python just got easier
Voidspace just released Mock 0.4.0 – an update to the excellent Mock library which brings a few conveniences and easier patching of module and class-level attributes.
This makes tests using mocks easier to read, for example inside a test case:
self.assertEquals(my_mock.my_method.call_args, (('goodbye',),{'hello': False}))
Can now be written as:
my_mock.my_method.assert_called_with('goodbye', hello=False)
Check it out!
You should check out chai, it makes it even easier http://pypi.python.org/pypi/chai#example
Vitaly babiy
June 21, 2011 at 8:48 pm
Hi Vitaly! Just to make the comparison obvious, the contrived example of mocking a particular method on an object looks like this with Chai:
obj = CustomObject() self.expect(obj.get).args('name').returns('My Name') self.assert_equals(obj.get('name'), 'My Name')while the mock way looks like:
obj = CustomObject() with patch.object(obj, 'get') as mock_get: mock_get.return_value = 'My Name' self.assertEqual(obj.get('name'), 'My Name')In a real example, the mock version would probably look more like this:
mock_obj = Mock(spec=CustomObject) # Make the call that should result in calling the get method. mock_obj.get.assert_called_with('name') self.assertEqual(returned_name_from_actual_call, mock_object.get.return_value)Maybe it’s just because I’m used to it, but in both examples I personally find the mock version easier (ie. I don’t have to specify the return value to know that the correct value was received and returned by my calling function, and assert_called_with is just so easy to read).
Michael
June 22, 2011 at 9:01 am