Skip to content

Remove/replace some unneeded usages of py.path #8440

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
Mar 14, 2021
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 doc/en/builtin.rst
Original file line number Diff line number Diff line change
Expand Up @@ -148,10 +148,10 @@ For information about fixtures, see :ref:`fixtures`. To see a complete list of a
on warning categories.

tmpdir_factory [session scope]
Return a :class:`_pytest.tmpdir.TempdirFactory` instance for the test session.
Return a :class:`pytest.TempdirFactory` instance for the test session.

tmp_path_factory [session scope]
Return a :class:`_pytest.tmpdir.TempPathFactory` instance for the test session.
Return a :class:`pytest.TempPathFactory` instance for the test session.

tmpdir
Return a temporary directory path object which is unique to each test
Expand Down
6 changes: 3 additions & 3 deletions doc/en/example/assertion/test_failures.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@
pytest_plugins = ("pytester",)


def test_failure_demo_fails_properly(testdir):
target = testdir.tmpdir.join(os.path.basename(failure_demo))
def test_failure_demo_fails_properly(pytester):
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

as a followup we might want to make this use examples

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one I'm not exactly sure where it's used, so left it as is.

target = pytester.path.joinpath(os.path.basename(failure_demo))
shutil.copy(failure_demo, target)
result = testdir.runpytest(target, syspathinsert=True)
result = pytester.runpytest(target, syspathinsert=True)
result.stdout.fnmatch_lines(["*44 failed*"])
assert result.ret != 0
12 changes: 6 additions & 6 deletions doc/en/example/multipython.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,8 @@


@pytest.fixture(params=pythonlist)
def python1(request, tmpdir):
picklefile = tmpdir.join("data.pickle")
def python1(request, tmp_path):
picklefile = tmp_path / "data.pickle"
return Python(request.param, picklefile)


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

