Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pytest setup_class() after fixture initialization

I am experimenting with pytest and got stuck with some unobvious behavior for me. I have session-scope fixture and use it like this:

@pytest.mark.usefixtures("myfixt")
class TestWithMyFixt(object):
    @classmethod
    def setup_class(cls):
        ...

And when I run test I see that setup_class() comes before fixture myfixt() call. What is the purpose behind such a behaviour? For me, it should be run after fixture initialization because it uses fixture. How can I use setup_class() after session fixture initialization?

Thanks in advance!

like image 279
DuXeN0N Avatar asked Sep 28 '22 07:09

DuXeN0N


1 Answers

I found this question while looking for similar issue, and here is what I came up with.

  1. You can create fixtures with different scope. Possible scopes are session, module, class and function.
  2. Fixture can be defined as a method in the class.
  3. Fixture can have autouse=True flag.

If we combine these, we will get this nice approach which doesn't use setup_class at all (in py.test, setup_class is considered an obsolete approach):

class TestWithMyFixt(object):
    @pytest.fixture(autouse=True, scope='class')
    def _prepare(self, myfixt):
        ...

With such implementation, _prepare will be started just once before first of tests within the class, and will be finalized after last test within the class. At the time _prepare fixture is started, myfixt is already applied as a dependency of _prepare.

like image 172
MarSoft Avatar answered Oct 05 '22 05:10

MarSoft