Skip to content

Commit df6d527

Browse files
committed
TST: Simplify parts of animation tests
The animation writers will put its temporary files in `TemporaryDirectory`, so there's no need to `chdir` to avoid polluting the current directory. For that same reason, drop `test_cleanup_temporaries`, which is now just a test for the Python standard library. Also, at some point, `pytest` will want to deprecate the `tmpdir` fixture, so switch to `tmp_path`.
1 parent d359d93 commit df6d527

File tree

1 file changed

+28
-53
lines changed

1 file changed

+28
-53
lines changed

lib/matplotlib/tests/test_animation.py

Lines changed: 28 additions & 53 deletions
Original file line numberDiff line numberDiff line change
@@ -158,8 +158,7 @@ def isAvailable(cls):
158158
def gen_writers():
159159
for writer, output in WRITER_OUTPUT:
160160
if not animation.writers.is_available(writer):
161-
mark = pytest.mark.skip(
162-
f"writer '{writer}' not available on this system")
161+
mark = pytest.mark.skip(f"writer '{writer}' not available on this system")
163162
yield pytest.param(writer, None, output, marks=[mark])
164163
yield pytest.param(writer, None, Path(output), marks=[mark])
165164
continue
@@ -175,7 +174,7 @@ def gen_writers():
175174
# matplotlib.testing.image_comparison
176175
@pytest.mark.parametrize('writer, frame_format, output', gen_writers())
177176
@pytest.mark.parametrize('anim', [dict(klass=dict)], indirect=['anim'])
178-
def test_save_animation_smoketest(tmpdir, writer, frame_format, output, anim):
177+
def test_save_animation_smoketest(tmp_path, writer, frame_format, output, anim):
179178
if frame_format is not None:
180179
plt.rcParams["animation.frame_format"] = frame_format
181180
anim = animation.FuncAnimation(**anim)
@@ -187,17 +186,14 @@ def test_save_animation_smoketest(tmpdir, writer, frame_format, output, anim):
187186
dpi = 100.
188187
codec = 'h264'
189188

190-
# Use temporary directory for the file-based writers, which produce a file
191-
# per frame with known names.
192-
with tmpdir.as_cwd():
193-
anim.save(output, fps=30, writer=writer, bitrate=500, dpi=dpi,
194-
codec=codec)
189+
anim.save(tmp_path / output, fps=30, writer=writer, bitrate=500, dpi=dpi,
190+
codec=codec)
195191

196192
del anim
197193

198194

199195
@pytest.mark.parametrize('writer, frame_format, output', gen_writers())
200-
def test_grabframe(tmpdir, writer, frame_format, output):
196+
def test_grabframe(tmp_path, writer, frame_format, output):
201197
WriterClass = animation.writers[writer]
202198

203199
if frame_format is not None:
@@ -214,18 +210,14 @@ def test_grabframe(tmpdir, writer, frame_format, output):
214210
codec = 'h264'
215211

216212
test_writer = WriterClass()
217-
# Use temporary directory for the file-based writers, which produce a file
218-
# per frame with known names.
219-
with tmpdir.as_cwd():
220-
with test_writer.saving(fig, output, dpi):
221-
# smoke test it works
222-
test_writer.grab_frame()
223-
for k in {'dpi', 'bbox_inches', 'format'}:
224-
with pytest.raises(
225-
TypeError,
226-
match=f"grab_frame got an unexpected keyword argument {k!r}"
227-
):
228-
test_writer.grab_frame(**{k: object()})
213+
with test_writer.saving(fig, tmp_path / output, dpi):
214+
# smoke test it works
215+
test_writer.grab_frame()
216+
for k in {'dpi', 'bbox_inches', 'format'}:
217+
with pytest.raises(
218+
TypeError,
219+
match=f"grab_frame got an unexpected keyword argument {k!r}"):
220+
test_writer.grab_frame(**{k: object()})
229221

230222

231223
@pytest.mark.parametrize('writer', [
@@ -295,46 +287,31 @@ def test_movie_writer_registry():
295287
reason="animation writer not installed")),
296288
"to_jshtml"])
297289
@pytest.mark.parametrize('anim', [dict(frames=1)], indirect=['anim'])
298-
def test_embed_limit(method_name, caplog, tmpdir, anim):
290+
def test_embed_limit(method_name, caplog, tmp_path, anim):
299291
caplog.set_level("WARNING")
300-
with tmpdir.as_cwd():
301-
with mpl.rc_context({"animation.embed_limit": 1e-6}): # ~1 byte.
302-
getattr(anim, method_name)()
292+
with mpl.rc_context({"animation.embed_limit": 1e-6}): # ~1 byte.
293+
getattr(anim, method_name)()
303294
assert len(caplog.records) == 1
304295
record, = caplog.records
305296
assert (record.name == "matplotlib.animation"
306297
and record.levelname == "WARNING")
307298

