From 839df008ff42e82d4e8d3d56e6ecca68da5c4e85 Mon Sep 17 00:00:00 2001 From: Chelsea Lin Date: Tue, 28 Jan 2025 21:07:12 +0000 Subject: [PATCH 1/2] fix: bring back ModuleNotFoundError handler in pandas_backports.py --- db_dtypes/pandas_backports.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) 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) From c5f979f722b1b2fadfb9c3311a416c7ada063875 Mon Sep 17 00:00:00 2001 From: Chelsea Lin Date: Thu, 30 Jan 2025 21:11:36 +0000 Subject: [PATCH 2/2] add unit-test for import_default functions --- tests/unit/test_pandas_backports.py | 37 +++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 tests/unit/test_pandas_backports.py 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