Fix `EncodedFile.writelines`

This is implemented by the underlying stream already, which additionally
checks if the stream is not closed, and calls `write` per line.

Ref/via: https://github.com/pytest-dev/pytest/pull/6558#issuecomment-578210807
This commit is contained in:
Daniel Hahler 2020-01-25 10:58:26 +01:00
parent b687f20d25
commit 039d582b52
3 changed files with 16 additions and 3 deletions

View File

@ -0,0 +1 @@
Fix ``EncodedFile.writelines`` to call the underlying buffer's ``writelines`` method.

View File

@ -9,6 +9,7 @@ import os
import sys
from io import UnsupportedOperation
from tempfile import TemporaryFile
from typing import List
import pytest
from _pytest.compat import CaptureIO
@ -426,9 +427,8 @@ class EncodedFile:
)
return self.buffer.write(obj)
def writelines(self, linelist):
data = "".join(linelist)
self.write(data)
def writelines(self, linelist: List[str]) -> None:
self.buffer.writelines([x.encode(self.encoding, "replace") for x in linelist])
@property
def name(self):

View File

@ -1497,3 +1497,15 @@ def test_typeerror_encodedfile_write(testdir):
def test_stderr_write_returns_len(capsys):
"""Write on Encoded files, namely captured stderr, should return number of characters written."""
assert sys.stderr.write("Foo") == 3
def test_encodedfile_writelines(tmpfile) -> None:
ef = capture.EncodedFile(tmpfile, "utf-8")
with pytest.raises(AttributeError):
ef.writelines([b"line1", b"line2"]) # type: ignore[list-item] # noqa: F821
assert ef.writelines(["line1", "line2"]) is None # type: ignore[func-returns-value] # noqa: F821
tmpfile.seek(0)
assert tmpfile.read() == b"line1line2"
tmpfile.close()
with pytest.raises(ValueError):
ef.read()