I am trying to replace a method function during testing. The original method is complicated so I want to use a simple function to replace it in testing.
I have tried using mock library. But looks like it only modifies the object directly created in the test case. If some other functions inside the test case call the method, the method will not be replaced.
class1.py:
class Class1:
def foo(self):
#do a lot of calculation
return 1
class2.py:
from .class1 import Class1
class Class2:
def doo(self):
my_class1 = Class1()
return my_class1.foo()
test.py:
import mock
from .class1 import Class1
from .class2 import Class2
class Class1:
def foo(self):
# no calculation
return 2
@mock.patch.object(Class1, "foo")
def test_case(mock):
my_class2 = Class2()
assert my_class2.doo() == 2
What I am trying is to replace the foo() inside Class1 to the new foo() created in test.py. But because the Class1 object is created inside the Class2 object, the method is not replaced in this way.`
Aucun commentaire:
Enregistrer un commentaire