我在某个模块中有一个函数,我想在运行时重新定义(模拟)以进行测试.据我所知,函数定义只不过是python中的赋值(模块定义本身就是一种正在执行的函数).正如我所说,我想在测试用例的设置中这样做,因此要重新定义的功能存在于另一个模块中.这样做的语法是什么?例如,'module1'是我的模块,'func1'是我的函数,在我的测试用例中我试过这个(没有成功):
import module1
module1.func1 = lambda x: return True
Run Code Online (Sandbox Code Playgroud)
Ned*_*der 11
import module1
import unittest
class MyTest(unittest.TestCase):
def setUp(self):
# Replace othermod.function with our own mock
self.old_func1 = module1.func1
module1.func1 = self.my_new_func1
def tearDown(self):
module1.func1 = self.old_func1
def my_new_func1(self, x):
"""A mock othermod.function just for our tests."""
return True
def test_func1(self):
module1.func1("arg1")
Run Code Online (Sandbox Code Playgroud)
许多模拟库提供了进行此类模拟的工具,您应该对它们进行调查,因为您可能会从中获得大量帮助.