Skip to content

Commit a255c63

Browse files
authored
Merge pull request #4161 from bartbroere/patch-1
Be more forgiving when anything with opening a webbrowser fails
2 parents 42266b0 + cdc7ffd commit a255c63

File tree

2 files changed

+49
-4
lines changed

2 files changed

+49
-4
lines changed

Diff for: packages/python/plotly/plotly/io/_renderers.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -525,13 +525,15 @@ def show(fig, renderer=None, validate=True, **kwargs):
525525
else:
526526
# If ipython isn't available, try to display figures in the default
527527
# browser
528-
import webbrowser
529-
530528
try:
529+
import webbrowser
530+
531531
webbrowser.get()
532532
default_renderer = "browser"
533-
except webbrowser.Error:
534-
# Default browser could not be loaded
533+
except Exception:
534+
# Many things could have gone wrong
535+
# There could not be a webbrowser Python module,
536+
# or the module may be a dumb placeholder
535537
pass
536538

537539
renderers.render_on_display = True

Diff for: packages/python/plotly/plotly/tests/test_io/test_renderers.py

+43
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,7 @@ def test_plotly_mimetype_renderer_show(fig1, renderer):
126126
# ------------
127127
# See plotly/tests/test_orca/test_image_renderers.py
128128

129+
129130
# HTML
130131
# ----
131132
def assert_full_html(html):
@@ -381,3 +382,45 @@ def test_repr_mimebundle_mixed_renderer(fig1):
381382
assert set(fig1._repr_mimebundle_().keys()) == set(
382383
{"application/vnd.plotly.v1+json", "text/html"}
383384
)
385+
386+
387+
def test_missing_webbrowser_module(fig1):
388+
"""
389+
Assert that no errors occur if the webbrowser module is absent
390+
"""
391+
try:
392+
import builtins
393+
except ImportError:
394+
import __builtin__ as builtins
395+
realimport = builtins.__import__
396+
397+
def webbrowser_absent_import(name, globals, locals, fromlist, level):
398+
"""
399+
Mimick an absent webbrowser module
400+
"""
401+
if name == "webbrowser":
402+
raise ImportError
403+
return realimport(name, globals, locals, fromlist, level)
404+
405+
with mock.patch("builtins.__import__", webbrowser_absent_import):
406+
# 1: check whether importing webbrowser actually results in an ImportError
407+
with pytest.raises(ImportError):
408+
import webbrowser
409+
410+
# 2: check whether the _repr_html_ can handle it regardless
411+
fig1._repr_html_()
412+
413+
414+
def test_missing_webbrowser_methods(fig1):
415+
"""
416+
Assert that no errors occur if the webbrowser module does not contain some methods
417+
"""
418+
import webbrowser
419+
420+
removed_webbrowser_get_method = webbrowser.get
421+
try:
422+
del webbrowser.get
423+
fig1._repr_html_()
424+
finally:
425+
# restore everything after this test
426+
webbrowser.get = removed_webbrowser_get_method

0 commit comments

Comments
 (0)