7
votes

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)

1

1 Answers

5
votes

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.