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?

2
  • Just in case: is it django settings you are talking about? Commented Nov 18, 2014 at 2:34
  • @alecxe not exactly, it's an App setting in v1.7, I just simplified it for SO. Commented Nov 18, 2014 at 2:35

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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):

1 Comment

I am curious if it would be too late to modify the settings since the module gets parsed before changing the settings?

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.