Python 单元测试覆盖模块级函数

标签 python python-2.7

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/

相关文章:

python - 在 Python 3 中为 urllib.request.urlopen 更改用户代理

python - python 2 和 3 中的 UTF-8 字符串

python - 使用 Apache 和 Mod_wsgi (windows) 部署现有的 Django 项目

python - 将 char 转换为日期时间 odoo 9

python-2.7 - hashlib 哈希器到底如何处理输入?

python - put_records() 仅接受 Kinesis boto3 Python API 中的关键字参数

python - 将对象属性链接到类或对象的最佳实践方法

Python函数返回最小的数字

python - 检查非索引列是否在 Pandas 中排序

python - 解码包含双黑斜杠的 Python Unicode 字符串