Debian Codegraph @

testing/test_capture.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from collections.abc import Generator
5 import contextlib
6 import io
7 from io import UnsupportedOperation
8 import os
9 import re
10 import subprocess
11 import sys
12 import textwrap
13 from typing import BinaryIO
14 from typing import cast
15 from typing import TextIO
16
17 from _pytest import capture
18 from _pytest.capture import _get_multicapture
19 from _pytest.capture import CaptureFixture
20 from _pytest.capture import CaptureManager
21 from _pytest.capture import CaptureResult
22 from _pytest.capture import MultiCapture
23 from _pytest.config import ExitCode
24 from _pytest.monkeypatch import MonkeyPatch
25 from _pytest.pytester import Pytester
26 import pytest
27
28
29 # note: py.io capture tests where copied from
30 # pylib 1.4.20.dev2 (rev 13d9af95547e)
31
32
33 def StdCaptureFD(
34 out: bool = True, err: bool = True, in_: bool = True
35 ) -> MultiCapture[str]:
36 return capture.MultiCapture(
37 in_=capture.FDCapture(0) if in_ else None,
38 out=capture.FDCapture(1) if out else None,
39 err=capture.FDCapture(2) if err else None,
40 )
41
42
43 def StdCapture(
44 out: bool = True, err: bool = True, in_: bool = True
45 ) -> MultiCapture[str]:
46 return capture.MultiCapture(
47 in_=capture.SysCapture(0) if in_ else None,
48 out=capture.SysCapture(1) if out else None,
49 err=capture.SysCapture(2) if err else None,
50 )
51
52
53 def TeeStdCapture(
54 out: bool = True, err: bool = True, in_: bool = True
55 ) -> MultiCapture[str]:
56 return capture.MultiCapture(
57 in_=capture.SysCapture(0, tee=True) if in_ else None,
58 out=capture.SysCapture(1, tee=True) if out else None,
59 err=capture.SysCapture(2, tee=True) if err else None,
60 )
61
62
63 class TestCaptureManager:
64 @pytest.mark.parametrize("method", ["no", "sys", "fd"])
65 def test_capturing_basic_api(self, method) -> None:
66 capouter = StdCaptureFD()
67 old = sys.stdout, sys.stderr, sys.stdin
68 try:
69 capman = CaptureManager(method)
70 capman.start_global_capturing()
71 capman.suspend_global_capture()
72 outerr = capman.read_global_capture()
73 assert outerr == ("", "")
74 capman.suspend_global_capture()
75 outerr = capman.read_global_capture()
76 assert outerr == ("", "")
77 print("hello")
78 capman.suspend_global_capture()
79 out, _err = capman.read_global_capture()
80 if method == "no":
81 assert old == (sys.stdout, sys.stderr, sys.stdin)
82 else:
83 assert not out
84 capman.resume_global_capture()
85 print("hello")
86 capman.suspend_global_capture()
87 out, _err = capman.read_global_capture()
88 if method != "no":
89 assert out == "hello\n"
90 capman.stop_global_capturing()
91 finally:
92 capouter.stop_capturing()
93
94 def test_init_capturing(self):
95 capouter = StdCaptureFD()
96 try:
97 capman = CaptureManager("fd")
98 capman.start_global_capturing()
99 with pytest.raises(AssertionError):
100 capman.start_global_capturing()
101 capman.stop_global_capturing()
102 finally:
103 capouter.stop_capturing()
104
105
106 @pytest.mark.parametrize("method", ["fd", "sys"])
107 def test_capturing_unicode(pytester: Pytester, method: str) -> None:
108 obj = "'b\u00f6y'"
109 pytester.makepyfile(
110 f"""\
111 # taken from issue 227 from nosetests
112 def test_unicode():
113 import sys
114 print(sys.stdout)
115 print({obj})
116 """
117 )
118 result = pytester.runpytest(f"--capture={method}")
119 result.stdout.fnmatch_lines(["*1 passed*"])
120
121
122 @pytest.mark.parametrize("method", ["fd", "sys"])
123 def test_capturing_bytes_in_utf8_encoding(pytester: Pytester, method: str) -> None:
124 pytester.makepyfile(
125 """\
126 def test_unicode():
127 print('b\\u00f6y')
128 """
129 )
130 result = pytester.runpytest(f"--capture={method}")
131 result.stdout.fnmatch_lines(["*1 passed*"])
132
133
134 def test_collect_capturing(pytester: Pytester) -> None:
135 p = pytester.makepyfile(
136 """
137 import sys
138
139 print("collect %s failure" % 13)
140 sys.stderr.write("collect %s_stderr failure" % 13)
141 import xyz42123
142 """
143 )
144 result = pytester.runpytest(p)
145 result.stdout.fnmatch_lines(
146 [
147 "*Captured stdout*",
148 "collect 13 failure",
149 "*Captured stderr*",
150 "collect 13_stderr failure",
151 ]
152 )
153
154
155 class TestPerTestCapturing:
156 def test_capture_and_fixtures(self, pytester: Pytester) -> None:
157 p = pytester.makepyfile(
158 """
159 def setup_module(mod):
160 print("setup module")
161 def setup_function(function):
162 print("setup " + function.__name__)
163 def test_func1():
164 print("in func1")
165 assert 0
166 def test_func2():
167 print("in func2")
168 assert 0
169 """
170 )
171 result = pytester.runpytest(p)
172 result.stdout.fnmatch_lines(
173 [
174 "setup module*",
175 "setup test_func1*",
176 "in func1*",
177 "setup test_func2*",
178 "in func2*",
179 ]
180 )
181
182 @pytest.mark.xfail(reason="unimplemented feature")
183 def test_capture_scope_cache(self, pytester: Pytester) -> None:
184 p = pytester.makepyfile(
185 """
186 import sys
187 def setup_module(func):
188 print("module-setup")
189 def setup_function(func):
190 print("function-setup")
191 def test_func():
192 print("in function")
193 assert 0
194 def teardown_function(func):
195 print("in teardown")
196 """
197 )
198 result = pytester.runpytest(p)
199 result.stdout.fnmatch_lines(
200 [
201 "*test_func():*",
202 "*Captured stdout during setup*",
203 "module-setup*",
204 "function-setup*",
205 "*Captured stdout*",
206 "in teardown*",
207 ]
208 )
209
210 def test_no_carry_over(self, pytester: Pytester) -> None:
211 p = pytester.makepyfile(
212 """
213 def test_func1():
214 print("in func1")
215 def test_func2():
216 print("in func2")
217 assert 0
218 """
219 )
220 result = pytester.runpytest(p)
221 s = result.stdout.str()
222 assert "in func1" not in s
223 assert "in func2" in s
224
225 def test_teardown_capturing(self, pytester: Pytester) -> None:
226 p = pytester.makepyfile(
227 """
228 def setup_function(function):
229 print("setup func1")
230 def teardown_function(function):
231 print("teardown func1")
232 assert 0
233 def test_func1():
234 print("in func1")
235 pass
236 """
237 )
238 result = pytester.runpytest(p)
239 result.stdout.fnmatch_lines(
240 [
241 "*teardown_function*",
242 "*Captured stdout*",
243 "setup func1*",
244 "in func1*",
245 "teardown func1*",
246 # "*1 fixture failure*"
247 ]
248 )
249
250 def test_teardown_capturing_final(self, pytester: Pytester) -> None:
251 p = pytester.makepyfile(
252 """
253 def teardown_module(mod):
254 print("teardown module")
255 assert 0
256 def test_func():
257 pass
258 """
259 )
260 result = pytester.runpytest(p)
261 result.stdout.fnmatch_lines(
262 [
263 "*def teardown_module(mod):*",
264 "*Captured stdout*",
265 "*teardown module*",
266 "*1 error*",
267 ]
268 )
269
270 def test_capturing_outerr(self, pytester: Pytester) -> None:
271 p1 = pytester.makepyfile(
272 """\
273 import sys
274 def test_capturing():
275 print(42)
276 sys.stderr.write(str(23))
277 def test_capturing_error():
278 print(1)
279 sys.stderr.write(str(2))
280 raise ValueError
281 """
282 )
283 result = pytester.runpytest(p1)
284 result.stdout.fnmatch_lines(
285 [
286 "*test_capturing_outerr.py .F*",
287 "====* FAILURES *====",
288 "____*____",
289 "*test_capturing_outerr.py:8: ValueError",
290 "*--- Captured stdout *call*",
291 "1",
292 "*--- Captured stderr *call*",
293 "2",
294 ]
295 )
296
297
298 class TestLoggingInteraction:
299 def test_logging_stream_ownership(self, pytester: Pytester) -> None:
300 p = pytester.makepyfile(
301 """\
302 def test_logging():
303 import logging
304 import pytest
305 stream = capture.CaptureIO()
306 logging.basicConfig(stream=stream)
307 stream.close() # to free memory/release resources
308 """
309 )
310 result = pytester.runpytest_subprocess(p)
311 assert result.stderr.str().find("atexit") == -1
312
313 def test_logging_and_immediate_setupteardown(self, pytester: Pytester) -> None:
314 p = pytester.makepyfile(
315 """\
316 import logging
317 def setup_function(function):
318 logging.warning("hello1")
319
320 def test_logging():
321 logging.warning("hello2")
322 assert 0
323
324 def teardown_function(function):
325 logging.warning("hello3")
326 assert 0
327 """
328 )
329 for optargs in (("--capture=sys",), ("--capture=fd",)):
330 print(optargs)
331 result = pytester.runpytest_subprocess(p, *optargs)
332 s = result.stdout.str()
333 result.stdout.fnmatch_lines(
334 ["*WARN*hello3", "*WARN*hello1", "*WARN*hello2"] # errors show first!
335 )
336 # verify proper termination
337 assert "closed" not in s
338
339 def test_logging_and_crossscope_fixtures(self, pytester: Pytester) -> None:
340 p = pytester.makepyfile(
341 """\
342 import logging
343 def setup_module(function):
344 logging.warning("hello1")
345
346 def test_logging():
347 logging.warning("hello2")
348 assert 0
349
350 def teardown_module(function):
351 logging.warning("hello3")
352 assert 0
353 """
354 )
355 for optargs in (("--capture=sys",), ("--capture=fd",)):
356 print(optargs)
357 result = pytester.runpytest_subprocess(p, *optargs)
358 s = result.stdout.str()
359 result.stdout.fnmatch_lines(
360 ["*WARN*hello3", "*WARN*hello1", "*WARN*hello2"] # errors come first
361 )
362 # verify proper termination
363 assert "closed" not in s
364
365 def test_conftestlogging_is_shown(self, pytester: Pytester) -> None:
366 pytester.makeconftest(
367 """\
368 import logging
369 logging.basicConfig()
370 logging.warning("hello435")
371 """
372 )
373 # make sure that logging is still captured in tests
374 result = pytester.runpytest_subprocess("-s", "-p", "no:capturelog")
375 assert result.ret == ExitCode.NO_TESTS_COLLECTED
376 result.stderr.fnmatch_lines(["WARNING*hello435*"])
377 assert "operation on closed file" not in result.stderr.str()
378
379 def test_conftestlogging_and_test_logging(self, pytester: Pytester) -> None:
380 pytester.makeconftest(
381 """\
382 import logging
383 logging.basicConfig()
384 """
385 )
386 # make sure that logging is still captured in tests
387 p = pytester.makepyfile(
388 """\
389 def test_hello():
390 import logging
391 logging.warning("hello433")
392 assert 0
393 """
394 )
395 result = pytester.runpytest_subprocess(p, "-p", "no:capturelog")
396 assert result.ret != 0
397 result.stdout.fnmatch_lines(["WARNING*hello433*"])
398 assert "something" not in result.stderr.str()
399 assert "operation on closed file" not in result.stderr.str()
400
401 def test_logging_after_cap_stopped(self, pytester: Pytester) -> None:
402 pytester.makeconftest(
403 """\
404 import pytest
405 import logging
406
407 log = logging.getLogger(__name__)
408
409 @pytest.fixture
410 def log_on_teardown():
411 yield
412 log.warning('Logging on teardown')
413 """
414 )
415 # make sure that logging is still captured in tests
416 p = pytester.makepyfile(
417 """\
418 def test_hello(log_on_teardown):
419 import logging
420 logging.warning("hello433")
421 assert 1
422 raise KeyboardInterrupt()
423 """
424 )
425 result = pytester.runpytest_subprocess(p, "--log-cli-level", "info")
426 assert result.ret != 0
427 result.stdout.fnmatch_lines(
428 ["*WARNING*hello433*", "*WARNING*Logging on teardown*"]
429 )
430 assert (
431 "AttributeError: 'NoneType' object has no attribute 'resume_capturing'"
432 not in result.stderr.str()
433 )
434
435
436 class TestCaptureFixture:
437 @pytest.mark.parametrize("opt", [[], ["-s"]])
438 def test_std_functional(self, pytester: Pytester, opt) -> None:
439 reprec = pytester.inline_runsource(
440 """\
441 def test_hello(capsys):
442 print(42)
443 out, err = capsys.readouterr()
444 assert out.startswith("42")
445 """,
446 *opt,
447 )
448 reprec.assertoutcome(passed=1)
449
450 def test_capteesys(self, pytester: Pytester) -> None:
451 p = pytester.makepyfile(
452 """\
453 import sys
454 def test_one(capteesys):
455 print("sTdoUt")
456 print("sTdeRr", file=sys.stderr)
457 out, err = capteesys.readouterr()
458 assert out == "sTdoUt\\n"
459 assert err == "sTdeRr\\n"
460 """
461 )
462 # -rN and --capture=tee-sys means we'll read them on stdout/stderr,
463 # as opposed to both being reported on stdout
464 result = pytester.runpytest(p, "--quiet", "--quiet", "-rN", "--capture=tee-sys")
465 assert result.ret == ExitCode.OK
466 result.stdout.fnmatch_lines(["sTdoUt"]) # tee'd out
467 result.stderr.fnmatch_lines(["sTdeRr"]) # tee'd out
468
469 result = pytester.runpytest(p, "--quiet", "--quiet", "-rA", "--capture=tee-sys")
470 assert result.ret == ExitCode.OK
471 result.stdout.fnmatch_lines(
472 ["sTdoUt", "sTdoUt", "sTdeRr"]
473 ) # tee'd out, the next two reported
474 result.stderr.fnmatch_lines(["sTdeRr"]) # tee'd out
475
476 # -rA and --capture=sys means we'll read them on stdout.
477 result = pytester.runpytest(p, "--quiet", "--quiet", "-rA", "--capture=sys")
478 assert result.ret == ExitCode.OK
479 result.stdout.fnmatch_lines(["sTdoUt", "sTdeRr"]) # no tee, just reported
480 assert not result.stderr.lines
481
482 def test_capteesys_no_double_output_with_capture_no(
483 self, pytester: Pytester
484 ) -> None:
485 """Capteesys with --capture=no should not produce doubled output (#13784)."""
486 p = pytester.makepyfile(
487 """\
488 def test_one(capteesys):
489 print("hello world stdout")
490 out, err = capteesys.readouterr()
491 assert out == "hello world stdout\\n"
492 """
493 )
494 result = pytester.runpytest(p, "--quiet", "--quiet", "-rN", "-s")
495 assert result.ret == ExitCode.OK
496 # "hello world stdout" should appear exactly once, not twice.
497 count = result.stdout.lines.count("hello world stdout")
498 assert count == 1, (
499 f"Expected 'hello world stdout' once, but found {count} times"
500 )
501
502 def test_capsyscapfd(self, pytester: Pytester) -> None:
503 p = pytester.makepyfile(
504 """\
505 def test_one(capsys, capfd):
506 pass
507 def test_two(capfd, capsys):
508 pass
509 """
510 )
511 result = pytester.runpytest(p)
512 result.stdout.fnmatch_lines(
513 [
514 "*ERROR*setup*test_one*",
515 "E*capfd*capsys*same*time*",
516 "*ERROR*setup*test_two*",
517 "E*capsys*capfd*same*time*",
518 "*2 errors*",
519 ]
520 )
521
522 def test_capturing_getfixturevalue(self, pytester: Pytester) -> None:
523 """Test that asking for "capfd" and "capsys" using request.getfixturevalue
524 in the same test is an error.
525 """
526 pytester.makepyfile(
527 """\
528 def test_one(capsys, request):
529 request.getfixturevalue("capfd")
530 def test_two(capfd, request):
531 request.getfixturevalue("capsys")
532 """
533 )
534 result = pytester.runpytest()
535 result.stdout.fnmatch_lines(
536 [
537 "*test_one*",
538 "E * cannot use capfd and capsys at the same time",
539 "*test_two*",
540 "E * cannot use capsys and capfd at the same time",
541 "*2 failed in*",
542 ]
543 )
544
545 def test_capsyscapfdbinary(self, pytester: Pytester) -> None:
546 p = pytester.makepyfile(
547 """\
548 def test_one(capsys, capfdbinary):
549 pass
550 """
551 )
552 result = pytester.runpytest(p)
553 result.stdout.fnmatch_lines(
554 ["*ERROR*setup*test_one*", "E*capfdbinary*capsys*same*time*", "*1 error*"]
555 )
556
557 @pytest.mark.parametrize("method", ["sys", "fd"])
558 def test_capture_is_represented_on_failure_issue128(
559 self, pytester: Pytester, method
560 ) -> None:
561 p = pytester.makepyfile(
562 f"""\
563 def test_hello(cap{method}):
564 print("xxx42xxx")
565 assert 0
566 """
567 )
568 result = pytester.runpytest(p)
569 result.stdout.fnmatch_lines(["xxx42xxx"])
570
571 def test_stdfd_functional(self, pytester: Pytester) -> None:
572 reprec = pytester.inline_runsource(
573 """\
574 def test_hello(capfd):
575 import os
576 os.write(1, b"42")
577 out, err = capfd.readouterr()
578 assert out.startswith("42")
579 capfd.close()
580 """
581 )
582 reprec.assertoutcome(passed=1)
583
584 @pytest.mark.parametrize("nl", ("\n", "\r\n", "\r"))
585 def test_cafd_preserves_newlines(self, capfd, nl) -> None:
586 print("test", end=nl)
587 out, _err = capfd.readouterr()
588 assert out.endswith(nl)
589
590 def test_capfdbinary(self, pytester: Pytester) -> None:
591 reprec = pytester.inline_runsource(
592 """\
593 def test_hello(capfdbinary):
594 import os
595 # some likely un-decodable bytes
596 os.write(1, b'\\xfe\\x98\\x20')
597 out, err = capfdbinary.readouterr()
598 assert out == b'\\xfe\\x98\\x20'
599 assert err == b''
600 """
601 )
602 reprec.assertoutcome(passed=1)
603
604 def test_capsysbinary(self, pytester: Pytester) -> None:
605 p1 = pytester.makepyfile(
606 r"""
607 def test_hello(capsysbinary):
608 import sys
609
610 sys.stdout.buffer.write(b'hello')
611
612 # Some likely un-decodable bytes.
613 sys.stdout.buffer.write(b'\xfe\x98\x20')
614
615 sys.stdout.buffer.flush()
616
617 # Ensure writing in text mode still works and is captured.
618 # https://github.com/pytest-dev/pytest/issues/6871
619 print("world", flush=True)
620
621 out, err = capsysbinary.readouterr()
622 assert out == b'hello\xfe\x98\x20world\n'
623 assert err == b''
624
625 print("stdout after")
626 print("stderr after", file=sys.stderr)
627 """
628 )
629 result = pytester.runpytest(str(p1), "-rA")
630 result.stdout.fnmatch_lines(
631 [
632 "*- Captured stdout call -*",
633 "stdout after",
634 "*- Captured stderr call -*",
635 "stderr after",
636 "*= 1 passed in *",
637 ]
638 )
639
640 def test_partial_setup_failure(self, pytester: Pytester) -> None:
641 p = pytester.makepyfile(
642 """\
643 def test_hello(capsys, missingarg):
644 pass
645 """
646 )
647 result = pytester.runpytest(p)
648 result.stdout.fnmatch_lines(["*test_partial_setup_failure*", "*1 error*"])
649
650 def test_keyboardinterrupt_disables_capturing(self, pytester: Pytester) -> None:
651 p = pytester.makepyfile(
652 """\
653 def test_hello(capfd):
654 import os
655 os.write(1, b'42')
656 raise KeyboardInterrupt()
657 """
658 )
659 result = pytester.runpytest_subprocess(p)
660 result.stdout.fnmatch_lines(["*KeyboardInterrupt*"])
661 assert result.ret == 2
662
663 def test_capture_and_logging(self, pytester: Pytester) -> None:
664 """#14"""
665 p = pytester.makepyfile(
666 """\
667 import logging
668 def test_log(capsys):
669 logging.error('x')
670 """
671 )
672 result = pytester.runpytest_subprocess(p)
673 assert "closed" not in result.stderr.str()
674
675 @pytest.mark.parametrize("fixture", ["capsys", "capfd"])
676 @pytest.mark.parametrize("no_capture", [True, False])
677 def test_disabled_capture_fixture(
678 self, pytester: Pytester, fixture: str, no_capture: bool
679 ) -> None:
680 pytester.makepyfile(
681 f"""\
682 def test_disabled({fixture}):
683 print('captured before')
684 with {fixture}.disabled():
685 print('while capture is disabled')
686 print('captured after')
687 assert {fixture}.readouterr() == ('captured before\\ncaptured after\\n', '')
688
689 def test_normal():
690 print('test_normal executed')
691 """
692 )
693 args = ("-s",) if no_capture else ()
694 result = pytester.runpytest_subprocess(*args)
695 result.stdout.fnmatch_lines(["*while capture is disabled*", "*= 2 passed in *"])
696 result.stdout.no_fnmatch_line("*captured before*")
697 result.stdout.no_fnmatch_line("*captured after*")
698 if no_capture:
699 assert "test_normal executed" in result.stdout.str()
700 else:
701 result.stdout.no_fnmatch_line("*test_normal executed*")
702
703 def test_disabled_capture_fixture_twice(self, pytester: Pytester) -> None:
704 """Test that an inner disabled() exit doesn't undo an outer disabled().
705
706 Issue #7148.
707 """
708 pytester.makepyfile(
709 """
710 def test_disabled(capfd):
711 print('captured before')
712 with capfd.disabled():
713 print('while capture is disabled 1')
714 with capfd.disabled():
715 print('while capture is disabled 2')
716 print('while capture is disabled 1 after')
717 print('captured after')
718 assert capfd.readouterr() == ('captured before\\ncaptured after\\n', '')
719 """
720 )
721 result = pytester.runpytest_subprocess()
722 result.stdout.fnmatch_lines(
723 [
724 "*while capture is disabled 1",
725 "*while capture is disabled 2",
726 "*while capture is disabled 1 after",
727 ],
728 consecutive=True,
729 )
730
731 @pytest.mark.parametrize("fixture", ["capsys", "capfd"])
732 def test_fixture_use_by_other_fixtures(self, pytester: Pytester, fixture) -> None:
733 """Ensure that capsys and capfd can be used by other fixtures during
734 setup and teardown."""
735 pytester.makepyfile(
736 f"""\
737 import sys
738 import pytest
739
740 @pytest.fixture
741 def captured_print({fixture}):
742 print('stdout contents begin')
743 print('stderr contents begin', file=sys.stderr)
744 out, err = {fixture}.readouterr()
745
746 yield out, err
747
748 print('stdout contents end')
749 print('stderr contents end', file=sys.stderr)
750 out, err = {fixture}.readouterr()
751 assert out == 'stdout contents end\\n'
752 assert err == 'stderr contents end\\n'
753
754 def test_captured_print(captured_print):
755 out, err = captured_print
756 assert out == 'stdout contents begin\\n'
757 assert err == 'stderr contents begin\\n'
758 """
759 )
760 result = pytester.runpytest_subprocess()
761 result.stdout.fnmatch_lines(["*1 passed*"])
762 result.stdout.no_fnmatch_line("*stdout contents begin*")
763 result.stdout.no_fnmatch_line("*stderr contents begin*")
764
765 @pytest.mark.parametrize("cap", ["capsys", "capfd"])
766 def test_fixture_use_by_other_fixtures_teardown(
767 self, pytester: Pytester, cap
768 ) -> None:
769 """Ensure we can access setup and teardown buffers from teardown when using capsys/capfd (##3033)"""
770 pytester.makepyfile(
771 f"""\
772 import sys
773 import pytest
774 import os
775
776 @pytest.fixture()
777 def fix({cap}):
778 print("setup out")
779 sys.stderr.write("setup err\\n")
780 yield
781 out, err = {cap}.readouterr()
782 assert out == 'setup out\\ncall out\\n'
783 assert err == 'setup err\\ncall err\\n'
784
785 def test_a(fix):
786 print("call out")
787 sys.stderr.write("call err\\n")
788 """
789 )
790 reprec = pytester.inline_run()
791 reprec.assertoutcome(passed=1)
792
793
794 def test_setup_failure_does_not_kill_capturing(pytester: Pytester) -> None:
795 sub1 = pytester.mkpydir("sub1")
796 sub1.joinpath("conftest.py").write_text(
797 textwrap.dedent(
798 """\
799 def pytest_runtest_setup(item):
800 raise ValueError(42)
801 """
802 ),
803 encoding="utf-8",
804 )
805 sub1.joinpath("test_mod.py").write_text("def test_func1(): pass", encoding="utf-8")
806 result = pytester.runpytest(pytester.path, "--traceconfig")
807 result.stdout.fnmatch_lines(["*ValueError(42)*", "*1 error*"])
808
809
810 def test_capture_conftest_runtest_setup(pytester: Pytester) -> None:
811 pytester.makeconftest(
812 """
813 def pytest_runtest_setup():
814 print("hello19")
815 """
816 )
817 pytester.makepyfile("def test_func(): pass")
818 result = pytester.runpytest()
819 assert result.ret == 0
820 result.stdout.no_fnmatch_line("*hello19*")
821
822
823 def test_capture_badoutput_issue412(pytester: Pytester) -> None:
824 pytester.makepyfile(
825 """
826 import os
827
828 def test_func():
829 omg = bytearray([1,129,1])
830 os.write(1, omg)
831 assert 0
832 """
833 )
834 result = pytester.runpytest("--capture=fd")
835 result.stdout.fnmatch_lines(
836 """
837 *def test_func*
838 *assert 0*
839 *Captured*
840 *1 failed*
841 """
842 )
843
844
845 def test_capture_early_option_parsing(pytester: Pytester) -> None:
846 pytester.makeconftest(
847 """
848 def pytest_runtest_setup():
849 print("hello19")
850 """
851 )
852 pytester.makepyfile("def test_func(): pass")
853 result = pytester.runpytest("-vs")
854 assert result.ret == 0
855 assert "hello19" in result.stdout.str()
856
857
858 def test_capture_binary_output(pytester: Pytester) -> None:
859 pytester.makepyfile(
860 r"""
861 import pytest
862
863 def test_a():
864 import sys
865 import subprocess
866 subprocess.call([sys.executable, __file__])
867
868 def test_foo():
869 import os;os.write(1, b'\xc3')
870
871 if __name__ == '__main__':
872 test_foo()
873 """
874 )
875 result = pytester.runpytest("--assert=plain")
876 result.assert_outcomes(passed=2)
877
878
879 def test_error_during_readouterr(pytester: Pytester) -> None:
880 """Make sure we suspend capturing if errors occur during readouterr"""
881 pytester.makepyfile(
882 pytest_xyz="""
883 from _pytest.capture import FDCapture
884
885 def bad_snap(self):
886 raise Exception('boom')
887
888 assert FDCapture.snap
889 FDCapture.snap = bad_snap
890 """
891 )
892 result = pytester.runpytest_subprocess("-p", "pytest_xyz")
893 result.stderr.fnmatch_lines(
894 ["*in bad_snap", " raise Exception('boom')", "Exception: boom"]
895 )
896
897
898 class TestCaptureIO:
899 def test_text(self) -> None:
900 f = capture.CaptureIO()
901 f.write("hello")
902 s = f.getvalue()
903 assert s == "hello"
904 f.close()
905
906 def test_unicode_and_str_mixture(self) -> None:
907 f = capture.CaptureIO()
908 f.write("\u00f6")
909 with pytest.raises(TypeError):
910 f.write(b"hello") # type: ignore[arg-type]
911
912 def test_write_bytes_to_buffer(self) -> None:
913 """In python3, stdout / stderr are text io wrappers (exposing a buffer
914 property of the underlying bytestream). See issue #1407
915 """
916 f = capture.CaptureIO()
917 f.buffer.write(b"foo\r\n")
918 assert f.getvalue() == "foo\r\n"
919
920
921 class TestTeeCaptureIO(TestCaptureIO):
922 def test_text(self) -> None:
923 sio = io.StringIO()
924 f = capture.TeeCaptureIO(sio)
925 f.write("hello")
926 s1 = f.getvalue()
927 assert s1 == "hello"
928 s2 = sio.getvalue()
929 assert s2 == s1
930 f.close()
931 sio.close()
932
933 def test_unicode_and_str_mixture(self) -> None:
934 sio = io.StringIO()
935 f = capture.TeeCaptureIO(sio)
936 f.write("\u00f6")
937 with pytest.raises(TypeError):
938 f.write(b"hello") # type: ignore[arg-type]
939
940
941 def test_dontreadfrominput() -> None:
942 from _pytest.capture import DontReadFromInput
943
944 f = DontReadFromInput()
945 assert f.buffer is f # type: ignore[comparison-overlap]
946 assert not f.isatty() # type: ignore[unreachable]
947 with pytest.raises(OSError):
948 f.read()
949 with pytest.raises(OSError):
950 f.readlines()
951 iter_f = iter(f)
952 with pytest.raises(OSError):
953 next(iter_f)
954 with pytest.raises(UnsupportedOperation):
955 f.fileno()
956 with pytest.raises(UnsupportedOperation):
957 f.flush()
958 assert not f.readable()
959 with pytest.raises(UnsupportedOperation):
960 f.seek(0)
961 assert not f.seekable()
962 with pytest.raises(UnsupportedOperation):
963 f.tell()
964 with pytest.raises(UnsupportedOperation):
965 f.truncate(0)
966 with pytest.raises(UnsupportedOperation):
967 f.write(b"")
968 with pytest.raises(UnsupportedOperation):
969 f.writelines([])
970 assert not f.writable()
971 assert isinstance(f.encoding, str)
972 f.close() # just for completeness
973 with f:
974 pass
975
976
977 def test_captureresult() -> None:
978 cr = CaptureResult("out", "err")
979 assert len(cr) == 2
980 assert cr.out == "out"
981 assert cr.err == "err"
982 out, err = cr
983 assert out == "out"
984 assert err == "err"
985 assert cr[0] == "out"
986 assert cr[1] == "err"
987 assert cr == cr
988 assert cr == CaptureResult("out", "err")
989 assert cr != CaptureResult("wrong", "err")
990 assert cr == ("out", "err")
991 assert cr != ("out", "wrong")
992 assert hash(cr) == hash(CaptureResult("out", "err"))
993 assert hash(cr) == hash(("out", "err"))
994 assert hash(cr) != hash(("out", "wrong"))
995 assert cr < ("z",)
996 assert cr < ("z", "b")
997 assert cr < ("z", "b", "c")
998 assert cr.count("err") == 1
999 assert cr.count("wrong") == 0
1000 assert cr.index("err") == 1
1001 with pytest.raises(ValueError):
1002 assert cr.index("wrong") == 0
1003 assert next(iter(cr)) == "out"
1004 assert cr._replace(err="replaced") == ("out", "replaced")
1005
1006
1007 @pytest.fixture
1008 def tmpfile(pytester: Pytester) -> Generator[BinaryIO]:
1009 f = pytester.makepyfile("").open("wb+")
1010 yield f
1011 if not f.closed:
1012 f.close()
1013
1014
1015 @contextlib.contextmanager
1016 def lsof_check():
1017 pid = os.getpid()
1018 try:
1019 out = subprocess.check_output(("lsof", "-p", str(pid)), timeout=10).decode()
1020 except (
1021 OSError,
1022 UnicodeDecodeError,
1023 subprocess.CalledProcessError,
1024 subprocess.TimeoutExpired,
1025 ) as exc:
1026 # about UnicodeDecodeError, see note on pytester
1027 pytest.skip(f"could not run 'lsof' ({exc!r})")
1028 yield
1029 out2 = subprocess.check_output(("lsof", "-p", str(pid))).decode()
1030 len1 = len([x for x in out.split("\n") if "REG" in x])
1031 len2 = len([x for x in out2.split("\n") if "REG" in x])
1032 assert len2 < len1 + 3, out2
1033
1034
1035 class TestFDCapture:
1036 def test_simple(self, tmpfile: BinaryIO) -> None:
1037 fd = tmpfile.fileno()
1038 cap = capture.FDCapture(fd)
1039 data = b"hello"
1040 os.write(fd, data)
1041 with pytest.raises(AssertionError):
1042 cap.snap()
1043 cap.done()
1044 cap = capture.FDCapture(fd)
1045 cap.start()
1046 os.write(fd, data)
1047 s = cap.snap()
1048 cap.done()
1049 assert s == "hello"
1050
1051 def test_simple_many(self, tmpfile: BinaryIO) -> None:
1052 for i in range(10):
1053 self.test_simple(tmpfile)
1054
1055 def test_simple_many_check_open_files(self, pytester: Pytester) -> None:
1056 with lsof_check():
1057 with pytester.makepyfile("").open("wb+") as tmpfile:
1058 self.test_simple_many(tmpfile)
1059
1060 def test_simple_fail_second_start(self, tmpfile: BinaryIO) -> None:
1061 fd = tmpfile.fileno()
1062 cap = capture.FDCapture(fd)
1063 cap.done()
1064 with pytest.raises(AssertionError):
1065 cap.start()
1066
1067 def test_stderr(self) -> None:
1068 cap = capture.FDCapture(2)
1069 cap.start()
1070 print("hello", file=sys.stderr)
1071 s = cap.snap()
1072 cap.done()
1073 assert s == "hello\n"
1074
1075 def test_stdin(self) -> None:
1076 cap = capture.FDCapture(0)
1077 cap.start()
1078 x = os.read(0, 100).strip()
1079 cap.done()
1080 assert x == b""
1081
1082 def test_writeorg(self, tmpfile: BinaryIO) -> None:
1083 data1, data2 = b"foo", b"bar"
1084 cap = capture.FDCapture(tmpfile.fileno())
1085 cap.start()
1086 tmpfile.write(data1)
1087 tmpfile.flush()
1088 cap.writeorg(data2.decode("ascii"))
1089 scap = cap.snap()
1090 cap.done()
1091 assert scap == data1.decode("ascii")
1092 with open(tmpfile.name, "rb") as stmp_file:
1093 stmp = stmp_file.read()
1094 assert stmp == data2
1095
1096 def test_simple_resume_suspend(self) -> None:
1097 with saved_fd(1):
1098 cap = capture.FDCapture(1)
1099 cap.start()
1100 data = b"hello"
1101 os.write(1, data)
1102 sys.stdout.write("whatever")
1103 s = cap.snap()
1104 assert s == "hellowhatever"
1105 cap.suspend()
1106 os.write(1, b"world")
1107 sys.stdout.write("qlwkej")
1108 assert not cap.snap()
1109 cap.resume()
1110 os.write(1, b"but now")
1111 sys.stdout.write(" yes\n")
1112 s = cap.snap()
1113 assert s == "but now yes\n"
1114 cap.suspend()
1115 cap.done()
1116 with pytest.raises(AssertionError):
1117 cap.suspend()
1118
1119 assert repr(cap) == (
1120 f"<FDCapture 1 oldfd={cap.targetfd_save} _state='done' tmpfile={cap.tmpfile!r}>"
1121 )
1122 # Should not crash with missing "_old".
1123 assert isinstance(cap.syscapture, capture.SysCapture)
1124 assert repr(cap.syscapture) == (
1125 f"<SysCapture stdout _old=<UNSET> _state='done' tmpfile={cap.syscapture.tmpfile!r}>"
1126 )
1127
1128 def test_capfd_sys_stdout_mode(self, capfd) -> None:
1129 assert "b" not in sys.stdout.mode
1130
1131
1132 @contextlib.contextmanager
1133 def saved_fd(fd):
1134 new_fd = os.dup(fd)
1135 try:
1136 yield
1137 finally:
1138 os.dup2(new_fd, fd)
1139 os.close(new_fd)
1140
1141
1142 class TestStdCapture:
1143 captureclass = staticmethod(StdCapture)
1144
1145 @contextlib.contextmanager
1146 def getcapture(self, **kw):
1147 cap = self.__class__.captureclass(**kw)
1148 cap.start_capturing()
1149 try:
1150 yield cap
1151 finally:
1152 cap.stop_capturing()
1153
1154 def test_capturing_done_simple(self) -> None:
1155 with self.getcapture() as cap:
1156 sys.stdout.write("hello")
1157 sys.stderr.write("world")
1158 out, err = cap.readouterr()
1159 assert out == "hello"
1160 assert err == "world"
1161
1162 def test_capturing_reset_simple(self) -> None:
1163 with self.getcapture() as cap:
1164 print("hello world")
1165 sys.stderr.write("hello error\n")
1166 out, err = cap.readouterr()
1167 assert out == "hello world\n"
1168 assert err == "hello error\n"
1169
1170 def test_capturing_readouterr(self) -> None:
1171 with self.getcapture() as cap:
1172 print("hello world")
1173 sys.stderr.write("hello error\n")
1174 out, err = cap.readouterr()
1175 assert out == "hello world\n"
1176 assert err == "hello error\n"
1177 sys.stderr.write("error2")
1178 out, err = cap.readouterr()
1179 assert err == "error2"
1180
1181 def test_capture_results_accessible_by_attribute(self) -> None:
1182 with self.getcapture() as cap:
1183 sys.stdout.write("hello")
1184 sys.stderr.write("world")
1185 capture_result = cap.readouterr()
1186 assert capture_result.out == "hello"
1187 assert capture_result.err == "world"
1188
1189 def test_capturing_readouterr_unicode(self) -> None:
1190 with self.getcapture() as cap:
1191 print("hxąć")
1192 out, _err = cap.readouterr()
1193 assert out == "hxąć\n"
1194
1195 def test_reset_twice_error(self) -> None:
1196 with self.getcapture() as cap:
1197 print("hello")
1198 out, err = cap.readouterr()
1199 with pytest.raises(ValueError):
1200 cap.stop_capturing()
1201 assert out == "hello\n"
1202 assert not err
1203
1204 def test_capturing_modify_sysouterr_in_between(self) -> None:
1205 oldout = sys.stdout
1206 olderr = sys.stderr
1207 with self.getcapture() as cap:
1208 sys.stdout.write("hello")
1209 sys.stderr.write("world")
1210 sys.stdout = capture.CaptureIO()
1211 sys.stderr = capture.CaptureIO()
1212 print("not seen")
1213 sys.stderr.write("not seen\n")
1214 out, err = cap.readouterr()
1215 assert out == "hello"
1216 assert err == "world"
1217 assert sys.stdout == oldout
1218 assert sys.stderr == olderr
1219
1220 def test_capturing_error_recursive(self) -> None:
1221 with self.getcapture() as cap1:
1222 print("cap1")
1223 with self.getcapture() as cap2:
1224 print("cap2")
1225 out2, _err2 = cap2.readouterr()
1226 out1, _err1 = cap1.readouterr()
1227 assert out1 == "cap1\n"
1228 assert out2 == "cap2\n"
1229
1230 def test_just_out_capture(self) -> None:
1231 with self.getcapture(out=True, err=False) as cap:
1232 sys.stdout.write("hello")
1233 sys.stderr.write("world")
1234 out, err = cap.readouterr()
1235 assert out == "hello"
1236 assert not err
1237
1238 def test_just_err_capture(self) -> None:
1239 with self.getcapture(out=False, err=True) as cap:
1240 sys.stdout.write("hello")
1241 sys.stderr.write("world")
1242 out, err = cap.readouterr()
1243 assert err == "world"
1244 assert not out
1245
1246 def test_stdin_restored(self) -> None:
1247 old = sys.stdin
1248 with self.getcapture(in_=True):
1249 newstdin = sys.stdin
1250 assert newstdin != sys.stdin
1251 assert sys.stdin is old
1252
1253 def test_stdin_nulled_by_default(self) -> None:
1254 print("XXX this test may well hang instead of crashing")
1255 print("XXX which indicates an error in the underlying capturing")
1256 print("XXX mechanisms")
1257 with self.getcapture():
1258 with pytest.raises(OSError):
1259 sys.stdin.read()
1260
1261
1262 class TestTeeStdCapture(TestStdCapture):
1263 captureclass = staticmethod(TeeStdCapture)
1264
1265 def test_capturing_error_recursive(self) -> None:
1266 r"""For TeeStdCapture since we passthrough stderr/stdout, cap1
1267 should get all output, while cap2 should only get "cap2\n"."""
1268 with self.getcapture() as cap1:
1269 print("cap1")
1270 with self.getcapture() as cap2:
1271 print("cap2")
1272 out2, _err2 = cap2.readouterr()
1273 out1, _err1 = cap1.readouterr()
1274 assert out1 == "cap1\ncap2\n"
1275 assert out2 == "cap2\n"
1276
1277
1278 class TestStdCaptureFD(TestStdCapture):
1279 captureclass = staticmethod(StdCaptureFD)
1280
1281 def test_simple_only_fd(self, pytester: Pytester) -> None:
1282 pytester.makepyfile(
1283 """\
1284 import os
1285 def test_x():
1286 os.write(1, b"hello\\n")
1287 assert 0
1288 """
1289 )
1290 result = pytester.runpytest_subprocess()
1291 result.stdout.fnmatch_lines(
1292 """
1293 *test_x*
1294 *assert 0*
1295 *Captured stdout*
1296 """
1297 )
1298
1299 def test_intermingling(self):
1300 with self.getcapture() as cap:
1301 os.write(1, b"1")
1302 sys.stdout.write(str(2))
1303 sys.stdout.flush()
1304 os.write(1, b"3")
1305 os.write(2, b"a")
1306 sys.stderr.write("b")
1307 sys.stderr.flush()
1308 os.write(2, b"c")
1309 out, err = cap.readouterr()
1310 assert out == "123"
1311 assert err == "abc"
1312
1313 def test_many(self, capfd):
1314 with lsof_check():
1315 for i in range(10):
1316 cap = StdCaptureFD()
1317 cap.start_capturing()
1318 cap.stop_capturing()
1319
1320
1321 class TestStdCaptureFDinvalidFD:
1322 def test_stdcapture_fd_invalid_fd(self, pytester: Pytester) -> None:
1323 pytester.makepyfile(
1324 """
1325 import os
1326 from fnmatch import fnmatch
1327 from _pytest import capture
1328
1329 def StdCaptureFD(out=True, err=True, in_=True):
1330 return capture.MultiCapture(
1331 in_=capture.FDCapture(0) if in_ else None,
1332 out=capture.FDCapture(1) if out else None,
1333 err=capture.FDCapture(2) if err else None,
1334 )
1335
1336 def test_stdout():
1337 os.close(1)
1338 cap = StdCaptureFD(out=True, err=False, in_=False)
1339 assert fnmatch(repr(cap.out), "<FDCapture 1 oldfd=* _state='initialized' tmpfile=*>")
1340 cap.start_capturing()
1341 os.write(1, b"stdout")
1342 assert cap.readouterr() == ("stdout", "")
1343 cap.stop_capturing()
1344
1345 def test_stderr():
1346 os.close(2)
1347 cap = StdCaptureFD(out=False, err=True, in_=False)
1348 assert fnmatch(repr(cap.err), "<FDCapture 2 oldfd=* _state='initialized' tmpfile=*>")
1349 cap.start_capturing()
1350 os.write(2, b"stderr")
1351 assert cap.readouterr() == ("", "stderr")
1352 cap.stop_capturing()
1353
1354 def test_stdin():
1355 os.close(0)
1356 cap = StdCaptureFD(out=False, err=False, in_=True)
1357 assert fnmatch(repr(cap.in_), "<FDCapture 0 oldfd=* _state='initialized' tmpfile=*>")
1358 cap.stop_capturing()
1359 """
1360 )
1361 result = pytester.runpytest_subprocess("--capture=fd")
1362 assert result.ret == 0
1363 assert result.parseoutcomes()["passed"] == 3
1364
1365 def test_fdcapture_invalid_fd_with_fd_reuse(self, pytester: Pytester) -> None:
1366 with saved_fd(1):
1367 os.close(1)
1368 cap = capture.FDCaptureBinary(1)
1369 cap.start()
1370 os.write(1, b"started")
1371 cap.suspend()
1372 os.write(1, b" suspended")
1373 cap.resume()
1374 os.write(1, b" resumed")
1375 assert cap.snap() == b"started resumed"
1376 cap.done()
1377 with pytest.raises(OSError):
1378 os.write(1, b"done")
1379
1380 def test_fdcapture_invalid_fd_without_fd_reuse(self, pytester: Pytester) -> None:
1381 with saved_fd(1), saved_fd(2):
1382 os.close(1)
1383 os.close(2)
1384 cap = capture.FDCaptureBinary(2)
1385 cap.start()
1386 os.write(2, b"started")
1387 cap.suspend()
1388 os.write(2, b" suspended")
1389 cap.resume()
1390 os.write(2, b" resumed")
1391 assert cap.snap() == b"started resumed"
1392 cap.done()
1393 with pytest.raises(OSError):
1394 os.write(2, b"done")
1395
1396
1397 def test_capture_not_started_but_reset() -> None:
1398 capsys = StdCapture()
1399 capsys.stop_capturing()
1400
1401
1402 def test_using_capsys_fixture_works_with_sys_stdout_encoding(
1403 capsys: CaptureFixture[str],
1404 ) -> None:
1405 test_text = "test text"
1406
1407 print(test_text.encode(sys.stdout.encoding, "replace"))
1408 (out, err) = capsys.readouterr()
1409 assert out
1410 assert err == ""
1411
1412
1413 def test_capsys_results_accessible_by_attribute(capsys: CaptureFixture[str]) -> None:
1414 sys.stdout.write("spam")
1415 sys.stderr.write("eggs")
1416 capture_result = capsys.readouterr()
1417 assert capture_result.out == "spam"
1418 assert capture_result.err == "eggs"
1419
1420
1421 def test_fdcapture_tmpfile_remains_the_same() -> None:
1422 cap = StdCaptureFD(out=False, err=True)
1423 assert isinstance(cap.err, capture.FDCapture)
1424 try:
1425 cap.start_capturing()
1426 capfile = cap.err.tmpfile
1427 cap.readouterr()
1428 finally:
1429 cap.stop_capturing()
1430 capfile2 = cap.err.tmpfile
1431 assert capfile2 == capfile
1432
1433
1434 def test_close_and_capture_again(pytester: Pytester) -> None:
1435 pytester.makepyfile(
1436 """
1437 import os
1438 def test_close():
1439 os.close(1)
1440 def test_capture_again():
1441 os.write(1, b"hello\\n")
1442 assert 0
1443 """
1444 )
1445 result = pytester.runpytest_subprocess()
1446 result.stdout.fnmatch_lines(
1447 """
1448 *test_capture_again*
1449 *assert 0*
1450 *stdout*
1451 *hello*
1452 """
1453 )
1454
1455
1456 @pytest.mark.parametrize(
1457 "method", ["SysCapture(2)", "SysCapture(2, tee=True)", "FDCapture(2)"]
1458 )
1459 def test_capturing_and_logging_fundamentals(pytester: Pytester, method: str) -> None:
1460 # here we check a fundamental feature
1461 p = pytester.makepyfile(
1462 f"""
1463 import sys, os, logging
1464 from _pytest import capture
1465 cap = capture.MultiCapture(
1466 in_=None,
1467 out=None,
1468 err=capture.{method},
1469 )
1470 cap.start_capturing()
1471
1472 logging.warning("hello1")
1473 outerr = cap.readouterr()
1474 print("suspend, captured %s" %(outerr,))
1475 logging.warning("hello2")
1476
1477 cap.pop_outerr_to_orig()
1478 logging.warning("hello3")
1479
1480 outerr = cap.readouterr()
1481 print("suspend2, captured %s" % (outerr,))
1482 """
1483 )
1484 result = pytester.runpython(p)
1485 result.stdout.fnmatch_lines(
1486 """
1487 suspend, captured*hello1*
1488 suspend2, captured*WARNING:root:hello3*
1489 """
1490 )
1491 result.stderr.fnmatch_lines(
1492 """
1493 WARNING:root:hello2
1494 """
1495 )
1496 assert "atexit" not in result.stderr.str()
1497
1498
1499 def test_error_attribute_issue555(pytester: Pytester) -> None:
1500 pytester.makepyfile(
1501 """
1502 import sys
1503 def test_capattr():
1504 assert sys.stdout.errors == "replace"
1505 assert sys.stderr.errors == "replace"
1506 """
1507 )
1508 reprec = pytester.inline_run()
1509 reprec.assertoutcome(passed=1)
1510
1511
1512 @pytest.mark.skipif(
1513 not sys.platform.startswith("win"),
1514 reason="only on windows",
1515 )
1516 def test_windowsconsoleio_workaround_non_standard_streams() -> None:
1517 """
1518 Ensure _windowsconsoleio_workaround function works with objects that
1519 do not implement the full ``io``-based stream protocol, for example execnet channels (#2666).
1520 """
1521 from _pytest.capture import _windowsconsoleio_workaround
1522
1523 class DummyStream:
1524 def write(self, s):
1525 pass
1526
1527 stream = cast(TextIO, DummyStream())
1528 _windowsconsoleio_workaround(stream)
1529
1530
1531 def test_dontreadfrominput_has_encoding(pytester: Pytester) -> None:
1532 pytester.makepyfile(
1533 """
1534 import sys
1535 def test_capattr():
1536 # should not raise AttributeError
1537 assert sys.stdout.encoding
1538 assert sys.stderr.encoding
1539 """
1540 )
1541 reprec = pytester.inline_run()
1542 reprec.assertoutcome(passed=1)
1543
1544
1545 def test_crash_on_closing_tmpfile_py27(
1546 pytester: Pytester, monkeypatch: MonkeyPatch
1547 ) -> None:
1548 p = pytester.makepyfile(
1549 """
1550 import threading
1551 import sys
1552
1553 printing = threading.Event()
1554
1555 def spam():
1556 f = sys.stderr
1557 print('SPAMBEFORE', end='', file=f)
1558 printing.set()
1559
1560 while True:
1561 try:
1562 f.flush()
1563 except (OSError, ValueError):
1564 break
1565
1566 def test_spam_in_thread():
1567 t = threading.Thread(target=spam)
1568 t.daemon = True
1569 t.start()
1570
1571 printing.wait()
1572 """
1573 )
1574 # Do not consider plugins like hypothesis, which might output to stderr.
1575 monkeypatch.setenv("PYTEST_DISABLE_PLUGIN_AUTOLOAD", "1")
1576 result = pytester.runpytest_subprocess(str(p))
1577 assert result.ret == 0
1578 assert result.stderr.str() == ""
1579 result.stdout.no_fnmatch_line("*OSError*")
1580
1581
1582 def test_global_capture_with_live_logging(pytester: Pytester) -> None:
1583 # Issue 3819
1584 # capture should work with live cli logging
1585
1586 # Teardown report seems to have the capture for the whole process (setup, capture, teardown)
1587 pytester.makeconftest(
1588 """
1589 def pytest_runtest_logreport(report):
1590 if "test_global" in report.nodeid:
1591 if report.when == "teardown":
1592 with open("caplog", "w", encoding="utf-8") as f:
1593 f.write(report.caplog)
1594 with open("capstdout", "w", encoding="utf-8") as f:
1595 f.write(report.capstdout)
1596 """
1597 )
1598
1599 pytester.makepyfile(
1600 """
1601 import logging
1602 import sys
1603 import pytest
1604
1605 logger = logging.getLogger(__name__)
1606
1607 @pytest.fixture
1608 def fix1():
1609 print("fix setup")
1610 logging.info("fix setup")
1611 yield
1612 logging.info("fix teardown")
1613 print("fix teardown")
1614
1615 def test_global(fix1):
1616 print("begin test")
1617 logging.info("something in test")
1618 print("end test")
1619 """
1620 )
1621 result = pytester.runpytest_subprocess("--log-cli-level=INFO")
1622 assert result.ret == 0
1623
1624 with open("caplog", encoding="utf-8") as f:
1625 caplog = f.read()
1626
1627 assert "fix setup" in caplog
1628 assert "something in test" in caplog
1629 assert "fix teardown" in caplog
1630
1631 with open("capstdout", encoding="utf-8") as f:
1632 capstdout = f.read()
1633
1634 assert "fix setup" in capstdout
1635 assert "begin test" in capstdout
1636 assert "end test" in capstdout
1637 assert "fix teardown" in capstdout
1638
1639
1640 @pytest.mark.parametrize("capture_fixture", ["capsys", "capfd"])
1641 def test_capture_with_live_logging(
1642 pytester: Pytester, capture_fixture: CaptureFixture[str]
1643 ) -> None:
1644 # Issue 3819
1645 # capture should work with live cli logging
1646
1647 pytester.makepyfile(
1648 f"""
1649 import logging
1650 import sys
1651
1652 logger = logging.getLogger(__name__)
1653
1654 def test_capture({capture_fixture}):
1655 print("hello")
1656 sys.stderr.write("world\\n")
1657 captured = {capture_fixture}.readouterr()
1658 assert captured.out == "hello\\n"
1659 assert captured.err == "world\\n"
1660
1661 logging.info("something")
1662 print("next")
1663 logging.info("something")
1664
1665 captured = {capture_fixture}.readouterr()
1666 assert captured.out == "next\\n"
1667 """
1668 )
1669
1670 result = pytester.runpytest_subprocess("--log-cli-level=INFO")
1671 assert result.ret == 0
1672
1673
1674 def test_typeerror_encodedfile_write(pytester: Pytester) -> None:
1675 """It should behave the same with and without output capturing (#4861)."""
1676 p = pytester.makepyfile(
1677 """
1678 def test_fails():
1679 import sys
1680 sys.stdout.write(b"foo")
1681 """
1682 )
1683 result_without_capture = pytester.runpytest("-s", str(p))
1684 result_with_capture = pytester.runpytest(str(p))
1685
1686 assert result_with_capture.ret == result_without_capture.ret
1687 out = result_with_capture.stdout.str()
1688 assert ("TypeError: write() argument must be str, not bytes" in out) or (
1689 "TypeError: unicode argument expected, got 'bytes'" in out
1690 )
1691
1692
1693 def test_stderr_write_returns_len(capsys: CaptureFixture[str]) -> None:
1694 """Write on Encoded files, namely captured stderr, should return number of characters written."""
1695 assert sys.stderr.write("Foo") == 3
1696
1697
1698 def test_encodedfile_writelines(tmpfile: BinaryIO) -> None:
1699 ef = capture.EncodedFile(tmpfile, encoding="utf-8")
1700 with pytest.raises(TypeError):
1701 ef.writelines([b"line1", b"line2"]) # type: ignore[list-item]
1702 assert ef.writelines(["line3", "line4"]) is None # type: ignore[func-returns-value]
1703 ef.flush()
1704 tmpfile.seek(0)
1705 assert tmpfile.read() == b"line3line4"
1706 tmpfile.close()
1707 with pytest.raises(ValueError):
1708 ef.read()
1709
1710
1711 def test__get_multicapture() -> None:
1712 assert isinstance(_get_multicapture("no"), MultiCapture)
1713 with pytest.raises(ValueError, match=r"^unknown capturing method: 'unknown'$"):
1714 _get_multicapture("unknown") # type: ignore[arg-type]
1715
1716
1717 def test_logging_while_collecting(pytester: Pytester) -> None:
1718 """Issue #6240: Calls to logging.xxx() during collection causes all logging calls to be duplicated to stderr"""
1719 p = pytester.makepyfile(
1720 """\
1721 import logging
1722
1723 logging.warning("during collection")
1724
1725 def test_logging():
1726 logging.warning("during call")
1727 assert False
1728 """
1729 )
1730 result = pytester.runpytest_subprocess(p)
1731 assert result.ret == ExitCode.TESTS_FAILED
1732 result.stdout.fnmatch_lines(
1733 [
1734 "*test_*.py F*",
1735 "====* FAILURES *====",
1736 "____*____",
1737 "*--- Captured log call*",
1738 "WARNING * during call",
1739 "*1 failed*",
1740 ]
1741 )
1742 result.stdout.no_fnmatch_line("*Captured stderr call*")
1743 result.stdout.no_fnmatch_line("*during collection*")
1744
1745
1746 def test_libedit_workaround(pytester: Pytester) -> None:
1747 pytester.makeconftest("""
1748 import pytest
1749
1750
1751 def pytest_terminal_summary(config):
1752 capture = config.pluginmanager.getplugin("capturemanager")
1753 capture.suspend_global_capture(in_=True)
1754
1755 print("Enter 'hi'")
1756 value = input()
1757 print(f"value: {value!r}")
1758
1759 capture.resume_global_capture()
1760 """)
1761 readline = pytest.importorskip("readline")
1762 backend = getattr(readline, "backend", readline.__doc__) # added in Python 3.13
1763 print(f"Readline backend: {backend}")
1764
1765 child = pytester.spawn_pytest("")
1766 child.expect(r"Enter 'hi'")
1767 child.sendline("hi")
1768 rest = child.read().decode("utf8")
1769 print(rest)
1770 match = re.search(r"^value: '(.*)'\r?$", rest, re.MULTILINE)
1771 assert match is not None
1772 assert match.group(1) == "hi"