1

I am trying to test a function inside a module. A simplified example.

from my.cool.lib import MyHarvester

class TestMyHarvester(unittest.TestCase):
    def mock_getaction(self):
        # return a mocked group
        return {
            'id': '123-456-789',
            'name': 'My Existing Group'
        }
    @patch('ckan.logic.get_action', spec=mock_getaction)
    def test_add_package_groups(self, get_action):
        context = {}
        bh = MyHarvester()
        package_dict = bh._add_package_groups({}, 'mygroup', context)
        assert_equal(len(package_dict['groups']), 1)

in MyHarvester.py:

from ckan.logic import get_action

class MyHarvester():
    def _add_package_groups(self, package_dict, group_name, context):
        package_dict['groups'] = [] # just for demonstration
        group = get_action('group_show')(context, {'id': group_name})
        # I would catch a NotFound error here...
        if group:
            package_dict['groups'] = [ group ] # just for demonstration
        return package_dict

The example does not mock the get_action inside of the module. Instead, it uses the actual method in the module.

reggie
  • 3,523
  • 14
  • 62
  • 97
  • 1
    You're mocking where `get_action` **comes from**, not where it's **actually used**. You should have `@patch('my.cool.lib.get_action', ...`, per [where to patch](https://docs.python.org/3/library/unittest.mock.html#where-to-patch). – jonrsharpe Jul 20 '16 at 11:13
  • Ah, okay! Post it as a reply, please, and I'll accept it as answer. – reggie Jul 20 '16 at 11:17
  • There are many existing questions that give the same information, e.g. http://stackoverflow.com/a/16693949/3001761. I can't see another being useful in the long term. – jonrsharpe Jul 20 '16 at 11:19

0 Answers0