【问题标题】:How to dynamically select a pytest fixture?如何动态选择 pytest 夹具?
【发布时间】:2021-06-16 16:12:59
【问题描述】:
import pytest


@pytest.fixture()
def fixture1(fixture_a):
    print('In fixture 1')
    <do>
    step a
    step b
    <end>
    return <some object1> 



@pytest.fixture()
def fixture2(fixture_b):
    print('In fixture 2')
    <do>
    step x
    step y
    <end>
    return <some object2> 


def decide():
    a = 1
    if a == 1:
        return fixture1: Object1
    else:
        return fixture2: Object2


def test_me():
    res = decide()
    assert res == Object

我有两个夹具 arg1 和 arg2,现在我想将其中一个夹具返回给测试,但这必须是基于条件的动态选择。如何做到这一点?

更新:fixture arg1 和 arg2 有一个依赖链,它们被用于不同的测试。

另外,决定函数需要在多个测试中使用。

【问题讨论】:

    标签: python python-3.x pytest


    【解决方案1】:

    我想这会有所帮助 - 让夹具构建器在某些情况下运行函数(将夹具 A、B 转换为函数):

    def arg1():
        print('In arg 1')
        return 1
    
    def arg2():
        print('In arg 2')
        return 2
    
    @pytest.fixture
    def env_builder():
        if condition:
            return arg1()
        else
            return arg2()
    
    def test_smth(env_builder):
       assert 2 == env_builder
    

    你的条件取决于你,os.getenv('environment'),或者可能在运行测试时定位 cli 参数

    【讨论】:

      【解决方案2】:

      您可以将arg1arg2 传递给test 并测试条件本身。

      def decide():
          a = 1
          if a == 1:
              return 1
          else:
              return 2
      
      def test_me(fixture1, fixture2):
          arg = decide()
          if arg == 1:
              assert fixture1 == 1
          else:
              assert fixture2 == 2
      

      【讨论】:

      • 但是我有多个测试需要这个。更新所有测试可能不是一个好主意。
      • 好的,我添加了一个单独的函数来返回值来决定 arg。如果有帮助,请告诉我。
      • 对不起,我已经更新了更接近我要解决的用例的问题代码。就我而言,我无法真正从夹具 1 和夹具 2 中提取逻辑。这些装置也使用其他装置,因此实现依赖链将是痛苦的。有没有办法在不接触fixture1和fixture2的情况下实现这一点,并且仍然能够根据特定条件将其中一个传递给测试?
      • 在我的回答中,我没有改变夹具中的任何东西。您只需在测试函数中传递这些夹具,然后返回值,而不是从决定函数返回函数对象。
      • 您已经从fixture1 和fixture1 中提取了逻辑,并将其用作decision 中的返回值。就我而言,在决定函数中实现夹具的逻辑将是一个痛苦的改变,因为存在夹具的依赖关系。
      猜你喜欢
      • 1970-01-01
      • 2015-06-27
      • 2020-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-03
      • 1970-01-01
      相关资源
      最近更新 更多