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.
More on Testing, services & metrics
Why should automation scripts have tests at all?BeginnerHow does pytest discover and run tests?BeginnerWhy does pytest use plain `assert` instead of `assertEqual`?BeginnerWhat are pytest fixtures, and what scopes exist?IntermediateWhat built-in fixtures do you use most?IntermediateHow does `@pytest.mark.parametrize` work?Beginner