Skip to content

Commit 10fa66e

Browse files
authored
Merge pull request #5059 from blueyed/pytester-popen-run-stdin
pytester: allow passing in stdin to run/popen
2 parents 5e26304 + b84f826 commit 10fa66e

File tree

4 files changed

+113
-6
lines changed

4 files changed

+113
-6
lines changed

changelog/5059.feature.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Standard input (stdin) can be given to pytester's ``Testdir.run()`` and ``Testdir.popen()``.

changelog/5059.trivial.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
pytester's ``Testdir.popen()`` uses ``stdout`` and ``stderr`` via keyword arguments with defaults now (``subprocess.PIPE``).

src/_pytest/pytester.py

Lines changed: 34 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -473,6 +473,8 @@ class Testdir(object):
473473
474474
"""
475475

476+
CLOSE_STDIN = object
477+
476478
class TimeoutExpired(Exception):
477479
pass
478480

@@ -1032,7 +1034,14 @@ def collect_by_name(self, modcol, name):
10321034
if colitem.name == name:
10331035
return colitem
10341036

1035-
def popen(self, cmdargs, stdout, stderr, **kw):
1037+
def popen(
1038+
self,
1039+
cmdargs,
1040+
stdout=subprocess.PIPE,
1041+
stderr=subprocess.PIPE,
1042+
stdin=CLOSE_STDIN,
1043+
**kw
1044+
):
10361045
"""Invoke subprocess.Popen.
10371046
10381047
This calls subprocess.Popen making sure the current working directory
@@ -1050,10 +1059,18 @@ def popen(self, cmdargs, stdout, stderr, **kw):
10501059
env["USERPROFILE"] = env["HOME"]
10511060
kw["env"] = env
10521061

1053-
popen = subprocess.Popen(
1054-
cmdargs, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw
1055-
)
1056-
popen.stdin.close()
1062+
if stdin is Testdir.CLOSE_STDIN:
1063+
kw["stdin"] = subprocess.PIPE
1064+
elif isinstance(stdin, bytes):
1065+
kw["stdin"] = subprocess.PIPE
1066+
else:
1067+
kw["stdin"] = stdin
1068+
1069+
popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)
1070+
if stdin is Testdir.CLOSE_STDIN:
1071+
popen.stdin.close()
1072+
elif isinstance(stdin, bytes):
1073+
popen.stdin.write(stdin)
10571074

10581075
return popen
10591076

@@ -1065,13 +1082,18 @@ def run(self, *cmdargs, **kwargs):
10651082
:param args: the sequence of arguments to pass to `subprocess.Popen()`
10661083
:param timeout: the period in seconds after which to timeout and raise
10671084
:py:class:`Testdir.TimeoutExpired`
1085+
:param stdin: optional standard input. Bytes are being send, closing
1086+
the pipe, otherwise it is passed through to ``popen``.
1087+
Defaults to ``CLOSE_STDIN``, which translates to using a pipe
1088+
(``subprocess.PIPE``) that gets closed.
10681089
10691090
Returns a :py:class:`RunResult`.
10701091
10711092
"""
10721093
__tracebackhide__ = True
10731094

10741095
timeout = kwargs.pop("timeout", None)
1096+
stdin = kwargs.pop("stdin", Testdir.CLOSE_STDIN)
10751097
raise_on_kwargs(kwargs)
10761098

10771099
cmdargs = [
@@ -1086,8 +1108,14 @@ def run(self, *cmdargs, **kwargs):
10861108
try:
10871109
now = time.time()
10881110
popen = self.popen(
1089-
cmdargs, stdout=f1, stderr=f2, close_fds=(sys.platform != "win32")
1111+
cmdargs,
1112+
stdin=stdin,
1113+
stdout=f1,
1114+
stderr=f2,
1115+
close_fds=(sys.platform != "win32"),
10901116
)
1117+
if isinstance(stdin, bytes):
1118+
popen.stdin.close()
10911119

10921120
def handle_timeout():
10931121
__tracebackhide__ = True

testing/test_pytester.py

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from __future__ import print_function
55

66
import os
7+
import subprocess
78
import sys
89
import time
910

@@ -482,3 +483,79 @@ def test_pytester_addopts(request, monkeypatch):
482483
testdir.finalize()
483484

484485
assert os.environ["PYTEST_ADDOPTS"] == "--orig-unused"
486+
487+
488+
def test_run_stdin(testdir):
489+
with pytest.raises(testdir.TimeoutExpired):
490+
testdir.run(
491+
sys.executable,
492+
"-c",
493+
"import sys, time; time.sleep(1); print(sys.stdin.read())",
494+
stdin=subprocess.PIPE,
495+
timeout=0.1,
496+
)
497+
498+
with pytest.raises(testdir.TimeoutExpired):
499+
result = testdir.run(
500+
sys.executable,
501+
"-c",
502+
"import sys, time; time.sleep(1); print(sys.stdin.read())",
503+
stdin=b"input\n2ndline",
504+
timeout=0.1,
505+
)
506+
507+
result = testdir.run(
508+
sys.executable,
509+
"-c",
510+
"import sys; print(sys.stdin.read())",
511+
stdin=b"input\n2ndline",
512+
)
513+
assert result.stdout.lines == ["input", "2ndline"]
514+
assert result.stderr.str() == ""
515+
assert result.ret == 0
516+
517+
518+
def test_popen_stdin_pipe(testdir):
519+
proc = testdir.popen(
520+
[sys.executable, "-c", "import sys; print(sys.stdin.read())"],
521+
stdout=subprocess.PIPE,
522+
stderr=subprocess.PIPE,
523+
stdin=subprocess.PIPE,
524+
)
525+
stdin = b"input\n2ndline"
526+
stdout, stderr = proc.communicate(input=stdin)
527+
assert stdout.decode("utf8").splitlines() == ["input", "2ndline"]
528+
assert stderr == b""
529+
assert proc.returncode == 0
530+
531+
532+
def test_popen_stdin_bytes(testdir):
533+
proc = testdir.popen(
534+
[sys.executable, "-c", "import sys; print(sys.stdin.read())"],
535+
stdout=subprocess.PIPE,
536+
stderr=subprocess.PIPE,
537+
stdin=b"input\n2ndline",
538+
)
539+
stdout, stderr = proc.communicate()
540+
assert stdout.decode("utf8").splitlines() == ["input", "2ndline"]
541+
assert stderr == b""
542+
assert proc.returncode == 0
543+
544+
545+
def test_popen_default_stdin_stderr_and_stdin_None(testdir):
546+
# stdout, stderr default to pipes,
547+
# stdin can be None to not close the pipe, avoiding
548+
# "ValueError: flush of closed file" with `communicate()`.
549+
p1 = testdir.makepyfile(
550+
"""
551+
import sys
552+
print(sys.stdin.read()) # empty
553+
print('stdout')
554+
sys.stderr.write('stderr')
555+
"""
556+
)
557+
proc = testdir.popen([sys.executable, str(p1)], stdin=None)
558+
stdout, stderr = proc.communicate(b"ignored")
559+
assert stdout.splitlines() == [b"", b"stdout"]
560+
assert stderr.splitlines() == [b"stderr"]
561+
assert proc.returncode == 0

0 commit comments

Comments
 (0)