How to mock a helper method for errbot

151 Views Asked by At

I'm trying to complete my unit tests for the errbot plugin I am writing. Can anyone tell me how to mock out a helper method which is used by a botcmd method?

Example:

class ChatBot(BotPlugin):

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

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

How can I mock the mycommandhelper class when executing the my command class? In my case this class is performing some remote operations which should not be executed during unit testing.

2

There are 2 best solutions below

0
On

After a lot of fiddling around the following seems to work:

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

Although I believe using patch decorators would be cleaner.

3
On

A very simple/crude way would be to simply redefine the function that does the remote operations. Example:

def new_command_helper(cls):
    return 'Mocked!' 

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

If you'd like to have this method mocked throughout all of your tests, simply do it in the setUp unittest method.

def new_command_helper(cls):
    return 'Mocked!'

class Tests(unittest.TestCase):
    def setUp(self):
        ChatBot.mycommandhelper = new_command_helper