QA
Intermediate LevelPython

Why has pytest replaced standard unittest in modern engineering and how do modular pytest fixtures (@pytest.fixture) work?

❓ Interview Prompt: Compare legacy `unittest` (class-based, `self.assertEqual`) vs `pytest` (plain `assert`, `@pytest.fixture` dependency injection, yield teardown).

1. 'unittest' (Standard Library):

Legacy class-based framework requiring 'self.assertEqual()' assertion methods.

2. 'pytest' (Industry Standard):

•
Uses plain Python 'assert' statements with rich error introspection.
•
Fixtures ('@pytest.fixture'): Modular dependency injection framework supporting setup and 'yield' teardown cleanly!

Code Implementation Example

python
import pytest

@pytest.fixture
def db_connection():
    conn = {'status': 'CONNECTED'}
    yield conn # Control passes to test function!
    conn['status'] = 'CLOSED' # Teardown cleanup after test finishes!

def test_database_query(db_connection):
    assert db_connection['status'] == 'CONNECTED'
💡Writing modular test fixtures with setup and teardown in pytest.
🎯 Interview Key Takeaway

Use pytest with @pytest.fixture for modern, clean test suites with automated fixture teardown.

#pytest#unittest#Testing#Fixtures#Intermediate
Back to all Python Questions→

More Python Interview Questions

Beginner LevelPython

What is the Python Global Interpreter Lock (GIL) and how does it affect multi-threading?

Beginner LevelPython

What is the difference between a List, Tuple, Set, and Dictionary in Python?

Beginner LevelPython

Why are mutable default arguments (like def func(items=[])) dangerous in Python and how do you fix them?