Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
ENH: change unittest to verify ImportError is raised when required de…
…pendencies are missing
  • Loading branch information
chilin0525 committed Apr 5, 2025
commit 5f5ab6a33481f5509dfe620e5737f91671ee2709
20 changes: 6 additions & 14 deletions pandas/tests/test_downstream.py
Original file line number Diff line number Diff line change
Expand Up @@ -190,28 +190,20 @@ def test_yaml_dump(df):
@pytest.mark.parametrize("dependency", ["numpy", "dateutil"])
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we monkeypatch _hard_dependencies with a fake module and test that instead? I'm worried about this test having side effects by modifying sys.modules

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed, modifying sys.modules directly is not an ideal approach.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in 5f5ab6a. Instead of monkeypatching _hard_dependencies, I mocked builtins.__import__ to raise an ImportError when a specific dependency is imported. This approach was chosen because reloading pandas with importlib.reload() resets the module, which would override any monkeypatch applied to _hard_dependencies.

If there's a better approach, I'm happy to consider it.

def test_missing_required_dependency(monkeypatch, dependency):
# GH#61030
# test pandas raises appropriate error when a required dependency is missing
real_module = sys.modules.get(dependency)
original_import = __import__
mock_error = ImportError(f"Mock error for {dependency}")

def mock_import(name, *args, **kwargs):
if name == dependency:
raise mock_error
return importlib.import_module(name)
return original_import(name, *args, **kwargs)

try:
monkeypatch.setattr("builtins.__import__", mock_import)

if dependency in sys.modules:
del sys.modules[dependency]
monkeypatch.setattr("builtins.__import__", mock_import)

with pytest.raises(ImportError) as excinfo:
importlib.reload(importlib.import_module("pandas"))
with pytest.raises(ImportError) as excinfo:
importlib.reload(importlib.import_module("pandas"))

assert dependency in str(excinfo.value)
finally:
if real_module is not None:
sys.modules[dependency] = real_module
assert dependency in str(excinfo.value)


def test_frame_setitem_dask_array_into_new_col(request):
Expand Down
Loading