Pickels
Pickels

Reputation: 34680

Python Mock: Unexpected result with patch and return_value

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.

Upvotes: 4

Views: 689

Answers (1)

Pickels
Pickels

Reputation: 34680

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

Upvotes: 4

Related Questions