mirror of
				https://github.com/zulip/zulip.git
				synced 2025-11-04 05:53:43 +00:00 
			
		
		
		
	bots: Test get_config_info with giphy bot.
This involves both using the new `initialize` method for calling `get_config_info`, and refactoring the testing framework by adding a way for mocking this method.
This commit is contained in:
		@@ -12,9 +12,10 @@ import re
 | 
				
			|||||||
 | 
					
 | 
				
			||||||
GIPHY_TRANSLATE_API = 'http://api.giphy.com/v1/gifs/translate'
 | 
					GIPHY_TRANSLATE_API = 'http://api.giphy.com/v1/gifs/translate'
 | 
				
			||||||
 | 
					
 | 
				
			||||||
if not os.path.exists(os.environ['HOME'] + '/.giphy_config'):
 | 
					if not os.path.exists(os.path.join(os.path.dirname(os.path.realpath(__file__)), 'giphy.conf')):
 | 
				
			||||||
    print('Giphy bot config file not found, please set up it in ~/.giphy_config'
 | 
					    print('Giphy bot config file not found, please set it up in this bot\'s folder '
 | 
				
			||||||
          '\n\nUsing format:\n\n[giphy-config]\nkey=<giphy API key here>\n\n')
 | 
					          'with the name \'giphy.conf\'\n\nUsing format:\n\n[giphy-config]\nkey=<giphy'
 | 
				
			||||||
 | 
					          'API key here>\n\n')
 | 
				
			||||||
    sys.exit(1)
 | 
					    sys.exit(1)
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
@@ -33,6 +34,10 @@ class GiphyHandler(object):
 | 
				
			|||||||
            The bot responds also to private messages.
 | 
					            The bot responds also to private messages.
 | 
				
			||||||
            '''
 | 
					            '''
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def initialize(self, bot_handler):
 | 
				
			||||||
 | 
					        global config_info
 | 
				
			||||||
 | 
					        config_info = bot_handler.get_config_info('giphy')
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def handle_message(self, message, bot_handler, state_handler):
 | 
					    def handle_message(self, message, bot_handler, state_handler):
 | 
				
			||||||
        bot_response = get_bot_giphy_response(message, bot_handler)
 | 
					        bot_response = get_bot_giphy_response(message, bot_handler)
 | 
				
			||||||
        bot_handler.send_reply(message, bot_response)
 | 
					        bot_handler.send_reply(message, bot_response)
 | 
				
			||||||
@@ -42,13 +47,6 @@ class GiphyNoResultException(Exception):
 | 
				
			|||||||
    pass
 | 
					    pass
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					
 | 
				
			||||||
def get_giphy_api_key_from_config():
 | 
					 | 
				
			||||||
    config = SafeConfigParser()
 | 
					 | 
				
			||||||
    with open(os.environ['HOME'] + '/.giphy_config', 'r') as config_file:
 | 
					 | 
				
			||||||
        config.readfp(config_file)
 | 
					 | 
				
			||||||
    return config.get("giphy-config", "key")
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
 | 
					 | 
				
			||||||
def get_url_gif_giphy(keyword, api_key):
 | 
					def get_url_gif_giphy(keyword, api_key):
 | 
				
			||||||
    # Return a URL for a Giphy GIF based on keywords given.
 | 
					    # Return a URL for a Giphy GIF based on keywords given.
 | 
				
			||||||
    # In case of error, e.g. failure to fetch a GIF URL, it will
 | 
					    # In case of error, e.g. failure to fetch a GIF URL, it will
 | 
				
			||||||
