python - mock.patch does not work properly -
i try patch calc class in code below. inside test code want each 'client' created 'mockcalc' , not 'calc'. not happen , test return 12 , not 7. calc not replaced mockcalc.
note: 'test_mock_play' name of python module (file) holds code.
note: prefer not use decoration
import mock import sys import unittest 7 = 7 class calc: def __init__(self): print self.__class__ def add(self,a,b): return + b class mockcalc: def __init__(self): print self.__class__ def add(self,a,b): return 7 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): self.mock_calc = mock.patch('test_mock_play.calc',create=true, new=mockcalc) self.mock_calc.start() def teardown(self): self.mock_calc.stop() def test_patch_class(self): '''mocking calc , replace mockcalc.''' print " \npatch class " # client should created 'mockcalc' client = client() # result should 7 result = client.add(4,8) print "1)" + str(result) self.assertequal(result,seven) if __name__ == "__main__": unittest.main()
workaround
replace test_mock_play.calc __main__.calc. not recommended.
recommended way
split test_mock_play.py 2 files: - test code test_mock_play.py. - implementation code: calc.py.
import calc test_mock_play. replace references calc/client calc.calc/calc.client.
patch calc.calc instead of test_mock_play.calc.
calc.py
class calc: def __init__(self): print self.__class__ def add(self,a,b): return + b class client: def __init__(self): self.calc = calc() def add(self,a,b): return self.calc.add(a,b) test_mock_play.py
import unittest import mock import calc 7 = 7 class mockcalc: def __init__(self): print self.__class__ def add(self,a,b): return 7 class testit(unittest.testcase): def setup(self): self.mock_calc = mock.patch('calc.calc',create=true, new=mockcalc) self.mock_calc.start() def teardown(self): self.mock_calc.stop() def test_patch_class(self): '''mocking calc , replace mockcalc.''' print " \npatch class " # client should created 'mockcalc' client = calc.client() # result should 7 result = client.add(4,8) print "1)" + str(result) self.assertequal(result,seven) if __name__ == "__main__": unittest.main()
Comments
Post a Comment