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])}
这是我的装饰器功能。我如何为此编写测试功能?有什么通用的方法吗?
最佳答案
当然...只要做一个(真的!)简单的函数并装饰它,看看它是否具有正确的行为。
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函数,然后确保在引发时从未调用过该实例。