Skip to content

Commit 9b6cceb

Browse files
larsonerclaude
andcommitted
test: compact the sphinx-gallery scraper tests
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
1 parent 4d3e325 commit 9b6cceb

3 files changed

Lines changed: 46 additions & 63 deletions

File tree

‎plotly/io/_sg_scraper.py‎

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -180,5 +180,3 @@ def _write_image(fig_dict, file, image_format):
180180
"See https://plotly.com/python/static-image-export/ for "
181181
"requirements and installation instructions."
182182
) from exc
183-
184-

‎plotly/io/_utils.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -101,7 +101,7 @@ def resize_after_load_script(div_id):
101101
the time loading finishes, so fix it up once afterwards.
102102
"""
103103
return (
104-
'<script>(function() {'
104+
"<script>(function() {"
105105
"function fit() {"
106106
f'var gd = document.getElementById("{div_id}");'
107107
"if (window.Plotly && gd) Plotly.Plots.resize(gd);"

‎tests/test_io/test_sg_scraper.py‎

Lines changed: 45 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,6 @@
88

99
import functools
1010
import importlib
11-
import logging
1211
import os
1312
from pathlib import Path
1413
from types import SimpleNamespace
@@ -24,24 +23,7 @@
2423
COLORS = ["red", "blue"]
2524

2625

27-
def dummy_image_writer():
28-
"""Return a pio.write_image stand-in, so the tests do not need Kaleido."""
29-
colors = iter(COLORS)
30-
31-
def write_dummy_image(fig, file, format="png", **kwargs):
32-
color = next(colors)
33-
if format == "svg":
34-
with open(file, "w") as f:
35-
f.write(f'<svg xmlns="http://www.w3.org/2000/svg" fill="{color}"/>')
36-
else:
37-
from PIL import Image
38-
39-
Image.new("RGB", (16, 16), color).save(file)
40-
41-
return write_dummy_image
42-
43-
44-
def assert_image_color(path, color, image_format):
26+
def assert_image_color(path, color, image_format="png"):
4527
"""Assert an image came from the figure that was written in `color`."""
4628
if image_format == "svg":
4729
assert f'fill="{color}"' in path.read_text()
@@ -69,12 +51,23 @@ def gallery(tmp_path, monkeypatch):
6951

7052
import plotly.io._sg_scraper as sg_scraper
7153
from plotly.io._base_renderers import sphinx_gallery_figures
72-
from plotly.io._sg_scraper import plotly_sg_scraper
54+
55+
colors = iter(COLORS)
56+
57+
def write_dummy_image(fig, file, format="png", **kwargs):
58+
color = next(colors)
59+
if format == "svg":
60+
svg = f'<svg xmlns="http://www.w3.org/2000/svg" fill="{color}"/>'
61+
Path(file).write_text(svg)
62+
else:
63+
from PIL import Image
64+
65+
Image.new("RGB", (16, 16), color).save(file)
7366

7467
# Importing the scraper sets the renderer too, but only the first time it
7568
# is imported, which may have happened in another test already.
7669
monkeypatch.setattr(pio.renderers, "default", "sphinx_gallery_png")
77-
monkeypatch.setattr(pio, "write_image", dummy_image_writer())
70+
monkeypatch.setattr(pio, "write_image", write_dummy_image)
7871
# Images come from the stand-in above, so the Kaleido probe must pass too
7972
monkeypatch.setattr(pio, "to_image", lambda *args, **kwargs: b"")
8073
sg_scraper._static_export_available.cache_clear()
@@ -87,7 +80,7 @@ def gallery(tmp_path, monkeypatch):
8780
conf = {
8881
**DEFAULT_GALLERY_CONF,
8982
"src_dir": str(tmp_path),
90-
"image_scrapers": (plotly_sg_scraper,),
83+
"image_scrapers": (sg_scraper.plotly_sg_scraper,),
9184
}
9285
block_vars = {
9386
"image_path_iterator": ImagePathIterator(template),
@@ -110,7 +103,7 @@ def thumbnail(**file_conf):
110103
example_dir=example_dir,
111104
globals=block_vars["example_globals"],
112105
paths=block_vars["image_path_iterator"].paths,
113-
scraper=plotly_sg_scraper,
106+
scraper=sg_scraper.plotly_sg_scraper,
114107
scrape=scrape,
115108
thumbnail=thumbnail,
116109
)
@@ -126,7 +119,7 @@ def test_scraper(gallery, image_format):
126119
gallery.conf["image_scrapers"] = (
127120
functools.partial(gallery.scraper, format=image_format),
128121
)
129-
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[3, 2, 1])])
122+
fig = go.Figure()
130123
pio.show(fig)
131124
fig.show() # both ways of showing a figure must be scraped
132125

@@ -136,14 +129,18 @@ def test_scraper(gallery, image_format):
136129
for path, color in zip(gallery.paths, COLORS):
137130
root = os.path.splitext(path)[0]
138131
assert_image_color(Path(f"{root}.{image_format}"), color, image_format)
139-
assert rst.count(".. raw:: html") == 2
140-
assert rst.count("plotly-graph-div") == 2
141-
# The wrapper sphinx-gallery uses for HTML reprs, so themes can style both
142-
assert rst.count('class="output_subarea') == 2
143-
# Fixes up figures drawn while the page was still laying out
144-
assert rst.count("Plotly.Plots.resize") == 2
145-
# Styled as a card so the light-background figure works on dark pages
146-
assert rst.count('class="plotly-output-card"') == 2
132+
# One interactive embed per figure: wrapped like sphinx-gallery wraps HTML
133+
# reprs so themes can style both alike, resized once the page finishes
134+
# laying out, and styled as a card so the light background works on dark
135+
# pages.
136+
for token in (
137+
".. raw:: html",
138+
"plotly-graph-div",
139+
'class="output_subarea',
140+
"Plotly.Plots.resize",
141+
'class="plotly-output-card"',
142+
):
143+
assert rst.count(token) == 2, token
147144

148145
# The thumbnail must be a scraped figure rather than a "no image" default,
149146
# and one image per figure in order is what makes `thumbnail_number` work
@@ -181,32 +178,23 @@ def test_scraper_repr_figure(gallery):
181178
Sphinx-gallery embeds the HTML of such figures itself (repr capture), so
182179
the scraper must contribute only the static image.
183180
"""
184-
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[3, 2, 1])])
181+
fig = go.Figure()
185182
gallery.globals["___"] = fig # as sphinx-gallery's repr capture leaves it
186-
rst = gallery.scrape("fig.update_layout(title='hi')\nfig")
187-
188-
assert rst == ""
183+
assert gallery.scrape("fig.update_layout(title='hi')\nfig") == ""
189184
assert len(gallery.paths) == 1
190-
root = os.path.splitext(gallery.paths[0])[0]
191-
assert not os.path.isfile(f"{root}.html")
192-
assert_image_color(Path(f"{root}.png"), COLORS[0], "png")
193-
assert_image_color(gallery.thumbnail(), COLORS[0], "png")
185+
assert_image_color(Path(gallery.paths[0]), COLORS[0])
186+
assert_image_color(gallery.thumbnail(), COLORS[0])
194187

