如何为装饰器编写测试函数?

时间:2014-07-29 02:30:28

标签: python python-2.7 testing python-decorators

from __future__ import print_function
    def nonnegative(f):
    def wrapper(xs):
        for x in xs:
            if x < 0:
                raise ValueError("{} < 0".format(x))
        return f(xs)
    return wrapper


    @nonnegative
    def inputs(xs):
        for x in xs:
            print(x)

inputs([1, 2, 3, 4])
inputs([-1])}

这是我的装饰功能。我怎么能为它编写测试函数?有什么共同的方式吗?

1 个答案:

答案 0 :(得分:2)

当然......只需制作一个(真的!)简单的功能并装饰它,看它是否有正确的行为。

import unittest

class TestNonNegative(unittest.TestCase):
    def setUp(self):
        super(TestNonNegative, self).setUp()

        self.fn = nonnegative(lambda x: x)

    def test_raises(self):
        with self.assertRaises(ValueError):
            self.fn([1, 2, 3, -1])

        # doesn't raise with all positive numbers
        expected = [1, 2, 3]
        self.assertEqual(self.fn(expected), expected)

如果您真的想要,您甚至可以使用mock.Mock实例而不是lambda函数,然后确保在提升时从未调用它。