[BangPypers] Query with respect to mock module

Sateesh Kumar sateeshpyper at gmail.com
Tue Mar 25 15:48:59 CET 2014


On Tue, Mar 25, 2014 at 12:30 PM, Nitin Kumar <nitin.nitp at gmail.com> wrote:

> Hi All,
>
> I am try to write test case with mocking original libraries.
> But we have scenario that some time we need this mock but some time we need
> to create object of original class so that test run on real scenario.
>
> Is there a way we can play with mock library or any other way that some
> time same test case runs with mock and some time with original objects?
>
> Right now we are writing 2 testcases one using mock and one with original
> class object.
>
>
You have not mentioned which is the mock module you are using.
If you are using 'Mock'[1], one way in which you can switch between
invoking real method and mock method is to use the 'patch' decoratror
provided by mock module as a context manager.

The below example illustrates the approach:

%cat sample.py

from mock import patch
import unittest

class Hello(object):
    def process(self):
        print 'I am real method'
        return 200


class Secondary(object):
    def __init__(self, r):
        self.requester = r

    def manage(self):
        return self.requester.process()

class TestSecondary(unittest.TestCase):

    def test_manage_withmock(self):
        h = Hello()
        s = Secondary(h)

        with patch.object(Hello, 'process', return_value= 100) as
mock_method:
            print s.manage()

        print s.manage()

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


%python sample.py

100
I am real method
200

The above approach is explained in the Mock quick guide [1].

1. http://www.voidspace.org.uk/python/mock/index.html

HTH,
sateesh


More information about the BangPypers mailing list