5

What is the difference between the following two tests? (if any)

** in 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)

One uses side_effect to preserve the original method while the other uses wraps to effectively do the same thing (or at least as far as I can tell).

Marcel Wilson
  • 3,842
  • 1
  • 26
  • 55

0 Answers0