How to call objects' attributes in Pytest parametrize feature

2.3k Views Asked by At

I have some fixtures that just return the objects of a class. The objects contain a property of that class which I am trying to verify in pytest, so the code looks something like this:

from main import My_class
import pytest

@pytest.fixture()
def fixt1():
    object1 = My_class("atr1", "atr2")
    return object1

@pytest.fixture()
def fixt2():
    object2 = My_class("atr3", "atr4")
    return object2

@pytest.mark.parametrize('inputs, results',
                         [
                            (fixt1, 10.0),
                            (fixt2, 22.5)
                         ]
                         )
def test_fixts(inputs, results):
    assert inputs.price == results

This code will always return Attribute error:

AttributeError: 'function' object has no attribute 'price'

However, attempting to test these attributes with simple tests like this will work:

def test_simple(fixt1):
    assert fixt1.price == 10.0

Can I get some advice on this issue, as I couldn't find instructions on how to properly call objects attributes in parametrize anywhere?

Much appreciated!

1

There are 1 best solutions below

0
On BEST ANSWER

Fixtures cannot be used like functions - they have to be used as arguments in test functions or in other fixtures. In the parameters of mark.parametrize you can use normal functions instead:

def param1():
    return My_class("atr1", "atr2")

def param2():
    return My_class("atr3", "atr4")

@pytest.mark.parametrize('inputs, results',
                         [
                            (param1(), 10.0),
                            (param2(), 22.5)
                         ]
                         )
def test_fixts(inputs, results):
    assert inputs.price == results

Note that you can only use functions that can be executed at load time, because the mark.parametrize decorator is evaluated at load time, so it cannot depend on any run-time changes.