0

我正在尝试完成我正在编写的 errbot 插件的单元测试。谁能告诉我如何模拟一个方法使用的辅助botcmd方法?

例子:

class ChatBot(BotPlugin):

    @classmethod
    def mycommandhelper(cls):
        return 'This is my awesome commandz'

    @botcmd
    def mycommand(self, message, args):
        return self.mycommandhelper()

执行我的命令类时如何模拟 mycommandhelper 类?在我的例子中,这个类正在执行一些在单元测试期间不应该执行的远程操作。

4

2 回答 2

0

一种非常简单/粗略的方法是简单地重新定义执行远程操作的功能。例子:

def new_command_helper(cls):
    return 'Mocked!' 

def test(self):
    ch_bot = ChatBot()
    ch_bot.mycommandhelper = new_command_helper
    # Add your test logic

如果您想在所有测试中模拟此方法,只需在setUpunittest 方法中进行。

def new_command_helper(cls):
    return 'Mocked!'

class Tests(unittest.TestCase):
    def setUp(self):
        ChatBot.mycommandhelper = new_command_helper
于 2017-01-25T10:46:30.540 回答
0

经过大量摆弄以下似乎可行:

class TestChatBot(object):
extra_plugin_dir = '.'

def test_command(self, testbot):
    def othermethod():
        return 'O no'
    plugin = testbot.bot.plugin_manager.get_plugin_obj_by_name('chatbot')
    with mock.patch.object(plugin, 'mycommandhelper') as mock_cmdhelper:
        mock_cmdhelper.return_value = othermethod()
        testbot.push_message('!mycommand')
        assert 'O no' in testbot.pop_message()

虽然我相信使用补丁装饰器会更干净。

于 2017-01-25T10:58:08.327 回答