In setUp() method of unittest I've setup some self variables, which are later referenced in actual tests. I've also created a decorator to do some logging. Is there a way in which I can access those self variables from decorator?
For the sake of simplicity, I'm posting this code:
def decorator(func): def _decorator(*args, **kwargs): # access a from TestSample func(*args, **kwargs) return _decorator class TestSample(unittest.TestCase): def setUp(self): self.a = 10 def tearDown(self): # tear down code @decorator def test_a(self): # testing code goes here
What would be the best way of accessing a (set in setUp()) from decorator?
If you want to access self (instanse where decorator is called from) you can use args[0] inside the decorator.
Writing your own decorator Any function can be used as a decorator. In this example the decorator is passed a function, and returns a different object. It simply swallows the function it is given entirely, and always returns 5.
You'll use a decorator when you need to change the behavior of a function without modifying the function itself. A few good examples are when you want to add logging, test performance, perform caching, verify permissions, and so on. You can also use one when you need to run the same code on multiple functions.
Since you're decorating a method, and self
is a method argument, your decorator has access to self
at runtime. Obviously not at parsetime, because there are no objects yet, just a class.
So you change your decorator to:
def decorator(func): def _decorator(self, *args, **kwargs): # access a from TestSample print 'self is %s' % self return func(self, *args, **kwargs) return _decorator
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With