我没有使用类或测试用例,我只是使用 pytest 函数(想保持这种方式)。
这不起作用:
@pytest.fixture(scope="function")
def set_env():
with MonkeyPatch.context() as mp:
mp.setenv("VAR_ONE", "123")
mp.setenv("VAR_TWO", "test")
def test_blah(set_env):
print(os.environ["VAR_ONE"])
print(os.environ["VAR_TWO"])
这样做:
@pytest.fixture(scope="function")
def set_env(monkeypatch):
monkeypatch.setenv("VAR_ONE", "123")
monkeypatch.setenv("VAR_TWO", "test")
def test_blah(monkeypatch, set_env):
print(os.environ["VAR_ONE"])
print(os.environ["VAR_TWO"])
我希望避免像这样传递猴子补丁装置。我想我可以使用
MonkeyPatch
将其抽象到单个装置后面。我是否误解了 MonkeyPatch
作为上下文管理器?
整个 pytest 固定装置魔法并不能很好地配合类型提示,所以我真的想最小化我需要传递的固定装置(同时仍然不使用测试用例和类)。
您只需要
context
在单个函数中在有限的时间内执行和撤消更改。
import pytest, os
@pytest.fixture(scope="function")
def set_env(monkeypatch):
monkeypatch.setenv("VAR_ONE", "123")
monkeypatch.setenv("VAR_TWO", "test")
def test_one(set_env):
assert os.environ["VAR_ONE"] == "123"
assert os.environ["VAR_TWO"] == "test"
def test_two():
assert "VAR_ONE" not in os.environ
assert "VAR_TWO" not in os.environ