Skip to content

Be more forgiving when anything with opening a webbrowser fails #4161

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

Merged
merged 12 commits into from
Jun 4, 2023
10 changes: 6 additions & 4 deletions packages/python/plotly/plotly/io/_renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -525,13 +525,15 @@ def show(fig, renderer=None, validate=True, **kwargs):
else:
# If ipython isn't available, try to display figures in the default
# browser
import webbrowser

try:
import webbrowser

webbrowser.get()
default_renderer = "browser"
except webbrowser.Error:
# Default browser could not be loaded
except Exception:
# Many things could have gone wrong
# There could not be a webbrowser Python module,
# or the module may be a dumb placeholder
pass

renderers.render_on_display = True
Expand Down
43 changes: 43 additions & 0 deletions packages/python/plotly/plotly/tests/test_io/test_renderers.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,7 @@ def test_plotly_mimetype_renderer_show(fig1, renderer):
# ------------
# See plotly/tests/test_orca/test_image_renderers.py


# HTML
# ----
def assert_full_html(html):
Expand Down Expand Up @@ -381,3 +382,45 @@ def test_repr_mimebundle_mixed_renderer(fig1):
assert set(fig1._repr_mimebundle_().keys()) == set(
{"application/vnd.plotly.v1+json", "text/html"}
)


def test_missing_webbrowser_module(fig1):
"""
Assert that no errors occur if the webbrowser module is absent
"""
try:
import builtins
except ImportError:
import __builtin__ as builtins
realimport = builtins.__import__

def webbrowser_absent_import(name, globals, locals, fromlist, level):
"""
Mimick an absent webbrowser module
"""
if name == "webbrowser":
raise ImportError
return realimport(name, globals, locals, fromlist, level)

with mock.patch("builtins.__import__", webbrowser_absent_import):
# 1: check whether importing webbrowser actually results in an ImportError
with pytest.raises(ImportError):
import webbrowser

# 2: check whether the _repr_html_ can handle it regardless
fig1._repr_html_()


def test_missing_webbrowser_methods(fig1):
"""
Assert that no errors occur if the webbrowser module does not contain some methods
"""
import webbrowser

removed_webbrowser_get_method = webbrowser.get
try:
del webbrowser.get
fig1._repr_html_()
finally:
# restore everything after this test
webbrowser.get = removed_webbrowser_get_method