Skip to content

Commit

Permalink
[4.6] capsys: ensure fd is unbuffered
Browse files Browse the repository at this point in the history
  • Loading branch information
blueyed committed Oct 26, 2019
1 parent 3edf417 commit 6fcbb5e
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 0 deletions.
1 change: 1 addition & 0 deletions changelog/5134.bugfix.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix buffering with capsys fixture on Python 2.
3 changes: 3 additions & 0 deletions src/_pytest/capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -652,6 +652,9 @@ class SysCapture(object):
def __init__(self, fd, tmpfile=None):
name = patchsysdict[fd]
self._old = getattr(sys, name)
if six.PY2:
# Ensure fd is unbuffered (#5134).
self._old = os.fdopen(self._old.fileno(), "wb+", 0)
self.name = name
if tmpfile is None:
if name == "stdin":
Expand Down
49 changes: 49 additions & 0 deletions testing/test_capture.py
Original file line number Diff line number Diff line change
Expand Up @@ -1577,3 +1577,52 @@ def test_fails():
)
else:
assert result_with_capture.ret == 0


def test_syscapture_is_unbuffered_when_suspended(testdir, LineMatcher):
import time

stampfile = testdir.tmpdir.join("stampfile")
testdir.makepyfile(
**{
"conftest.py": """
import ctypes
libc = ctypes.CDLL(None)
libc.puts(b'this comes from C via conftest')
""",
"test_pass.py": """
import os
import time
def test_capfd(capfd):
print("test_capfd 1")
with capfd.disabled():
for i in range(0, 5):
if os.path.exists({stampfile!r}):
break
print("test_capfd 2: %d" % i)
time.sleep(1)
""".format(
stampfile=str(stampfile)
),
}
)

child = testdir.spawn_pytest("-s --color=no -vv")
start = time.time()
child.expect_exact("test_capfd 2: 0\r\n")
stampfile.ensure()
out = child.before + child.buffer + child.after
duration = time.time() - start
assert duration < 5

out += child.read()
lm = LineMatcher(out.decode().splitlines())
lm.fnmatch_lines(
[
"this comes from C via conftest",
"test_pass.py::test_capfd test_capfd 2: 0",
"*= 1 passed in *",
]
)

0 comments on commit 6fcbb5e

Please sign in to comment.