[pytest-dev] Fixture ordering and scopes

Floris Bruynooghe flub at devork.be
Fri Mar 16 13:35:58 EDT 2018


Bruno Oliveira <nicoddemus at gmail.com> writes:
>
> On Fri, Mar 16, 2018 at 5:42 AM Floris Bruynooghe <flub at devork.be> wrote:
>
>> Bruno Oliveira <nicoddemus at gmail.com> writes:
>>
> For example suppose you have two session scoped fixtures from different
> libraries which don't know about each other:
>
> * `log_setup` from `core_logging` setups the builtin logging module in a
> certain way (logs to a central server for instance).
> * `db_setup` from `db` configures the database for testing, and makes use
> of the builtin logging to log where the database is being created, etc.
>
> In my application tests, which use `core_logging` and `db`, I want to setup
> the fixtures in the correct order and the canonical way for that would be
> to define an autouse session-scoped fixture in my conftest.py:
>
> @pytest.fixture(scope='session', autouse=True)
> def setup_logging_and_db(log_setup, db_setup): pass
>
> So the order is important here, and leaving it undefined will require
> people to write this instead:
>
> @pytest.fixture(scope='session', autouse=True)
> def my_setup_logging(log_setup): pass
>
> @pytest.fixture(scope='session', autouse=True)
> def my_db_setup(my_setup_logging  ): pass
>
> While it works, it feels like unnecessary boilerplate.

I'm not sure you finished your example there.  I'm actually curious what
you'd do.

It is a great example, it really stretches the composability of
fixtures.  If someone where to ask me this though I think the only thing
I'd come up with is this:

import db

@pytest.fixture(scope='session', autouse=True)
def my_db(log_setup):
    return db.db_setup()  # This needs to do the right thing.

I'm actually pretty fine with this, fixtures are after all just a
convenient shortcut to do dependency injection into your test functions.
There's no reason that fixtures have be able to do everything we can
already do in a programming language.


But as much as I may not like it, I guess it is a good argument for
guaranteeing the behaviour you use.



More information about the pytest-dev mailing list