liveBook · Manning

Pytest-mock

As explained in Data Pipelines with Apache Airflow, Second Edition

pytest-mock is a Python package that provides pytest integration and a convenience wrapper for mock objects.

pytest-mock is a Python package that integrates mocking with pytest through a small convenience wrapper around Python’s built-in mock package. Tests receive a mocker fixture as their main point of interaction. section 10.1.4

Use mocker.patch.object to replace an external operation at runtime. A test can return a predefined Airflow Connection instead of querying the Airflow metastore, allowing operator tests to run without external systems. section 10.1.4

A practical pytest-mock test workflow is:

  • Install the package with pip install pytest-mock. section 10.1.4
  • Accept mocker in the test function and patch the object’s external method. section 10.1.4
  • Execute the task, then inspect call_count or assert_called_with to verify behavior. section 10.1.4
  • Patch the method at the import location used by the code under test. section 10.1.4

Mocking a connection lookup

mocker.patch.object(MovielensHook, "get_connection", return_value=Connection(conn_id="test", login="airflow", password="airflow")) After executing MovielensPopularityOperator with conn_id="test", assert that the mocked method was called once with "test". section 10.1.4

pip install pytest-mock

Open the installation command before configuring pytest-mock in a test project. section 10.1.4

How Data Pipelines with Apache Airflow, Second Edition covers it

How deep it goes
Explains installation, fixture usage, runtime patching, return values, call assertions, and import-location concerns.
Examples
Demonstrates mocking MovielensHook.get_connection and checking call_count and assert_called_with after operator execution.
What it assumes
Assumes pytest and Python testing basics while requiring enough implementation knowledge to identify the correct patch target.
What you can do after
Diagnose and test operator behavior without connecting to unavailable external systems.
How it connects
Connects mocking with pytest, monkey patching, mock objects, Airflow operators, hooks, and the Airflow metastore.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Data Pipelines with Apache Airflow, Second Edition. The section links point to the parts of the book it draws on.