【问题标题】:Python unit testing overriding module level functionsPython单元测试覆盖模块级函数
【发布时间】:2013-04-24 10:01:01
【问题描述】:

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

我有点担心当我并行运行 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?

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    我不知道这是否是最好的方法,但我通常在测试中这样做时使用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
    

    如果这是测试中的常见操作,另一种方法是创建一个上下文管理器来执行此操作。

    【讨论】:

    • 这里的name_getter是什么?是TestNameGetter类所在的模块吗?
    • 是的,对不起,我以stackoverflow.com/questions/14956825/… 的答案为例。让我更新一下我的例子,使其更清晰。
    • 是的,当两个测试并行执行并命中相同的 name_getter 模块并且两者都需要不同的 raw_input 函数时会发生什么?这还能用吗?
    • 是的,它应该仍然有效。 Nose 使用单独的进程来并行执行测试,因此对其中一个功能/模块的更改不会影响另一个。
    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2015-04-25
    • 1970-01-01
    • 2013-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多