这个DeprecationWarning的内容是什么("可调用的是None")?

时间:2016-01-10 02:30:28

标签: python python-unittest

我正在编写模块,并且我使用unittest在实际代码旁边编写单元测试。

有时候(几乎不是确定性的,似乎),像下面那样没有表达的函数返回一个值,用self.assertRaises(mymodule.MyEmptyException, myfunc())断言(其中self指的是{{1}的子类提出一个神秘的unittest.TestCase

以下是此类功能的一个示例:

DeprecationWarning

其相应的单元测试:

def insertn(self, items, lidex):
    """( z y x -- z b y x )
    add a list of items to the stack at the given index"""
    iter(items)
    for idx, obj in enumerate(items):
        self.insert(lidex, obj)
        lidex += 1

给出(例如):

def test_insertn_fail(self):
    """expect failure during multiple insertion"""
    self.assertRaises(mouse16.BadInternalCallException,
        stack.insertn([8, 4, 12], 16))
    with self.assertRaises(TypeError):
        stack.insertn(8, 16)

我认为使函数具有非./mousetesting.py:103: DeprecationWarning: callable is None 返回值可能会解决问题(即None)但我得到(例如):

return 0

因此====================================================================== ERROR: test_insertn_fail (__main__.CoreStack) expect failure during multiple insertion ---------------------------------------------------------------------- Traceback (most recent call last): File "./mousetesting.py", line 103, in test_insertn_fail stack.insertn([8, 4, 12], 16)) File "/usr/lib/python3.5/unittest/case.py", line 727, in assertRaises return context.handle('assertRaises', args, kwargs) File "/usr/lib/python3.5/unittest/case.py", line 176, in handle callable_obj(*args, **kwargs) TypeError: 'int' object is not callable ---------------------------------------------------------------------- 模块正在尝试调用函数的返回值...但是并不抱怨unittest 不是<\ n> None

我对Python的内部结构不太了解,无法理解这里发生了什么。我希望避免让我的测试以一种我不知道将来如何修复的方式中断,因为我忽略了callable

必须我的函数(但只有部分函数,​​而不是所有的时间吗?)返回一个(内存浪费)闭包或无意义的lambda表达式来避免这种情况?或者我应该制作一个检测测试是否正在进行的事情,而只有才能返回一个无操作的lambda?这似乎只是为了避免使用DeprecationWarning

1 个答案:

答案 0 :(得分:4)

您错误地使用了stack build。它必须为你调用测试函数 ,以便捕获异常:

self.assertRaises()

您正在传递self.assertRaises(mouse16.BadInternalCallException, stack.insertn, [8, 4, 12], 16) 调用的结果(它没有引发异常,但返回了stack.insertn()或整数),并且返回值不可调用。该方法的旧版本也接受None该参数,不再受支持,因此传递None时的弃用警告与整数相比。

更好的方法是使用None作为上下文管理器:

self.assertRaises()