【问题标题】:How to use `fixture` and `parametrize` to set environmental variable for pytest tests如何使用`fixture`和`parametrize`为pytest测试设置环境变量
【发布时间】:2022-01-24 05:29:00
【问题描述】:

我有 pytest 测试,其结果可能取决于环境变量。我想测试它们的这个环境变量的多个值。

我只想拥有一个设置此环境变量的夹具,但我希望能够为每个测试配置这些值,而不是每个夹具。

我该怎么做?

【问题讨论】:

    标签: python python-3.x environment-variables pytest parametrized-testing


    【解决方案1】:

    在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 变量

    【讨论】:

      【解决方案2】:

      可以通过使用间接参数化的夹具来实现:

      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 中的样子:

      【讨论】:

      • 最好使用monkeypatch.setenv,这将在测试后恢复环境更改。这在您的情况下可能无关紧要,但通常是避免测试副作用的好习惯。
      • @MrBeanBremen 谢谢,我修改了答案,所以使用了monkeypatch.setenv。
      猜你喜欢
      • 2023-03-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-11
      • 2016-08-11
      • 2021-02-11
      • 2021-08-10
      相关资源
      最近更新 更多