Debian Codegraph @

testing/io/test_terminalwriter.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Generator
5 import io
6 from io import StringIO
7 import os
8 from pathlib import Path
9 import re
10 import shutil
11 import sys
12 from unittest import mock
13
14 from _pytest._io import terminalwriter
15 from _pytest.monkeypatch import MonkeyPatch
16 import pytest
17
18
19 # These tests were initially copied from py 1.8.1.
20
21
22 def test_terminal_width_COLUMNS(monkeypatch: MonkeyPatch) -> None:
23 monkeypatch.setenv("COLUMNS", "42")
24 assert terminalwriter.get_terminal_width() == 42
25 monkeypatch.delenv("COLUMNS", raising=False)
26
27
28 def test_terminalwriter_width_bogus(monkeypatch: MonkeyPatch) -> None:
29 monkeypatch.setattr(shutil, "get_terminal_size", mock.Mock(return_value=(10, 10)))
30 monkeypatch.delenv("COLUMNS", raising=False)
31 tw = terminalwriter.TerminalWriter()
32 assert tw.fullwidth == 80
33
34
35 def test_terminalwriter_computes_width(monkeypatch: MonkeyPatch) -> None:
36 monkeypatch.setattr(terminalwriter, "get_terminal_width", lambda: 42)
37 tw = terminalwriter.TerminalWriter()
38 assert tw.fullwidth == 42
39
40
41 def test_terminalwriter_dumb_term_no_markup(monkeypatch: MonkeyPatch) -> None:
42 monkeypatch.setattr(os, "environ", {"TERM": "dumb", "PATH": ""})
43
44 class MyFile:
45 closed = False
46
47 def isatty(self):
48 return True
49
50 with monkeypatch.context() as m:
51 m.setattr(sys, "stdout", MyFile())
52 assert sys.stdout.isatty()
53 tw = terminalwriter.TerminalWriter()
54 assert not tw.hasmarkup
55
56
57 def test_terminalwriter_not_unicode() -> None:
58 """If the file doesn't support Unicode, the string is unicode-escaped (#7475)."""
59 buffer = io.BytesIO()
60 file = io.TextIOWrapper(buffer, encoding="cp1252")
61 tw = terminalwriter.TerminalWriter(file)
62 tw.write("hello 🌀 wôrld אבג", flush=True)
63 assert buffer.getvalue() == rb"hello \U0001f300 w\xf4rld \u05d0\u05d1\u05d2"
64
65
66 win32 = int(sys.platform == "win32")
67
68
69 class TestTerminalWriter:
70 @pytest.fixture(params=["path", "stringio"])
71 def tw(self, request, tmp_path: Path) -> Generator[terminalwriter.TerminalWriter]:
72 f: io.TextIOWrapper | StringIO
73 if request.param == "path":
74 p = tmp_path.joinpath("tmpfile")
75 f = open(str(p), "w+", encoding="utf8")
76 tw = terminalwriter.TerminalWriter(f)
77
78 def getlines():
79 f.flush()
80 with open(str(p), encoding="utf8") as fp:
81 return fp.readlines()
82
83 elif request.param == "stringio":
84 f = io.StringIO()
85 tw = terminalwriter.TerminalWriter(f)
86
87 def getlines():
88 f.seek(0)
89 return f.readlines()
90
91 tw.getlines = getlines # type: ignore
92 tw.getvalue = lambda: "".join(getlines()) # type: ignore
93
94 with f:
95 yield tw
96
97 def test_line(self, tw) -> None:
98 tw.line("hello")
99 lines = tw.getlines()
100 assert len(lines) == 1
101 assert lines[0] == "hello\n"
102
103 def test_line_unicode(self, tw) -> None:
104 msg = "b\u00f6y"
105 tw.line(msg)
106 lines = tw.getlines()
107 assert lines[0] == msg + "\n"
108
109 def test_sep_no_title(self, tw) -> None:
110 tw.sep("-", fullwidth=60)
111 lines = tw.getlines()
112 assert len(lines) == 1
113 assert lines[0] == "-" * (60 - win32) + "\n"
114
115 def test_sep_with_title(self, tw) -> None:
116 tw.sep("-", "hello", fullwidth=60)
117 lines = tw.getlines()
118 assert len(lines) == 1
119 assert lines[0] == "-" * 26 + " hello " + "-" * (27 - win32) + "\n"
120
121 def test_sep_longer_than_width(self, tw) -> None:
122 tw.sep("-", "a" * 10, fullwidth=5)
123 (line,) = tw.getlines()
124 # even though the string is wider than the line, still have a separator
125 assert line == "- aaaaaaaaaa -\n"
126
127 @pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")
128 @pytest.mark.parametrize("bold", (True, False))
129 @pytest.mark.parametrize("color", ("red", "green"))
130 def test_markup(self, tw, bold: bool, color: str) -> None:
131 text = tw.markup("hello", **{color: True, "bold": bold})
132 assert "hello" in text
133
134 def test_markup_bad(self, tw) -> None:
135 with pytest.raises(ValueError):
136 tw.markup("x", wronkw=3)
137 with pytest.raises(ValueError):
138 tw.markup("x", wronkw=0)
139
140 def test_line_write_markup(self, tw) -> None:
141 tw.hasmarkup = True
142 tw.line("x", bold=True)
143 tw.write("x\n", red=True)
144 lines = tw.getlines()
145 if sys.platform != "win32":
146 assert len(lines[0]) >= 2, lines
147 assert len(lines[1]) >= 2, lines
148
149 def test_attr_fullwidth(self, tw) -> None:
150 tw.sep("-", "hello", fullwidth=70)
151 tw.fullwidth = 70
152 tw.sep("-", "hello")
153 lines = tw.getlines()
154 assert len(lines[0]) == len(lines[1])
155
156
157 @pytest.mark.skipif(sys.platform == "win32", reason="win32 has no native ansi")
158 def test_attr_hasmarkup() -> None:
159 file = io.StringIO()
160 tw = terminalwriter.TerminalWriter(file)
161 assert not tw.hasmarkup
162 tw.hasmarkup = True
163 tw.line("hello", bold=True)
164 s = file.getvalue()
165 assert len(s) > len("hello\n")
166 assert "\x1b[1m" in s
167 assert "\x1b[0m" in s
168
169
170 def assert_color(expected: bool, default: bool | None = None) -> None:
171 file = io.StringIO()
172 if default is None:
173 default = not expected
174 file.isatty = lambda: default # type: ignore
175 tw = terminalwriter.TerminalWriter(file=file)
176 assert tw.hasmarkup is expected
177 tw.line("hello", bold=True)
178 s = file.getvalue()
179 if expected:
180 assert len(s) > len("hello\n")
181 assert "\x1b[1m" in s
182 assert "\x1b[0m" in s
183 else:
184 assert s == "hello\n"
185
186
187 def test_should_do_markup_PY_COLORS_eq_1(monkeypatch: MonkeyPatch) -> None:
188 monkeypatch.setitem(os.environ, "PY_COLORS", "1")
189 assert_color(True)
190
191
192 def test_should_not_do_markup_PY_COLORS_eq_0(monkeypatch: MonkeyPatch) -> None:
193 monkeypatch.setitem(os.environ, "PY_COLORS", "0")
194 assert_color(False)
195
196
197 def test_should_not_do_markup_NO_COLOR(monkeypatch: MonkeyPatch) -> None:
198 monkeypatch.setitem(os.environ, "NO_COLOR", "1")
199 assert_color(False)
200
201
202 def test_should_do_markup_FORCE_COLOR(monkeypatch: MonkeyPatch) -> None:
203 monkeypatch.setitem(os.environ, "FORCE_COLOR", "1")
204 assert_color(True)
205
206
207 @pytest.mark.parametrize(
208 ["NO_COLOR", "FORCE_COLOR", "expected"],
209 [
210 ("1", "1", False),
211 ("", "1", True),
212 ("1", "", False),
213 ],
214 )
215 def test_NO_COLOR_and_FORCE_COLOR(
216 monkeypatch: MonkeyPatch,
217 NO_COLOR: str,
218 FORCE_COLOR: str,
219 expected: bool,
220 ) -> None:
221 monkeypatch.setitem(os.environ, "NO_COLOR", NO_COLOR)
222 monkeypatch.setitem(os.environ, "FORCE_COLOR", FORCE_COLOR)
223 assert_color(expected)
224
225
226 def test_empty_NO_COLOR_and_FORCE_COLOR_ignored(monkeypatch: MonkeyPatch) -> None:
227 monkeypatch.setenv("TERM", "xterm-256color")
228 monkeypatch.setitem(os.environ, "NO_COLOR", "")
229 monkeypatch.setitem(os.environ, "FORCE_COLOR", "")
230 assert_color(True, True)
231 assert_color(False, False)
232
233
234 class TestTerminalWriterLineWidth:
235 def test_init(self) -> None:
236 tw = terminalwriter.TerminalWriter()
237 assert tw.width_of_current_line == 0
238
239 def test_update(self) -> None:
240 tw = terminalwriter.TerminalWriter()
241 tw.write("hello world")
242 assert tw.width_of_current_line == 11
243
244 def test_update_with_newline(self) -> None:
245 tw = terminalwriter.TerminalWriter()
246 tw.write("hello\nworld")
247 assert tw.width_of_current_line == 5
248
249 def test_update_with_wide_text(self) -> None:
250 tw = terminalwriter.TerminalWriter()
251 tw.write("乇乂ㄒ尺卂 ㄒ卄丨匚匚")
252 assert tw.width_of_current_line == 21 # 5*2 + 1 + 5*2
253
254 def test_composed(self) -> None:
255 tw = terminalwriter.TerminalWriter()
256 text = "café food"
257 assert len(text) == 9
258 tw.write(text)
259 assert tw.width_of_current_line == 9
260
261 def test_combining(self) -> None:
262 tw = terminalwriter.TerminalWriter()
263 text = "café food"
264 assert len(text) == 10
265 tw.write(text)
266 assert tw.width_of_current_line == 9
267
268
269 @pytest.mark.parametrize(
270 ("has_markup", "code_highlight", "expected"),
271 [
272 pytest.param(
273 True,
274 True,
275 "{reset}{kw}assert{hl-reset} {number}0{hl-reset}{endline}\n",
276 id="with markup and code_highlight",
277 ),
278 pytest.param(
279 True,
280 False,
281 "assert 0\n",
282 id="with markup but no code_highlight",
283 ),
284 pytest.param(
285 False,
286 True,
287 "assert 0\n",
288 id="without markup but with code_highlight",
289 ),
290 pytest.param(
291 False,
292 False,
293 "assert 0\n",
294 id="neither markup nor code_highlight",
295 ),
296 ],
297 )
298 def test_code_highlight(has_markup, code_highlight, expected, color_mapping):
299 f = io.StringIO()
300 tw = terminalwriter.TerminalWriter(f)
301 tw.hasmarkup = has_markup
302 tw.code_highlight = code_highlight
303 tw._write_source(["assert 0"])
304
305 assert f.getvalue().splitlines(keepends=True) == color_mapping.format([expected])
306
307 with pytest.raises(
308 ValueError,
309 match=re.escape("indents size (2) should have same size as lines (1)"),
310 ):
311 tw._write_source(["assert 0"], [" ", " "])
312
313
314 def test_highlight_empty_source() -> None:
315 """Don't crash trying to highlight empty source code.
316
317 Issue #11758.
318 """
319 f = io.StringIO()
320 tw = terminalwriter.TerminalWriter(f)
321 tw.hasmarkup = True
322 tw.code_highlight = True
323 tw._write_source([])
324
325 assert f.getvalue() == ""