In this lesson, you will learn:
- What are fixture scopes.
- The different fixture scopes available.
- How to refactor/optimize our Scrapli example using fixture scopes.
Introduction to Fixture Scopes
Pytest fixtures have scope. This scope controls how often the fixture is executed or, in other words, how often the setup and teardown of the fixture is performed.
Fixture scopes are ideal when we have an "expensive" fixture being requested multiple times, and we want all of the requesting tests to have access to the data the fixture yields or returns, but we want the fixture to be only be performed a limited number of times.
There are 5 types of scope that can be assigned to a fixture. These are:
function- This is the default scope. The fixture setup and teardown is performed for each test function that requests it.
class- The fixture setup and teardown is performed once per test class. Even if multiple test functions within the test classe, the fixture setup/teardown will only be performed once.
module- The fixture setup and teardown is performed once per module. If you have multiple test functions within a module requesting the same fixture, the fixture setup/teardown will be performed once.
package- The fixture setup and teardown is performed once per package. No matter how many tests request the fixture, the fixture setup/teardown will only be performed once.
session- The fixture setup and teardown is performed only once per session, regardless of the number of tests requesting it. A session is simply a single Pytest executed run.