代码之家  ›  专栏  ›  技术社区  ›  samfrances

使用自动指定的模拟跟踪调用顺序

  •  1
  • samfrances  · 技术社区  · 6 年前

    unittest.mock python 3.6中的模块。

    下面是一个玩具例子来说明这个问题:

    import unittest
    from unittest import mock
    
    
    def add(a, b):
        return a + b
    
    
    def div(a, b):
        return a / b
    
    
    def add_plus_div(a, b):
        return [add(a, b), div(a, b)]
    
    
    @mock.patch("__main__.add")
    @mock.patch("__main__.div")
    class MyTests(unittest.TestCase):
    
        def test_one(self, mock_div, mock_add):
    
            parent = mock.Mock()
            parent.attach_mock(mock_div, "div")
            parent.attach_mock(mock_add, "add")
    
            add_plus_div(1, 2)
    
            parent.assert_has_calls([
                mock.call.add(1, 2),
                mock.call.div(1, 2),
            ])
    
    
    if __name__ == '__main__':
        unittest.main()
    

    @mock.patch("__main__.add", autospec=True)
    @mock.patch("__main__.div", autospec=True)
    class MyTests(unittest.TestCase):
    
        def test_one(self, mock_div, mock_add):
    
            parent = mock.Mock()
            parent.attach_mock(mock_div, "div")
            parent.attach_mock(mock_add, "add")
    
            add_plus_div(1, 2)
    
            parent.assert_has_calls([
                mock.call.add(1, 2),
                mock.call.div(1, 2),
            ])
    

    AssertionError: Calls not found.
    Expected: [call.add(1, 2), call.div(1, 2)]
    Actual: []
    

    有人知道为什么自动指定会破坏某些东西,以及我如何跟踪一些自动指定的模拟函数的调用顺序吗?

    1 回复  |  直到 6 年前