Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify the _get_default_display_method tests using unittest.mock #3537

Merged
merged 7 commits into from
Oct 22, 2024
41 changes: 15 additions & 26 deletions pygmt/tests/test_figure.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@
Doesn't include the plotting commands which have their own test files.
"""

import importlib
from pathlib import Path
from unittest.mock import Mock, patch

import numpy as np
import numpy.testing as npt
Expand All @@ -14,12 +16,7 @@
from pygmt.figure import SHOW_CONFIG, _get_default_display_method
from pygmt.helpers import GMTTempFile

try:
import IPython

_HAS_IPYTHON = True
except ImportError:
_HAS_IPYTHON = False
_HAS_IPYTHON = bool(importlib.util.find_spec("IPython"))


def test_figure_region():
Expand Down Expand Up @@ -436,26 +433,18 @@ def test_disable_external_display(self, monkeypatch):
assert _get_default_display_method() == "none"

@pytest.mark.skipif(not _HAS_IPYTHON, reason="Run when IPython is installed")
def test_notebook_display(self, monkeypatch):
def test_notebook_display(self):
"""
Default display method is "notebook" when an IPython kernel is running.
"""

class MockIPython:
"""
A simple mock class to simulate an IPython instance.
"""

def __init__(self):
self.config = {"IPKernelApp": True}

# Mock IPython.get_ipython() to return a MockIPython instance.
mock_ipython = MockIPython()
monkeypatch.setattr(IPython, "get_ipython", lambda: mock_ipython)

# Default display method should be "notebook" when an IPython kernel is running.
assert _get_default_display_method() == "notebook"

# PYGMT_USE_EXTERNAL_DISPLAY should not affect notebook display.
monkeypatch.setenv("PYGMT_USE_EXTERNAL_DISPLAY", "false")
assert _get_default_display_method() == "notebook"
# Mock IPython.get_ipython() to return an object with a config attribute,
# so PyGMT can detect that an IPython kernel is running.
with patch(
"IPython.get_ipython", return_value=Mock(config={"IPKernelApp": True})
):
# Display method should be "notebook" when an IPython kernel is running.
assert _get_default_display_method() == "notebook"

# PYGMT_USE_EXTERNAL_DISPLAY should not affect notebook display.
with patch.dict("os.environ", {"PYGMT_USE_EXTERNAL_DISPLAY": "false"}):
assert _get_default_display_method() == "notebook"