Something-driven development

Software development thoughts around Ubuntu, Python, Golang and other tools

Mocking in Python just got easier

with 2 comments

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!

About these ads

Written by Michael

October 14, 2008 at 6:31 am

Posted in python, testing

2 Responses

Subscribe to comments with RSS.

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

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


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 84 other followers

%d bloggers like this: