8000 Switch pytest fixture from tmpdir to tmp_path by timhoffm · Pull Request #27417 · matplotlib/matplotlib · GitHub
[go: up one dir, main page]

Skip to content

Switch pytest fixture from tmpdir to tmp_path #27417

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 1 commit into from
Dec 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_backend_ps.py
Original file line number Diff line number Diff line change
Expand Up @@ -124,11 +124,11 @@ def test_patheffects():

@needs_usetex
@needs_ghostscript
def test_tilde_in_tempfilename(tmpdir):
def test_tilde_in_tempfilename(tmp_path):
# Tilde ~ in the tempdir path (e.g. TMPDIR, TMP or TEMP on windows
# when the username is very long and windows uses a short name) breaks
# latex before https://github.com/matplotlib/matplotlib/pull/5928
base_tempdir = Path(tmpdir, "short-1")
base_tempdir = tmp_path / "short-1"
base_tempdir.mkdir()
# Change the path for new tempdirs, which is used internally by the ps
# backend to write a file.
Expand Down
5 changes: 2 additions & 3 deletions lib/matplotlib/tests/test_figure.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import copy
from datetime import datetime
import io
from pathlib import Path
import pickle
import platform
from threading import Timer
Expand Down Expand Up @@ -739,8 +738,8 @@ def test_add_artist(fig_test, fig_ref):


@pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])
def test_fspath(fmt, tmpdir):
out = Path(tmpdir, f"test.{fmt}")
def test_fspath(fmt, tmp_path):
out = tmp_path / f"test.{fmt}"
plt.savefig(out)
with out.open("rb") as file:
# All the supported formats include the format name (case-insensitive)
Expand Down
10 changes: 4 additions & 6 deletions lib/matplotlib/tests/test_font_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,11 @@ def test_score_weight():
fontManager.score_weight(400, 400))


def test_json_serialization(tmpdir):
def test_json_serialization(tmp_path):
# Can't open a NamedTemporaryFile twice on Windows, so use a temporary
# directory instead.
path = Path(tmpdir, "fontlist.json")
json_dump(fontManager, path)
copy = json_load(path)
json_dump(fontManager, tmp_path / "fontlist.json")
copy = json_load(tmp_path / "fontlist.json")
with warnings.catch_warnings():
warnings.filterwarnings('ignore', 'findfont: Font family.*not found')
for prop in ({'family': 'STIXGeneral'},
Expand Down Expand Up @@ -133,8 +132,7 @@ def test_find_noto():
fig.savefig(BytesIO(), format=fmt)


def test_find_invalid(tmpdir):
tmp_path = Path(tmpdir)
def test_find_invalid(tmp_path):

with pytest.raises(FileNotFoundError):
get_font(tmp_path / 'non-existent-font-name.ttf')
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_mathtext.py
Original file line number Diff line number Diff line change
Expand Up @@ -459,8 +459,8 @@ def test_mathtext_fallback(fallback, fontlist):
mpl.font_manager.fontManager.ttflist.pop()


def test_math_to_image(tmpdir):
mathtext.math_to_image('$x^2$', str(tmpdir.join('example.png')))
def test_math_to_image(tmp_path):
mathtext.math_to_image('$x^2$', tmp_path / 'example.png')
mathtext.math_to_image('$x^2$', io.BytesIO())
mathtext.math_to_image('$x^2$', io.BytesIO(), color='Maroon')

Expand Down
14 changes: 7 additions & 7 deletions 8000 lib/matplotlib/tests/test_matplotlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,26 +21,26 @@ def test_parse_to_version_info(version_str, version_tuple):
reason="chmod() doesn't work as is on Windows")
@pytest.mark.skipif(sys.platform != "win32" and os.geteuid() == 0,
reason="chmod() doesn't work as root")
def test_tmpconfigdir_warning(tmpdir):
def test_tmpconfigdir_warning(tmp_path):
"""Test that a warning is emitted if a temporary configdir must be used."""
mode = os.stat(tmpdir).st_mode
mode = os.stat(tmp_path).st_mode
try:
os.chmod(tmpdir, 0)
os.chmod(tmp_path, 0)
proc = subprocess.run(
[sys.executable, "-c", "import matplotlib"],
env={**os.environ, "MPLCONFIGDIR": str(tmpdir)},
env={**os.environ, "MPLCONFIGDIR": str(tmp_path)},
stderr=subprocess.PIPE, text=True, check=True)
assert "set the MPLCONFIGDIR" in proc.stderr
finally:
os.chmod(tmpdir, mode)
os.chmod(tmp_path, mode)


def test_importable_with_no_home(tmpdir):
def test_importable_with_no_home(tmp_path):
subprocess.run(
[sys.executable, "-c",
"import pathlib; pathlib.Path.home = lambda *args: 1/0; "
"import matplotlib.pyplot"],
env={**os.environ, "MPLCONFIGDIR": str(tmpdir)}, check=True)
env={**os.environ, "MPLCONFIGDIR": str(tmp_path)}, check=True)


def test_use_doc_standard_backends():
Expand Down
4 changes: 2 additions & 2 deletions lib/matplotlib/tests/test_pyplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,14 @@
from matplotlib import pyplot as plt


def test_pyplot_up_to_date(tmpdir):
def test_pyplot_up_to_date(tmp_path):
pytest.importorskip("black")

