Bird
0
0

In pytest, how can you initialize a resource once before all tests in a test class and clean it up after all tests have run?

hard🚀 Application Q9 of 15
PyTest - Test Organization
In pytest, how can you initialize a resource once before all tests in a test class and clean it up after all tests have run?
AUse pytest fixtures with scope='function'
BUse setup_method(self) and teardown_method(self) instance methods
CCreate __init__ method in the test class for initialization
DDefine @classmethod setup_class(cls) and teardown_class(cls) methods
Step-by-Step Solution
Solution:
  1. Step 1: Understand pytest class-level setup

    To run setup once per class, use classmethods named setup_class and teardown_class.
  2. Step 2: Analyze options

    setup_method runs before each test, __init__ is not used by pytest, and function-scoped fixtures run per test.
  3. Final Answer:

    Define @classmethod setup_class(cls) and teardown_class(cls) methods -> Option D
  4. Quick Check:

    Use setup_class/teardown_class for class-level setup [OK]
Quick Trick: Use setup_class and teardown_class for class-wide setup [OK]
Common Mistakes:
MISTAKES
  • Using setup_method which runs before each test
  • Adding __init__ method expecting pytest to call it
  • Using function-scoped fixtures for class-wide resources

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PyTest Quizzes