我有 pytest 測驗,其結果可能取決于環境變數。我想測驗它們是否有這個環境變數的多個值。
我只想擁有一個設定此環境變數的夾具,但我希望能夠為每個測驗配置這些值,而不是每個夾具。
我該怎么做?
uj5u.com熱心網友回復:
試試這個conftest.py:
def pytest_addoption(parser):
parser.addoption("--env", action="store", default="sit")
@pytest.fixture(scope="session")
def env(request):
return request.config.getoption("--env")
--env=xxx使用命令列引數運行測驗:
python -m pytest foo_test.py --env=sit
在測驗中使用env變數
uj5u.com熱心網友回復:
它可以通過使用具有間接引數化的夾具來實作:
conftest.py
import pytest, os
@pytest.fixture(scope="function")
def my_variable(request, monkeypatch):
"""Set MY_VARIABLE environment variable, this fixture must be used with `parametrize`"""
monkeypatch.setenv("MY_VARIABLE", request.param)
yield request.param
test_something.py
import pytest, os
@pytest.mark.parametrize("my_variable", ["value1", "value2", "abc"], indirect=True)
class TestSomethingClassTests:
"""a few test with the same `parametrize` values"""
def test_aaa_1(self, my_variable):
"""test 1"""
assert os.environ["MY_VARIABLE"] == my_variable
def test_aaa_2(self, my_variable):
"""test 2"""
assert True
@pytest.mark.parametrize("my_variable", ["value2", "value5", "qwerty"], indirect=True)
def test_bbb(my_variable):
"""test bbb"""
assert os.environ["MY_VARIABLE"] == my_variable
它在 VSCode 中的外觀:

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/420507.html
標籤:
