【问题标题】:Extending the py.test fixture parameters扩展 py.test 夹具参数
【发布时间】:2017-08-24 14:15:18
【问题描述】:

是否可以扩展py.test fixture 中使用的参数?

例如,我将使用此代码生成一个简单的夹具来返回字母 abc

@pytest.fixture(params=['a', 'b', 'c'])
    def first_three_letters(self, request):
        return request.param

但是,如果我想再扩展三个字母 - 即 def - 我目前正在创建一个全新的装置

@pytest.fixture(params=['a', 'b', 'c', 'd', 'e', 'f'])
    def first_six_letters(self, request):
        return request.param

这感觉不符合DRY原则。有没有办法以可扩展的方式使用 py.test 固定装置?

我可以直接在测试中使用参数,但是两个fixture都有很多测试,所以会有很多包含@pytest.mark.parametrize的重复行,所以感觉更不干。

【问题讨论】:

    标签: python pytest fixtures


    【解决方案1】:

    简答

    还没有。

    长答案

    如果参数列表始终是静态的,则可以将它们组合为常量并作为参数传递:

    LETTERS = ['a', 'b', 'c', 'd', 'e', 'f']
    
    @pytest.fixture(params=LETTERS[:3])
    def first_three_letters(self, request):
        return request.param
    
    @pytest.fixture(params=LETTERS)
    def first_six_letters(self, request):
        return request.param
    

    但是,如果在调用pytest.fixture() 之前参数未知,则没有简单的解决方案。然而,there is a proposal 允许一个夹具从其他夹具“屈服”。下面是它的外观:

    @pytest.fixture(params=['a', 'b', 'c'])
    def first_three_letters(request):
        return request.param
    
    
    @pytest.fixture(params=['d', 'e', 'f'])
    def second_three_letters(request):
        return request.param
    
    
    @pytest.fixture(params=[
        pytest.fixture_request('first_three_letters'),
        pytest.fixture_request('second_three_letters'),
    ])
    def first_six_letters(request):
        return request.param
    

    【讨论】:

      猜你喜欢
      • 2019-02-02
      • 2014-03-08
      • 1970-01-01
      • 2018-10-07
      • 2018-01-30
      • 1970-01-01
      • 1970-01-01
      • 2017-09-02
      • 2015-04-01
      相关资源
      最近更新 更多