Skip to content

Commit

Permalink
Handle optional import where imported module raises exception on impo…
Browse files Browse the repository at this point in the history
…rt (#1192)

* Handle optional import where imported module raises exception on import. Log exception but don't raise
  • Loading branch information
jonmmease authored Sep 25, 2018
1 parent 79cdc1e commit 237b6e1
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 2 deletions.
6 changes: 6 additions & 0 deletions plotly/optional_imports.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@
from __future__ import absolute_import

from importlib import import_module
import logging

logger = logging.getLogger(__name__)
_not_importable = set()


Expand All @@ -23,3 +25,7 @@ def get_module(name):
return import_module(name)
except ImportError:
_not_importable.add(name)
except Exception as e:
_not_importable.add(name)
msg = "Error importing optional module {}".format(name)
logger.exception(msg)
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# A module that raises and exception on import
raise Exception("Boom!")
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import absolute_import

import sys
from unittest import TestCase

from plotly.optional_imports import get_module


Expand All @@ -22,3 +21,33 @@ def test_get_module_exists_submodule(self):
def test_get_module_does_not_exist(self):
module = get_module('hoopla')
self.assertIsNone(module)

def test_get_module_import_exception(self):
# Get module that raises an exception on import
module_str = ('plotly.tests.test_core.'
'test_optional_imports.exploding_module')

if sys.version_info.major == 3 and sys.version_info.minor >= 4:
with self.assertLogs('plotly.optional_imports', level='ERROR') as cm:
module = get_module(module_str)

# No exception should be raised and None should be returned
self.assertIsNone(module)

# Check logging level and log message
expected_start = ('ERROR:plotly.optional_imports:'
'Error importing optional module ' + module_str)

self.assertEqual(
cm.output[0][:len(expected_start)], expected_start)

# Check that exception message is included after log message
expected_end = 'Boom!'
self.assertEqual(
cm.output[0][-len(expected_end):], expected_end)
else:
# Don't check logging
module = get_module(module_str)

# No exception should be raised and None should be returned
self.assertIsNone(module)

0 comments on commit 237b6e1

Please sign in to comment.