Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Many pytest fixtures vs. one large "container" fixture

Tags:

We have a large python project which is tested using pytest, currently with unittest style classes, and we started migrating it to module-based, function style tests.

We are having a debate whether we should:

  1. Split our large test base-class to many small, independent pytest fixtures; or
  2. Maintain a one large fixture which lazily imports all other fixtures.

Pros for many fixtures:

  • Modular and probably easy to maintain
  • Each test only uses what it needs

Pros for one large fixture:

  • Less boilerplate code, each test only has one extra keyword arg

What should we do? Any opinions are welcome as long as they are explained. Thanks :)

like image 894
Tzach Avatar asked Dec 16 '18 07:12

Tzach


1 Answers

The use of specific fixtures has a lot of advantages over the big one. Thanks to this pytest gained its popularity.

  1. Different fixtures can reproduce various mutually exclusive states of the system under test. This is useful when you want to test various cases of your system behavior. Single fixture does not give such flexibility.
  2. Pytest allows you to flexibly assemble a call to a fixture, when one fixture uses the results of the execution of another. Decomposition is an effective programming pattern and tests are no exception.
  3. Fixtures in pytest can be parameterized, this is a very useful functionality, but its application will be impossible if you make one big fixture for all tests.
  4. Conftest.py is a directory specific in pytest. So fixtures in pytest can be global (located in conftest), local (located inside the test module) and intermediate (located in conftest at the package level). This allows you to reuse common code, while not losing flexibility in specific cases.
  5. Fixtures have scope (function, class, module, session), which gives additional flexibility.

The root idea of ​​the pytest framework is the use of fixtures at those levels where necessary. This is a big advantage over the xUnit style, but if you don’t use these advantages, the transition to pytest makes no sense.

like image 59
Andrey Glazkov Avatar answered Oct 11 '22 17:10

Andrey Glazkov