如何在python中重新定义函数? [英] How do I redefine functions in python?
问题描述
我在某个模块中有一个函数,我想在运行时重新定义(模拟)以进行测试。据我了解,函数定义不过是python中的赋值(模块定义本身就是一种正在执行的函数)。正如我所说,我想在测试用例的设置中执行此操作,因此要重新定义的功能存在于另一个模块中。这样做的语法是什么?
例如,'module1'是我的模块,'func1'是我的函数,在我的测试用例中,我尝试了此操作(没有成功):
I got a function in a certain module that I want to redefine(mock) at runtime for testing purposes. As far as I understand, function definition is nothing more than an assignment in python(the module definition itself is a kind of function being executed). As I said, I wanna do this in the setup of a test case, so the function to be redefined lives in another module. What is the syntax for doing this? For example, 'module1' is my module and 'func1' is my function, in my testcase I have tried this (no success):
import module1
module1.func1 = lambda x: return True
推荐答案
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")
很多模拟库都提供了进行这种模拟的工具,您应该对其进行研究,因为您可能会从中获得很多帮助。 m。
Lots of mocking libraries provide tools for doing this sort of mocking, you should investigate them as you will likely get a good deal of help from them.
这篇关于如何在python中重新定义函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!