@@ -78,7 +76,7 @@ def get_bot_giphy_response(message, bot_handler):
 | 
				
			|||||||
    # The bot will post the appropriate message for the error.
 | 
					    # The bot will post the appropriate message for the error.
 | 
				
			||||||
    keyword = message['content']
 | 
					    keyword = message['content']
 | 
				
			||||||
    try:
 | 
					    try:
 | 
				
			||||||
        gif_url = get_url_gif_giphy(keyword, get_giphy_api_key_from_config())
 | 
					        gif_url = get_url_gif_giphy(keyword, config_info['key'])
 | 
				
			||||||
    except requests.exceptions.ConnectionError:
 | 
					    except requests.exceptions.ConnectionError:
 | 
				
			||||||
        return ('Uh oh, sorry :slightly_frowning_face:, I '
 | 
					        return ('Uh oh, sorry :slightly_frowning_face:, I '
 | 
				
			||||||
                'cannot process your request right now. But, '
 | 
					                'cannot process your request right now. But, '
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -22,7 +22,9 @@ class TestGiphyBot(BotTestCase):
 | 
				
			|||||||
                       '(https://media4.giphy.com/media/3o6ZtpxSZbQRRnwCKQ/giphy.gif)' \
 | 
					                       '(https://media4.giphy.com/media/3o6ZtpxSZbQRRnwCKQ/giphy.gif)' \
 | 
				
			||||||
                       '[](/static/images/interactive-bot/giphy/powered-by-giphy.png)'
 | 
					                       '[](/static/images/interactive-bot/giphy/powered-by-giphy.png)'
 | 
				
			||||||
        # This message calls the `send_reply` function of BotHandlerApi
 | 
					        # This message calls the `send_reply` function of BotHandlerApi
 | 
				
			||||||
        with self.mock_http_conversation('test_1'):
 | 
					        with self.mock_config_info({'key': '12345678'}), \
 | 
				
			||||||
 | 
					                self.mock_http_conversation('test_1'):
 | 
				
			||||||
 | 
					            self.initialize_bot()
 | 
				
			||||||
            self.assert_bot_response(
 | 
					            self.assert_bot_response(
 | 
				
			||||||
                message = {'content': 'Hello'},
 | 
					                message = {'content': 'Hello'},
 | 
				
			||||||
                response = {'content': bot_response},
 | 
					                response = {'content': bot_response},
 | 
				
			||||||
 
 | 
				
			|||||||
@@ -52,6 +52,10 @@ class BotTestCase(TestCase):
 | 
				
			|||||||
        # type: () -> None
 | 
					        # type: () -> None
 | 
				
			||||||
        self.patcher.stop()
 | 
					        self.patcher.stop()
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    def initialize_bot(self):
 | 
				
			||||||
 | 
					        # type: () -> None
 | 
				
			||||||
 | 
					        self.message_handler.initialize(self.MockClass())
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    def check_expected_responses(self, expectations, expected_method='send_reply',
 | 
					    def check_expected_responses(self, expectations, expected_method='send_reply',
 | 
				
			||||||
                                 email="foo_sender@zulip.com", recipient="foo", subject="foo",
 | 
					                                 email="foo_sender@zulip.com", recipient="foo", subject="foo",
 | 
				
			||||||
                                 type="all"):
 | 
					                                 type="all"):
 | 
				
			||||||
@@ -87,6 +91,13 @@ class BotTestCase(TestCase):
 | 
				
			|||||||
        else:
 | 
					        else:
 | 
				
			||||||
            instance.send_reply.assert_called_with(message, response['content'])
 | 
					            instance.send_reply.assert_called_with(message, response['content'])
 | 
				
			||||||
 | 
					
 | 
				
			||||||
 | 
					    @contextmanager
 | 
				
			||||||
 | 
					    def mock_config_info(self, config_info):
 | 
				
			||||||
 | 
					        # type: (Dict[str, str]) -> Any
 | 
				
			||||||
 | 
					        self.MockClass.return_value.get_config_info.return_value = config_info
 | 
				
			||||||
 | 
					        yield
 | 
				
			||||||
 | 
					        self.MockClass.return_value.get_config_info.return_value = None
 | 
				
			||||||
 | 
					
 | 
				
			||||||
    @contextmanager
 | 
					    @contextmanager
 | 
				
			||||||
    def mock_http_conversation(self, test_name):
 | 
					    def mock_http_conversation(self, test_name):
 | 
				
			||||||
        # type: (str) -> Any
 | 
					        # type: (str) -> Any
 | 
				
			||||||
 
 | 
				
			|||||||
		Reference in New Issue
	
	Block a user