Skip to content

Commit 63bc49d

Browse files
authored
Merge pull request pytest-dev#8440 from bluetech/unnecessary-py-path
Remove/replace some unneeded usages of py.path
2 parents cdbeb03 + 59251e8 commit 63bc49d

18 files changed

+102
-105
lines changed

doc/en/builtin.rst

+2-2
Original file line numberDiff line numberDiff line change
@@ -148,10 +148,10 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
148148
on warning categories.
149149
150150
tmpdir_factory [session scope]
151-
Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.
151+
Return a :class:`pytest.TempdirFactory` instance for the test session.
152152
153153
tmp_path_factory [session scope]
154-
Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session.
154+
Return a :class:`pytest.TempPathFactory` instance for the test session.
155155
156156
tmpdir
157157
Return a temporary directory path object which is unique to each test

doc/en/example/assertion/test_failures.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -5,9 +5,9 @@
55
pytest_plugins = ("pytester",)
66

77

8-
def test_failure_demo_fails_properly(testdir):
9-
target = testdir.tmpdir.join(os.path.basename(failure_demo))
8+
def test_failure_demo_fails_properly(pytester):
9+
target = pytester.path.joinpath(os.path.basename(failure_demo))
1010
shutil.copy(failure_demo, target)
11-
result = testdir.runpytest(target, syspathinsert=True)
11+
result = pytester.runpytest(target, syspathinsert=True)
1212
result.stdout.fnmatch_lines(["*44 failed*"])
1313
assert result.ret != 0

doc/en/example/multipython.py

+6-6
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,8 @@
1212

1313

1414
@pytest.fixture(params=pythonlist)
15-
def python1(request, tmpdir):
16-
picklefile = tmpdir.join("data.pickle")
15+
def python1(request, tmp_path):
16+
picklefile = tmp_path / "data.pickle"
1717
return Python(request.param, picklefile)
1818

1919

@@ -30,8 +30,8 @@ def __init__(self, version, picklefile):
3030
self.picklefile = picklefile
3131

