Skip to content

Commit

Permalink
fix: a fake stdout might not have isatty
Browse files Browse the repository at this point in the history
  • Loading branch information
nedbat committed Apr 30, 2023
1 parent 31c216b commit 731e9a7
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 2 deletions.
4 changes: 3 additions & 1 deletion CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,9 @@ development at the same time, such as 4.5.x and 5.0.
Unreleased
----------

Nothing yet.
- Fix: ``html_report()`` could fail with an AttributeError on ``isatty`` if run
in an unusual environment where sys.stdout had been replaced. This is now
fixed.


.. scriv-start-here
Expand Down
2 changes: 1 addition & 1 deletion coverage/misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def stdout_link(text: str, url: str) -> str:
If attached to a terminal, use escape sequences. Otherwise, just return
the text.
"""
if sys.stdout.isatty():
if hasattr(sys.stdout, "isatty") and sys.stdout.isatty():
return f"\033]8;;{url}\a{text}\033]8;;\a"
else:
return text
17 changes: 17 additions & 0 deletions tests/test_misc.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
from __future__ import annotations

import sys
from typing import Any
from unittest import mock

import pytest
Expand Down Expand Up @@ -165,3 +166,19 @@ def test_stdout_link_tty() -> None:
def test_stdout_link_not_tty() -> None:
# Without mocking isatty, it reports False in a pytest suite.
assert stdout_link("some text", "some url") == "some text"


def test_stdout_link_with_fake_stdout() -> None:
# If stdout is another object, we should still be ok.
class FakeStdout:
"""New stdout, has .write(), but not .isatty()."""
def __init__(self, f: Any) -> None:
self.f = f

def write(self, data: str) -> Any:
"""Write through to the underlying file."""
return self.f.write(data)

with mock.patch.object(sys, "stdout", FakeStdout(sys.stdout)):
link = stdout_link("some text", "some url")
assert link == "some text"

0 comments on commit 731e9a7

Please sign in to comment.