Skip to content

Commit

Permalink
Subclass StringIO for _WarningStream. (#886)
Browse files Browse the repository at this point in the history
This is responding to a change in readme_renderer.rst.render that
expects an `IO[str]` instance. See discussion at
pypa/readme_renderer#231 (review)
  • Loading branch information
bhrutledge committed Mar 31, 2022
1 parent aa7c047 commit 7cd0b23
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 28 deletions.
15 changes: 4 additions & 11 deletions tests/test_check.py
Expand Up @@ -24,25 +24,18 @@
class TestWarningStream:
def setup(self):
self.stream = check._WarningStream()
self.stream.output = pretend.stub(
write=pretend.call_recorder(lambda a: None),
getvalue=lambda: "result",
)

def test_write_match(self):
self.stream.write("<string>:2: (WARNING/2) Title underline too short.")

assert self.stream.output.write.calls == [
pretend.call("line 2: Warning: Title underline too short.\n")
]
assert self.stream.getvalue() == "line 2: Warning: Title underline too short.\n"

def test_write_nomatch(self):
self.stream.write("this does not match")

assert self.stream.output.write.calls == [pretend.call("this does not match")]
assert self.stream.getvalue() == "this does not match"

def test_str_representation(self):
assert str(self.stream) == "result"
self.stream.write("<string>:2: (WARNING/2) Title underline too short.")
assert str(self.stream) == "line 2: Warning: Title underline too short."


def test_check_no_distributions(monkeypatch, caplog):
Expand Down
26 changes: 9 additions & 17 deletions twine/commands/check.py
Expand Up @@ -48,27 +48,19 @@
)


class _WarningStream:
def __init__(self) -> None:
self.output = io.StringIO()

def write(self, text: str) -> None:
class _WarningStream(io.StringIO):
def write(self, text: str) -> int:
matched = _REPORT_RE.search(text)
if matched:
line = matched.group("line")
level_text = matched.group("level").capitalize()
message = matched.group("message").rstrip("\r\n")
text = f"line {line}: {level_text}: {message}\n"

if not matched:
self.output.write(text)
return

self.output.write(
"line {line}: {level_text}: {message}\n".format(
level_text=matched.group("level").capitalize(),
line=matched.group("line"),
message=matched.group("message").rstrip("\r\n"),
)
)
return super().write(text)

def __str__(self) -> str:
return self.output.getvalue().strip()
return self.getvalue().strip()


def _check_file(
Expand Down

0 comments on commit 7cd0b23

Please sign in to comment.