gpt4 book ai didi

python-3.x - Monkeypatch setenv 值在 python unittest 中跨测试用例持续存在

转载 作者:行者123 更新时间:2023-12-05 01:32:46 25 4
gpt4 key购买 nike

我必须为我的测试用例设置不同的环境变量。

我的假设是一旦测试用例完成,monkeypatch 将从 os.environ 中删除环境变量。但事实并非如此。如何为每个测试设置和恢复环境变量?

这是我使用 monkeypatch 库简化的测试用例代码。

import os
import unittest
import time
from _pytest.monkeypatch import MonkeyPatch

class Test_Monkey_Patch_Env(unittest.TestCase):
def setUp(self):
print("Setup")

def test_1(self):
monkeypatch = MonkeyPatch()
monkeypatch.setenv("TESTVAR1", "This env value is persistent")

def test_2(self):
# I was expected the env TESTVAR1 set in test_1 using monkeypatch
# should not persist across test cases. But it is.
print(os.environ["TESTVAR1"])

def tearDown(self):
print("tearDown")


if __name__ == '__main__':
unittest.main()

Output:

Setup
tearDown
.Setup
This env value is persistent
tearDown
.
----------------------------------------------------------------------
Ran 2 tests in 0.001s

OK

最佳答案

这对@MaNKuR 给出的(正确)答案做了一些扩展。

它不能按预期工作的原因是在 pytest 中,它不是设计为以这种方式使用的——而是使用 monkeypatch fixture,它在离开测试范围时进行清理.要在 unittest 中进行清理,您可以在 tearDown 中进行清理,如答案所示 - 尽管我会使用不太具体的 undo为此:

from _pytest.monkeypatch import MonkeyPatch

class Test_Monkey_Patch_Env(unittest.TestCase):
def setUp(self):
self.monkeypatch = MonkeyPatch()

def tearDown(self):
self.monkeypatch.undo()

这会恢复使用 MonkeyPatch 实例所做的任何更改,而不仅仅是上面显示的特定 setenv 调用,因此更安全。

此外,还可以使用 MonkeyPatch 作为上下文管理器。如果您只想在一个或几个测试中使用它,这会派上用场。在这种情况下你可以这样写:

...
def test_1(self):
with MonkeyPatch() as mp:
mp.setenv("TESTVAR1", "This env value is not persistent")
do_something()

这种情况下的清理是在退出上下文管理器时完成的。

关于python-3.x - Monkeypatch setenv 值在 python unittest 中跨测试用例持续存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65390907/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com