Coverage for tests / test_types_file.py: 100%
256 statements
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
« prev ^ index » next coverage.py v7.13.1, created at 2026-11-18 11:12 +0000
1import subprocess 1abcdefghij
2import sys 1abcdefghij
3from io import BytesIO, StringIO 1abcdefghij
4from pathlib import Path 1abcdefghij
6import pytest 1abcdefghij
7import typer 1abcdefghij
8from typer._click._compat import get_best_encoding, should_strip_ansi 1abcdefghij
9from typer._click.utils import PacifyFlushWrapper 1abcdefghij
10from typer.testing import CliRunner 1abcdefghij
12from tests.utils import needs_linux, needs_macos, needs_windows 1abcdefghij
14app = typer.Typer() 1abcdefghij
17@app.command() 1abcdefghij
18def read_text(file_in: typer.FileText = typer.Option(..., lazy=True)): 1abcdefghij
19 data = file_in.read() 1abcdefghij
20 typer.echo(f"text-len={len(data)}") 1abcdefghij
23@app.command() 1abcdefghij
24def write_text(file_out: typer.FileTextWrite = typer.Option(..., lazy=None)): 1abcdefghij
25 file_out.write("This is a single line\n") 1abcdefghij
26 typer.echo("1 line written") 1abcdefghij
29@app.command() 1abcdefghij
30def write_lazy(file_out: typer.FileTextWrite = typer.Option(..., lazy=True)): 1abcdefghij
31 file_out.write("This is a single lazy line\n") 1abcdefghij
32 typer.echo("1 line written") 1abcdefghij
35@app.command() 1abcdefghij
36def probe_lazy_file_behaviors( 1abcdefghij
37 file_in: typer.FileText = typer.Option(..., lazy=True),
38 file_out: typer.FileTextWrite = typer.Option(..., lazy=True),
39):
40 typer.echo(f"repr-before={repr(file_out)}") 1abcdefghij
41 file_out.write("repr-opened\n") 1abcdefghij
42 typer.echo(f"repr-after={repr(file_out)}") 1abcdefghij
43 with file_in as stream: 1abcdefghij
44 typer.echo(f"context-len={len(stream.read())}") 1abcdefghij
45 stream.seek(0) 1abcdefghij
46 first_line = next(iter(stream), "") 1abcdefghij
47 typer.echo(f"first-line={first_line.rstrip()}") 1abcdefghij
50@app.command() 1abcdefghij
51def write_binary(file_out: typer.FileBinaryWrite = typer.Option(...)): 1abcdefghij
52 file_out.write(b"binary-written\n") 1abcdefghij
55@app.command() 1abcdefghij
56def write_binary_stderr(): 1abcdefghij
57 stream = typer.get_binary_stream("stderr") 1abcdefghij
58 stream.write(b"binary-stderr\n") 1abcdefghij
59 stream.flush() 1abcdefghij
62@app.command() 1abcdefghij
63def read_binary(file_in: typer.FileBinaryRead = typer.Option(...)): 1abcdefghij
64 data = file_in.read() 1abcdefghij
65 typer.echo(f"binary-len={len(data)}") 1abcdefghij
68runner = CliRunner() 1abcdefghij
71def test_text_stdin_dash() -> None: 1abcdefghij
72 result = runner.invoke(app, ["read-text", "--file-in=-"], input="hello\n") 1abcdefghij
73 assert result.exit_code == 0 1abcdefghij
74 assert "text-len=6" in result.output 1abcdefghij
77def test_lazy_file(tmp_path: Path) -> None: 1abcdefghij
78 # dash: written to stdout
79 result = runner.invoke(app, ["write-text", "--file-out=-"]) 1abcdefghij
80 assert result.exit_code == 0 1abcdefghij
81 assert "This is a single line" in result.output 1abcdefghij
82 assert "1 line written" in result.output 1abcdefghij
84 # lazy + file
85 file_path = tmp_path / "example.txt" 1abcdefghij
86 result = runner.invoke(app, ["write-lazy", f"--file-out={file_path}"]) 1abcdefghij
87 assert result.exit_code == 0 1abcdefghij
88 assert "This is a single lazy line" not in result.output 1abcdefghij
89 assert "1 line written" in result.output 1abcdefghij
90 assert file_path.exists() 1abcdefghij
91 assert file_path.read_text() == "This is a single lazy line\n" 1abcdefghij
93 # lazy probe: unopened/opened repr, context manager, and iteration.
94 result = runner.invoke( 1abcdefghij
95 app,
96 [
97 "probe-lazy-file-behaviors",
98 f"--file-in={file_path}",
99 f"--file-out={tmp_path / 'repr-opened.txt'}",
100 ],
101 )
102 assert result.exit_code == 0 1abcdefghij
103 assert "repr-before=<unopened file" in result.output 1abcdefghij
104 assert "repr-after=<unopened file" not in result.output 1abcdefghij
105 assert "repr-opened.txt" in result.output 1abcdefghij
106 assert "context-len=27" in result.output 1abcdefghij
107 assert "first-line=This is a single lazy line" in result.output 1abcdefghij
109 # lazy + dash: written to stdout (lazy setting is pretty much ignored)
110 result = runner.invoke(app, ["write-lazy", "--file-out=-"]) 1abcdefghij
111 assert result.exit_code == 0 1abcdefghij
112 assert "This is a single lazy line" in result.output 1abcdefghij
113 assert "1 line written" in result.output 1abcdefghij
116def test_filelike_conversion() -> None: 1abcdefghij
117 stream = StringIO() 1abcdefghij
118 result = runner.invoke( 1abcdefghij
119 app, ["write-text"], default_map={"write-text": {"file_out": stream}}
120 )
121 assert result.exit_code == 0 1abcdefghij
122 assert "1 line written" in result.output 1abcdefghij
123 assert stream.getvalue() == "This is a single line\n" 1abcdefghij
126def test_binary_dash() -> None: 1abcdefghij
127 result = runner.invoke(app, ["write-binary", "--file-out=-"]) 1abcdefghij
128 assert result.exit_code == 0 1abcdefghij
129 assert result.stdout_bytes == b"binary-written\n" 1abcdefghij
131 result = runner.invoke( 1abcdefghij
132 app, ["read-binary", "--file-in=-"], input=b"\x00\x01\x02abc"
133 )
134 assert result.exit_code == 0 1abcdefghij
135 assert "binary-len=6" in result.output 1abcdefghij
138def test_binary_stderr() -> None: 1abcdefghij
139 result = subprocess.run( 1abcdefghij
140 [
141 sys.executable,
142 "-m",
143 "coverage",
144 "run",
145 __file__,
146 "write-binary-stderr",
147 ],
148 capture_output=True,
149 )
150 assert result.returncode == 0 1abcdefghij
151 assert result.stderr == b"binary-stderr\n" 1abcdefghij
154@pytest.mark.parametrize( 1abcdefghij
155 ("errors_arg", "expected_errors"),
156 [
157 (None, "replace"),
158 ("strict", "strict"),
159 ],
160)
161def test_get_text_stream_errors( 1abcdefghij
162 monkeypatch,
163 errors_arg: str | None,
164 expected_errors: str,
165) -> None:
166 class BinaryStdout(BytesIO): 1abcdefghij
167 pass 1abcdefghij
169 binary_stdout = BinaryStdout() 1abcdefghij
170 monkeypatch.setattr(sys, "stdout", binary_stdout) 1abcdefghij
172 text_stream = typer.get_text_stream("stdout", encoding=None, errors=errors_arg) 1abcdefghij
173 text_stream.write("stream-text") 1abcdefghij
174 text_stream.flush() 1abcdefghij
176 assert text_stream.errors == expected_errors 1abcdefghij
177 assert text_stream.writable() is True 1abcdefghij
178 assert binary_stdout.getvalue() == b"stream-text" 1abcdefghij
181def test_get_best_encoding() -> None: 1abcdefghij
182 """Test that ASCII is being transformed into UTF-8"""
184 class AsciiStream: 1abcdefghij
185 encoding = "ascii" 1abcdefghij
187 class Utf8Stream: 1abcdefghij
188 encoding = "utf-8" 1abcdefghij
190 class UnknownStream: 1abcdefghij
191 encoding = "unknown" 1abcdefghij
193 assert get_best_encoding(AsciiStream()) == "utf-8" 1abcdefghij
194 assert get_best_encoding(Utf8Stream()) == "utf-8" 1abcdefghij
195 assert get_best_encoding(UnknownStream()) == "unknown" 1abcdefghij
198def test_pacify_flush_wrapper() -> None: 1abcdefghij
199 class Wrapped: 1abcdefghij
200 def __init__(self) -> None: 1abcdefghij
201 self.name = "wrapped-stream" 1abcdefghij
203 def flush(self) -> None: 1abcdefghij
204 return None # pragma: no cover
206 wrapped = PacifyFlushWrapper(Wrapped()) 1abcdefghij
207 assert wrapped.name == "wrapped-stream" 1abcdefghij
210def test_text_stream_isatty(monkeypatch) -> None: 1abcdefghij
211 class BinaryStdout(BytesIO): 1abcdefghij
212 def isatty(self) -> bool: 1abcdefghij
213 return True 1abcdefghij
215 binary_stdout = BinaryStdout() 1abcdefghij
216 monkeypatch.setattr(sys, "stdout", binary_stdout) 1abcdefghij
217 text_stream = typer.get_text_stream("stdout", encoding="utf-8", errors=None) 1abcdefghij
218 assert text_stream.isatty() is True 1abcdefghij
221def test_text_stream_buffer_read1(monkeypatch) -> None: 1abcdefghij
222 class BinaryStdinNoRead1: 1abcdefghij
223 def __init__(self, data: bytes) -> None: 1abcdefghij
224 self._data = data 1abcdefghij
225 self._pos = 0 1abcdefghij
227 def read(self, size: int = -1) -> bytes: 1abcdefghij
228 if size < 0: 1abcdefghij
229 size = len(self._data) - self._pos # pragma: no cover
230 chunk = self._data[self._pos : self._pos + size] 1abcdefghij
231 self._pos += len(chunk) 1abcdefghij
232 return chunk 1abcdefghij
234 binary_stdin = BinaryStdinNoRead1(b"hello") 1abcdefghij
235 monkeypatch.setattr(sys, "stdin", binary_stdin) 1abcdefghij
236 text_stream = typer.get_text_stream("stdin", encoding="utf-8", errors=None) 1abcdefghij
237 assert text_stream._stream.read1(4) == b"hell" 1abcdefghij
240def test_binary_stream(monkeypatch) -> None: 1abcdefghij
241 binary_stdin = BytesIO(b"hello") 1abcdefghij
242 binary_stdout = BytesIO() 1abcdefghij
243 monkeypatch.setattr(sys, "stdin", binary_stdin) 1abcdefghij
244 monkeypatch.setattr(sys, "stdout", binary_stdout) 1abcdefghij
246 assert typer.get_binary_stream("stdin") is binary_stdin 1abcdefghij
247 assert typer.get_binary_stream("stdout") is binary_stdout 1abcdefghij
250def test_binary_stream_raises(monkeypatch) -> None: 1abcdefghij
251 class TextOnlyStdin: 1abcdefghij
252 def read(self, n: int = -1) -> str: 1abcdefghij
253 return "hello" 1abcdefghij
255 monkeypatch.setattr(sys, "stdin", TextOnlyStdin()) 1abcdefghij
256 with pytest.raises(RuntimeError, match="Was not able to determine binary stream"): 1abcdefghij
257 typer.get_binary_stream("stdin") 1abcdefghij
260def test_stream_unknown() -> None: 1abcdefghij
261 with pytest.raises(TypeError, match="Unknown standard stream 'Plumbus'"): 1abcdefghij
262 typer.get_binary_stream("Plumbus") # type: ignore[arg-type] 1abcdefghij
264 with pytest.raises(TypeError, match="Unknown standard stream 'Fleeb'"): 1abcdefghij
265 typer.get_text_stream("Fleeb") # type: ignore[arg-type] 1abcdefghij
268def test_format_filename() -> None: 1abcdefghij
269 filename = b"folder/subdir/demo.txt" 1abcdefghij
270 assert typer.format_filename(filename, shorten=True) == "demo.txt" 1abcdefghij
273def test_file_error(monkeypatch, tmp_path: Path) -> None: 1abcdefghij
274 file_path = tmp_path / "cannot-open.txt" 1abcdefghij
276 def fake_open(path, *args, **kwargs): 1abcdefghij
277 if Path(path) == file_path: 1abcdefghij
278 raise OSError() 1abcdefghij
280 monkeypatch.setattr("builtins.open", fake_open) 1abcdefghij
281 result = runner.invoke(app, ["write-text", f"--file-out={file_path}"]) 1abcdefghij
282 assert result.exit_code == 1 1abcdefghij
283 assert "Could not open file" in result.output 1abcdefghij
284 assert "cannot-open.txt" in result.output 1abcdefghij
285 assert "unknown error" in result.output 1abcdefghij
288@needs_windows 1abcdefghij
289def test_app_dir_windows_fallback( 1abcdefghij
290 monkeypatch: pytest.MonkeyPatch,
291) -> None:
292 monkeypatch.delenv("APPDATA", raising=False) 1efg
293 monkeypatch.setattr("os.path.expanduser", lambda _path: r"C:\Users\Tester") 1efg
295 assert typer.get_app_dir("My App", roaming=True) == r"C:\Users\Tester\My App" 1efg
298@needs_linux 1abcdefghij
299def test_app_dir_force_posix(monkeypatch: pytest.MonkeyPatch) -> None: 1abcdefghij
300 monkeypatch.setattr("os.path.expanduser", lambda _path: "/home/tester/.my-app") 1abcd
302 assert typer.get_app_dir("My App", force_posix=True) == "/home/tester/.my-app" 1abcd
305@needs_linux 1abcdefghij
306def test_app_dir_linux_xdg_config_home(monkeypatch: pytest.MonkeyPatch) -> None: 1abcdefghij
307 monkeypatch.setenv("XDG_CONFIG_HOME", "/home/tester/config") 1abcd
309 assert typer.get_app_dir("My App") == "/home/tester/config/my-app" 1abcd
312@needs_linux 1abcdefghij
313def test_app_dir_linux_default(monkeypatch: pytest.MonkeyPatch) -> None: 1abcdefghij
314 monkeypatch.delenv("XDG_CONFIG_HOME", raising=False) 1abcd
315 monkeypatch.setattr("os.path.expanduser", lambda _path: "/home/tester/.config") 1abcd
317 assert typer.get_app_dir("My App") == "/home/tester/.config/my-app" 1abcd
320@needs_macos 1abcdefghij
321def test_app_dir_macos(monkeypatch: pytest.MonkeyPatch) -> None: 1abcdefghij
322 monkeypatch.setattr( 1hij
323 "os.path.expanduser", lambda _path: "/Users/tester/Library/Application Support"
324 )
326 assert ( 1hij
327 typer.get_app_dir("My App")
328 == "/Users/tester/Library/Application Support/My App"
329 )
332def test_text_stream_binary_buffer(monkeypatch) -> None: 1abcdefghij
333 class TextStdinWithBinaryBuffer: 1abcdefghij
334 def __init__(self, data: bytes) -> None: 1abcdefghij
335 self.buffer = BytesIO(data) 1abcdefghij
336 self.encoding = "latin-1" 1abcdefghij
338 def read(self, n: int = -1) -> str: 1abcdefghij
339 raise OSError("text stream is not readable directly") 1abcdefghij
341 class TextStdoutWithBinaryBuffer: 1abcdefghij
342 def __init__(self) -> None: 1abcdefghij
343 self.buffer = BytesIO() 1abcdefghij
344 self.encoding = "latin-1" 1abcdefghij
346 def write(self, s: str) -> int: 1abcdefghij
347 raise OSError("text stream is not writable directly") 1abcdefghij
349 stdin = TextStdinWithBinaryBuffer(b"hello") 1abcdefghij
350 stdout = TextStdoutWithBinaryBuffer() 1abcdefghij
352 monkeypatch.setattr(sys, "stdin", stdin) 1abcdefghij
353 monkeypatch.setattr(sys, "stdout", stdout) 1abcdefghij
355 text_stdin = typer.get_text_stream("stdin", encoding="utf-8", errors=None) 1abcdefghij
356 text_stdout = typer.get_text_stream("stdout", encoding="utf-8", errors=None) 1abcdefghij
358 assert text_stdin.read() == "hello" 1abcdefghij
359 text_stdout.write("ok") 1abcdefghij
360 text_stdout.flush() 1abcdefghij
361 assert stdout.buffer.getvalue() == b"ok" 1abcdefghij
364def test_text_stream_binary_stream(monkeypatch) -> None: 1abcdefghij
365 binary_stdout = BytesIO() 1abcdefghij
366 monkeypatch.setattr(sys, "stdout", binary_stdout) 1abcdefghij
367 text_stream = typer.get_text_stream("stdout", encoding="utf-8", errors=None) 1abcdefghij
368 text_stream.write("ok") 1abcdefghij
369 text_stream.flush() 1abcdefghij
370 assert binary_stdout.getvalue() == b"ok" 1abcdefghij
373def test_text_stream_stdout_no_binary( 1abcdefghij
374 monkeypatch,
375) -> None:
376 class TextStdoutNoBinaryFallback: 1abcdefghij
377 encoding = "utf-8" 1abcdefghij
378 errors = "strict" 1abcdefghij
380 def write(self, s: str) -> int: 1abcdefghij
381 if isinstance(s, bytes): 1abcdefghij
382 raise TypeError("bytes not supported") 1abcdefghij
383 return len(s) 1abcdefghij
385 stdout = TextStdoutNoBinaryFallback() 1abcdefghij
386 monkeypatch.setattr(sys, "stdout", stdout) 1abcdefghij
387 text_stream = typer.get_text_stream("stdout", encoding="utf-8", errors="replace") 1abcdefghij
388 assert text_stream is stdout 1abcdefghij
391def test_jupyter_wrapped_stream(monkeypatch) -> None: 1abcdefghij
392 class JupyterLikeStdout(BytesIO): 1abcdefghij
393 __module__ = "ipykernel.iostream" 1abcdefghij
395 def isatty(self) -> bool: 1abcdefghij
396 return False 1abcdefghij
398 binary_stdout = JupyterLikeStdout() 1abcdefghij
399 monkeypatch.setattr(sys, "stdout", binary_stdout) 1abcdefghij
400 text_stream = typer.get_text_stream("stdout", encoding="utf-8", errors=None) 1abcdefghij
401 assert should_strip_ansi(text_stream, color=None) is False 1abcdefghij
404def test_should_strip_ansi(monkeypatch) -> None: 1abcdefghij
405 class NonTtyStdin(BytesIO): 1abcdefghij
406 def isatty(self) -> bool: 1abcdefghij
407 return False 1abcdefghij
409 stdin = NonTtyStdin() 1abcdefghij
410 monkeypatch.setattr(sys, "stdin", stdin) 1abcdefghij
411 assert should_strip_ansi(stream=None, color=None) is True 1abcdefghij
412 assert should_strip_ansi(stream=None, color=True) is False 1abcdefghij
413 assert should_strip_ansi(stream=None, color=False) is True 1abcdefghij
416if __name__ == "__main__": 1abcdefghij
417 app() 1abcdefghij