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.

You can find the scripts and code for this lesson within the Pytest repo under the directory: 003_fixtures/004_scope.

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.

Scope Types

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.
Ready to Master Network Automation? Start Your Journey Today!
Our membership provides:
  • Full deep-dive course library (inc. Batfish, pyATS, Netmiko)
  • Code repositories inc. full course code, scripts and examples
  • 24x7 multi-vendor labs (Arista, Cisco, Juniper)
  • Private online community
  • Live monthly tech sessions
  • Access to tech session library

Join Now ➜
Close You've successfully subscribed to Packet Coders.
Close Success! Your account is fully activated, you now have access to all content.
Close Welcome back! You've successfully signed in.
Close Nearly there! To activate your account, please click the link in the email we just sent you.