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

patching multiple module variables in all tests

我有一个包含两个模块变量的模块。我想为我的文件中的所有测试列出它们。最初我做了猴子补丁,但结果证明这是其他文件测试的问题,需要这些变量完好无损。 这是我目前想到的。这很可怕,但它有效。不过,我想做一些更 "by the book" 的事情(即为我修补的所有变量保留一个缩进的事情):

@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

With 语句具有多个上下文,跨越多行

显然你的行会变得很长,这里有一种方法可以分解它们,它仍然符合 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 在一个文件上面的代码片段上,它通过了。