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
