如果没有通过,Pytest 会跳过寻找间接参数吗?

Pytest skip looking for indirect parameter if not passed?

假设我有 2 个文件 conftest.pytestcases.py。在 conftest.py 中,我有一个 @pytest.fixture 函数,它接受从 testcases.py 中的函数间接传递的参数(参见下面的示例)。

conftest.py

    @pytest.fixture()
    def func_in_conftest(passed_parameter):
        if passed_parameter == something:
           do_something()

testcases.py

      @pytest.mark.parametrize('passed_parameter', ['some_scenario'])
      def test1(func_in_conftest):
          some_testing
    
      

      def test2(func_in_conftest):
          some_testing2

当我在 test2 中未通过 passed_parameter 时,测试失败。我想知道是否有办法检查 passed_parameter 是否存在,如果不存在 -> 跳过 if 检查。

我尝试的另一个解决方案是在我不需要的测试中传递具有通用值的参数。它部分起作用,但如果我有依赖于另一个测试的测试,它们就会被跳过。我不明白为什么?示例(conftest.py 保持不变):

testcases.py

  @pytest.mark.parametrize('passed_parameter', ['all'])
  @pytest.mark.dependency()
  def test1(func_in_conftest):
      some_testing


  @pytest.mark.dependency(depends=["test1"])
  def test2(func_in_conftest):
      some_testing2

如果我将 @pytest.mark.parametrize(passed_parameter, [all]) 添加到 test2,它仍然会被跳过。我找不到解决这些问题的方法,所以我决定 post。 我正在使用 pytest 5.4.1 和 python 3.7.7

夹具参数设置在request.param,所以你可以检查它们是否存在,例如:


@pytest.fixture
def passed_parameter(request):
    if hasattr(request, 'param'):
        if request.param == 'one':
            yield request.param + '_changed'
        else:
            yield request.param * 2
    else:
        yield 42

@pytest.mark.parametrize('passed_parameter', ['one', 'two'], indirect=True)
def test1(passed_parameter):
    print(passed_parameter)
    # first test prints "one_changed", second prints "twotwo"

def test2(passed_parameter):
    print(passed_parameter)
    # prints 42

请注意,您不能将参数作为夹具参数传递,如果这是您的意图的话。传递给夹具的参数必须是其他(现有)夹具。
另请注意,在这种情况下,参数名称必须与灯具名称相匹配。

编辑:将示例更改为使用间接参数,以便能够产生与参数不同的夹具结果,并使其自包含。