Skip to content

Commit

Permalink
Log an error or abort startup if apps cannot be imported.
Browse files Browse the repository at this point in the history
  • Loading branch information
Alexander Ivanov committed Feb 23, 2018
1 parent 5e8a1b7 commit 57eb1d8
Show file tree
Hide file tree
Showing 6 changed files with 58 additions and 5 deletions.
13 changes: 8 additions & 5 deletions django_telegrambot/apps.py
Original file line number Diff line number Diff line change
Expand Up @@ -178,7 +178,7 @@ def ready(self):

bot.more_info = webhook_info
logger.info('Telegram Bot <{}> setting webhook [ {} ] max connections:{} allowed updates:{} pending updates:{} : {}'.format(bot.username, webhook_info.url, webhook_info.max_connections, real_allowed, webhook_info.pending_update_count, setted))

except InvalidToken:
logger.error('Invalid Token : {}'.format(token))
return
Expand Down Expand Up @@ -208,7 +208,7 @@ def ready(self):

logger.debug('Telegram Bot <{}> set as default bot'.format(DjangoTelegramBot.bots[0].username))

def module_exists(module_name, method_name, execute):
def module_imported(module_name, method_name, execute):
try:
m = importlib.import_module(module_name)
if execute and hasattr(m, method_name):
Expand All @@ -218,16 +218,19 @@ def module_exists(module_name, method_name, execute):
logger.debug('Run {}'.format(module_name))

except ImportError as er:
logger.debug('{} : {}'.format(module_name, repr(er)))
return False
if settings.DJANGO_TELEGRAMBOT.get('STRICT_INIT'):
raise er
else:
logger.error('{} : {}'.format(module_name, repr(er)))
return False

return True

# import telegram bot handlers for all INSTALLED_APPS
for app_config in apps.get_app_configs():
if module_has_submodule(app_config.module, TELEGRAM_BOT_MODULE_NAME):
module_name = '%s.%s' % (app_config.name, TELEGRAM_BOT_MODULE_NAME)
if module_exists(module_name, 'main', True):
if module_imported(module_name, 'main', True):
logger.info('Loaded {}'.format(module_name))

num_bots=len(DjangoTelegramBot.__used_tokens)
Expand Down
Empty file added tests/test_app/__init__.py
Empty file.
1 change: 1 addition & 0 deletions tests/test_app/telegrambot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
print("Import successful")
48 changes: 48 additions & 0 deletions tests/test_apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import logging

from django.apps.registry import Apps
from django.test import TestCase
from django_telegrambot.apps import DjangoTelegramBot
import mock

logging.basicConfig(level=logging.INFO)


# Need to mock some of the Telegram Bot's methods with dummy values to make
# sure that the initialisation completes with mock credentials.
@mock.patch('telegram.bot.Bot.delete_webhook', lambda bot: None)
@mock.patch('telegram.bot.Bot.username', 'mock_bot')
@mock.patch('django_telegrambot.apps.DjangoTelegramBot.ready_run', False)
@mock.patch('django_telegrambot.apps.logger')
class TestDjangoTelegramBot(TestCase):

def setUp(self):
self.app = DjangoTelegramBot.create('django_telegrambot')

@mock.patch('django_telegrambot.apps.apps',
Apps(installed_apps=('tests.test_app',)))
def test_good_app_loading(self, log):
"""Normal initialisation - should complete without error messages."""
self.assertFalse(DjangoTelegramBot.ready_run)
self.app.ready()
self.assertEquals(log.error.call_count, 0)
self.assertTrue(DjangoTelegramBot.ready_run)

@mock.patch('django_telegrambot.apps.apps',
Apps(installed_apps=('tests.test_bad_app',)))
def test_bad_app_loading(self, log):
"""If a telegrambot.py module in some of the apps contains a mistake,
an error message should be loaded."""
self.app.ready()
self.assertEquals(log.error.call_count, 1)

@mock.patch('django_telegrambot.apps.apps',
Apps(installed_apps=('tests.test_bad_app',)))
@mock.patch.dict('django_telegrambot.apps.settings.DJANGO_TELEGRAMBOT',
STRICT_INIT=True)
def test_bad_app_loading_strict(self, _):
"""With STRICT_INIT set to true in the DJANGO_TELEGRAMBOT settings, the
app must not start if the telegrambot.py files are not imported
successfully."""
with self.assertRaises(ImportError):
self.app.ready()
Empty file added tests/test_bad_app/__init__.py
Empty file.
1 change: 1 addition & 0 deletions tests/test_bad_app/telegrambot.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
raise ImportError()

0 comments on commit 57eb1d8

Please sign in to comment.