在pytest中将函数作为参数传递

3
我需要在pytest参数化中将函数作为参数传递,并在测试函数内调用这些函数。有没有不使用eval的方法来实现?
我在conftest.py中定义了fixtures,它返回给helper.py中的类对象。 我需要从测试函数中调用helper.py中的类方法。我将类名.方法名作为参数传递。
  Eg: 
@pytest.mar.parametrize('fun', ['class_a.function1()','class_b.function2()'])
   def test1(class_a, class_b): 
       eval(fun)

eval()调用了classA.function1和classB.function2,其中class_a和Class_b是返回ClassA和ClassB对象的固定装置。
上述示例运行良好。但我需要用更好的方法替换eval。
有没有更好的方法来做到这一点? 非常感谢您的帮助!

2
将其作为fun传入,并调用为fun() - quamrana
2个回答

2
您可以传入任何函数,只是不要将它们用引号括起来。这是一个例子:
#!/usr/bin/env python3
import pytest


class ClassA:
    def function1(self):
        return "function1"


class ClassB:
    def function2(self):
        return "function2"


class_a = ClassA()
class_b = ClassB()


@pytest.mark.parametrize(
    "fun",
    [class_a.function1, class_b.function2],
)
def test1(fun):
    actual = fun()
    assert "function" in actual

1
在Python中,函数的行为与其他对象相同。因此,您可以将它们作为常规参数值使用(而无需在parametrize中调用它们)。
@pytest.mar.parametrize('fun', [class_a.function1, class_b.function2])
def test1(fun): 
    fun()  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接