Bird
0
0

Given this pytest code snippet, how many times will setup_db run?

medium📝 Predict Output Q13 of 15
PyTest - Fixtures
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
A1 time
B3 times
C2 times
D4 times
Step-by-Step Solution
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]
Quick Trick: Class scope runs once per test class [OK]
Common Mistakes:
MISTAKES
  • Counting runs per test method instead of per class
  • Confusing class scope with function scope
  • Ignoring multiple test classes

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes