2013-04-24 97 views
6

Python unit testing code which calls OS/Module level python functions相关。在我的单元测试过程中,我重载了一些python系统调用,让我的测试驱动模块的不同路径。这种技术称为Monkey Patch(在相关问题中)用于隔离测试。Python单元测试覆盖模块级功能

我有点担心当我在“鼻子”中并行运行Python测试时会发生什么情况。当两个测试并行运行并且都想模拟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? 

回答

4

我不知道这是否是最好的方式,但我一般用try ... finally当我在做这在测试中,为了设置,则恢复每个过程中的变化测试。

A的这个简单的例子:

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 

另一种可能是创建上下文经理这样做,如果它在测试中常见的操作。

+0

这是什么name_getter?它是TestNameGetter类所在的模块吗? – 2013-04-24 10:34:18

+0

是的,对不起,我以http://stackoverflow.com/questions/14956825/python-unit-testing-code-which-calls-os-module-level-python-functions为例使用了答案。让我更新我的例子,使其更清晰。 – 2013-04-24 10:40:00

+0

雅所以当两个测试并行执行命中相同的name_getter模块时,如果两个想要不同的raw_input函数会发生什么?这是否仍然有效? – 2013-04-24 10:42:00