Skip to content

Commit 73991e2

Browse files
committed
SysCaptureBinary: decode in writeorg
Fixes #6871.
1 parent ac7ebfa commit 73991e2

File tree

3 files changed

+22
-3
lines changed

3 files changed

+22
-3
lines changed

changelog/6871.bugfix.rst

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix crash with captured output when using the :fixture:`capsysbinary fixture <capsysbinary>`.

src/_pytest/capture.py

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -681,7 +681,8 @@ def resume(self):
681681
setattr(sys, self.name, self.tmpfile)
682682
self._state = "resumed"
683683

684-
def writeorg(self, data):
684+
def writeorg(self, data: str) -> None:
685+
data = data.decode(self._old.encoding)
685686
self._old.write(data)
686687
self._old.flush()
687688

@@ -695,6 +696,10 @@ def snap(self):
695696
self.tmpfile.truncate()
696697
return res
697698

699+
def writeorg(self, data: str) -> None:
700+
self._old.write(data)
701+
self._old.flush()
702+
698703

699704
class TeeSysCapture(SysCapture):
700705
def __init__(self, fd, tmpfile=None):

testing/test_capture.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -542,18 +542,31 @@ def test_hello(capfdbinary):
542542
reprec.assertoutcome(passed=1)
543543

544544
def test_capsysbinary(self, testdir):
545-
reprec = testdir.inline_runsource(
545+
p1 = testdir.makepyfile(
546546
"""\
547547
def test_hello(capsysbinary):
548548
import sys
549+
549550
# some likely un-decodable bytes
550551
sys.stdout.buffer.write(b'\\xfe\\x98\\x20')
552+
551553
out, err = capsysbinary.readouterr()
552554
assert out == b'\\xfe\\x98\\x20'
553555
assert err == b''
556+
557+
# handles writing strings
558+
print("hello")
559+
print("hello stderr", file=sys.stderr)
554560
"""
555561
)
556-
reprec.assertoutcome(passed=1)
562+
result = testdir.runpytest(str(p1), "-rA")
563+
result.stdout.fnmatch_lines([
564+
"*- Captured stdout call -*",
565+
"hello",
566+
"*- Captured stderr call -*",
567+
"hello stderr",
568+
"*= 1 passed in *",
569+
])
557570

558571
def test_partial_setup_failure(self, testdir):
559572
p = testdir.makepyfile(

0 commit comments

Comments
 (0)