def dumps(self, obj):
dumpfile = self.picklefile.dirpath("dump.py")
dumpfile.write(
dumpfile = self.picklefile.with_name("dump.py")
dumpfile.write_text(
textwrap.dedent(
r"""
import pickle
Expand All @@ -46,8 +46,8 @@ def dumps(self, obj):
subprocess.check_call((self.pythonpath, str(dumpfile)))

def load_and_is_true(self, expression):
loadfile = self.picklefile.dirpath("load.py")
loadfile.write(
loadfile = self.picklefile.with_name("load.py")
loadfile.write_text(
textwrap.dedent(
r"""
import pickle
Expand Down
10 changes: 5 additions & 5 deletions doc/en/example/simple.rst
Original file line number Diff line number Diff line change
Expand Up @@ -768,8 +768,8 @@ case we just write some information out to a ``failures`` file:
mode = "a" if os.path.exists("failures") else "w"
with open("failures", mode) as f:
# let's also access a fixture for the fun of it
if "tmpdir" in item.fixturenames:
extra = " ({})".format(item.funcargs["tmpdir"])
if "tmp_path" in item.fixturenames:
extra = " ({})".format(item.funcargs["tmp_path"])
else:
extra = ""

Expand All @@ -781,7 +781,7 @@ if you then have failing tests:
.. code-block:: python

# content of test_module.py
def test_fail1(tmpdir):
def test_fail1(tmp_path):
assert 0


Expand All @@ -804,9 +804,9 @@ and run them:
================================= FAILURES =================================
________________________________ test_fail1 ________________________________

tmpdir = local('PYTEST_TMPDIR/test_fail10')
tmp_path = Path('PYTEST_TMPDIR/test_fail10')

def test_fail1(tmpdir):
def test_fail1(tmp_path):
> assert 0
E assert 0

Expand Down
20 changes: 10 additions & 10 deletions doc/en/getting-started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -213,35 +213,35 @@ Request a unique temporary directory for functional tests

.. code-block:: python

# content of test_tmpdir.py
def test_needsfiles(tmpdir):
print(tmpdir)
# content of test_tmp_path.py
def test_needsfiles(tmp_path):
print(tmp_path)
assert 0

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:
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:

.. code-block:: pytest

$ pytest -q test_tmpdir.py
$ pytest -q test_tmp_path.py
F [100%]
================================= FAILURES =================================
_____________________________ test_needsfiles ______________________________

tmpdir = local('PYTEST_TMPDIR/test_needsfiles0')
tmp_path = Path('PYTEST_TMPDIR/test_needsfiles0')

def test_needsfiles(tmpdir):
print(tmpdir)
def test_needsfiles(tmp_path):
print(tmp_path)
> assert 0
E assert 0

test_tmpdir.py:3: AssertionError
--------------------------- Captured stdout call ---------------------------
PYTEST_TMPDIR/test_needsfiles0
========================= short test summary info ==========================
FAILED test_tmpdir.py::test_needsfiles - assert 0
FAILED test_tmp_path.py::test_needsfiles - assert 0
1 failed in 0.12s

More info on tmpdir handling is available at :ref:`Temporary directories and files <tmpdir handling>`.
More info on temporary directory handling is available at :ref:`Temporary directories and files <tmpdir handling>`.

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

Expand Down
2 changes: 1 addition & 1 deletion doc/en/reference/doctest.rst
Original file line number Diff line number Diff line change
Expand Up @@ -194,7 +194,7 @@ It is possible to use fixtures using the ``getfixture`` helper:
.. code-block:: text

# content of example.rst
>>> tmp = getfixture('tmpdir')
>>> tmp = getfixture('tmp_path')
>>> ...
>>>

Expand Down
6 changes: 3 additions & 3 deletions doc/en/reference/reference.rst
Original file line number Diff line number Diff line change
Expand Up @@ -284,9 +284,9 @@ Example of a fixture requiring another fixture:
.. code-block:: python

@pytest.fixture
def db_session(tmpdir):
fn = tmpdir / "db.file"
return connect(str(fn))
def db_session(tmp_path):
fn = tmp_path / "db.file"
return connect(fn)

For more details, consult the full :ref:`fixtures docs <fixture>`.

Expand Down
9 changes: 5 additions & 4 deletions doc/en/reference/unittest.rst
Original file line number Diff line number Diff line change
Expand Up @@ -190,21 +190,22 @@ and define the fixture function in the context where you want it used.
Let's look at an ``initdir`` fixture which makes all test methods of a
``TestCase`` class execute in a temporary directory with a
pre-initialized ``samplefile.ini``. Our ``initdir`` fixture itself uses
the pytest builtin :ref:`tmpdir <tmpdir>` fixture to delegate the
the pytest builtin :fixture:`tmp_path` fixture to delegate the
creation of a per-test temporary directory:

.. code-block:: python

# content of test_unittest_cleandir.py
import os
import pytest
import unittest


class MyTest(unittest.TestCase):
@pytest.fixture(autouse=True)
def initdir(self, tmpdir):
tmpdir.chdir() # change to pytest-provided temporary directory
tmpdir.join("samplefile.ini").write("# testdata")
def initdir(self, tmp_path, monkeypatch):
monkeypatch.chdir(tmp_path) # change to pytest-provided temporary directory
tmp_path.joinpath("samplefile.ini").write_text("# testdata")

def test_method(self):
with open("samplefile.ini") as f:
Expand Down
4 changes: 2 additions & 2 deletions src/_pytest/pytester.py
Original file line number Diff line number Diff line change
Expand Up @@ -875,7 +875,7 @@ def test_something(pytester):
def syspathinsert(
self, path: Optional[Union[str, "os.PathLike[str]"]] = None
) -> None:
"""Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.
"""Prepend a directory to sys.path, defaults to :attr:`path`.

This is undone automatically when this object dies at the end of each
test.
Expand Down Expand Up @@ -964,7 +964,7 @@ def getnode(
"""
session = Session.from_config(config)
assert "::" not in str(arg)
p = legacy_path(arg)
p = Path(os.path.abspath(arg))
config.hook.pytest_sessionstart(session=session)
res = session.perform_collect([str(p)], genitems=False)[0]
config.hook.pytest_sessionfinish(session=session, exitstatus=ExitCode.OK)
Expand Down
8 changes: 4 additions & 4 deletions src/_pytest/tmpdir.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,11 +166,11 @@ def get_user() -> Optional[str]:


def pytest_configure(config: Config) -> None:
"""Create a TempdirFactory and attach it to the config object.
"""Create a TempPathFactory and attach it to the config object.

This is to comply with existing plugins which expect the handler to be
available at pytest_configure time, but ideally should be moved entirely
to the tmpdir_factory session fixture.
to the tmp_path_factory session fixture.
"""
mp = MonkeyPatch()
tmppath_handler = TempPathFactory.from_config(config, _ispytest=True)
Expand All @@ -182,14 +182,14 @@ def pytest_configure(config: Config) -> None:

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


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

Expand Down
7 changes: 7 additions & 0 deletions testing/example_scripts/tmpdir/tmp_path_fixture.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import pytest


@pytest.mark.parametrize("a", [r"qwe/\abc"])
def test_fixture(tmp_path, a):
assert tmp_path.is_dir()
assert list(tmp_path.iterdir()) == []
7 changes: 0 additions & 7 deletions testing/example_scripts/tmpdir/tmpdir_fixture.py

This file was deleted.

39 changes: 20 additions & 19 deletions testing/python/fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -982,11 +982,11 @@ def arg1():
def farg(arg1):
pass
@pytest.fixture(autouse=True)
def sarg(tmpdir):
def sarg(tmp_path):
pass
def test_function(request, farg):
assert set(get_public_names(request.fixturenames)) == \
set(["tmpdir", "sarg", "arg1", "request", "farg",
set(["sarg", "arg1", "request", "farg",
"tmp_path", "tmp_path_factory"])
"""
)
Expand Down Expand Up @@ -1059,7 +1059,7 @@ def arg1():
def test_show_fixtures_color_yes(self, pytester: Pytester) -> None:
pytester.makepyfile("def test_this(): assert 1")
result = pytester.runpytest("--color=yes", "--fixtures")
assert "\x1b[32mtmpdir" in result.stdout.str()
assert "\x1b[32mtmp_path" in result.stdout.str()

def test_newstyle_with_request(self, pytester: Pytester) -> None:
pytester.makepyfile(
Expand Down Expand Up @@ -1752,11 +1752,11 @@ def pytester(self, pytester: Pytester) -> Pytester:
"""
import pytest
@pytest.fixture(autouse=True)
def perfunction(request, tmpdir):
def perfunction(request, tmp_path):
pass

@pytest.fixture()
def arg1(tmpdir):
def arg1(tmp_path):
pass
@pytest.fixture(autouse=True)
def perfunction2(arg1):
Expand Down Expand Up @@ -3334,9 +3334,9 @@ def test_show_fixtures(self, pytester: Pytester) -> None:
result = pytester.runpytest("--fixtures")
result.stdout.fnmatch_lines(
[
"tmpdir_factory [[]session scope[]]",
"tmp_path_factory [[]session scope[]]",
"*for the test session*",
"tmpdir",
"tmp_path",
"*temporary directory*",
]
)
Expand All @@ -3345,9 +3345,9 @@ def test_show_fixtures_verbose(self, pytester: Pytester) -> None:
result = pytester.runpytest("--fixtures", "-v")
result.stdout.fnmatch_lines(
[
"tmpdir_factory [[]session scope[]] -- *tmpdir.py*",
"tmp_path_factory [[]session scope[]] -- *tmpdir.py*",
"*for the test session*",
"tmpdir -- *tmpdir.py*",
"tmp_path -- *tmpdir.py*",
"*temporary directory*",
]
)
Expand All @@ -3367,7 +3367,7 @@ def arg1():
result = pytester.runpytest("--fixtures", p)
result.stdout.fnmatch_lines(
"""
*tmpdir
*tmp_path
*fixtures defined from*
*arg1*
*hello world*
Expand Down Expand Up @@ -3395,7 +3395,7 @@ def test_hello():
result = pytester.runpytest("--fixtures")
result.stdout.fnmatch_lines(
"""
*tmpdir*
*tmp_path*
*fixtures defined from*conftest*
*arg1*
*hello world*
Expand Down Expand Up @@ -4000,15 +4000,15 @@ def m1():
FIXTURE_ORDER.append('m1')

@pytest.fixture(scope='session')
def my_tmpdir_factory():
FIXTURE_ORDER.append('my_tmpdir_factory')
def my_tmp_path_factory():
FIXTURE_ORDER.append('my_tmp_path_factory')

@pytest.fixture
def my_tmpdir(my_tmpdir_factory):
FIXTURE_ORDER.append('my_tmpdir')
def my_tmp_path(my_tmp_path_factory):
FIXTURE_ORDER.append('my_tmp_path')

@pytest.fixture
def f1(my_tmpdir):
def f1(my_tmp_path):
FIXTURE_ORDER.append('f1')

@pytest.fixture
Expand All @@ -4022,12 +4022,13 @@ def test_foo(f1, p1, m1, f2, s1): pass
request = FixtureRequest(items[0], _ispytest=True)
# order of fixtures based on their scope and position in the parameter list
assert (
request.fixturenames == "s1 my_tmpdir_factory p1 m1 f1 f2 my_tmpdir".split()
request.fixturenames
== "s1 my_tmp_path_factory p1 m1 f1 f2 my_tmp_path".split()
)
pytester.runpytest()
# actual fixture execution differs: dependent fixtures must be created first ("my_tmpdir")
# actual fixture execution differs: dependent fixtures must be created first ("my_tmp_path")
FIXTURE_ORDER = pytest.FIXTURE_ORDER # type: ignore[attr-defined]
assert FIXTURE_ORDER == "s1 my_tmpdir_factory p1 m1 my_tmpdir f1 f2".split()
assert FIXTURE_ORDER == "s1 my_tmp_path_factory p1 m1 my_tmp_path f1 f2".split()

def test_func_closure_module(self, pytester: Pytester) -> None:
pytester.makepyfile(
Expand Down
3 changes: 1 addition & 2 deletions testing/test_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -1346,15 +1346,14 @@ def test_fscollector_from_parent(pytester: Pytester, request: FixtureRequest) ->

Context: https://github.com/pytest-dev/pytest-cpp/pull/47
"""
from _pytest.compat import legacy_path

class MyCollector(pytest.File):
def __init__(self, *k, x, **kw):
super().__init__(*k, **kw)
self.x = x

collector = MyCollector.from_parent(
parent=request.session, fspath=legacy_path(pytester.path) / "foo", x=10
parent=request.session, path=pytester.path / "foo", x=10
)
assert collector.x == 10

Expand Down
1 change: 0 additions & 1 deletion testing/test_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -1488,7 +1488,6 @@ def pytest_addoption(parser):
)
pytester.makepyfile(
"""
import py.path
def test_pathlist(pytestconfig):
config_paths = pytestconfig.getini("paths")
print(config_paths)
Expand Down
Loading