Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Package-scoped fixtures in pytest 2.3

Tags:

python

pytest

In the latest release of pytest, it is easy to create fixtures that are function, class, module or session-scoped like this:

@pytest.fixture(scope="module") 
def db():
     return DB()

That creates a fixture that is going to be called only once for each python module in which it is used.

But what about fixtures that need to be called once per python package ? (With nose, it can be done using setUp/tearDown methods in the __init__.py of the package)

like image 411
benselme Avatar asked Nov 06 '12 21:11

benselme


People also ask

What is scope in pytest fixture?

Fixtures include an optional parameter called scope, which controls how often a fixture gets set up and torn down. The scope parameter to @pytest. fixture() can have the values of function, class, module, or session. The default scope is function.

Can you import pytest fixtures?

Fixtures and their visibility are a bit odd in pytest. They don't require importing, but if you defined them in a test_*. py file, they'll only be available in that file. You can however put them in a (project- or subfolder-wide) conftest.py to use them in multiple files.

Can pytest fixtures use other fixtures?

A fixture can use multiple other fixtures. Just like a test method can take multiple fixtures as arguments, a fixture can take multiple other fixtures as arguments and use them to create the fixture value that it returns.

Which command can be used to show all available fixtures?

Additionally, if you wish to display a list of fixtures for each test, try the --fixtures-per-test flag.


1 Answers

For package or directory-level fixtures, you can declare a fixture in a conftest.py file in the directory where you need it, using scope='session'. The fixture will be instantiated once the first test in the package/directory uses it. Here is an example However, if the fixture function registers a finalizer, you might see it executing not directly after the last test in that directory. I think pytest could be made to support more eager teardown or introduce a "directory" scope if needed. Usually it's not a big problem if the teardown executes a little later as long as it doesn't execute too early :) Note also that apparently Jason intends to drop package-level setup/teardown support for nose

Anyway, if you have a need for more eager/exact pytest teardown, please feel free to open an issue.

like image 162
hpk42 Avatar answered Sep 22 '22 19:09

hpk42