在Python3.6中,可以模拟内置的len()函数吗?在
我有一个类,它定义了一个依赖于len()函数的简单方法,如下所示:class MyLenFunc(object):
def is_longer_than_three_characters(self, some_string):
return len(some_string) > 3
我试图为这个方法编写一个单元测试,但是我无法模拟出len()函数而不产生错误。
以下是我目前所掌握的情况:
^{pr2}$
我发现了另一个SO-question/answerhere,这表明不可能模仿内置函数,因为它们是不可变的。然而,我发现了另外两个网站here和{a3},它们提出了不同的建议。我在上面的单元测试类中的尝试是直接从这些网站中的后者获得的(是的,我已经尝试了其中提到的其他技术)。所有这些都以相同的错误结束)。在
我得到的错误对于发布完整的内容来说是相当长的,所以我将剪去它的重复部分(您将看到它是从错误消息的最后部分递归而来的)。错误文本如下:ERROR: test_len_function_is_called (__main__.TestMyLenFunc)
----------------------------------------------------------------------
Traceback (most recent call last):
File "C:\Python36\Lib\unittest\mock.py", line 1179, in patched
return func(*args, **keywargs)
File "C:/Python/scratchpad/my_len_func_tests.py", line 16, in test_len_function_is_called
test_object.is_longer_than_three_characters(test_string)
File "C:\Python\scratchpad\my_len_func.py", line 3, in is_longer_than_three_characters
return len(some_string) > 3
File "C:\Python36\Lib\unittest\mock.py", line 939, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "C:\Python36\Lib\unittest\mock.py", line 949, in _mock_call
_call = _Call((args, kwargs), two=True)
File "C:\Python36\Lib\unittest\mock.py", line 1972, in __new__
_len = len(value)
...
(Repeat errors from lines 939, 949, and 1972 another 95 times!)
...
File "C:\Python36\Lib\unittest\mock.py", line 939, in __call__
return _mock_self._mock_call(*args, **kwargs)
File "C:\Python36\Lib\unittest\mock.py", line 944, in _mock_call
self.called = True RecursionError: maximum recursion depth exceeded while calling a Python object
----------------------------------------------------------------------
Ran 1 test in 0.004s
FAILED (errors=1)
提前致谢。在