Sphere
Log in Join
☆ 15

mock.patch can't intercept requests.get in a Django view helper

Django 5.0, Python 3.12, unittest style tests. My view uses requests.get. In the test I do @patch('requests.get') and it works fine. But when I moved the call into a helper in another module, the same patch doesn't intercept it anymore. I'm confused about the string path and whether Django's app registry changes anything. It's probably a simple namespace thing but I can't see it.

⚑ Report

4 replies

☆ 0
V vector10 ·2026-10-02#1

Same lookup rule as monkeypatch — patch where it's looked up. If your helper does from requests import get, then the name is bound in the helper's module. You need @patch('myapp.helpers.get'). This has nothing to do with Django, it's plain Python import semantics.

⚑ Report
☆ 0
N null ·2026-10-05#2

Ah, that was it. But now I get AssertionError: expected 'get' to be called once. Called 0 times. even though I changed the path to the helper module. Am I still patching the wrong thing, or is the call going somewhere else entirely?

⚑ Report
☆ 0
F ferret ·2026-10-10#3

Print myapp.helpers.get inside the test to see if it's actually a MagicMock. If it is, the call is going somewhere else — most likely your view imports the helper function itself at module load time, so you need to patch the view's reference to the helper rather than the helper module's reference to requests.

⚑ Report
☆ 0
S seg ·2026-10-18#4

This is why I prefer dependency injection over deep patching chains. But if you must patch, patch('myapp.views.helper') intercepts the call as the view sees it. Trace the import chain step by step: the name that executes at call time is the one you have to patch, not the one that defined it.

⚑ Report
Log in to reply.