Python Tutorial 0/52 lessons ~6 min read Lesson 41
Testing with pytest
Testing with pytest in Production & Ecosystem: core concepts, worked examples, and practical guidance in one focused lesson.
Course progress0%
Focus
8 guided sections
Practice signal
Examples included
Career prep
Interview Q&A included
Introduction
pytest is the de-facto Python test framework — minimal boilerplate, powerful fixtures, parametrization, plugin ecosystem.
Understanding the topic
Core concepts to understand:
- Tests are functions starting with
test_. assert+ rich introspection.- Fixtures for setup/teardown.
@pytest.mark.parametrizefor table tests.
Syntax reference
Visual flow / code:
python
# test_math.pyimport pytestdef add(a, b): return a + b@pytest.mark.parametrize("a,b,want", [(1, 2, 3),(-1, 1, 0),(0, 0, 0),])def test_add(a, b, want):assert add(a, b) == want@pytest.fixturedef db():conn = connect()yield connconn.close()def test_user(db):assert db.query("users") is not None
Execution workflow
1Testing with pytest Workflow
1 / 4Tests are functions starting with test_
Tests are functions starting with test_.
Real-world use
pytest + pytest-cov + pytest-asyncio covers 95% of test needs. Most Python projects ship with pytest, mypy, and ruff in CI.
Best practices
- Write tests as you write code.
- Use fixtures for shared setup.
- Parametrize over duplicating tests.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionunittest vs pytest?+
Answer
unittest is the standard-library framework modelled on xUnit, using TestCase classes and self.assertEqual style methods. pytest uses plain functions and bare assert with rewritten, detailed failure output, plus fixtures, parametrization, and a large plugin ecosystem. pytest can also run existing unittest tests, so migration can be gradual.Follow-up
How does
@pytest.mark.parametrize reduce duplication?2BeginnerQuestionWhat's a fixture?+
Answer
A pytest fixture is a function decorated with
@pytest.fixture that provides setup, and optionally teardown, for tests. A test requests it by naming it as a parameter, and pytest injects the result. Fixtures have scopes (function, class, module, session), can depend on other fixtures, and use yield to run cleanup after the test.Follow-up
What is the purpose of
conftest.py?3IntermediateQuestionHow do you mock in pytest?+
Answer
pytest has no built-in mocking framework beyond the
monkeypatch fixture, which temporarily sets attributes, env vars, or dict items. Most people use unittest.mock (patch, MagicMock) or the pytest-mock plugin's mocker fixture. Patch the name where it is looked up, not where it is defined, and prefer fakes or dependency injection when mocks get too deep.Follow-up
Why does patching the wrong import path not work?
Summary
In summary: pytest = clean, powerful. Fixtures + parametrize = scalable tests.
Ready to mark this lesson complete?Track your journey across the entire course.