Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use pytest fixture in class constructor

I'm using pytest and trying to create object that supposed to be used in many classes of my project. I am trying to pass the object to one of the classes but the pycharm show me 'Unresolved reference 'custom_inst'.

Here is my code:

conftest.py:

@pytest.fixture(scope="function", autouse=True)
def fixture_example(request):
    custom_inst = FixtureClass()
    yield custom_inst
    custom_inst.do_something()

some class:

@pytest.mark.usefixtures('fixture_example')
class DummyClass(object):
    def __init__(self, arg1=None, arg2=None):
        self.arg1 = arg1
        self.arg2 = arg2
        self.custom_inst = fixture_example

how can I pass the instance 'custom_inst' to my DummyClass as class member?

Thanks.

like image 991
Gababi Avatar asked Oct 20 '25 01:10

Gababi


1 Answers

The problem is you try to mix pytest entity(fixture) and non-pytest entity(class DummyClass).

In this case DummyClass will never execute by pytest, because pytest runner collects and executes classes that start from "Test" keyword only. In other hand if you call DummyClass() directly, fixture_example will not execute because only pytest runner use it.

like image 168
Andrey Glazkov Avatar answered Oct 22 '25 04:10

Andrey Glazkov