from unittest.mock import MagicMock
class Person:
def __init__(self, name):
self.name = name
def myfunc(self):
return self.name
p1 = Person("John")
print(p1.myfunc()) # "John"
p1.myfunc = MagicMock(return_value="Mock Return")
print(p1.myfunc()) # "Mock Return"
del(p1.myfunc) #instead of del how do I use reset_mock() here to get the same output?
print(p1.myfunc()) # "John"
from unittest.mock import MagicMock
class Person:
def __init__(self, name):
self.name = name
def myfunc(self):
return self.name
p1 = Person("John")
print(p1.myfunc())
orig_func = p1.myfunc
p1.myfunc = MagicMock(return_value="Mock Return")
print(p1.myfunc())
p1.myfunc = orig_func
print(p1.myfunc())
This should work. Just store it in a variable before you mock it and restore it when you’re done with the mock.
Thanks for your response. I wasn’t looking for an alternative since the code in the OP is working as expected. I want to specifically use reset_mock() and can’t figure out how to use it in this simple piece of code.
1 Like
What are you expecting it to do? p1.myfunc.reset_mock()
is how you’d call it, but that just resets the state of the mock. I.e.,
p1.myfunc = MagicMock(return_value="Mock Return")
print(p1.myfunc.call_count) # "0"
print(p1.myfunc()) # "Mock Return"
print(p1.myfunc.call_count) # "1"
p1.myfunc.reset_mock()
print(p1.myfunc.call_count) # "0"
I was expecting p1.myfunc.reset_mock()
to reset the return and producing identical output of the code in OP, i.e.
from unittest.mock import MagicMock
class Person:
def __init__(self, name):
self.name = name
def myfunc(self):
return self.name
p1 = Person("John")
print(p1.myfunc()) # "John"
p1.myfunc = MagicMock(return_value="Mock Return")
print(p1.myfunc()) # "Mock Return"
p1.myfunc.reset_mock(return_value=True)
print(p1.myfunc()) # "John"
But I guess that’s not how reset_mock()
works. p1.myfunc()
is still a mock after reset_mock()
and not the actual function call