将mock.patch.object 与wraps 和side_effect一起使用有什么区别吗?

Mar*_*son 7 python python-mock python-3.10

下面两个测试有什么区别? (如果有的话)

**在 python 3.10 中

import unittest
from unittest.mock import Mock, patch

class Potato(object):
    def spam(self, n):
        return self.foo(n=n)

    def foo(self, n):
        return self.bar(n)

    def bar(self, n):
        return n + 2

class PotatoTest(unittest.TestCase):
    def test_side_effect(self):
        spud = Potato()
        with patch.object(spud, 'foo', side_effect=spud.foo) as mock_foo:
            forty_two = spud.spam(n=40)
            mock_foo.assert_called_once_with(n=40)
        self.assertEqual(forty_two, 42)

    def test_wraps(self):
        spud = Potato()
        with patch.object(spud, 'foo', wraps=spud.foo) as mock_foo:
            forty_two = spud.spam(n=40)
            mock_foo.assert_called_once_with(n=40)
        self.assertEqual(forty_two, 42)
Run Code Online (Sandbox Code Playgroud)

一个用于side_effect保留原始方法,而另一个用于wraps有效地做同样的事情(或者至少据我所知)。