4

Lets say I have a settings.py

value = 10

and I have a function like this with a decorator inside module a

import settings

@some_decorator(repeat=settings.value):
def do_work():
   print settings.value
   // prints 1
   ...

In unittest I am trying to patch the settings.value to 1 like this:

with patch('settings.value', new=1):
    do_work()

But the do_work function still gets repeated 10 times, I don't think the parameter of the decorator was patched because it gets executed before the unittest starts. How do I change this?

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
James Lin
  • 25,028
  • 36
  • 133
  • 233

2 Answers2

1

In short you cannot patch a value passed to a decorator parameter.

Anyway, your patch does not work because when do_work() is decorated settings.value was 10 and you cannot change it after that: it is not a variable that is resolved at run time but just a value (not mutable).

Of course, when do_work() is executed settings.value is 1 and then it prints 1 but the value used in decorated do_work() is still 10 and cannot change.

How you can work around it? If you cannot change the decorator I cannot see any way to do it, otherwise if repeat in the decorator is a callable, it will be resolved every time you call the decorated function.

houss
  • 7
  • 4
Michele d'Amico
  • 22,111
  • 8
  • 69
  • 76
0

Try overriding the settings?

https://docs.djangoproject.com/en/1.7/topics/testing/tools/#overriding-settings

@override_settings(LOGIN_URL='/other/login/')
def test_login(self):
John Mee
  • 50,179
  • 34
  • 152
  • 186
  • I am curious if it would be too late to modify the settings since the module gets parsed before changing the settings? – James Lin Nov 18 '14 at 02:50