Namedtuple和tuple比较python2.7和python3.5之间的区别

时间:2017-04-24 14:36:35

标签: python python-2.7 python-3.x unit-testing mocking

此代码适用于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

1 个答案:

答案 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"))