此代码适用于python 3.5,但不适用于2.7。
我正在尝试使用包含mock.ANY
特殊对象的常规元组来匹配namedtuple。
try:
import unittest.mock as mock # python 3.5
except:
import mock # python 2.7
def test_datetime():
from collections import namedtuple
from datetime import datetime
A = namedtuple("A", ["a", "b"])
now = datetime.utcnow()
def foo(a):
a.bar(A(now, "b"))
a = mock.MagicMock()
foo(a)
a.bar.assert_called_once_with((mock.ANY, "b"))
if __name__ == "__main__":
print("Testing")
test_datetime()
如何在python 2.7中使它工作? 这是什么原因?
我无法更改解释器版本
修改:
进一步减少到
try:
import unittest.mock as mock # python 3.5
except:
import mock # python 2.7
from collections import namedtuple
from datetime import datetime
now = datetime.now()
A = namedtuple("A", ["a"])
(mock.ANY,)==A(now) # False in py2.7, true in py3.5
答案 0 :(得分:0)
出于某种原因,mock将元组和命名元素视为不同的对象。以下代码在python 2.7中传递给我
>>> def test_datetime():
... from collections import namedtuple
... from datetime import datetime
... A = namedtuple("A", ["a", "b"])
... now = datetime.utcnow()
... def foo(a):
... a.bar(A(now, "b"))
... a = mock.MagicMock()
... foo(a)
... a.bar.assert_called_once_with(A(mock.ANY, "b"))