Michael Foord's python-mock for testing


Posted: 2012/03/22 17:37:57 | Source | More posts about Fedora News Python

The project page is here.

Why you need it ? Say you are writing unittests for your favourite application  and in some function you are using xmlrpclib module to interact with a web-application. Now for testing you can easily mock that interaction out, which will help to run your code in fast and easy way. Mocking database calls can be another example.

Example:

import unittest
import xmlrpclib
from mock import patch

class TestFoo(unittest.TestCase):
    """
    A simple test
    """
    @patch('xmlrpclib.Server')
    def test_first(self, mock_xmlrpc):
        m = mock_xmlrpc.return_value
        m.multiply.return_value = 6
        server = xmlrpclib.Server("http://kushaldas.in/")
        res = server.multiply(2, 3)
        self.assertEqual(res, 6)


if __name__ == '__main__':
    unittest.main()

In Fedora you can just yum install python-mock.

comments powered by Disqus
Contents © 2004-2014 Kushal Das - Powered by Shonku