Sobes.tech
Senior

Tell me about the scope of fixtures in pytest and the pitfalls when using session scope.

sobes.tech AI

Answer from AI

In pytest, fixtures can have different scope levels, which determine the lifetime and scope of the fixture:

  • function — the fixture is recreated for each test (default).
  • class — the fixture is created once per test class.
  • module — the fixture is created once per module (test file).
  • package — the fixture is created once per package.
  • session — the fixture is created once for the entire test session.

Using session scope is useful for expensive operations in terms of time or resources, such as setting up a test environment, connecting to a database, or starting external services.

Pitfalls when using session scope:

  • Fixture state persists between tests: if the fixture returns a mutable object, changes in one test can affect others, leading to hard-to-detect bugs.
  • Isolation difficulties: tests may become dependent on each other due to shared state.
  • Cleanup issues: teardown for session fixtures runs only once at the end, which can lead to resource or data accumulation.
  • Parallel execution: when using parallel test execution (e.g., pytest-xdist), session scope may behave unexpectedly, as the session can be local to each process.

It is recommended to carefully consider what to include in the session scope and to use additional mechanisms to clean up state between tests if necessary.