308299

309-
@pytest.mark.parametrize(
310-
"method_name",
311-
[pytest.param("to_html5_video", marks=pytest.mark.skipif(
312-
not animation.writers.is_available(mpl.rcParams["animation.writer"]),
313-
reason="animation writer not installed")),
314-
"to_jshtml"])
315-
@pytest.mark.parametrize('anim', [dict(frames=1)], indirect=['anim'])
316-
def test_cleanup_temporaries(method_name, tmpdir, anim):
317-
with tmpdir.as_cwd():
318-
getattr(anim, method_name)()
319-
assert list(Path(str(tmpdir)).iterdir()) == []
320-
321-
322300
@pytest.mark.skipif(shutil.which("/bin/sh") is None, reason="requires a POSIX OS")
323-
def test_failing_ffmpeg(tmpdir, monkeypatch, anim):
301+
def test_failing_ffmpeg(tmp_path, monkeypatch, anim):
324302
"""
325303
Test that we correctly raise a CalledProcessError when ffmpeg fails.
326304
327305
To do so, mock ffmpeg using a simple executable shell script that
328306
succeeds when called with no arguments (so that it gets registered by
329307
`isAvailable`), but fails otherwise, and add it to the $PATH.
330308
"""
331-
with tmpdir.as_cwd():
332-
monkeypatch.setenv("PATH", ".:" + os.environ["PATH"])
333-
exe_path = Path(str(tmpdir), "ffmpeg")
334-
exe_path.write_bytes(b"#!/bin/sh\n[[ $@ -eq 0 ]]\n")
335-
os.chmod(exe_path, 0o755)
336-
with pytest.raises(subprocess.CalledProcessError):
337-
anim.save("test.mpeg")
309+
monkeypatch.setenv("PATH", str(tmp_path), prepend=":")
310+
exe_path = tmp_path / "ffmpeg"
311+
exe_path.write_bytes(b"#!/bin/sh\n[[ $@ -eq 0 ]]\n")
312+
os.chmod(exe_path, 0o755)
313+
with pytest.raises(subprocess.CalledProcessError):
314+
anim.save("test.mpeg")
338315

339316

340317
@pytest.mark.parametrize("cache_frame_data", [False, True])
@@ -418,7 +395,7 @@ def animate(i):
418395
)
419396

420397

421-
def test_exhausted_animation(tmpdir):
398+
def test_exhausted_animation(tmp_path):
422399
fig, ax = plt.subplots()
423400

424401
def update(frame):
@@ -429,14 +406,13 @@ def update(frame):
429406
cache_frame_data=False
430407
)
431408

432-
with tmpdir.as_cwd():
433-
anim.save("test.gif", writer='pillow')
409+
anim.save(tmp_path / "test.gif", writer='pillow')
434410

435411
with pytest.warns(UserWarning, match="exhausted"):
436412
anim._start()
437413

438414

439-
def test_no_frame_warning(tmpdir):
415+
def test_no_frame_warning():
440416
fig, ax = plt.subplots()
441417

442418
def update(frame):
@@ -452,7 +428,7 @@ def update(frame):
452428

453429

454430
@check_figures_equal(extensions=["png"])
455-
def test_animation_frame(tmpdir, fig_test, fig_ref):
431+
def test_animation_frame(tmp_path, fig_test, fig_ref):
456432
# Test the expected image after iterating through a few frames
457433
# we save the animation to get the iteration because we are not
458434
# in an interactive framework.
@@ -473,8 +449,7 @@ def animate(i):
473449
anim = animation.FuncAnimation(
474450
fig_test, animate, init_func=init, frames=5,
475451
blit=True, repeat=False)
476-
with tmpdir.as_cwd():
477-
anim.save("test.gif")
452+
anim.save(tmp_path / "test.gif")
478453

479454
# Reference figure without animation
480455
ax = fig_ref.add_subplot()

0 commit comments

Comments
 (0)