I don’t want unit tests that fail because a website is down or Wi-Fi is off. unittest.mock.patch swaps the real call for a fake while the test runs.
import urllib.request
from unittest.mock import patch
def fetch_status(url):
with urllib.request.urlopen(url) as r:
return r.status
def test_fetch_status():
with patch("urllib.request.urlopen") as fake:
fake.return_value.__enter__.return_value.status = 503
assert fetch_status("https://example.com") == 503
fake.assert_called_once_with("https://example.com")
Inside the with block, urlopen is a MagicMock. You tell it what to return and afterwards you can ask how it was called. No network traffic happens, so the test is fast and you can easily check how your code handles a 503 that’s hard to get from a real server.
The __enter__ part looks odd but it’s needed because the code uses urlopen as a context manager. The mock follows the same chain your code does.
The classic mistake is patching the wrong name. You patch where the name is looked up, not where it was defined. If your module does from urllib.request import urlopen, it has its own reference, and you must patch "mymodule.urlopen". Patching urllib.request.urlopen then changes nothing, and your test quietly goes out to the internet.
Further reading: unittest.mock.patch, Where to patch