Skip to content

Commit 9ad0071

Browse files
committed
pytester: allow passing in stdin to run/popen
1 parent b549438 commit 9ad0071

File tree

3 files changed

+91
-6
lines changed

3 files changed

+91
-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()``.

src/_pytest/pytester.py

Lines changed: 32 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,8 @@
3636
u"/var/lib/sss/mc/passwd"
3737
]
3838

39+
CLOSE_STDIN = object
40+
3941

4042
def pytest_addoption(parser):
4143
parser.addoption(
@@ -1032,7 +1034,7 @@ 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(self, cmdargs, stdout, stderr, stdin=CLOSE_STDIN, **kw):
10361038
"""Invoke subprocess.Popen.
10371039
10381040
This calls subprocess.Popen making sure the current working directory
@@ -1050,10 +1052,18 @@ def popen(self, cmdargs, stdout, stderr, **kw):
10501052
env["USERPROFILE"] = env["HOME"]
10511053
kw["env"] = env
10521054

1053-
popen = subprocess.Popen(
1054-
cmdargs, stdin=subprocess.PIPE, stdout=stdout, stderr=stderr, **kw
1055-
)
1056-
popen.stdin.close()
1055+
if stdin is CLOSE_STDIN:
1056+
kw["stdin"] = subprocess.PIPE
1057+
elif isinstance(stdin, bytes):
1058+
kw["stdin"] = subprocess.PIPE
1059+
else:
1060+
kw["stdin"] = stdin
1061+
1062+
popen = subprocess.Popen(cmdargs, stdout=stdout, stderr=stderr, **kw)
1063+
if stdin is CLOSE_STDIN:
1064+
popen.stdin.close()
1065+
elif isinstance(stdin, bytes):
1066+
popen.stdin.write(stdin)
10571067

10581068
return popen
10591069

@@ -1065,15 +1075,24 @@ def run(self, *cmdargs, **kwargs):
10651075
:param args: the sequence of arguments to pass to `subprocess.Popen()`
10661076
:param timeout: the period in seconds after which to timeout and raise
10671077
:py:class:`Testdir.TimeoutExpired`
1078+
:param stdin: optional standard input. Bytes are being send, closing
1079+
the pipe, otherwise it is passed through to ``popen``.
1080+
Defaults to ``CLOSE_STDIN``, which translates to using a pipe
1081+
(``subprocess.PIPE``) that gets closed.
10681082
10691083
Returns a :py:class:`RunResult`.
10701084
10711085
"""
10721086
__tracebackhide__ = True
10731087

10741088
timeout = kwargs.pop("timeout", None)
1089+
stdin = kwargs.pop("stdin", CLOSE_STDIN)
10751090
raise_on_kwargs(kwargs)
10761091

1092+
popen_kwargs = {"stdin": stdin}
1093+
if isinstance(stdin, bytes):
1094+
popen_kwargs["stdin"] = subprocess.PIPE
1095+
10771096
cmdargs = [
10781097
str(arg) if isinstance(arg, py.path.local) else arg for arg in cmdargs
10791098
]
@@ -1086,8 +1105,15 @@ def run(self, *cmdargs, **kwargs):
10861105
try:
10871106
now = time.time()
10881107
popen = self.popen(
1089-
cmdargs, stdout=f1, stderr=f2, close_fds=(sys.platform != "win32")
1108+
cmdargs,
1109+
stdout=f1,
1110+
stderr=f2,
1111+
close_fds=(sys.platform != "win32"),
1112+
**popen_kwargs
10901113
)
1114+
if isinstance(stdin, bytes):
1115+
popen.stdin.write(stdin)
1116+
popen.stdin.close()
10911117

10921118
def handle_timeout():
10931119
__tracebackhide__ = True

testing/test_pytester.py

Lines changed: 58 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,60 @@ 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; 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

0 commit comments

Comments
 (0)