【问题标题】:Specify configuration settings per pytest test为每个 pytest 测试指定配置设置
【发布时间】:2019-10-18 23:09:51
【问题描述】:

我使用 https://github.com/theskumar/python-dotenv 管理 Python 应用程序的配置,并使用 pytest 进行测试。

对于一组特定的测试,我想要针对每个测试的自定义配置。现在我知道https://github.com/quiqua/pytest-dotenv,它使我能够为每个环境(产品/测试)设置一个配置,但我希望在每个测试的基础上获得更精细的粒度。到目前为止,我已经通过模拟包含我所有配置的 Config 对象来处理这个问题。这很麻烦,因为对于每个测试,我都需要为每个加载它的模块模拟​​这个 Config 对象。

理想情况下,我会有这样的东西:

def test_1(config):
    config.foo = 'bar'
    run_code_that_uses_config()

def test_2(config):
    config.foo = 'bleh'
    run_code_that_uses_config()

【问题讨论】:

    标签: python pytest


    【解决方案1】:

    我最终使用了monkeypatch 并采用了这种方法:

    from my_library.settings import Config
    
    @pytest.fixture
    def config(monkeypatch):
        monkeypatch.setattr(Config, 'foo', 'bar')
        return Config
    
    
    def test_1(config, monkeypatch):
        monkeypatch.setattr(config, 'foo', 'some value specific to this test')
        run_code_that_uses_config()
    
    

    使用monkeypatch,我能够通过 pytest 固定装置传递Config 对象,以创建默认值并为每个测试覆盖它。使用配置的代码能够获取更改。以前,我使用标准 mock 库中的 patch,但我必须修补每个查找配置的位置 (https://docs.python.org/3/library/unittest.mock.html#where-to-patch),这使得维护变得困难。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2022-11-04
      • 2017-09-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多