Patching in helper function not appled to instance

I am creating a test with unittest.mock.patch that looks something like this:

class TestService:
  def test_patched(self):
    service = Service()
    with patch.object(service, "_send_to_third_party") as patch_send:
      with patch.object(service, "_notify_listeners") as patch_notify:
        service.do_something()
        patch_send.assert_called_once()
        patch_notify.assert_called_once()

All that works fine, but I’d like to put those patches in a method so that I can reuse it across a bunch of tests. Like this:

class TestService:
  def _patched_service(self):
    service = Service()
    with patch.object(service, "_send_to_third_party") as patch_send:
      with patch.object(service, "_notify_listeners") as patch_notify:
        return service, patch_send, patch_notify

  def test_patched(self):
    service, patch_send, patch_notify = self._patched_service()
    service.do_something()
    patch_send.assert_called_once()
    patch_notify.assert_called_once()

This fails because it’s calling the real methods not the patched one.

To simplify, in the following test the third option fails, and I’m trying to wrap my head around why and if there’s a good way to do what I want?

from unittest.mock import patch

class ExampleClass:
    def __init__(self):
        self.value = 0

    def add(self, value):
        self.value += self._add(value)

    def subtract(self, value):
        self.value -= self._subtract(value)

    def what_is_my_value(self):
        return self.value

    def _add(self, value):
        return value

    def _subtract(self, value):
        return value

def patch_me(exa: ExampleClass):
    with patch.object(exa, '_add', return_value=99):
        with patch.object(exa, '_subtract', return_value=66):
            return exa

class TestPatchingWorks:

    def test_unpatched_works(self):
        exa = ExampleClass()
        exa.add(5)
        exa.subtract(2)
        assert exa.what_is_my_value() == 3

    def test_patching_works_with_patch_class(self):
        exa = ExampleClass()
        with patch.object(ExampleClass, '_add', return_value=30):
            with patch.object(ExampleClass, '_subtract', return_value=10):
                assert exa.what_is_my_value() == 0
                exa.add(5)
                assert exa.what_is_my_value() == 30
                exa.subtract(2)
                assert exa.what_is_my_value() == 20

    def test_patching_works_with_patch_instance(self):
        exa = ExampleClass()
        with patch.object(exa, '_add', return_value=40):
            with patch.object(exa, '_subtract', return_value=30):
                assert exa.what_is_my_value() == 0
                exa.add(5)
                assert exa.what_is_my_value() == 40
                exa.subtract(2)
                assert exa.what_is_my_value() == 10

    def test_patching_works_with_function(self):
        exa = ExampleClass()
        exa = patch_me(exa)
        assert exa.what_is_my_value() == 0
        exa.add(5)
        assert exa.what_is_my_value() == 99
        exa.subtract(2)
        assert exa.what_is_my_value() == 33

Well, the patches are unwound as soon as you exit from the with blocks, which happens when you return.

To not do that, you can make your patcher function a context manager, most easily with the contextlib.contextmanager decorator.

@contextlib.contextmanager
def _patched_service(self):
  service = Service()
  with patch.object(service, "_send_to_third_party") as patch_send:
    with patch.object(service, "_notify_listeners") as patch_notify:
      yield service, patch_send, patch_notify

...

def test_patched(self):
  with self._patched_service() as (service, patch_send, patch_notify):
    service.do_something()
    patch_send.assert_called_once()
    patch_notify.assert_called_once()

should do the trick.

The same thing in Pytest fixtures would be

@pytest.fixture
def patched_service():
  service = Service()
  with patch.object(service, "_send_to_third_party") as patch_send:
    with patch.object(service, "_notify_listeners") as patch_notify:
      yield service, patch_send, patch_notify

def test_patched(patched_service):
  (service, patch_send, patch_notify) = patched_service
  service.do_something()
  patch_send.assert_called_once()
  patch_notify.assert_called_once()

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật