|
| 1 | +"""Tests for lazy import behavior of optional dependencies.""" |
| 2 | + |
| 3 | +import sys |
| 4 | +import unittest |
| 5 | +from io import StringIO |
| 6 | +import importlib |
| 7 | +import pytest |
| 8 | + |
| 9 | +try: |
| 10 | + import semantic_kernel |
| 11 | + |
| 12 | + has_semantic_kernel = True |
| 13 | +except ImportError: |
| 14 | + has_semantic_kernel = False |
| 15 | + |
| 16 | + |
| 17 | +class TestLazyImports(unittest.TestCase): |
| 18 | + """Test lazy import behavior for optional dependencies.""" |
| 19 | + |
| 20 | + @pytest.mark.unittest |
| 21 | + @pytest.mark.skipif(has_semantic_kernel, reason="semantic-kernel is installed") |
| 22 | + def test_no_messages_during_module_import(self): |
| 23 | + """Test that no messages are printed when importing the main module.""" |
| 24 | + # Capture stderr to check for unwanted messages |
| 25 | + captured_stderr = StringIO() |
| 26 | + original_stderr = sys.stderr |
| 27 | + sys.stderr = captured_stderr |
| 28 | + |
| 29 | + try: |
| 30 | + # Test imports that would normally fail with missing dependencies |
| 31 | + # Since we can't easily control the dependency availability in the test environment, |
| 32 | + # we test the lazy import setup directly |
| 33 | + |
| 34 | + # This should not print any messages during setup |
| 35 | + _lazy_imports = {} |
| 36 | + _patch_all = [] |
| 37 | + |
| 38 | + def _create_lazy_import(class_name, module_path, dependency_name): |
| 39 | + """Create a lazy import function for optional dependencies.""" |
| 40 | + |
| 41 | + def lazy_import(): |
| 42 | + try: |
| 43 | + module = __import__(module_path, fromlist=[class_name]) |
| 44 | + cls = getattr(module, class_name) |
| 45 | + _patch_all.append(class_name) |
| 46 | + return cls |
| 47 | + except ImportError: |
| 48 | + raise ImportError( |
| 49 | + f"Could not import {class_name}. Please install the dependency with `pip install {dependency_name}`." |
| 50 | + ) |
| 51 | + |
| 52 | + return lazy_import |
| 53 | + |
| 54 | + # Setting up lazy imports should not print any messages |
| 55 | + _lazy_imports["SKAgentConverter"] = _create_lazy_import( |
| 56 | + "SKAgentConverter", |
| 57 | + "azure.ai.evaluation._converters._sk_services", |
| 58 | + "semantic-kernel", |
| 59 | + ) |
| 60 | + |
| 61 | + # Check that no messages were printed during setup |
| 62 | + stderr_output = captured_stderr.getvalue() |
| 63 | + self.assertEqual( |
| 64 | + stderr_output, |
| 65 | + "", |
| 66 | + "No messages should be printed during lazy import setup", |
| 67 | + ) |
| 68 | + |
| 69 | + finally: |
| 70 | + sys.stderr = original_stderr |
| 71 | + |
| 72 | + @pytest.mark.unittest |
| 73 | + @pytest.mark.skipif(has_semantic_kernel, reason="semantic-kernel is installed") |
| 74 | + def test_message_shown_when_accessing_missing_dependency(self): |
| 75 | + """Test that appropriate message is shown when accessing a class with missing dependency.""" |
| 76 | + # Test the __getattr__ functionality |
| 77 | + _lazy_imports = {} |
| 78 | + |
| 79 | + def _create_lazy_import(class_name, module_path, dependency_name): |
| 80 | + """Create a lazy import function for optional dependencies.""" |
| 81 | + |
| 82 | + def lazy_import(): |
| 83 | + try: |
| 84 | + # This should fail in most test environments |
| 85 | + module = __import__(module_path, fromlist=[class_name]) |
| 86 | + cls = getattr(module, class_name) |
| 87 | + return cls |
| 88 | + except ImportError: |
| 89 | + raise ImportError( |
| 90 | + f"Could not import {class_name}. Please install the dependency with `pip install {dependency_name}`." |
| 91 | + ) |
| 92 | + |
| 93 | + return lazy_import |
| 94 | + |
| 95 | + _lazy_imports["SKAgentConverter"] = _create_lazy_import( |
| 96 | + "SKAgentConverter", |
| 97 | + "azure.ai.evaluation._converters._sk_services", |
| 98 | + "semantic-kernel", |
| 99 | + ) |
| 100 | + |
| 101 | + def mock_getattr(name): |
| 102 | + """Mock __getattr__ function like the one in __init__.py""" |
| 103 | + if name in _lazy_imports: |
| 104 | + return _lazy_imports[name]() |
| 105 | + raise AttributeError(f"module has no attribute '{name}'") |
| 106 | + |
| 107 | + # This should raise ImportError directly |
| 108 | + with self.assertRaises(ImportError) as cm: |
| 109 | + mock_getattr("SKAgentConverter") |
| 110 | + |
| 111 | + # Check that the ImportError message contains the expected information |
| 112 | + error_message = str(cm.exception) |
| 113 | + self.assertIn("Could not import SKAgentConverter", error_message) |
| 114 | + self.assertIn("pip install semantic-kernel", error_message) |
| 115 | + |
| 116 | + @pytest.mark.unittest |
| 117 | + def test_getattr_with_non_existent_attribute(self): |
| 118 | + """Test __getattr__ behavior with non-existent attributes.""" |
| 119 | + _lazy_imports = {} |
| 120 | + |
| 121 | + def mock_getattr(name): |
| 122 | + """Mock __getattr__ function like the one in __init__.py""" |
| 123 | + if name in _lazy_imports: |
| 124 | + return _lazy_imports[name]() |
| 125 | + raise AttributeError(f"module has no attribute '{name}'") |
| 126 | + |
| 127 | + # Test with a non-existent attribute |
| 128 | + with self.assertRaises(AttributeError) as cm: |
| 129 | + mock_getattr("NonExistentClass") |
| 130 | + |
| 131 | + self.assertIn("has no attribute 'NonExistentClass'", str(cm.exception)) |
| 132 | + |
| 133 | + |
| 134 | +if __name__ == "__main__": |
| 135 | + unittest.main() |
0 commit comments