Skip to content

Commit

Permalink
Merge pull request #15 from alephyud/fail-on-initialization-error
Browse files Browse the repository at this point in the history
Fail on initialization error
  • Loading branch information
JungDev authored Feb 28, 2018
2 parents 5e8a1b7 + e6109c5 commit 3672963
Show file tree
Hide file tree
Showing 7 changed files with 62 additions and 5 deletions.
4 changes: 4 additions & 0 deletions README.rst
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,10 @@ And set your bots::
#certificate, must be set with location of your public key
#certificate.(More info at https://core.telegram.org/bots/self-signed )

'STRICT_INIT': True, # If set to True, the server will fail to start if some of the
# apps contain telegrambot.py files that cannot be successfully
# imported.

'BOTS' : [
{
'TOKEN': '123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11', #Your bot token.
Expand Down
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 3672963

Please sign in to comment.