3232
def dumps(self, obj):
33-
dumpfile = self.picklefile.dirpath("dump.py")
34-
dumpfile.write(
33+
dumpfile = self.picklefile.with_name("dump.py")
34+
dumpfile.write_text(
3535
textwrap.dedent(
3636
r"""
3737
import pickle
@@ -46,8 +46,8 @@ def dumps(self, obj):
4646
subprocess.check_call((self.pythonpath, str(dumpfile)))
4747

4848
def load_and_is_true(self, expression):
49-
loadfile = self.picklefile.dirpath("load.py")
50-
loadfile.write(
49+
loadfile = self.picklefile.with_name("load.py")
50+
loadfile.write_text(
5151
textwrap.dedent(
5252
r"""
5353
import pickle

doc/en/example/simple.rst

+5-5
Original file line numberDiff line numberDiff line change
@@ -768,8 +768,8 @@ case we just write some information out to a ``failures`` file:
768768
mode = "a" if os.path.exists("failures") else "w"
769769
with open("failures", mode) as f:
770770
# let's also access a fixture for the fun of it
771-
if "tmpdir" in item.fixturenames:
772-
extra = " ({})".format(item.funcargs["tmpdir"])
771+
if "tmp_path" in item.fixturenames:
772+
extra = " ({})".format(item.funcargs["tmp_path"])
773773
else:
774774
extra = ""
775775
@@ -781,7 +781,7 @@ if you then have failing tests:
781781
.. code-block:: python
782782
783783
# content of test_module.py
784-
def test_fail1(tmpdir):
784+
def test_fail1(tmp_path):
785785
assert 0
786786
787787
@@ -804,9 +804,9 @@ and run them:
804804
================================= FAILURES =================================
805805
________________________________ test_fail1 ________________________________
806806
807-
tmpdir = local('PYTEST_TMPDIR/test_fail10')
807+
tmp_path = Path('PYTEST_TMPDIR/test_fail10')
808808
809-
def test_fail1(tmpdir):
809+
def test_fail1(tmp_path):
810810
> assert 0
811811
E assert 0
812812

doc/en/getting-started.rst

+10-10
Original file line numberDiff line numberDiff line change
@@ -213,35 +213,35 @@ Request a unique temporary directory for functional tests
213213

214214
.. code-block:: python
215215
216-
# content of test_tmpdir.py
217-
def test_needsfiles(tmpdir):
218-
print(tmpdir)
216+
# content of test_tmp_path.py
217+
def test_needsfiles(tmp_path):
218+
print(tmp_path)
219219
assert 0
220220
221-
List the name ``tmpdir`` in the test function signature and ``pytest`` will lookup and call a fixture factory to create the resource before performing the test function call. Before the test runs, ``pytest`` creates a unique-per-test-invocation temporary directory:
221+
List the name ``tmp_path`` in the test function signature and ``pytest`` will lookup and call a fixture factory to create the resource before performing the test function call. Before the test runs, ``pytest`` creates a unique-per-test-invocation temporary directory:
222222

223223
.. code-block:: pytest
224224
225-
$ pytest -q test_tmpdir.py
225+
$ pytest -q test_tmp_path.py
226226
F [100%]
227227
================================= FAILURES =================================
228228
_____________________________ test_needsfiles ______________________________
229229
230-
tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')
230+
tmp_path = Path('PYTEST_TMPDIR/test_needsfiles0')
231231
232-
def test_needsfiles(tmpdir):
233-
print(tmpdir)
232+
def test_needsfiles(tmp_path):
233+
print(tmp_path)
234234
> assert 0
235235
E assert 0
236236
237237
test_tmpdir.py:3: AssertionError
238238
--------------------------- Captured stdout call ---------------------------
239239
PYTEST_TMPDIR/test_needsfiles0
240240
========================= short test summary info ==========================
241-
FAILED test_tmpdir.py::test_needsfiles - assert 0
241+
FAILED test_tmp_path.py::test_needsfiles - assert 0
242242
1 failed in 0.12s
243243
244-
More info on tmpdir handling is available at :ref:`Temporary directories and files <tmpdir handling>`.
244+
More info on temporary directory handling is available at :ref:`Temporary directories and files <tmpdir handling>`.
245245

246246
Find out what kind of builtin :ref:`pytest fixtures <fixtures>` exist with the command:
247247

doc/en/reference/doctest.rst

+1-1
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,7 @@ It is possible to use fixtures using the ``getfixture`` helper:
194194
.. code-block:: text
195195
196196
# content of example.rst
197-
>>> tmp = getfixture('tmpdir')
197+
>>> tmp = getfixture('tmp_path')
198198
>>> ...
199199
>>>
200200

doc/en/reference/reference.rst

+3-3
Original file line numberDiff line numberDiff line change
@@ -284,9 +284,9 @@ Example of a fixture requiring another fixture:
284284
.. code-block:: python
285285
286286
@pytest.fixture
287-
def db_session(tmpdir):
288-
fn = tmpdir / "db.file"
289-
return connect(str(fn))
287+
def db_session(tmp_path):
288+
fn = tmp_path / "db.file"
289+
return connect(fn)
290290
291291
For more details, consult the full :ref:`fixtures docs <fixture>`.
292292

doc/en/reference/unittest.rst

+5-4
Original file line numberDiff line numberDiff line change
@@ -190,21 +190,22 @@ and define the fixture function in the context where you want it used.
190190
Let's look at an ``initdir`` fixture which makes all test methods of a
191191
``TestCase`` class execute in a temporary directory with a
192192
pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses
193-
the pytest builtin :ref:`tmpdir <tmpdir>` fixture to delegate the
193+
the pytest builtin :fixture:`tmp_path` fixture to delegate the
194194
creation of a per-test temporary directory:
195195

196196
.. code-block:: python
197197
198198
# content of test_unittest_cleandir.py
199+
import os
199200
import pytest
200201
import unittest
201202
202203
203204
class MyTest(unittest.TestCase):
204205
@pytest.fixture(autouse=True)
205-
def initdir(self, tmpdir):
206-
tmpdir.chdir() # change to pytest-provided temporary directory
207-
tmpdir.join("samplefile.ini").write("# testdata")
206+
def initdir(self, tmp_path, monkeypatch):
207+
monkeypatch.chdir(tmp_path) # change to pytest-provided temporary directory
208+
tmp_path.joinpath("samplefile.ini").write_text("# testdata")
208209
209210
def test_method(self):
210211
with open("samplefile.ini") as f:

src/_pytest/pytester.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -875,7 +875,7 @@ def test_something(pytester):
875875
def syspathinsert(
876876
self, path: Optional[Union[str, "os.PathLike[str]"]] = None
877877
) -> None:
878-
"""Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.
878+
"""Prepend a directory to sys.path, defaults to :attr:`path`.
879879
880880
This is undone automatically when this object dies at the end of each
881881
test.
@@ -964,7 +964,7 @@ def getnode(
964964
"""
965965
session = Session.from_config(config)
966966
assert "::" not in str(arg)
967-
p = legacy_path(arg)
967+
p = Path(os.path.abspath(arg))
968968
config.hook.pytest_sessionstart(session=session)
969969
res = session.perform_collect([str(p)], genitems=False)[0]
970970
config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)

src/_pytest/tmpdir.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -166,11 +166,11 @@ def get_user() -> Optional[str]:
166166

167167

168168
def pytest_configure(config: Config) -> None:
169-
"""Create a TempdirFactory and attach it to the config object.
169+
"""Create a TempPathFactory and attach it to the config object.
170170
171171
This is to comply with existing plugins which expect the handler to be
172172
available at pytest_configure time, but ideally should be moved entirely
173-
to the tmpdir_factory session fixture.
173+
to the tmp_path_factory session fixture.
174174
"""
175175
mp = MonkeyPatch()
176176
tmppath_handler = TempPathFactory.from_config(config, _ispytest=True)
@@ -182,14 +182,14 @@ def pytest_configure(config: Config) -> None:
182182

183183
@fixture(scope="session")
184184
def tmpdir_factory(request: FixtureRequest) -> TempdirFactory:
185-
"""Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session."""
185+
"""Return a :class:`pytest.TempdirFactory` instance for the test session."""
186186
# Set dynamically by pytest_configure() above.
187187
return request.config._tmpdirhandler # type: ignore
188188

189189

190190
@fixture(scope="session")
191191
def tmp_path_factory(request: FixtureRequest) -> TempPathFactory:
192-
"""Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session."""
192+
"""Return a :class:`pytest.TempPathFactory` instance for the test session."""
193193
# Set dynamically by pytest_configure() above.
194194
return request.config._tmp_path_factory # type: ignore
195195

Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
import pytest
2+
3+
4+
@pytest.mark.parametrize("a", [r"qwe/\abc"])
5+
def test_fixture(tmp_path, a):
6+
assert tmp_path.is_dir()
7+
assert list(tmp_path.iterdir()) == []

testing/example_scripts/tmpdir/tmpdir_fixture.py

-7
This file was deleted.

testing/python/fixtures.py

+20-19
Original file line numberDiff line numberDiff line change
@@ -982,11 +982,11 @@ def arg1():
982982
def farg(arg1):
983983
pass
984984
@pytest.fixture(autouse=True)
985-
def sarg(tmpdir):
985+
def sarg(tmp_path):
986986
pass
987987
def test_function(request, farg):
988988
assert set(get_public_names(request.fixturenames)) == \
989-
set(["tmpdir", "sarg", "arg1", "request", "farg",
989+
set(["sarg", "arg1", "request", "farg",
990990
"tmp_path", "tmp_path_factory"])
991991
"""
992992
)
@@ -1059,7 +1059,7 @@ def arg1():
10591059
def test_show_fixtures_color_yes(self, pytester: Pytester) -> None:
10601060
pytester.makepyfile("def test_this(): assert 1")
10611061
result = pytester.runpytest("--color=yes", "--fixtures")
1062-
assert "\x1b[32mtmpdir" in result.stdout.str()
1062+
assert "\x1b[32mtmp_path" in result.stdout.str()
10631063

10641064
def test_newstyle_with_request(self, pytester: Pytester) -> None:
10651065
pytester.makepyfile(
@@ -1752,11 +1752,11 @@ def pytester(self, pytester: Pytester) -> Pytester:
17521752
"""
17531753
import pytest
17541754
@pytest.fixture(autouse=True)
1755-
def perfunction(request, tmpdir):
1755+
def perfunction(request, tmp_path):
17561756
pass
17571757
17581758
@pytest.fixture()
1759-
def arg1(tmpdir):
1759+
def arg1(tmp_path):
17601760
pass
17611761
@pytest.fixture(autouse=True)
17621762
def perfunction2(arg1):
@@ -3334,9 +3334,9 @@ def test_show_fixtures(self, pytester: Pytester) -> None:
33343334
result = pytester.runpytest("--fixtures")
33353335
result.stdout.fnmatch_lines(
33363336
[
3337-
"tmpdir_factory [[]session scope[]]",
3337+
"tmp_path_factory [[]session scope[]]",
33383338
"*for the test session*",
3339-
"tmpdir",
3339+
"tmp_path",
33403340
"*temporary directory*",
33413341
]
33423342
)
@@ -3345,9 +3345,9 @@ def test_show_fixtures_verbose(self, pytester: Pytester) -> None:
33453345
result = pytester.runpytest("--fixtures", "-v")
33463346
result.stdout.fnmatch_lines(
33473347
[
3348-
"tmpdir_factory [[]session scope[]] -- *tmpdir.py*",
3348+
"tmp_path_factory [[]session scope[]] -- *tmpdir.py*",
33493349
"*for the test session*",
3350-
"tmpdir -- *tmpdir.py*",
3350+
"tmp_path -- *tmpdir.py*",
33513351
"*temporary directory*",
33523352
]
33533353
)
@@ -3367,7 +3367,7 @@ def arg1():
33673367
result = pytester.runpytest("--fixtures", p)
33683368
result.stdout.fnmatch_lines(
33693369
"""
3370-
*tmpdir
3370+
*tmp_path
33713371
*fixtures defined from*
33723372
*arg1*
33733373
*hello world*
@@ -3395,7 +3395,7 @@ def test_hello():
33953395
result = pytester.runpytest("--fixtures")
33963396
result.stdout.fnmatch_lines(
33973397
"""
3398-
*tmpdir*
3398+
*tmp_path*
33993399
*fixtures defined from*conftest*
34003400
*arg1*
34013401
*hello world*
@@ -4000,15 +4000,15 @@ def m1():
40004000
FIXTURE_ORDER.append('m1')
40014001
40024002
@pytest.fixture(scope='session')
4003-
def my_tmpdir_factory():
4004-
FIXTURE_ORDER.append('my_tmpdir_factory')
4003+
def my_tmp_path_factory():
4004+
FIXTURE_ORDER.append('my_tmp_path_factory')
40054005
40064006
@pytest.fixture
4007-
def my_tmpdir(my_tmpdir_factory):
4008-
FIXTURE_ORDER.append('my_tmpdir')
4007+
def my_tmp_path(my_tmp_path_factory):
4008+
FIXTURE_ORDER.append('my_tmp_path')
40094009
40104010
@pytest.fixture
4011-
def f1(my_tmpdir):
4011+
def f1(my_tmp_path):
40124012
FIXTURE_ORDER.append('f1')
40134013
40144014
@pytest.fixture
@@ -4022,12 +4022,13 @@ def test_foo(f1, p1, m1, f2, s1): pass
40224022
request = FixtureRequest(items[0], _ispytest=True)
40234023
# order of fixtures based on their scope and position in the parameter list
40244024
assert (
4025-
request.fixturenames == "s1 my_tmpdir_factory p1 m1 f1 f2 my_tmpdir".split()
4025+
request.fixturenames
4026+
== "s1 my_tmp_path_factory p1 m1 f1 f2 my_tmp_path".split()
40264027
)
40274028
pytester.runpytest()
4028-
# actual fixture execution differs: dependent fixtures must be created first ("my_tmpdir")
4029+
# actual fixture execution differs: dependent fixtures must be created first ("my_tmp_path")
40294030
FIXTURE_ORDER = pytest.FIXTURE_ORDER # type: ignore[attr-defined]
4030-
assert FIXTURE_ORDER == "s1 my_tmpdir_factory p1 m1 my_tmpdir f1 f2".split()
4031+
assert FIXTURE_ORDER == "s1 my_tmp_path_factory p1 m1 my_tmp_path f1 f2".split()
40314032

40324033
def test_func_closure_module(self, pytester: Pytester) -> None:
40334034
pytester.makepyfile(

testing/test_collection.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -1346,15 +1346,14 @@ def test_fscollector_from_parent(pytester: Pytester, request: FixtureRequest) ->
13461346
13471347
Context: https://github.com/pytest-dev/pytest-cpp/pull/47
13481348
"""
1349-
from _pytest.compat import legacy_path
13501349

13511350
class MyCollector(pytest.File):
13521351
def __init__(self, *k, x, **kw):
13531352
super().__init__(*k, **kw)
13541353
self.x = x
13551354

13561355
collector = MyCollector.from_parent(
1357-
parent=request.session, fspath=legacy_path(pytester.path) / "foo", x=10
1356+
parent=request.session, path=pytester.path / "foo", x=10
13581357
)
13591358
assert collector.x == 10
13601359

testing/test_config.py

-1
Original file line numberDiff line numberDiff line change
@@ -1488,7 +1488,6 @@ def pytest_addoption(parser):
14881488
)
14891489
pytester.makepyfile(
14901490
"""
1491-
import py.path
14921491
def test_pathlist(pytestconfig):
14931492
config_paths = pytestconfig.getini("paths")
14941493
print(config_paths)

0 commit comments

Comments
 (0)