gen_script = Path(mpl.__file__).parents[2] / "tools/boilerplate.py"
if not gen_script.exists():
pytest.skip("boilerplate.py not found")
orig_contents = Path(plt.__file__).read_text()
plt_file = tmpdir.join('pyplot.py')
plt_file = tmp_path / 'pyplot.py'
plt_file.write_text(orig_contents, 'utf-8')

subprocess_run_for_testing(
Expand Down
29 changes: 14 additions & 15 deletions lib/matplotlib/tests/test_rcparams.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import copy
import os
from pathlib import Path
import subprocess
import sys
from unittest import mock
Expand Down Expand Up @@ -32,14 +31,14 @@
_listify_validator)


def test_rcparams(tmpdir):
def test_rcparams(tmp_path):
mpl.rc('text', usetex=False)
mpl.rc('lines', linewidth=22)

usetex = mpl.rcParams['text.usetex']
linewidth = mpl.rcParams['lines.linewidth']

rcpath = Path(tmpdir) / 'test_rcparams.rc'
rcpath = tmp_path / 'test_rcparams.rc'
rcpath.write_text('lines.linewidth: 33', encoding='utf-8')

# test context given dictionary
Expand Down Expand Up @@ -197,8 +196,8 @@ def test_axes_titlecolor_rcparams():
assert title.get_color() == 'r'


def test_Issue_1713(tmpdir):
rcpath = Path(tmpdir) / 'test_rcparams.rc'
def test_Issue_1713(tmp_path):
rcpath = tmp_path / 'test_rcparams.rc'
rcpath.write_text('timezone: UTC', encoding='utf-8')
with mock.patch('locale.getpreferredencoding', return_value='UTF-32-BE'):
rc = mpl.rc_params_from_file(rcpath, True, False)
Expand Down Expand Up @@ -522,10 +521,10 @@ def test_rcparams_reset_after_fail():


@pytest.mark.skipif(sys.platform != "linux", reason="Linux only")
def test_backend_fallback_headless(tmpdir):
def test_backend_fallback_headless(tmp_path):
env = {**os.environ,
"DISPLAY": "", "WAYLAND_DISPLAY": "",
"MPLBACKEND": "", "MPLCONFIGDIR": str(tmpdir)}
"MPLBACKEND": "", "MPLCONFIGDIR": str(tmp_path)}
with pytest.raises(subprocess.CalledProcessError):
subprocess.run(
[sys.executable, "-c",
Expand All @@ -540,9 +539,9 @@ def test_backend_fallback_headless(tmpdir):
@pytest.mark.skipif(
sys.platform == "linux" and not _c_internal_utils.display_is_valid(),
reason="headless")
def test_backend_fallback_headful(tmpdir):
def test_backend_fallback_headful(tmp_path):
pytest.importorskip("tkinter")
env = {**os.environ, "MPLBACKEND": "", "MPLCONFIGDIR": str(tmpdir)}
env = {**os.environ, "MPLBACKEND": "", "MPLCONFIGDIR": str(tmp_path)}
backend = subprocess.check_output(
[sys.executable, "-c",
"import matplotlib as mpl; "
Expand Down Expand Up @@ -620,12 +619,12 @@ def test_rcparams_legend_loc(value):
(0.9, .7),
(-0.9, .7),
])
def test_rcparams_legend_loc_from_file(tmpdir, value):
def test_rcparams_legend_loc_from_file(tmp_path, value):
# rcParams['legend.loc'] should be settable from matplotlibrc.
# if any of these are not allowed, an exception will be raised.
# test for gh issue #22338
rc_path = tmpdir.join("matplotlibrc")
rc_path.write(f"legend.loc: {value}")
rc_path = tmp_path / "matplotlibrc"
rc_path.write_text(f"legend.loc: {value}")

with mpl.rc_context(fname=rc_path):
assert mpl.rcParams["legend.loc"] == value
Expand All @@ -647,8 +646,8 @@ def test_validate_sketch_error(value):


@pytest.mark.parametrize("value", ['1, 2, 3', '(1,2,3)'])
def test_rcparams_path_sketch_from_file(tmpdir, value):
rc_path = tmpdir.join("matplotlibrc")
rc_path.write(f"path.sketch: {value}")
def test_rcparams_path_sketch_from_file(tmp_path, value):
rc_path = tmp_path / "matplotlibrc"
rc_path.write_text(f"path.sketch: {value}")
with mpl.rc_context(fname=rc_path):
assert mpl.rcParams["path.sketch"] == (1, 2, 3)
9 changes: 4 additions & 5 deletions lib/matplotlib/tests/test_style.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ def test_use():
assert mpl.rcParams[PARAM] == VALUE


def test_use_url(tmpdir):
path = Path(tmpdir, 'file')
def test_use_url(tmp_path):
path = tmp_path / 'file'
path.write_text('axes.facecolor: adeade', encoding='utf-8')
with temp_style('test', DUMMY_SETTINGS):
url = ('file:'
Expand All @@ -69,10 +69,9 @@ def test_use_url(tmpdir):
assert mpl.rcParams['axes.facecolor'] == "#adeade"


def test_single_path(tmpdir):
def test_single_path(tmp_path):
mpl.rcParams[PARAM] = 'gray'
temp_file = f'text.{STYLE_EXTENSION}'
path = Path(tmpdir, temp_file)
path = tmp_path / f'text.{STYLE_EXTENSION}'
path.write_text(f'{PARAM} : {VALUE}', encoding='utf-8')
with style.context(path):
assert mpl.rcParams[PARAM] == VALUE
Expand Down
0