def test_optional_import(self): # Test excusing dependency and the logging behaviour logger = logging.getLogger(self.id()) with self.assertLogs(logger, level="DEBUG") as log_context: with optional_import("random_missing_lib", "fail to import", logger): # assume this library is not importable. import random_missing_lib # noqa: F401 log, = log_context.output self.assertIn("fail to import", log)
import unittest # importlib.resources is new in Python 3.7, and importlib.resources.files is # new in Python 3.9, so for Python < 3.9 we must rely on the 3rd party # importlib_resources package. try: from importlib.resources import files except ImportError: from importlib_resources import files from pyface.util._optional_dependencies import optional_import Image = None with optional_import("pillow", msg="PILImage not available due to missing pillow.", logger=logging.getLogger(__name__)): from PIL import Image from ..pil_image import PILImage IMAGE_PATH = os.fspath(files("pyface.tests") / "images" / "core.png") @unittest.skipIf(Image is None, "Pillow not available") class TestPILImage(unittest.TestCase): def setUp(self): self.pil_image = Image.open(IMAGE_PATH) def test_create_image(self): image = PILImage(self.pil_image)
def test_optional_import_reraise(self): # Test if the import error was about something else, reraise logger = logging.getLogger(self.id()) with self.assertRaises(ImportError): with optional_import("some_random_lib", "", logger): import some_random_missing_lib # noqa: F401