python - 在所有测试中修补多个模块变量

标签 python python-2.7 pytest

我有一个带有两个模块变量的模块。我想为我文件中的所有测试将它们导出。最初我做了猴子补丁,但结果证明这对于其他文件中的测试来说是一个问题,需要这些变量保持完整。
这是我目前想到的。这很可怕,但它有效。不过,我想做一些更“按书”的事情(即为我修补的所有变量保留一个缩进):

@pytest.yield_fixture(autouse=True)
def stub_module_variables():
    with patch.object(my_module, 'old_first_variable', new=new_first_variable):
        with patch.object(my_module, 'old_second_variable', new=new_second_variable):
            yield

最佳答案

but I feel like the proper way to do that would be something that keeps a single indent.



带有多个上下文的语句

您可以将多个语句放入一个 with
with patch.object(my_module, 'old_first_variable', new=new_first_variable), patch.object(my_module, 'old_second_variable', new=new_second_variable):
    # your code here, single indent

带有多个上下文的语句,跨越多行

显然你的台词可能会很长,这里有一种分解它们的方法仍然符合 PEP8
with patch.object(my_module, 'old_first_variable', new=new_first_variable), \
     patch.object(my_module, 'old_second_variable', new=new_second_variable), \
     patch.object(my_module, 'old_third_variable', new=new_third_variable):
    # Your code here, single indent
    pass

我跑了pep8在具有上述代码段的文件上,它通过了。

关于python - 在所有测试中修补多个模块变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37937632/

相关文章:

python - 仅比较文件/文件夹名称的目录,打印任何差异?

python - 有没有办法在不触摸 tkinter/python 的情况下按下按钮?

python - 如何根据值中存储的列表的第 n 个条目返回键的排序列表?

python - 如何安装 six.moves.xmlrpc_client?

django - 从Django View 中写入 Elasticsearch

python - 范围为 "class"的 Pytest fixture 在每个方法上运行

pytest - 仅抑制其他人代码的 pytest 警告

python - VTK中没有照明

python - 从字典值创建词云

python - 是否可以编写将模拟装饰器应用于函数的函数级 pytest fixture ?