[TIP] Unable to mock.patch methods in __init__.py

Ratnadeep Debnath rtnpro at transifex.com
Sat Jul 14 13:40:17 PDT 2012

Hi Alfredo,

Thanks for your reply :)

On Sun, Jul 15, 2012 at 1:51 AM, Alfredo Deza <alfredodeza at gmail.com> wrote:
> Hi Ratnadeep
> On Sat, Jul 14, 2012 at 3:48 PM, Ratnadeep Debnath <rtnpro at transifex.com>
> wrote:
>> Hi,
>> I am trying to patch gettext(), ugettext(), etc. methods in
>> django/utils/translation/__init__.py (django.utils.translation). I am
>> trying something like below:
>> from mock import patch
>> def mock_gettext(s):
>>    # do something
>> @patch('django.utils.translation.gettext', mock_gettext)
>> def myview(request):
>>    ...
>>    ...
>> This is just not working. I see no reason why it should not. I
>> successfully patched `_trans` object from the same module above.
> That will not work as you are patching it in the wrong namespace. What you
> need to do here is to patch in
> the namespace of your view.
> So if your view is in the package: my_package.tests.test_my_view and in
> there you are importing gettext from django.utils.translation
> then what you need to patch it like this:
> @patch('my_package_name.tests.test_my_view.gettext', mock_gettext):
> def test_my_view
> Also, from your code example it doesn't seem like you where trying to patch
> on a test is this correct?

Yes, I am trying to patch gettext for the process_view() method in a
Django Middleware so that I can patch all subsequent calls to
gettext() from inside the view to get the desired result. What I am
trying to do is general for all the views. So, this rules out having
something like
@patch('my_package_name.tests.test_my_view.gettext', mock_gettext)

If I am able to patch the gettext() and similar methods in the
namespace of django.utils.translation, it will save me from writing a
lot of code.


More information about the testing-in-python mailing list