diff --git a/db_dtypes/pandas_backports.py b/db_dtypes/pandas_backports.py index 8112c54..f8009ea 100644 --- a/db_dtypes/pandas_backports.py +++ b/db_dtypes/pandas_backports.py @@ -62,7 +62,10 @@ def import_default(module_name, force=False, default=None): return default name = default.__name__ - module = __import__(module_name, {}, {}, [name]) + try: + module = __import__(module_name, {}, {}, [name]) + except ModuleNotFoundError: + return default return getattr(module, name, default) diff --git a/tests/unit/test_pandas_backports.py b/tests/unit/test_pandas_backports.py new file mode 100644 index 0000000..eb68b6a --- /dev/null +++ b/tests/unit/test_pandas_backports.py @@ -0,0 +1,37 @@ +# Copyright 2024 Google LLC +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import unittest.mock as mock + +import db_dtypes.pandas_backports as pandas_backports + + +@mock.patch("builtins.__import__") +def test_import_default_module_found(mock_import): + mock_module = mock.MagicMock() + mock_module.OpsMixin = "OpsMixin_from_module" # Simulate successful import + mock_import.return_value = mock_module + + default_class = type("OpsMixin", (), {}) # Dummy class + result = pandas_backports.import_default("module_name", default=default_class) + assert result == "OpsMixin_from_module" + + +@mock.patch("builtins.__import__") +def test_import_default_module_not_found(mock_import): + mock_import.side_effect = ModuleNotFoundError + + default_class = type("OpsMixin", (), {}) # Dummy class + result = pandas_backports.import_default("module_name", default=default_class) + assert result == default_class