Testing

pytest

Python's main testing framework: plain asserts, fixtures and parametrization.

What it is

pytest is an open source community project started by Holger Krekel. Tests are plain functions with a simple assert, no base classes or special methods. pytest rewrites assert to show a detailed diff on failure.

Its core strength is fixtures (setup and teardown of dependencies injected by argument name), parametrization (@pytest.mark.parametrize) and a plugin ecosystem (pytest-cov, pytest-asyncio, pytest-django, pytest-xdist).

It also runs unittest-style tests. pytest is used to test applications, FastAPI and Django APIs, as well as data and ML code.

Use it when

  • Any Python project: libraries, web APIs, scripts.
  • You need parametrization and reusable fixtures.
  • You want readable failure messages without extra code.

Avoid it when

  • A project where the team strictly sticks to unittest and does not want to change.
  • Tests are not in Python: use your language's tools.

Key concepts

Fixture
A function with @pytest.fixture that prepares a resource; a test receives it by argument name.
Parametrize
One test runs over a set of inputs.
Markers
Marks like skip, xfail and custom ones to select tests.
monkeypatch and tmp_path
Built-in fixtures for patching and temporary files.
conftest.py
A file with shared fixtures for a test directory.

Example

A parametrized test and a simple fixture.

Interview questions

  1. 1. What is a fixture and why?

    A function that prepares data or a resource for a test and cleans up after it if needed (via yield). A test just names it in arguments. scope sets the lifetime: function, module, session.

  2. 2. How do you parametrize a test?

    With the @pytest.mark.parametrize('a, b', [...]) decorator. pytest creates a separate test for each value pair with its own result.

  3. 3. How does pytest differ from unittest?

    Plain functions and assert instead of classes and assertEqual methods, powerful fixtures, parametrization and plugins. It also runs unittest tests.

  4. 4. How do you replace an external dependency?

    With the monkeypatch fixture or unittest.mock.patch. Patch network calls, environment variables and time so the test is isolated.

Interview questions from the bank

Logos belong to their owners and are used for identification only. Icons: Simple Icons (CC0), Devicon (MIT).