Interview Prep/Python for DevOps/Testing, services & metrics

How do you mock things with `unittest.mock`, and what is "patch where it is looked up"?

AdvancedConceptTesting, services & metrics
Answer

patch replaces a name for the duration of a test. You must patch the name in the module that uses it, not where it was defined.

# app/notify.py:  import requests  ...  requests.post(...)
@patch("app.notify.requests.post")
def test_slack(mock_post):
    mock_post.return_value.status_code = 200
    notify("hi")
    mock_post.assert_called_once()

If app/notify.py did from requests import post, you would patch app.notify.post. Use autospec=True so the mock enforces the real signature and catches wrong arguments.

All Python for DevOps questions Roadmap: Python for automation

More on Testing, services & metrics