Merge pull request #8013 from itsmegarvi/master

#7942 migrate from tempdir to pytester
This commit is contained in:
Ran Benita 2020-11-16 19:44:43 +02:00 committed by GitHub
commit c2f949d68e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 213 additions and 185 deletions

View File

@ -1,31 +1,42 @@
import argparse
import os import os
import textwrap import textwrap
from pathlib import Path from pathlib import Path
from typing import cast
from typing import Dict
from typing import List
from typing import Optional
import py import py
import pytest import pytest
from _pytest.config import ExitCode from _pytest.config import ExitCode
from _pytest.config import PytestPluginManager from _pytest.config import PytestPluginManager
from _pytest.monkeypatch import MonkeyPatch
from _pytest.pathlib import symlink_or_skip from _pytest.pathlib import symlink_or_skip
from _pytest.pytester import Pytester
from _pytest.pytester import Testdir
def ConftestWithSetinitial(path): def ConftestWithSetinitial(path) -> PytestPluginManager:
conftest = PytestPluginManager() conftest = PytestPluginManager()
conftest_setinitial(conftest, [path]) conftest_setinitial(conftest, [path])
return conftest return conftest
def conftest_setinitial(conftest, args, confcutdir=None): def conftest_setinitial(
conftest: PytestPluginManager, args, confcutdir: Optional[py.path.local] = None
) -> None:
class Namespace: class Namespace:
def __init__(self): def __init__(self) -> None:
self.file_or_dir = args self.file_or_dir = args
self.confcutdir = str(confcutdir) self.confcutdir = str(confcutdir)
self.noconftest = False self.noconftest = False
self.pyargs = False self.pyargs = False
self.importmode = "prepend" self.importmode = "prepend"
conftest._set_initial_conftests(Namespace()) namespace = cast(argparse.Namespace, Namespace())
conftest._set_initial_conftests(namespace)
@pytest.mark.usefixtures("_sys_snapshot") @pytest.mark.usefixtures("_sys_snapshot")
@ -82,28 +93,29 @@ class TestConftestValueAccessGlobal:
assert path.purebasename.startswith("conftest") assert path.purebasename.startswith("conftest")
def test_conftest_in_nonpkg_with_init(tmpdir, _sys_snapshot): def test_conftest_in_nonpkg_with_init(tmp_path: Path, _sys_snapshot) -> None:
tmpdir.ensure("adir-1.0/conftest.py").write("a=1 ; Directory = 3") tmp_path.joinpath("adir-1.0/b").mkdir(parents=True)
tmpdir.ensure("adir-1.0/b/conftest.py").write("b=2 ; a = 1.5") tmp_path.joinpath("adir-1.0/conftest.py").write_text("a=1 ; Directory = 3")
tmpdir.ensure("adir-1.0/b/__init__.py") tmp_path.joinpath("adir-1.0/b/conftest.py").write_text("b=2 ; a = 1.5")
tmpdir.ensure("adir-1.0/__init__.py") tmp_path.joinpath("adir-1.0/b/__init__.py").touch()
ConftestWithSetinitial(tmpdir.join("adir-1.0", "b")) tmp_path.joinpath("adir-1.0/__init__.py").touch()
ConftestWithSetinitial(tmp_path.joinpath("adir-1.0", "b"))
def test_doubledash_considered(testdir): def test_doubledash_considered(testdir: Testdir) -> None:
conf = testdir.mkdir("--option") conf = testdir.mkdir("--option")
conf.ensure("conftest.py") conf.join("conftest.py").ensure()
conftest = PytestPluginManager() conftest = PytestPluginManager()
conftest_setinitial(conftest, [conf.basename, conf.basename]) conftest_setinitial(conftest, [conf.basename, conf.basename])
values = conftest._getconftestmodules(conf, importmode="prepend") values = conftest._getconftestmodules(py.path.local(conf), importmode="prepend")
assert len(values) == 1 assert len(values) == 1
def test_issue151_load_all_conftests(testdir): def test_issue151_load_all_conftests(pytester: Pytester) -> None:
names = "code proj src".split() names = "code proj src".split()
for name in names: for name in names:
p = testdir.mkdir(name) p = pytester.mkdir(name)
p.ensure("conftest.py") p.joinpath("conftest.py").touch()
conftest = PytestPluginManager() conftest = PytestPluginManager()
conftest_setinitial(conftest, names) conftest_setinitial(conftest, names)
@ -111,9 +123,9 @@ def test_issue151_load_all_conftests(testdir):
assert len(d) == len(names) assert len(d) == len(names)
def test_conftest_global_import(testdir): def test_conftest_global_import(pytester: Pytester) -> None:
testdir.makeconftest("x=3") pytester.makeconftest("x=3")
p = testdir.makepyfile( p = pytester.makepyfile(
""" """
import py, pytest import py, pytest
from _pytest.config import PytestPluginManager from _pytest.config import PytestPluginManager
@ -131,11 +143,11 @@ def test_conftest_global_import(testdir):
assert conftest is mod2, (conftest, mod) assert conftest is mod2, (conftest, mod)
""" """
) )
res = testdir.runpython(p) res = pytester.runpython(p)
assert res.ret == 0 assert res.ret == 0
def test_conftestcutdir(testdir): def test_conftestcutdir(testdir: Testdir) -> None:
conf = testdir.makeconftest("") conf = testdir.makeconftest("")
p = testdir.mkdir("x") p = testdir.mkdir("x")
conftest = PytestPluginManager() conftest = PytestPluginManager()
@ -144,7 +156,7 @@ def test_conftestcutdir(testdir):
assert len(values) == 0 assert len(values) == 0
values = conftest._getconftestmodules(conf.dirpath(), importmode="prepend") values = conftest._getconftestmodules(conf.dirpath(), importmode="prepend")
assert len(values) == 0 assert len(values) == 0
assert conf not in conftest._conftestpath2mod assert Path(conf) not in conftest._conftestpath2mod
# but we can still import a conftest directly # but we can still import a conftest directly
conftest._importconftest(conf, importmode="prepend") conftest._importconftest(conf, importmode="prepend")
values = conftest._getconftestmodules(conf.dirpath(), importmode="prepend") values = conftest._getconftestmodules(conf.dirpath(), importmode="prepend")
@ -155,22 +167,25 @@ def test_conftestcutdir(testdir):
assert values[0].__file__.startswith(str(conf)) assert values[0].__file__.startswith(str(conf))
def test_conftestcutdir_inplace_considered(testdir): def test_conftestcutdir_inplace_considered(pytester: Pytester) -> None:
conf = testdir.makeconftest("") conf = pytester.makeconftest("")
conftest = PytestPluginManager() conftest = PytestPluginManager()
conftest_setinitial(conftest, [conf.dirpath()], confcutdir=conf.dirpath()) conftest_setinitial(conftest, [conf.parent], confcutdir=py.path.local(conf.parent))
values = conftest._getconftestmodules(conf.dirpath(), importmode="prepend") values = conftest._getconftestmodules(
py.path.local(conf.parent), importmode="prepend"
)
assert len(values) == 1 assert len(values) == 1
assert values[0].__file__.startswith(str(conf)) assert values[0].__file__.startswith(str(conf))
@pytest.mark.parametrize("name", "test tests whatever .dotdir".split()) @pytest.mark.parametrize("name", "test tests whatever .dotdir".split())
def test_setinitial_conftest_subdirs(testdir, name): def test_setinitial_conftest_subdirs(pytester: Pytester, name: str) -> None:
sub = testdir.mkdir(name) sub = pytester.mkdir(name)
subconftest = sub.ensure("conftest.py") subconftest = sub.joinpath("conftest.py")
subconftest.touch()
conftest = PytestPluginManager() conftest = PytestPluginManager()
conftest_setinitial(conftest, [sub.dirpath()], confcutdir=testdir.tmpdir) conftest_setinitial(conftest, [sub.parent], confcutdir=py.path.local(pytester.path))
key = Path(str(subconftest)).resolve() key = subconftest.resolve()
if name not in ("whatever", ".dotdir"): if name not in ("whatever", ".dotdir"):
assert key in conftest._conftestpath2mod assert key in conftest._conftestpath2mod
assert len(conftest._conftestpath2mod) == 1 assert len(conftest._conftestpath2mod) == 1
@ -179,10 +194,10 @@ def test_setinitial_conftest_subdirs(testdir, name):
assert len(conftest._conftestpath2mod) == 0 assert len(conftest._conftestpath2mod) == 0
def test_conftest_confcutdir(testdir): def test_conftest_confcutdir(pytester: Pytester) -> None:
testdir.makeconftest("assert 0") pytester.makeconftest("assert 0")
x = testdir.mkdir("x") x = pytester.mkdir("x")
x.join("conftest.py").write( x.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
def pytest_addoption(parser): def pytest_addoption(parser):
@ -190,12 +205,12 @@ def test_conftest_confcutdir(testdir):
""" """
) )
) )
result = testdir.runpytest("-h", "--confcutdir=%s" % x, x) result = pytester.runpytest("-h", "--confcutdir=%s" % x, x)
result.stdout.fnmatch_lines(["*--xyz*"]) result.stdout.fnmatch_lines(["*--xyz*"])
result.stdout.no_fnmatch_line("*warning: could not load initial*") result.stdout.no_fnmatch_line("*warning: could not load initial*")
def test_conftest_symlink(testdir): def test_conftest_symlink(pytester: Pytester) -> None:
"""`conftest.py` discovery follows normal path resolution and does not resolve symlinks.""" """`conftest.py` discovery follows normal path resolution and does not resolve symlinks."""
# Structure: # Structure:
# /real # /real
@ -208,11 +223,12 @@ def test_conftest_symlink(testdir):
# /symlinktests -> /real/app/tests (running at symlinktests should fail) # /symlinktests -> /real/app/tests (running at symlinktests should fail)
# /symlink -> /real (running at /symlink should work) # /symlink -> /real (running at /symlink should work)
real = testdir.tmpdir.mkdir("real") real = pytester.mkdir("real")
realtests = real.mkdir("app").mkdir("tests") realtests = real.joinpath("app/tests")
symlink_or_skip(realtests, testdir.tmpdir.join("symlinktests")) realtests.mkdir(parents=True)
symlink_or_skip(real, testdir.tmpdir.join("symlink")) symlink_or_skip(realtests, pytester.path.joinpath("symlinktests"))
testdir.makepyfile( symlink_or_skip(real, pytester.path.joinpath("symlink"))
pytester.makepyfile(
**{ **{
"real/app/tests/test_foo.py": "def test1(fixture): pass", "real/app/tests/test_foo.py": "def test1(fixture): pass",
"real/conftest.py": textwrap.dedent( "real/conftest.py": textwrap.dedent(
@ -230,19 +246,19 @@ def test_conftest_symlink(testdir):
) )
# Should fail because conftest cannot be found from the link structure. # Should fail because conftest cannot be found from the link structure.
result = testdir.runpytest("-vs", "symlinktests") result = pytester.runpytest("-vs", "symlinktests")
result.stdout.fnmatch_lines(["*fixture 'fixture' not found*"]) result.stdout.fnmatch_lines(["*fixture 'fixture' not found*"])
assert result.ret == ExitCode.TESTS_FAILED assert result.ret == ExitCode.TESTS_FAILED
# Should not cause "ValueError: Plugin already registered" (#4174). # Should not cause "ValueError: Plugin already registered" (#4174).
result = testdir.runpytest("-vs", "symlink") result = pytester.runpytest("-vs", "symlink")
assert result.ret == ExitCode.OK assert result.ret == ExitCode.OK
def test_conftest_symlink_files(testdir): def test_conftest_symlink_files(pytester: Pytester) -> None:
"""Symlinked conftest.py are found when pytest is executed in a directory with symlinked """Symlinked conftest.py are found when pytest is executed in a directory with symlinked
files.""" files."""
real = testdir.tmpdir.mkdir("real") real = pytester.mkdir("real")
source = { source = {
"app/test_foo.py": "def test1(fixture): pass", "app/test_foo.py": "def test1(fixture): pass",
"app/__init__.py": "", "app/__init__.py": "",
@ -258,16 +274,16 @@ def test_conftest_symlink_files(testdir):
""" """
), ),
} }
testdir.makepyfile(**{"real/%s" % k: v for k, v in source.items()}) pytester.makepyfile(**{"real/%s" % k: v for k, v in source.items()})
# Create a build directory that contains symlinks to actual files # Create a build directory that contains symlinks to actual files
# but doesn't symlink actual directories. # but doesn't symlink actual directories.
build = testdir.tmpdir.mkdir("build") build = pytester.mkdir("build")
build.mkdir("app") build.joinpath("app").mkdir()
for f in source: for f in source:
symlink_or_skip(real.join(f), build.join(f)) symlink_or_skip(real.joinpath(f), build.joinpath(f))
build.chdir() os.chdir(build)
result = testdir.runpytest("-vs", "app/test_foo.py") result = pytester.runpytest("-vs", "app/test_foo.py")
result.stdout.fnmatch_lines(["*conftest_loaded*", "PASSED"]) result.stdout.fnmatch_lines(["*conftest_loaded*", "PASSED"])
assert result.ret == ExitCode.OK assert result.ret == ExitCode.OK
@ -276,39 +292,39 @@ def test_conftest_symlink_files(testdir):
os.path.normcase("x") != os.path.normcase("X"), os.path.normcase("x") != os.path.normcase("X"),
reason="only relevant for case insensitive file systems", reason="only relevant for case insensitive file systems",
) )
def test_conftest_badcase(testdir): def test_conftest_badcase(pytester: Pytester) -> None:
"""Check conftest.py loading when directory casing is wrong (#5792).""" """Check conftest.py loading when directory casing is wrong (#5792)."""
testdir.tmpdir.mkdir("JenkinsRoot").mkdir("test") pytester.path.joinpath("JenkinsRoot/test").mkdir(parents=True)
source = {"setup.py": "", "test/__init__.py": "", "test/conftest.py": ""} source = {"setup.py": "", "test/__init__.py": "", "test/conftest.py": ""}
testdir.makepyfile(**{"JenkinsRoot/%s" % k: v for k, v in source.items()}) pytester.makepyfile(**{"JenkinsRoot/%s" % k: v for k, v in source.items()})
testdir.tmpdir.join("jenkinsroot/test").chdir() os.chdir(pytester.path.joinpath("jenkinsroot/test"))
result = testdir.runpytest() result = pytester.runpytest()
assert result.ret == ExitCode.NO_TESTS_COLLECTED assert result.ret == ExitCode.NO_TESTS_COLLECTED
def test_conftest_uppercase(testdir): def test_conftest_uppercase(pytester: Pytester) -> None:
"""Check conftest.py whose qualified name contains uppercase characters (#5819)""" """Check conftest.py whose qualified name contains uppercase characters (#5819)"""
source = {"__init__.py": "", "Foo/conftest.py": "", "Foo/__init__.py": ""} source = {"__init__.py": "", "Foo/conftest.py": "", "Foo/__init__.py": ""}
testdir.makepyfile(**source) pytester.makepyfile(**source)
testdir.tmpdir.chdir() os.chdir(pytester.path)
result = testdir.runpytest() result = pytester.runpytest()
assert result.ret == ExitCode.NO_TESTS_COLLECTED assert result.ret == ExitCode.NO_TESTS_COLLECTED
def test_no_conftest(testdir): def test_no_conftest(pytester: Pytester) -> None:
testdir.makeconftest("assert 0") pytester.makeconftest("assert 0")
result = testdir.runpytest("--noconftest") result = pytester.runpytest("--noconftest")
assert result.ret == ExitCode.NO_TESTS_COLLECTED assert result.ret == ExitCode.NO_TESTS_COLLECTED
result = testdir.runpytest() result = pytester.runpytest()
assert result.ret == ExitCode.USAGE_ERROR assert result.ret == ExitCode.USAGE_ERROR
def test_conftest_existing_junitxml(testdir): def test_conftest_existing_junitxml(pytester: Pytester) -> None:
x = testdir.mkdir("tests") x = pytester.mkdir("tests")
x.join("conftest.py").write( x.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
def pytest_addoption(parser): def pytest_addoption(parser):
@ -316,12 +332,12 @@ def test_conftest_existing_junitxml(testdir):
""" """
) )
) )
testdir.makefile(ext=".xml", junit="") # Writes junit.xml pytester.makefile(ext=".xml", junit="") # Writes junit.xml
result = testdir.runpytest("-h", "--junitxml", "junit.xml") result = pytester.runpytest("-h", "--junitxml", "junit.xml")
result.stdout.fnmatch_lines(["*--xyz*"]) result.stdout.fnmatch_lines(["*--xyz*"])
def test_conftest_import_order(testdir, monkeypatch): def test_conftest_import_order(testdir: Testdir, monkeypatch: MonkeyPatch) -> None:
ct1 = testdir.makeconftest("") ct1 = testdir.makeconftest("")
sub = testdir.mkdir("sub") sub = testdir.mkdir("sub")
ct2 = sub.join("conftest.py") ct2 = sub.join("conftest.py")
@ -333,16 +349,21 @@ def test_conftest_import_order(testdir, monkeypatch):
conftest = PytestPluginManager() conftest = PytestPluginManager()
conftest._confcutdir = testdir.tmpdir conftest._confcutdir = testdir.tmpdir
monkeypatch.setattr(conftest, "_importconftest", impct) monkeypatch.setattr(conftest, "_importconftest", impct)
assert conftest._getconftestmodules(sub, importmode="prepend") == [ct1, ct2] mods = cast(
List[py.path.local],
conftest._getconftestmodules(py.path.local(sub), importmode="prepend"),
)
expected = [ct1, ct2]
assert mods == expected
def test_fixture_dependency(testdir): def test_fixture_dependency(pytester: Pytester) -> None:
ct1 = testdir.makeconftest("") ct1 = pytester.makeconftest("")
ct1 = testdir.makepyfile("__init__.py") ct1 = pytester.makepyfile("__init__.py")
ct1.write("") ct1.write_text("")
sub = testdir.mkdir("sub") sub = pytester.mkdir("sub")
sub.join("__init__.py").write("") sub.joinpath("__init__.py").write_text("")
sub.join("conftest.py").write( sub.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
import pytest import pytest
@ -361,9 +382,10 @@ def test_fixture_dependency(testdir):
""" """
) )
) )
subsub = sub.mkdir("subsub") subsub = sub.joinpath("subsub")
subsub.join("__init__.py").write("") subsub.mkdir()
subsub.join("test_bar.py").write( subsub.joinpath("__init__.py").write_text("")
subsub.joinpath("test_bar.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
import pytest import pytest
@ -377,13 +399,13 @@ def test_fixture_dependency(testdir):
""" """
) )
) )
result = testdir.runpytest("sub") result = pytester.runpytest("sub")
result.stdout.fnmatch_lines(["*1 passed*"]) result.stdout.fnmatch_lines(["*1 passed*"])
def test_conftest_found_with_double_dash(testdir): def test_conftest_found_with_double_dash(pytester: Pytester) -> None:
sub = testdir.mkdir("sub") sub = pytester.mkdir("sub")
sub.join("conftest.py").write( sub.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
def pytest_addoption(parser): def pytest_addoption(parser):
@ -391,9 +413,9 @@ def test_conftest_found_with_double_dash(testdir):
""" """
) )
) )
p = sub.join("test_hello.py") p = sub.joinpath("test_hello.py")
p.write("def test_hello(): pass") p.write_text("def test_hello(): pass")
result = testdir.runpytest(str(p) + "::test_hello", "-h") result = pytester.runpytest(str(p) + "::test_hello", "-h")
result.stdout.fnmatch_lines( result.stdout.fnmatch_lines(
""" """
*--hello-world* *--hello-world*
@ -402,13 +424,13 @@ def test_conftest_found_with_double_dash(testdir):
class TestConftestVisibility: class TestConftestVisibility:
def _setup_tree(self, testdir): # for issue616 def _setup_tree(self, pytester: Pytester) -> Dict[str, Path]: # for issue616
# example mostly taken from: # example mostly taken from:
# https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html # https://mail.python.org/pipermail/pytest-dev/2014-September/002617.html
runner = testdir.mkdir("empty") runner = pytester.mkdir("empty")
package = testdir.mkdir("package") package = pytester.mkdir("package")
package.join("conftest.py").write( package.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
import pytest import pytest
@ -418,7 +440,7 @@ class TestConftestVisibility:
""" """
) )
) )
package.join("test_pkgroot.py").write( package.joinpath("test_pkgroot.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
def test_pkgroot(fxtr): def test_pkgroot(fxtr):
@ -427,9 +449,10 @@ class TestConftestVisibility:
) )
) )
swc = package.mkdir("swc") swc = package.joinpath("swc")
swc.join("__init__.py").ensure() swc.mkdir()
swc.join("conftest.py").write( swc.joinpath("__init__.py").touch()
swc.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
import pytest import pytest
@ -439,7 +462,7 @@ class TestConftestVisibility:
""" """
) )
) )
swc.join("test_with_conftest.py").write( swc.joinpath("test_with_conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
def test_with_conftest(fxtr): def test_with_conftest(fxtr):
@ -448,9 +471,10 @@ class TestConftestVisibility:
) )
) )
snc = package.mkdir("snc") snc = package.joinpath("snc")
snc.join("__init__.py").ensure() snc.mkdir()
snc.join("test_no_conftest.py").write( snc.joinpath("__init__.py").touch()
snc.joinpath("test_no_conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
def test_no_conftest(fxtr): def test_no_conftest(fxtr):
@ -460,9 +484,8 @@ class TestConftestVisibility:
) )
) )
print("created directory structure:") print("created directory structure:")
tmppath = Path(str(testdir.tmpdir)) for x in pytester.path.rglob(""):
for x in tmppath.rglob(""): print(" " + str(x.relative_to(pytester.path)))
print(" " + str(x.relative_to(tmppath)))
return {"runner": runner, "package": package, "swc": swc, "snc": snc} return {"runner": runner, "package": package, "swc": swc, "snc": snc}
@ -494,29 +517,32 @@ class TestConftestVisibility:
], ],
) )
def test_parsefactories_relative_node_ids( def test_parsefactories_relative_node_ids(
self, testdir, chdir, testarg, expect_ntests_passed self, pytester: Pytester, chdir: str, testarg: str, expect_ntests_passed: int
): ) -> None:
"""#616""" """#616"""
dirs = self._setup_tree(testdir) dirs = self._setup_tree(pytester)
print("pytest run in cwd: %s" % (dirs[chdir].relto(testdir.tmpdir))) print("pytest run in cwd: %s" % (dirs[chdir].relative_to(pytester.path)))
print("pytestarg : %s" % (testarg)) print("pytestarg : %s" % (testarg))
print("expected pass : %s" % (expect_ntests_passed)) print("expected pass : %s" % (expect_ntests_passed))
with dirs[chdir].as_cwd(): os.chdir(dirs[chdir])
reprec = testdir.inline_run(testarg, "-q", "--traceconfig") reprec = pytester.inline_run(testarg, "-q", "--traceconfig")
reprec.assertoutcome(passed=expect_ntests_passed) reprec.assertoutcome(passed=expect_ntests_passed)
@pytest.mark.parametrize( @pytest.mark.parametrize(
"confcutdir,passed,error", [(".", 2, 0), ("src", 1, 1), (None, 1, 1)] "confcutdir,passed,error", [(".", 2, 0), ("src", 1, 1), (None, 1, 1)]
) )
def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error): def test_search_conftest_up_to_inifile(
pytester: Pytester, confcutdir: str, passed: int, error: int
) -> None:
"""Test that conftest files are detected only up to an ini file, unless """Test that conftest files are detected only up to an ini file, unless
an explicit --confcutdir option is given. an explicit --confcutdir option is given.
""" """
root = testdir.tmpdir root = pytester.path
src = root.join("src").ensure(dir=1) src = root.joinpath("src")
src.join("pytest.ini").write("[pytest]") src.mkdir()
src.join("conftest.py").write( src.joinpath("pytest.ini").write_text("[pytest]")
src.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
import pytest import pytest
@ -525,7 +551,7 @@ def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):
""" """
) )
) )
src.join("test_foo.py").write( src.joinpath("test_foo.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
def test_1(fix1): def test_1(fix1):
@ -535,7 +561,7 @@ def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):
""" """
) )
) )
root.join("conftest.py").write( root.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
import pytest import pytest
@ -547,8 +573,8 @@ def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):
args = [str(src)] args = [str(src)]
if confcutdir: if confcutdir:
args = ["--confcutdir=%s" % root.join(confcutdir)] args = ["--confcutdir=%s" % root.joinpath(confcutdir)]
result = testdir.runpytest(*args) result = pytester.runpytest(*args)
match = "" match = ""
if passed: if passed:
match += "*%d passed*" % passed match += "*%d passed*" % passed
@ -557,8 +583,8 @@ def test_search_conftest_up_to_inifile(testdir, confcutdir, passed, error):
result.stdout.fnmatch_lines(match) result.stdout.fnmatch_lines(match)
def test_issue1073_conftest_special_objects(testdir): def test_issue1073_conftest_special_objects(pytester: Pytester) -> None:
testdir.makeconftest( pytester.makeconftest(
"""\ """\
class DontTouchMe(object): class DontTouchMe(object):
def __getattr__(self, x): def __getattr__(self, x):
@ -567,38 +593,38 @@ def test_issue1073_conftest_special_objects(testdir):
x = DontTouchMe() x = DontTouchMe()
""" """
) )
testdir.makepyfile( pytester.makepyfile(
"""\ """\
def test_some(): def test_some():
pass pass
""" """
) )
res = testdir.runpytest() res = pytester.runpytest()
assert res.ret == 0 assert res.ret == 0
def test_conftest_exception_handling(testdir): def test_conftest_exception_handling(pytester: Pytester) -> None:
testdir.makeconftest( pytester.makeconftest(
"""\ """\
raise ValueError() raise ValueError()
""" """
) )
testdir.makepyfile( pytester.makepyfile(
"""\ """\
def test_some(): def test_some():
pass pass
""" """
) )
res = testdir.runpytest() res = pytester.runpytest()
assert res.ret == 4 assert res.ret == 4
assert "raise ValueError()" in [line.strip() for line in res.errlines] assert "raise ValueError()" in [line.strip() for line in res.errlines]
def test_hook_proxy(testdir): def test_hook_proxy(pytester: Pytester) -> None:
"""Session's gethookproxy() would cache conftests incorrectly (#2016). """Session's gethookproxy() would cache conftests incorrectly (#2016).
It was decided to remove the cache altogether. It was decided to remove the cache altogether.
""" """
testdir.makepyfile( pytester.makepyfile(
**{ **{
"root/demo-0/test_foo1.py": "def test1(): pass", "root/demo-0/test_foo1.py": "def test1(): pass",
"root/demo-a/test_foo2.py": "def test1(): pass", "root/demo-a/test_foo2.py": "def test1(): pass",
@ -610,16 +636,16 @@ def test_hook_proxy(testdir):
"root/demo-c/test_foo4.py": "def test1(): pass", "root/demo-c/test_foo4.py": "def test1(): pass",
} }
) )
result = testdir.runpytest() result = pytester.runpytest()
result.stdout.fnmatch_lines( result.stdout.fnmatch_lines(
["*test_foo1.py*", "*test_foo3.py*", "*test_foo4.py*", "*3 passed*"] ["*test_foo1.py*", "*test_foo3.py*", "*test_foo4.py*", "*3 passed*"]
) )
def test_required_option_help(testdir): def test_required_option_help(pytester: Pytester) -> None:
testdir.makeconftest("assert 0") pytester.makeconftest("assert 0")
x = testdir.mkdir("x") x = pytester.mkdir("x")
x.join("conftest.py").write( x.joinpath("conftest.py").write_text(
textwrap.dedent( textwrap.dedent(
"""\ """\
def pytest_addoption(parser): def pytest_addoption(parser):
@ -627,6 +653,6 @@ def test_required_option_help(testdir):
""" """
) )
) )
result = testdir.runpytest("-h", x) result = pytester.runpytest("-h", x)
result.stdout.no_fnmatch_line("*argument --xyz is required*") result.stdout.no_fnmatch_line("*argument --xyz is required*")
assert "general:" in result.stdout.str() assert "general:" in result.stdout.str()

