It might be simpler to subclass the original Test
class for use in your tests:
class Test(object):
@staticmethod
def generate():
return 10
class PatchedTest(Test):
count = 1
@staticmethod
def generate():
if Test.count < 3:
Test.count += 1
return 1
else:
return 10
The replacement function could also be done in two somewhat better ways, both of which should make it a lot easier to patch the Test
class in the same way you were trying in your question:
Use a @classmethod
, allowing the function to access the class it's assigned to:
class PatchedTest(Test):
count = 1
@classmethod
def generate(cls):
if cls.count < 3:
cls.count += 1
return 1
else:
return 10
Use a generator instead - each time the function is called it will continue execution where it last left off. However, this will only work if you are iterating over the functions result:
def alternative_generate():
yield 1
yield 1
yield 10