195188
# ``___`` survives into blocks without a trailing expression; the stale
196189
# figure must not be scraped again
197190
assert gallery.scrape("x = 1") == ""
198191
assert len(gallery.paths) == 1
199192

200-
201-
def test_scraper_repr_of_shown_figure_not_duplicated(gallery):
202-
"""A figure that is both shown and the last expression is scraped once."""
203-
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[3, 2, 1])])
193+
# A figure both shown and repr-displayed is scraped once
204194
fig.show()
205-
gallery.globals["___"] = fig
206195
rst = gallery.scrape("fig.show()\nfig")
207-
208196
assert rst.count(".. raw:: html") == 1
209-
assert len(gallery.paths) == 1
197+
assert len(gallery.paths) == 2
210198

211199

212200
def test_scraper_bad_format(gallery):
@@ -228,30 +216,27 @@ def test_scraper_no_static_export(gallery, monkeypatch, caplog):
228216
def raise_no_browser(*args, **kwargs):
229217
raise ValueError("no browser")
230218

219+
def kaleido_warnings():
220+
return [r for r in caplog.records if "Kaleido" in r.getMessage()]
221+
231222
monkeypatch.setattr(pio, "to_image", raise_no_browser)
232223
sg_scraper._static_export_available.cache_clear()
233-
fig = go.Figure(data=[go.Scatter(x=[1, 2, 3], y=[3, 2, 1])])
224+
fig = go.Figure()
234225
pio.show(fig)
235226
gallery.globals["___"] = fig
236-
237-
with caplog.at_level(logging.WARNING):
238-
rst = gallery.scrape("fig.show()")
227+
rst = gallery.scrape("fig.show()")
239228

240229
# The shown figure is embedded inline instead of via files
241-
assert rst.count(".. raw:: html") == 1
242-
assert "Scatter" not in rst # inlined as HTML, not as a repr
243-
assert "plotly-graph-div" in rst
230+
assert rst.count("plotly-graph-div") == 1
244231
assert gallery.paths == []
245-
warnings = [r for r in caplog.records if "Kaleido" in r.getMessage()]
246-
assert len(warnings) == 1
247-
assert "no browser" in warnings[0].getMessage()
232+
(warning,) = kaleido_warnings()
233+
assert "no browser" in warning.getMessage()
248234

249235
# Only one warning per build, however many blocks follow; repr-displayed
250236
# figures are embedded by sphinx-gallery itself so they scrape to nothing
251-
with caplog.at_level(logging.WARNING):
252-
assert gallery.scrape("fig") == ""
237+
assert gallery.scrape("fig") == ""
253238
assert gallery.paths == []
254-
assert len([r for r in caplog.records if "Kaleido" in r.getMessage()]) == 1
239+
assert len(kaleido_warnings()) == 1
255240

256241

257242
def test_repr_html_fallback_size(monkeypatch):

0 commit comments

Comments
 (0)