View File

@ -3,6 +3,7 @@ import warnings
from typing import Optional from typing import Optional
import pytest import pytest
from _pytest.pytester import Pytester
from _pytest.recwarn import WarningsRecorder from _pytest.recwarn import WarningsRecorder
@ -12,8 +13,8 @@ def test_recwarn_stacklevel(recwarn: WarningsRecorder) -> None:
assert warn.filename == __file__ assert warn.filename == __file__
def test_recwarn_functional(testdir) -> None: def test_recwarn_functional(pytester: Pytester) -> None:
testdir.makepyfile( pytester.makepyfile(
""" """
import warnings import warnings
def test_method(recwarn): def test_method(recwarn):
@ -22,7 +23,7 @@ def test_recwarn_functional(testdir) -> None:
assert isinstance(warn.message, UserWarning) assert isinstance(warn.message, UserWarning)
""" """
) )
reprec = testdir.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
@ -328,9 +329,9 @@ class TestWarns:
assert str(record[0].message) == "user" assert str(record[0].message) == "user"
assert str(record[1].message) == "runtime" assert str(record[1].message) == "runtime"
def test_double_test(self, testdir) -> None: def test_double_test(self, pytester: Pytester) -> None:
"""If a test is run again, the warning should still be raised""" """If a test is run again, the warning should still be raised"""
testdir.makepyfile( pytester.makepyfile(
""" """
import pytest import pytest
import warnings import warnings
@ -341,7 +342,7 @@ class TestWarns:
warnings.warn("runtime", RuntimeWarning) warnings.warn("runtime", RuntimeWarning)
""" """
) )
result = testdir.runpytest() result = pytester.runpytest()
result.stdout.fnmatch_lines(["*2 passed in*"]) result.stdout.fnmatch_lines(["*2 passed in*"])
def test_match_regex(self) -> None: def test_match_regex(self) -> None:

