与Python unit testing code which calls OS/Module level python functions相关.在我的单元测试期间,我重载了一些 python 系统调用,以使我的测试能够驱动模块的不同路径。这种称为 Monkey Patch(在相关问题中)的技术用于隔离测试。
我有点担心当我并行运行 Python 测试时会发生什么,比如在“ Nose ”中。当两个测试并行运行并且都想模拟 os.path.exists 方法时会发生什么?
有没有办法在我的测试上下文中有选择地覆盖系统或模块函数?
以下面为例
fixture.py (say that is the module under test)
def my_func():
some_stuff
test_fixture.py (say this is my test case)
class MyTest(unittest.TestCase):
def test_mine(self):
fixture.my_func = my_new_func
fixture.execute_some_func_that_calls_my_func()
#What happens if another test is executing at the same time and accesses
#my_func I don't want it to start executing my_new_func?
最佳答案
我不知道这是否是最好的方法,但我通常在测试中使用 try ... finally
,以便在每次测试期间设置然后恢复更改。
一个简单的例子:
class TestRawInput(unittest.TestCase):
def test_raw_input(self):
orig_raw_input = raw_input
try:
raw_input = lambda _: 'Alice'
self.assertEquals(raw_input(), 'Alice')
finally:
raw_input = orig_raw_input
如果这是测试中的常见操作,另一种方法是创建一个上下文管理器来执行此操作。
关于Python 单元测试覆盖模块级函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16189054/