Reputation: 20906
I have python unittest that has a decorated function..When I run the unittest with the decorator the same function is called twice.
How can I prevent it from running second time?
import unittest
from ast import literal_eval
from functools import wraps
def log_decorator(f):
@wraps(f)
def wrapper(self, *args, **kw):
print 'process start'
f(self, *args, **kw)
print 'process end'
return f(self, *args, **kw)
return wrapper
class Correct(object):
def __init__(self, points=None):
self.points = points
@log_decorator
def apply(self):
try:
result = {}
for position, points in self.points.items():
i, j = literal_eval(position)
intr = []
for point in points:
point['x1'] = point['x1'] * 1 + j
point['x2'] = point['x2'] * 1 + j
intr.append(point)
result[position] = intr
except Exception as e:
print 'Exception ==', e
return result
val = {'(0, 100)': [{
'x1': 100.0,
'x2': 200.0,
}]}
class TestPoints(unittest.TestCase):
def setUp(self):
self.coordinates1 = val
def test_points(self):
import pprint
print 'points before == ', pprint.pprint(val)
points = Correct(val).apply()
print 'points after == ', pprint.pprint(val)
if __name__ == '__main__':
unittest.main()
Result:-
points before == {'(0, 100)': [{'x1': 100.0, 'x2': 200.0}]}
None
process start
process end
points after == {'(0, 100)': [{'x1': 300.0, 'x2': 400.0}]}
None
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK
Upvotes: 0
Views: 161
Reputation: 20224
def log_decorator(f):
@wraps(f)
def wrapper(self, *args, **kw):
print 'process start'
f(self, *args, **kw)
print 'process end'
return f(self, *args, **kw)
return wrapper
This decorator function is wrong. You execute f
twice. One is between two print
and another is following return
.
print 'process start'
f(self, *args, **kw) # One
print 'process end'
return f(self, *args, **kw) # Two
Right way:
print 'process start'
result = f(self, *args, **kw) # Only once
print 'process end'
return result
Upvotes: 3