View File

@ -18,14 +18,15 @@ from _pytest.pathlib import maybe_delete_a_numbered_dir
from _pytest.pathlib import on_rm_rf_error from _pytest.pathlib import on_rm_rf_error
from _pytest.pathlib import register_cleanup_lock_removal from _pytest.pathlib import register_cleanup_lock_removal
from _pytest.pathlib import rm_rf from _pytest.pathlib import rm_rf
from _pytest.pytester import Pytester
from _pytest.tmpdir import get_user from _pytest.tmpdir import get_user
from _pytest.tmpdir import TempdirFactory from _pytest.tmpdir import TempdirFactory
from _pytest.tmpdir import TempPathFactory from _pytest.tmpdir import TempPathFactory
def test_tmpdir_fixture(testdir): def test_tmpdir_fixture(pytester: Pytester) -> None:
p = testdir.copy_example("tmpdir/tmpdir_fixture.py") p = pytester.copy_example("tmpdir/tmpdir_fixture.py")
results = testdir.runpytest(p) results = pytester.runpytest(p)
results.stdout.fnmatch_lines(["*1 passed*"]) results.stdout.fnmatch_lines(["*1 passed*"])
@ -66,21 +67,21 @@ class TestTempdirHandler:
class TestConfigTmpdir: class TestConfigTmpdir:
def test_getbasetemp_custom_removes_old(self, testdir): def test_getbasetemp_custom_removes_old(self, pytester: Pytester) -> None:
mytemp = testdir.tmpdir.join("xyz") mytemp = pytester.path.joinpath("xyz")
p = testdir.makepyfile( p = pytester.makepyfile(
""" """
def test_1(tmpdir): def test_1(tmpdir):
pass pass
""" """
) )
testdir.runpytest(p, "--basetemp=%s" % mytemp) pytester.runpytest(p, "--basetemp=%s" % mytemp)
mytemp.check() assert mytemp.exists()
mytemp.ensure("hello") mytemp.joinpath("hello").touch()
testdir.runpytest(p, "--basetemp=%s" % mytemp) pytester.runpytest(p, "--basetemp=%s" % mytemp)
mytemp.check() assert mytemp.exists()
assert not mytemp.join("hello").check() assert not mytemp.joinpath("hello").exists()
testdata = [ testdata = [
@ -96,9 +97,9 @@ testdata = [
@pytest.mark.parametrize("basename, is_ok", testdata) @pytest.mark.parametrize("basename, is_ok", testdata)
def test_mktemp(testdir, basename, is_ok): def test_mktemp(pytester: Pytester, basename: str, is_ok: bool) -> None:
mytemp = testdir.tmpdir.mkdir("mytemp") mytemp = pytester.mkdir("mytemp")
p = testdir.makepyfile( p = pytester.makepyfile(
""" """
def test_abs_path(tmpdir_factory): def test_abs_path(tmpdir_factory):
tmpdir_factory.mktemp('{}', numbered=False) tmpdir_factory.mktemp('{}', numbered=False)
@ -107,54 +108,54 @@ def test_mktemp(testdir, basename, is_ok):
) )
) )
result = testdir.runpytest(p, "--basetemp=%s" % mytemp) result = pytester.runpytest(p, "--basetemp=%s" % mytemp)
if is_ok: if is_ok:
assert result.ret == 0 assert result.ret == 0
assert mytemp.join(basename).check() assert mytemp.joinpath(basename).exists()
else: else:
assert result.ret == 1 assert result.ret == 1
result.stdout.fnmatch_lines("*ValueError*") result.stdout.fnmatch_lines("*ValueError*")
def test_tmpdir_always_is_realpath(testdir): def test_tmpdir_always_is_realpath(pytester: Pytester) -> None:
# the reason why tmpdir should be a realpath is that # the reason why tmpdir should be a realpath is that
# when you cd to it and do "os.getcwd()" you will anyway # when you cd to it and do "os.getcwd()" you will anyway
# get the realpath. Using the symlinked path can thus # get the realpath. Using the symlinked path can thus
# easily result in path-inequality # easily result in path-inequality
# XXX if that proves to be a problem, consider using # XXX if that proves to be a problem, consider using
# os.environ["PWD"] # os.environ["PWD"]
realtemp = testdir.tmpdir.mkdir("myrealtemp") realtemp = pytester.mkdir("myrealtemp")
linktemp = testdir.tmpdir.join("symlinktemp") linktemp = pytester.path.joinpath("symlinktemp")
attempt_symlink_to(linktemp, str(realtemp)) attempt_symlink_to(linktemp, str(realtemp))
p = testdir.makepyfile( p = pytester.makepyfile(
""" """
def test_1(tmpdir): def test_1(tmpdir):
import os import os
assert os.path.realpath(str(tmpdir)) == str(tmpdir) assert os.path.realpath(str(tmpdir)) == str(tmpdir)
""" """
) )
result = testdir.runpytest("-s", p, "--basetemp=%s/bt" % linktemp) result = pytester.runpytest("-s", p, "--basetemp=%s/bt" % linktemp)
assert not result.ret assert not result.ret
def test_tmp_path_always_is_realpath(testdir, monkeypatch): def test_tmp_path_always_is_realpath(pytester: Pytester, monkeypatch) -> None:
# for reasoning see: test_tmpdir_always_is_realpath test-case # for reasoning see: test_tmpdir_always_is_realpath test-case
realtemp = testdir.tmpdir.mkdir("myrealtemp") realtemp = pytester.mkdir("myrealtemp")
linktemp = testdir.tmpdir.join("symlinktemp") linktemp = pytester.path.joinpath("symlinktemp")
attempt_symlink_to(linktemp, str(realtemp)) attempt_symlink_to(linktemp, str(realtemp))
monkeypatch.setenv("PYTEST_DEBUG_TEMPROOT", str(linktemp)) monkeypatch.setenv("PYTEST_DEBUG_TEMPROOT", str(linktemp))
testdir.makepyfile( pytester.makepyfile(
""" """
def test_1(tmp_path): def test_1(tmp_path):
assert tmp_path.resolve() == tmp_path assert tmp_path.resolve() == tmp_path
""" """
) )
reprec = testdir.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
def test_tmpdir_too_long_on_parametrization(testdir): def test_tmpdir_too_long_on_parametrization(pytester: Pytester) -> None:
testdir.makepyfile( pytester.makepyfile(
""" """
import pytest import pytest
@pytest.mark.parametrize("arg", ["1"*1000]) @pytest.mark.parametrize("arg", ["1"*1000])
@ -162,12 +163,12 @@ def test_tmpdir_too_long_on_parametrization(testdir):
tmpdir.ensure("hello") tmpdir.ensure("hello")
""" """
) )
reprec = testdir.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
def test_tmpdir_factory(testdir): def test_tmpdir_factory(pytester: Pytester) -> None:
testdir.makepyfile( pytester.makepyfile(
""" """
import pytest import pytest
@pytest.fixture(scope='session') @pytest.fixture(scope='session')
@ -177,23 +178,23 @@ def test_tmpdir_factory(testdir):
assert session_dir.isdir() assert session_dir.isdir()
""" """
) )
reprec = testdir.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
def test_tmpdir_fallback_tox_env(testdir, monkeypatch): def test_tmpdir_fallback_tox_env(pytester: Pytester, monkeypatch) -> None:
"""Test that tmpdir works even if environment variables required by getpass """Test that tmpdir works even if environment variables required by getpass
module are missing (#1010). module are missing (#1010).
""" """
monkeypatch.delenv("USER", raising=False) monkeypatch.delenv("USER", raising=False)
monkeypatch.delenv("USERNAME", raising=False) monkeypatch.delenv("USERNAME", raising=False)
testdir.makepyfile( pytester.makepyfile(
""" """
def test_some(tmpdir): def test_some(tmpdir):
assert tmpdir.isdir() assert tmpdir.isdir()
""" """
) )
reprec = testdir.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
@ -207,18 +208,18 @@ def break_getuser(monkeypatch):
@pytest.mark.usefixtures("break_getuser") @pytest.mark.usefixtures("break_getuser")
@pytest.mark.skipif(sys.platform.startswith("win"), reason="no os.getuid on windows") @pytest.mark.skipif(sys.platform.startswith("win"), reason="no os.getuid on windows")
def test_tmpdir_fallback_uid_not_found(testdir): def test_tmpdir_fallback_uid_not_found(pytester: Pytester) -> None:
"""Test that tmpdir works even if the current process's user id does not """Test that tmpdir works even if the current process's user id does not
correspond to a valid user. correspond to a valid user.
""" """
testdir.makepyfile( pytester.makepyfile(
""" """
def test_some(tmpdir): def test_some(tmpdir):
assert tmpdir.isdir() assert tmpdir.isdir()
""" """
) )
reprec = testdir.inline_run() reprec = pytester.inline_run()
reprec.assertoutcome(passed=1) reprec.assertoutcome(passed=1)
@ -423,9 +424,9 @@ def test_tmpdir_equals_tmp_path(tmpdir, tmp_path):
assert Path(tmpdir) == tmp_path assert Path(tmpdir) == tmp_path
def test_basetemp_with_read_only_files(testdir): def test_basetemp_with_read_only_files(pytester: Pytester) -> None:
"""Integration test for #5524""" """Integration test for #5524"""
testdir.makepyfile( pytester.makepyfile(
""" """
import os import os
import stat import stat
@ -437,8 +438,8 @@ def test_basetemp_with_read_only_files(testdir):
os.chmod(str(fn), mode & ~stat.S_IREAD) os.chmod(str(fn), mode & ~stat.S_IREAD)
""" """
) )
result = testdir.runpytest("--basetemp=tmp") result = pytester.runpytest("--basetemp=tmp")
assert result.ret == 0 assert result.ret == 0
# running a second time and ensure we don't crash # running a second time and ensure we don't crash
result = testdir.runpytest("--basetemp=tmp") result = pytester.runpytest("--basetemp=tmp")
assert result.ret == 0 assert result.ret == 0