0

I want to patch an assignment template_tag but that question is not Django specific.

Here is what I'm trying to achieve:

@patch('the_caller_path.my_function', _my_mock)
class MyTests(...):

And the "obvious" error I'm getting:

AttributeError: <module 'the_caller_path' from '...'> does not have the attribute 'my_function'

The problem is that the_caller dynamically calls my_function.


As expected, using the path were the function is declared has no effect:

@patch('the_real_path.my_function', _my_mock)
class MyTests(...):

my_function is not patched.


How can I globally patch a function?

6
  • My guess is that patch.object is the way to handle these cases, but you should provide a minimal runnable example or I can do just some speculations. I've already filed an answer on similar topic at Django/Python unittesting: How to Force Exception of Try/Except Block but I'm not sure if I can adapt it to your case. Commented Feb 17, 2015 at 8:02
  • BTW, is better if you file an example that fit exactly your real case otherwise we can fall in a XY Problem. Commented Feb 17, 2015 at 8:13
  • can you also show how exactly is your caller calling 'my_function'? Commented Feb 17, 2015 at 9:48
  • Thanks for the comments. I've found a workaround for now. This is not an XY problem; changing the code in the function directly gets these tests to pass. @user3012759, I'll look into it again when I have time - the caller is something in the Django template rendering code. Commented Feb 18, 2015 at 2:51
  • 1
    you can try to go through the Django code and see what's the exact context for the call, this may help you with the correct namespace to patch... but still may not be quite obvious, depending how obfuscated the templating code is - and i expect it to be quite obfuscated Commented Feb 18, 2015 at 10:08

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.