Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Mock: Unexpected result with patch and return_value

Tags:

python

mocking

I'll post some code first so it's more clear.

My class:

from tools import get_knife, sharpen

class Banana(object):
    def chop(self):
        knife = get_knife()
        sharpen(knife)

My test:

from mock import patch, sentinel
from banana import Banana

class TestBanana(unittest.TestCase):

    @patch('banana.get_knife')
    @patch('banana.sharpen')
    def test_chop(self, get_knife_mock, sharpen_mock):
        get_knife_mock.return_value = sentinel.knife
        Banana().chop()
        sharpen_mock.assert_called_with(sentinel.knife)

This test will fail because sharpen_mock wasn't called with the return_value of get_knife_mock.

like image 490
Pickels Avatar asked Sep 05 '25 17:09

Pickels


1 Answers

Note that the decorators are applied from the bottom upwards. This is the standard way that Python applies decorators. The order of the created mocks passed into your test function matches this order.

http://www.voidspace.org.uk/python/mock/patch.html#nesting-patch-decorators

like image 155
Pickels Avatar answered Sep 07 '25 16:09

Pickels