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)
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.
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.
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.
Additionally, if you wish to display a list of fixtures for each test, try the --fixtures-per-test flag.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With