Python 如何模拟errbot的助手方法
我正在尝试完成我正在编写的errbot插件的单元测试。谁能告诉我如何模拟Python 如何模拟errbot的助手方法,python,errbot,Python,Errbot,我正在尝试完成我正在编写的errbot插件的单元测试。谁能告诉我如何模拟botcmd方法使用的helper方法 例如: class ChatBot(BotPlugin): @classmethod def mycommandhelper(cls): return 'This is my awesome commandz' @botcmd def mycommand(self, message, args): return sel
botcmd
方法使用的helper方法
例如:
class ChatBot(BotPlugin):
@classmethod
def mycommandhelper(cls):
return 'This is my awesome commandz'
@botcmd
def mycommand(self, message, args):
return self.mycommandhelper()
在执行my命令类时,如何模拟mycommandhelper类?在我的例子中,这个类正在执行一些不应该在单元测试期间执行的远程操作。一个非常简单/粗糙的方法是简单地重新定义执行远程操作的函数。 例如: 如果您希望在所有测试中模拟此方法,只需在
setUp
unittest方法中进行
def new_command_helper(cls):
return 'Mocked!'
class Tests(unittest.TestCase):
def setUp(self):
ChatBot.mycommandhelper = new_command_helper
经过大量的摆弄,以下几点似乎奏效了:
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()
尽管我相信使用补丁修饰符会更干净。我认为这对“正常”单元测试有效,但我不知道这是否与errbot的testbot实现配合得很好,它提供了执行testbot.push_消息和testbot.pop_消息等操作的功能。好吧,testbot不会导入模拟类,而是插件的原始类和方法。如果您要导入该类,模拟它(通过直接更改其变量),然后导入TestBot,它将导入已修改的原始类。公平地说,这里的问题是该特定框架(errbot)提供了一个动态加载其插件的TestBot对象。为此,它使用了额外的插件,如我的示例中所示。因此,修改测试文件中的插件类不起作用,因为框架将加载未修改的原始插件类。我非常感谢你的帮助和努力。
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()