Writing repeat code is likely one of the things you least enjoy. At least it’s the case for me.
We often need to reuse resources (like input data, database connections, shared objects and so on) across our Unit Tests.
Pytest fixtures are a powerful tool for writing modular and reusable tests.
Fixture scopes in Pytest control the lifetime of fixtures. They define how often a fixture gets created and destroyed.
Pytest provides four levels of fixture scopes:
-
Function (Set up and tear down once for each test function)
-
Class (Set up and tear down once for each test class)
-
Module (Set up and tear down once for each test module/file)
-
Session (Set up and tear down once for each test session i.e comprising one or more test files)
Choosing The Right Fixture Scope
Function Scope (default):
-
Use function scope when the fixture data should be isolated for each test function.
-
Recommended for fixtures that are quick to set up and tear down and don’t have side effects that affect other tests.
Class Scope:
-
Use class scope when you want to share fixture data across all test methods within a test class.
-
Useful for reducing setup and teardown overhead when multiple test methods need the same initial state.
-
Be cautious of potential side effects between test methods in the same class.
Module Scope:
-
Use module scope when the fixture data needs to be shared across all test functions within a module.
-
Suitable for reducing setup and teardown overhead when multiple test functions require the same initial state.
-
Be mindful of potential interactions between different modules.
Session Scope:
-
Use session scope when the fixture data needs to be shared across all test functions in the entire test session.
-
Useful for scenarios where setting up the data is time-consuming and it’s more efficient to reuse the same data.
-
Be aware of potential side effects and interactions, as changes made by one test could impact subsequent tests.