3

I need to pass function as arguments in pytest parametrization. and need to call those functions inside test function. Is there any way to do it without using eval?

I have fixtures defined in conftest.py which returns object to classes(defined in helper.py) I need to call the class methods(in helper.py) from the test function. I am passing the class name.methodname as parameters.

  Eg: 
@pytest.mar.parametrize('fun', ['class_a.function1()','class_b.function2()'])
   def test1(class_a, class_b): 
       eval(fun)

eval() makes call to classA.function1 and classB.function2 where class_a and Class_b are fixtues that returns object of ClassA and ClassB Respectively.

The above example works fine. But I need to replace eval with something better.

Is there a better way to do this? Any help is appreciated!!!!

suryadevi
  • 77
  • 3

2 Answers2

2

You can pass in any function, just don't surround them with quotes. Here is an example:

#!/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
Hai Vu
  • 37,849
  • 11
  • 66
  • 93
1

In Python, functions behave like any other object. So you can use them as a regular parameter values (without calling them in parametrize)

@pytest.mar.parametrize('fun', [class_a.function1, class_b.function2])
def test1(fun): 
    fun()  
Kale Kundert
  • 1,144
  • 6
  • 18
Andrei Evtikheev
  • 331
  • 2
  • 12