Skip to content

Commit f6de998

Browse files
committed
pytester: testdir: add makefiles helper
This is a sane method to create a set of files, allowing for absolute paths. Ref: #6578 Ref: #6579
1 parent eb7a57f commit f6de998

File tree

2 files changed

+26
-0
lines changed

2 files changed

+26
-0
lines changed

src/_pytest/pytester.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import re
88
import subprocess
99
import sys
10+
import textwrap
1011
import time
1112
import traceback
1213
from fnmatch import fnmatch
@@ -665,6 +666,17 @@ def maketxtfile(self, *args, **kwargs):
665666
"""Shortcut for .makefile() with a .txt extension."""
666667
return self._makefile(".txt", args, kwargs)
667668

669+
def makefiles(self, **kwargs: str) -> Optional[Path]:
670+
"""Create the given set of files."""
671+
first_path = None
672+
for fname, content in kwargs.items():
673+
path = Path(self.tmpdir).joinpath(Path(fname))
674+
with open(path, "w") as fp:
675+
fp.write(textwrap.dedent(content))
676+
if not first_path:
677+
first_path = path
678+
return first_path
679+
668680
def syspathinsert(self, path=None):
669681
"""Prepend a directory to sys.path, defaults to :py:attr:`tmpdir`.
670682

testing/test_pytester.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
from _pytest.config import PytestPluginManager
1212
from _pytest.main import ExitCode
1313
from _pytest.outcomes import Failed
14+
from _pytest.pathlib import Path
1415
from _pytest.pytester import CwdSnapshot
1516
from _pytest.pytester import HookRecorder
1617
from _pytest.pytester import LineMatcher
@@ -710,3 +711,16 @@ def test_error2(bad_fixture):
710711
result.assert_outcomes(error=2)
711712

712713
assert result.parseoutcomes() == {"error": 2}
714+
715+
716+
def test_testdir_makefiles(testdir: Testdir) -> None:
717+
abspath = str(testdir.tmpdir / "bar")
718+
p1 = testdir.makefiles(**{"foo": "", abspath: ""})
719+
relpath = testdir.tmpdir / "foo"
720+
assert p1 == relpath
721+
722+
abspath_path = Path(abspath)
723+
assert abspath_path.exists()
724+
assert str(abspath_path) == abspath
725+
726+
assert testdir.makefiles() is None

0 commit comments

Comments
 (0)