Compare the different Pytest fixture scopes and discuss the tradeoffs associated with using broader scopes.

Python interview question for Advanced practice.

Answer

Pytest offers four main scopes: function (default), class, module, and session. Broader scopes like session or module significantly reduce test runtime by reusing expensive setup (e.g., a database container). However, they introduce the risk of shared state. If one test modifies the shared resource and fails to clean it up, subsequent tests may fail or exhibit flaky behavior, making debugging difficult.

Explanation

Session scope runs once per test execution process.

Related Questions