Bird
Raised Fist0
PyTesttesting~10 mins

Fixture scope (function, class, module, session) in PyTest - Test Execution Trace

Choose your learning style10 modes available
Test Overview

This test demonstrates how pytest fixtures with different scopes (function, class, module, session) are set up and used. It verifies that fixtures are created and destroyed according to their scope during test execution.

Test Code - pytest
PyTest
import pytest

@pytest.fixture(scope="function")
def func_scope():
    print("Setup function scope")
    yield
    print("Teardown function scope")

@pytest.fixture(scope="class")
def class_scope():
    print("Setup class scope")
    yield
    print("Teardown class scope")

@pytest.fixture(scope="module")
def module_scope():
    print("Setup module scope")
    yield
    print("Teardown module scope")

@pytest.fixture(scope="session")
def session_scope():
    print("Setup session scope")
    yield
    print("Teardown session scope")

class TestExample:
    def test_one(self, func_scope, class_scope, module_scope, session_scope):
        assert True

    def test_two(self, func_scope, class_scope, module_scope, session_scope):
        assert True

def test_three(func_scope, module_scope, session_scope):
    assert True
Execution Trace - 12 Steps
StepActionSystem StateAssertionResult
1pytest session starts and session_scope fixture setup runs onceSession scope fixture is set up, printed 'Setup session scope'—PASS
2module_scope fixture setup runs once for the moduleModule scope fixture is set up, printed 'Setup module scope'—PASS
3class_scope fixture setup runs once before TestExample testsClass scope fixture is set up, printed 'Setup class scope'—PASS
4test_one starts, func_scope fixture setup runsFunction scope fixture is set up, printed 'Setup function scope'assert True passesPASS
5test_one ends, func_scope fixture teardown runsFunction scope fixture is torn down, printed 'Teardown function scope'—PASS
6test_two starts, func_scope fixture setup runsFunction scope fixture is set up again, printed 'Setup function scope'assert True passesPASS
7test_two ends, func_scope fixture teardown runsFunction scope fixture is torn down, printed 'Teardown function scope'—PASS
8class_scope fixture teardown runs after all TestExample testsClass scope fixture is torn down, printed 'Teardown class scope'—PASS
9test_three starts, func_scope fixture setup runsFunction scope fixture is set up, printed 'Setup function scope'assert True passesPASS
10test_three ends, func_scope fixture teardown runsFunction scope fixture is torn down, printed 'Teardown function scope'—PASS
11module_scope fixture teardown runs after all tests in moduleModule scope fixture is torn down, printed 'Teardown module scope'—PASS
12session_scope fixture teardown runs after all tests in sessionSession scope fixture is torn down, printed 'Teardown session scope'—PASS
Failure Scenario
Failing Condition: Fixture setup or teardown fails or fixture is not found
Execution Trace Quiz - 3 Questions
Test your understanding
Which fixture scope causes the setup to run once per test function?
Aclass
Bfunction
Cmodule
Dsession
Key Result
Use fixture scopes to control how often setup and teardown code runs, improving test efficiency and clarity.

Practice

(1/5)
1. What does the function scope mean for a pytest fixture?
easy
A. The fixture runs once per entire test session.
B. The fixture runs once per test class.
C. The fixture runs once per test module.
D. The fixture runs once per test function.

Solution

  1. Step 1: Understand fixture scopes

    Pytest fixtures can have different scopes controlling how often they run.
  2. Step 2: Define function scope meaning

    Function scope means the fixture runs before each test function and tears down after it.
  3. Final Answer:

    The fixture runs once per test function. -> Option D
  4. Quick Check:

    function scope = runs per test function [OK]
Hint: Function scope means run before every test function [OK]
Common Mistakes:
  • Confusing function scope with class or module scope
  • Thinking function scope runs once per class
  • Assuming function scope runs once per session
2. Which of the following is the correct way to set a pytest fixture with module scope?
easy
A. @pytest.fixture(scope='module')
B. @pytest.fixture(scope='function')
C. @pytest.fixture(scope='class')
D. @pytest.fixture(scope='session')

Solution

  1. Step 1: Recall fixture scope syntax

    To set a fixture scope, use @pytest.fixture(scope='scope_name').
  2. Step 2: Match scope name for module

    The correct scope name for module is 'module'.
  3. Final Answer:

    @pytest.fixture(scope='module') -> Option A
  4. Quick Check:

    module scope syntax = scope='module' [OK]
Hint: Use scope='module' to run fixture once per file [OK]
Common Mistakes:
  • Using 'session' instead of 'module' for module scope
  • Forgetting to add scope parameter
  • Using incorrect quotes or misspelling scope
3. Given this pytest code snippet, how many times will setup_db run?
import pytest

@pytest.fixture(scope='class')
def setup_db():
    print('Setup DB')

class TestA:
    def test_1(self, setup_db):
        pass
    def test_2(self, setup_db):
        pass

class TestB:
    def test_3(self, setup_db):
        pass
medium
A. 1 time
B. 3 times
C. 2 times
D. 4 times

Solution

  1. Step 1: Understand class scope behavior

    Fixture with class scope runs once per test class, before any tests in that class.
  2. Step 2: Count test classes using the fixture

    There are two test classes: TestA and TestB, each uses setup_db fixture.
  3. Step 3: Calculate total runs

    setup_db runs once for TestA and once for TestB, total 2 times.
  4. Final Answer:

    2 times -> Option C
  5. Quick Check:

    class scope = once per class, 2 classes = 2 runs [OK]
Hint: Class scope runs once per test class [OK]
Common Mistakes:
  • Counting runs per test method instead of per class
  • Confusing class scope with function scope
  • Ignoring multiple test classes
4. Identify the error in this pytest fixture usage:
import pytest

@pytest.fixture(scope='modul')
def setup_env():
    pass

def test_example(setup_env):
    assert True
medium
A. Missing @pytest.mark.usefixtures decorator.
B. Typo in scope value causes fixture not to run.
C. Fixture function must return a value.
D. Test function missing parentheses.

Solution

  1. Step 1: Check fixture scope spelling

    The scope value 'modul' is misspelled; correct is 'module'.
  2. Step 2: Understand effect of typo

    Pytest will not recognize the scope and may default or error, causing fixture not to run properly.
  3. Final Answer:

    Typo in scope value causes fixture not to run. -> Option B
  4. Quick Check:

    Scope must be spelled correctly [OK]
Hint: Check scope spelling carefully to avoid errors [OK]
Common Mistakes:
  • Assuming fixture must return a value
  • Confusing fixture decorator with marker
  • Ignoring spelling errors in parameters
5. You want a pytest fixture to initialize a database connection once before all tests in multiple modules run, and close it after all tests finish. Which scope should you use and why?
hard
A. Use session scope to share across all tests in the run.
B. Use function scope to isolate each test.
C. Use module scope to share per file.
D. Use class scope to share per test class.

Solution

  1. Step 1: Understand the requirement

    The database connection should be initialized once before all tests in multiple modules and closed after all tests.
  2. Step 2: Match scope to requirement

    Session scope runs once per entire test session, perfect for setup/teardown across all modules.
  3. Final Answer:

    Use session scope to share across all tests in the run. -> Option A
  4. Quick Check:

    Session scope = once per test run [OK]
Hint: Session scope runs once for all tests in the run [OK]
Common Mistakes:
  • Choosing function or class scope which run too often
  • Using module scope which limits to one file
  • Not matching scope to resource lifetime
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard