Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit de67704

Browse files
committedApr 5, 2025·
TST: Use placeholders for text in layout tests
1 parent 662239c commit de67704

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

56 files changed

+3707
-6366
lines changed
 

‎lib/matplotlib/testing/conftest.py

+36
Original file line numberDiff line numberDiff line change
@@ -125,3 +125,39 @@ def test_imshow_xarray(xr):
125125

126126
xr = pytest.importorskip('xarray')
127127
return xr
128+
129+
130+
def _text_placeholders(monkeypatch):
131+
from matplotlib.patches import Rectangle
132+
133+
def patched_get_text_metrics_with_cache(renderer, text, fontprop, ismath, dpi):
134+
"""
135+
Replace ``_get_text_metrics_with_cache`` with fixed results.
136+
137+
The usual ``renderer.get_text_width_height_descent`` would depend on font
138+
metrics; instead the fixed results are based on font size and the length of the
139+
string only.
140+
"""
141+
height = fontprop.get_size()
142+
width = len(text) * height / 1.618 # Golden ratio for character size.
143+
return width, height, 0
144+
145+
def patched_text_draw(self, renderer):
146+
"""
147+
Replace ``Text.draw`` with a fixed bounding box Rectangle.
148+
149+
The bounding box corresponds to ``Text.get_window_extent``, which ultimately
150+
depends on the above patched ``_get_text_metrics_with_cache``.
151+
"""
152+
if renderer is not None:
153+
self._renderer = renderer
154+
if not self.get_visible():
155+
return
156+
if self.get_text() == '':
157+
return
158+
bbox = self.get_window_extent()
159+
Rectangle(bbox.p0, bbox.width, bbox.height, color='grey').draw(renderer)
160+
161+
monkeypatch.setattr('matplotlib.text._get_text_metrics_with_cache',
162+
patched_get_text_metrics_with_cache)
163+
monkeypatch.setattr('matplotlib.text.Text.draw', patched_text_draw)

‎lib/matplotlib/testing/conftest.pyi

+1
Original file line numberDiff line numberDiff line change
@@ -10,3 +10,4 @@ def mpl_test_settings(request: pytest.FixtureRequest) -> None: ...
1010
def pd() -> ModuleType: ...
1111
@pytest.fixture
1212
def xr() -> ModuleType: ...
13+
def _text_placeholders(monkeypatch: pytest.MonkeyPatch) -> None: ...

0 commit comments

Comments
 (0)