【问题标题】:how to write test functions for decorators?如何为装饰器编写测试函数?
【发布时间】:2014-09-20 08:32:39
【问题描述】:
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])}

这是我的装饰器功能。我怎样才能为它写一个测试函数?有什么常用的方法吗?

【问题讨论】:

    标签: python python-2.7 testing python-decorators


    【解决方案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 函数,然后确保在引发时从未调用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-20
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-05-19
      相关资源
      最近更新 更多