Mock pathc question

B

balderman

Hi
I would like to mock patch the attribute 'calc' in the 'Client' class (See code below).
I have 2 unit tests:
1) test1 - that patch an existing instance of 'Client' - it works fine.
1) test2 - that tries to patch the 'Client' class. My expectation is that after the patching, every instance of 'Client' will be created with 'MockClient'. However this is not the case..

Can you please advice?

Thanks

Avishay


code below:
-------------------------------------

import mock
import sys
import unittest

SEVEN = 7

class Calc:
def __init__(self):
print self.__class__
def add(self,a,b):
return a + b

class MockCalc:
def __init__(self):
print self.__class__
def add(self,a,b):
return SEVEN

class Client:
def __init__(self):
self.calc = Calc()
def add(self,a,b):
return self.calc.add(a,b)

class TestIt(unittest.TestCase):
def setUp(self):
pass

def test2(self):
'''Mocking the Calc and replace it with MockCalc.'''
print " \ntest2 "
my_mock = mock.patch('mock_play.Calc',create=True, new=MockCalc)
my_mock.start()
# client should be created with 'MockCalc'
client = Client()
# result should be 7
print str(client.add(1,34))
my_mock.stop()
# result should be 35 again
print str(client.add(1,34))

def test1(self):
'''Mocking the client instance.'''
print " test1 "
client = Client()
my_mock = mock.patch.object(client, 'calc', new_callable=MockCalc)
# result should be 35
print str(client.add(1,34))
# now i want to switch to the MockCalc
my_mock.start()
# result should be 7
print str(client.add(1,34))
my_mock.stop()
# result should be 35 again
print str(client.add(1,34))

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

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,482
Members
44,901
Latest member
Noble71S45

Latest Threads

Top