在模块内部模拟库

时间:2016-07-20 11:06:49

标签: python unit-testing

我正在尝试测试模块内的函数。一个简化的例子。

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)
在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

该示例不会模拟模块内部的get_action。相反,它使用模块中的实际方法。

0 个答案:

没有答案