使用装饰器多次执行nosetest运行unittest

时间:2017-12-15 01:07:06

标签: python

我有python unittest有一个装饰函数..当我用装饰器运行unittest时,同样的函数被调用两次。

如何阻止它第二次运行?

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

结果: -

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

1 个答案:

答案 0 :(得分:3)

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

这个装饰器功能错了。您执行f两次。一个在print之间,另一个在return之后。

print 'process start'
f(self, *args, **kw)  # One
print 'process end'
return f(self, *args, **kw)  # Two

更新

正确的方式:

print 'process start'
result = f(self, *args, **kw)  # Only once
print 'process end'
return result