Debian Codegraph @

testing/logging/test_reporting.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import io
5 import os
6 import re
7 from typing import cast
8
9 from _pytest.capture import CaptureManager
10 from _pytest.config import ExitCode
11 from _pytest.fixtures import FixtureRequest
12 from _pytest.pytester import Pytester
13 from _pytest.terminal import TerminalReporter
14 import pytest
15
16
17 def test_nothing_logged(pytester: Pytester) -> None:
18 pytester.makepyfile(
19 """
20 import sys
21
22 def test_foo():
23 sys.stdout.write('text going to stdout')
24 sys.stderr.write('text going to stderr')
25 assert False
26 """
27 )
28 result = pytester.runpytest()
29 assert result.ret == 1
30 result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
31 result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
32 with pytest.raises(pytest.fail.Exception):
33 result.stdout.fnmatch_lines(["*- Captured *log call -*"])
34
35
36 def test_messages_logged(pytester: Pytester) -> None:
37 pytester.makepyfile(
38 """
39 import sys
40 import logging
41
42 logger = logging.getLogger(__name__)
43
44 def test_foo():
45 sys.stdout.write('text going to stdout')
46 sys.stderr.write('text going to stderr')
47 logger.info('text going to logger')
48 assert False
49 """
50 )
51 result = pytester.runpytest("--log-level=INFO")
52 assert result.ret == 1
53 result.stdout.fnmatch_lines(["*- Captured *log call -*", "*text going to logger*"])
54 result.stdout.fnmatch_lines(["*- Captured stdout call -*", "text going to stdout"])
55 result.stdout.fnmatch_lines(["*- Captured stderr call -*", "text going to stderr"])
56
57
58 def test_root_logger_affected(pytester: Pytester) -> None:
59 pytester.makepyfile(
60 """
61 import logging
62 logger = logging.getLogger()
63
64 def test_foo():
65 logger.info('info text ' + 'going to logger')
66 logger.warning('warning text ' + 'going to logger')
67 logger.error('error text ' + 'going to logger')
68
69 assert 0
70 """
71 )
72 log_file = str(pytester.path.joinpath("pytest.log"))
73 result = pytester.runpytest("--log-level=ERROR", "--log-file=pytest.log")
74 assert result.ret == 1
75
76 # The capture log calls in the stdout section only contain the
77 # logger.error msg, because of --log-level=ERROR.
78 result.stdout.fnmatch_lines(["*error text going to logger*"])
79 stdout = result.stdout.str()
80 assert "warning text going to logger" not in stdout
81 assert "info text going to logger" not in stdout
82
83 # The log file should only contain the error log messages and
84 # not the warning or info ones, because the root logger is set to
85 # ERROR using --log-level=ERROR.
86 assert os.path.isfile(log_file)
87 with open(log_file, encoding="utf-8") as rfh:
88 contents = rfh.read()
89 assert "info text going to logger" not in contents
90 assert "warning text going to logger" not in contents
91 assert "error text going to logger" in contents
92
93
94 def test_log_cli_level_log_level_interaction(pytester: Pytester) -> None:
95 pytester.makepyfile(
96 """
97 import logging
98 logger = logging.getLogger()
99
100 def test_foo():
101 logger.debug('debug text ' + 'going to logger')
102 logger.info('info text ' + 'going to logger')
103 logger.warning('warning text ' + 'going to logger')
104 logger.error('error text ' + 'going to logger')
105 assert 0
106 """
107 )
108
109 result = pytester.runpytest("--log-cli-level=INFO", "--log-level=ERROR")
110 assert result.ret == 1
111
112 result.stdout.fnmatch_lines(
113 [
114 "*-- live log call --*",
115 "*INFO*info text going to logger",
116 "*WARNING*warning text going to logger",
117 "*ERROR*error text going to logger",
118 "=* 1 failed in *=",
119 ]
120 )
121 result.stdout.no_re_match_line("DEBUG")
122
123
124 def test_setup_logging(pytester: Pytester) -> None:
125 pytester.makepyfile(
126 """
127 import logging
128
129 logger = logging.getLogger(__name__)
130
131 def setup_function(function):
132 logger.info('text going to logger from setup')
133
134 def test_foo():
135 logger.info('text going to logger from call')
136 assert False
137 """
138 )
139 result = pytester.runpytest("--log-level=INFO")
140 assert result.ret == 1
141 result.stdout.fnmatch_lines(
142 [
143 "*- Captured *log setup -*",
144 "*text going to logger from setup*",
145 "*- Captured *log call -*",
146 "*text going to logger from call*",
147 ]
148 )
149
150
151 def test_teardown_logging(pytester: Pytester) -> None:
152 pytester.makepyfile(
153 """
154 import logging
155
156 logger = logging.getLogger(__name__)
157
158 def test_foo():
159 logger.info('text going to logger from call')
160
161 def teardown_function(function):
162 logger.info('text going to logger from teardown')
163 assert False
164 """
165 )
166 result = pytester.runpytest("--log-level=INFO")
167 assert result.ret == 1
168 result.stdout.fnmatch_lines(
169 [
170 "*- Captured *log call -*",
171 "*text going to logger from call*",
172 "*- Captured *log teardown -*",
173 "*text going to logger from teardown*",
174 ]
175 )
176
177
178 @pytest.mark.parametrize("enabled", [True, False])
179 def test_log_cli_enabled_disabled(pytester: Pytester, enabled: bool) -> None:
180 msg = "critical message logged by test"
181 pytester.makepyfile(
182 f"""
183 import logging
184 def test_log_cli():
185 logging.critical("{msg}")
186 """
187 )
188 if enabled:
189 pytester.makeini(
190 """
191 [pytest]
192 log_cli=true
193 """
194 )
195 result = pytester.runpytest()
196 if enabled:
197 result.stdout.fnmatch_lines(
198 [
199 "test_log_cli_enabled_disabled.py::test_log_cli ",
200 "*-- live log call --*",
201 "CRITICAL *test_log_cli_enabled_disabled.py* critical message logged by test",
202 "PASSED*",
203 ]
204 )
205 else:
206 assert msg not in result.stdout.str()
207
208
209 def test_log_cli_default_level(pytester: Pytester) -> None:
210 # Default log file level
211 pytester.makepyfile(
212 """
213 import pytest
214 import logging
215 def test_log_cli(request):
216 plugin = request.config.pluginmanager.getplugin('logging-plugin')
217 assert plugin.log_cli_handler.level == logging.NOTSET
218 logging.getLogger('catchlog').info("INFO message won't be shown")
219 logging.getLogger('catchlog').warning("WARNING message will be shown")
220 """
221 )
222 pytester.makeini(
223 """
224 [pytest]
225 log_cli=true
226 """
227 )
228
229 result = pytester.runpytest()
230
231 # fnmatch_lines does an assertion internally
232 result.stdout.fnmatch_lines(
233 [
234 "test_log_cli_default_level.py::test_log_cli ",
235 "WARNING*test_log_cli_default_level.py* message will be shown*",
236 ]
237 )
238 result.stdout.no_fnmatch_line("*INFO message won't be shown*")
239 # make sure that we get a '0' exit code for the testsuite
240 assert result.ret == 0
241
242
243 def test_log_cli_default_level_multiple_tests(
244 pytester: Pytester, request: FixtureRequest
245 ) -> None:
246 """Ensure we reset the first newline added by the live logger between tests"""
247 filename = request.node.name + ".py"
248 pytester.makepyfile(
249 """
250 import logging
251
252 def test_log_1():
253 logging.warning("log message from test_log_1")
254
255 def test_log_2():
256 logging.warning("log message from test_log_2")
257 """
258 )
259 pytester.makeini(
260 """
261 [pytest]
262 log_cli=true
263 """
264 )
265
266 result = pytester.runpytest()
267 result.stdout.fnmatch_lines(
268 [
269 f"{filename}::test_log_1 ",
270 "*WARNING*log message from test_log_1*",
271 "PASSED *50%*",
272 f"{filename}::test_log_2 ",
273 "*WARNING*log message from test_log_2*",
274 "PASSED *100%*",
275 "=* 2 passed in *=",
276 ]
277 )
278
279
280 def test_log_cli_default_level_sections(
281 pytester: Pytester, request: FixtureRequest
282 ) -> None:
283 """Check that with live logging enable we are printing the correct headers during
284 start/setup/call/teardown/finish."""
285 filename = request.node.name + ".py"
286 pytester.makeconftest(
287 """
288 import pytest
289 import logging
290
291 def pytest_runtest_logstart():
292 logging.warning('>>>>> START >>>>>')
293
294 def pytest_runtest_logfinish():
295 logging.warning('<<<<< END <<<<<<<')
296 """
297 )
298
299 pytester.makepyfile(
300 """
301 import pytest
302 import logging
303
304 @pytest.fixture
305 def fix(request):
306 logging.warning("log message from setup of {}".format(request.node.name))
307 yield
308 logging.warning("log message from teardown of {}".format(request.node.name))
309
310 def test_log_1(fix):
311 logging.warning("log message from test_log_1")
312
313 def test_log_2(fix):
314 logging.warning("log message from test_log_2")
315 """
316 )
317 pytester.makeini(
318 """
319 [pytest]
320 log_cli=true
321 """
322 )
323
324 result = pytester.runpytest()
325 result.stdout.fnmatch_lines(
326 [
327 f"{filename}::test_log_1 ",
328 "*-- live log start --*",
329 "*WARNING* >>>>> START >>>>>*",
330 "*-- live log setup --*",
331 "*WARNING*log message from setup of test_log_1*",
332 "*-- live log call --*",
333 "*WARNING*log message from test_log_1*",
334 "PASSED *50%*",
335 "*-- live log teardown --*",
336 "*WARNING*log message from teardown of test_log_1*",
337 "*-- live log finish --*",
338 "*WARNING* <<<<< END <<<<<<<*",
339 f"{filename}::test_log_2 ",
340 "*-- live log start --*",
341 "*WARNING* >>>>> START >>>>>*",
342 "*-- live log setup --*",
343 "*WARNING*log message from setup of test_log_2*",
344 "*-- live log call --*",
345 "*WARNING*log message from test_log_2*",
346 "PASSED *100%*",
347 "*-- live log teardown --*",
348 "*WARNING*log message from teardown of test_log_2*",
349 "*-- live log finish --*",
350 "*WARNING* <<<<< END <<<<<<<*",
351 "=* 2 passed in *=",
352 ]
353 )
354
355
356 def test_live_logs_unknown_sections(
357 pytester: Pytester, request: FixtureRequest
358 ) -> None:
359 """Check that with live logging enable we are printing the correct headers during
360 start/setup/call/teardown/finish."""
361 filename = request.node.name + ".py"
362 pytester.makeconftest(
363 """
364 import pytest
365 import logging
366
367 def pytest_runtest_protocol(item, nextitem):
368 logging.warning('Unknown Section!')
369
370 def pytest_runtest_logstart():
371 logging.warning('>>>>> START >>>>>')
372
373 def pytest_runtest_logfinish():
374 logging.warning('<<<<< END <<<<<<<')
375 """
376 )
377
378 pytester.makepyfile(
379 """
380 import pytest
381 import logging
382
383 @pytest.fixture
384 def fix(request):
385 logging.warning("log message from setup of {}".format(request.node.name))
386 yield
387 logging.warning("log message from teardown of {}".format(request.node.name))
388
389 def test_log_1(fix):
390 logging.warning("log message from test_log_1")
391
392 """
393 )
394 pytester.makeini(
395 """
396 [pytest]
397 log_cli=true
398 """
399 )
400
401 result = pytester.runpytest()
402 result.stdout.fnmatch_lines(
403 [
404 "*WARNING*Unknown Section*",
405 f"{filename}::test_log_1 ",
406 "*WARNING* >>>>> START >>>>>*",
407 "*-- live log setup --*",
408 "*WARNING*log message from setup of test_log_1*",
409 "*-- live log call --*",
410 "*WARNING*log message from test_log_1*",
411 "PASSED *100%*",
412 "*-- live log teardown --*",
413 "*WARNING*log message from teardown of test_log_1*",
414 "*WARNING* <<<<< END <<<<<<<*",
415 "=* 1 passed in *=",
416 ]
417 )
418
419
420 def test_sections_single_new_line_after_test_outcome(
421 pytester: Pytester, request: FixtureRequest
422 ) -> None:
423 """Check that only a single new line is written between log messages during
424 teardown/finish."""
425 filename = request.node.name + ".py"
426 pytester.makeconftest(
427 """
428 import pytest
429 import logging
430
431 def pytest_runtest_logstart():
432 logging.warning('>>>>> START >>>>>')
433
434 def pytest_runtest_logfinish():
435 logging.warning('<<<<< END <<<<<<<')
436 logging.warning('<<<<< END <<<<<<<')
437 """
438 )
439
440 pytester.makepyfile(
441 """
442 import pytest
443 import logging
444
445 @pytest.fixture
446 def fix(request):
447 logging.warning("log message from setup of {}".format(request.node.name))
448 yield
449 logging.warning("log message from teardown of {}".format(request.node.name))
450 logging.warning("log message from teardown of {}".format(request.node.name))
451
452 def test_log_1(fix):
453 logging.warning("log message from test_log_1")
454 """
455 )
456 pytester.makeini(
457 """
458 [pytest]
459 log_cli=true
460 """
461 )
462
463 result = pytester.runpytest()
464 result.stdout.fnmatch_lines(
465 [
466 f"{filename}::test_log_1 ",
467 "*-- live log start --*",
468 "*WARNING* >>>>> START >>>>>*",
469 "*-- live log setup --*",
470 "*WARNING*log message from setup of test_log_1*",
471 "*-- live log call --*",
472 "*WARNING*log message from test_log_1*",
473 "PASSED *100%*",
474 "*-- live log teardown --*",
475 "*WARNING*log message from teardown of test_log_1*",
476 "*-- live log finish --*",
477 "*WARNING* <<<<< END <<<<<<<*",
478 "*WARNING* <<<<< END <<<<<<<*",
479 "=* 1 passed in *=",
480 ]
481 )
482 assert (
483 re.search(
484 r"(.+)live log teardown(.+)\nWARNING(.+)\nWARNING(.+)",
485 result.stdout.str(),
486 re.MULTILINE,
487 )
488 is not None
489 )
490 assert (
491 re.search(
492 r"(.+)live log finish(.+)\nWARNING(.+)\nWARNING(.+)",
493 result.stdout.str(),
494 re.MULTILINE,
495 )
496 is not None
497 )
498
499
500 def test_log_cli_level(pytester: Pytester) -> None:
501 # Default log file level
502 pytester.makepyfile(
503 """
504 import pytest
505 import logging
506 def test_log_cli(request):
507 plugin = request.config.pluginmanager.getplugin('logging-plugin')
508 assert plugin.log_cli_handler.level == logging.INFO
509 logging.getLogger('catchlog').debug("This log message won't be shown")
510 logging.getLogger('catchlog').info("This log message will be shown")
511 print('PASSED')
512 """
513 )
514 pytester.makeini(
515 """
516 [pytest]
517 log_cli=true
518 """
519 )
520
521 result = pytester.runpytest("-s", "--log-cli-level=INFO")
522
523 # fnmatch_lines does an assertion internally
524 result.stdout.fnmatch_lines(
525 [
526 "*test_log_cli_level.py*This log message will be shown",
527 "PASSED", # 'PASSED' on its own line because the log message prints a new line
528 ]
529 )
530 result.stdout.no_fnmatch_line("*This log message won't be shown*")
531
532 # make sure that we get a '0' exit code for the testsuite
533 assert result.ret == 0
534
535 result = pytester.runpytest("-s", "--log-level=INFO")
536
537 # fnmatch_lines does an assertion internally
538 result.stdout.fnmatch_lines(
539 [
540 "*test_log_cli_level.py* This log message will be shown",
541 "PASSED", # 'PASSED' on its own line because the log message prints a new line
542 ]
543 )
544 result.stdout.no_fnmatch_line("*This log message won't be shown*")
545
546 # make sure that we get a '0' exit code for the testsuite
547 assert result.ret == 0
548
549
550 def test_log_cli_ini_level(pytester: Pytester) -> None:
551 pytester.makeini(
552 """
553 [pytest]
554 log_cli=true
555 log_cli_level = INFO
556 """
557 )
558 pytester.makepyfile(
559 """
560 import pytest
561 import logging
562 def test_log_cli(request):
563 plugin = request.config.pluginmanager.getplugin('logging-plugin')
564 assert plugin.log_cli_handler.level == logging.INFO
565 logging.getLogger('catchlog').debug("This log message won't be shown")
566 logging.getLogger('catchlog').info("This log message will be shown")
567 print('PASSED')
568 """
569 )
570
571 result = pytester.runpytest("-s")
572
573 # fnmatch_lines does an assertion internally
574 result.stdout.fnmatch_lines(
575 [
576 "*test_log_cli_ini_level.py* This log message will be shown",
577 "PASSED", # 'PASSED' on its own line because the log message prints a new line
578 ]
579 )
580 result.stdout.no_fnmatch_line("*This log message won't be shown*")
581
582 # make sure that we get a '0' exit code for the testsuite
583 assert result.ret == 0
584
585
586 @pytest.mark.parametrize(
587 "cli_args",
588 ["", "--log-level=WARNING", "--log-file-level=WARNING", "--log-cli-level=WARNING"],
589 )
590 def test_log_cli_auto_enable(pytester: Pytester, cli_args: str) -> None:
591 """Check that live logs are enabled if --log-level or --log-cli-level is passed on the CLI.
592
593 It should not be auto enabled if the same configs are set on the configuration file.
594 """
595 pytester.makepyfile(
596 """
597 import logging
598
599 def test_log_1():
600 logging.info("log message from test_log_1 not to be shown")
601 logging.warning("log message from test_log_1")
602
603 """
604 )
605 pytester.makeini(
606 """
607 [pytest]
608 log_level=INFO
609 log_cli_level=INFO
610 """
611 )
612
613 result = pytester.runpytest(cli_args)
614 stdout = result.stdout.str()
615 if cli_args == "--log-cli-level=WARNING":
616 result.stdout.fnmatch_lines(
617 [
618 "*::test_log_1 ",
619 "*-- live log call --*",
620 "*WARNING*log message from test_log_1*",
621 "PASSED *100%*",
622 "=* 1 passed in *=",
623 ]
624 )
625 assert "INFO" not in stdout
626 else:
627 result.stdout.fnmatch_lines(
628 ["*test_log_cli_auto_enable*100%*", "=* 1 passed in *="]
629 )
630 assert "INFO" not in stdout
631 assert "WARNING" not in stdout
632
633
634 def test_log_file_cli(pytester: Pytester) -> None:
635 # Default log file level
636 pytester.makepyfile(
637 """
638 import pytest
639 import logging
640 def test_log_file(request):
641 plugin = request.config.pluginmanager.getplugin('logging-plugin')
642 assert plugin.log_file_handler.level == logging.WARNING
643 logging.getLogger('catchlog').info("This log message won't be shown")
644 logging.getLogger('catchlog').warning("This log message will be shown")
645 print('PASSED')
646 """
647 )
648
649 log_file = str(pytester.path.joinpath("pytest.log"))
650
651 result = pytester.runpytest(
652 "-s", f"--log-file={log_file}", "--log-file-level=WARNING"
653 )
654
655 # fnmatch_lines does an assertion internally
656 result.stdout.fnmatch_lines(["test_log_file_cli.py PASSED"])
657
658 # make sure that we get a '0' exit code for the testsuite
659 assert result.ret == 0
660 assert os.path.isfile(log_file)
661 with open(log_file, encoding="utf-8") as rfh:
662 contents = rfh.read()
663 assert "This log message will be shown" in contents
664 assert "This log message won't be shown" not in contents
665
666
667 def test_log_file_mode_cli(pytester: Pytester) -> None:
668 # Default log file level
669 pytester.makepyfile(
670 """
671 import pytest
672 import logging
673 def test_log_file(request):
674 plugin = request.config.pluginmanager.getplugin('logging-plugin')
675 assert plugin.log_file_handler.level == logging.WARNING
676 logging.getLogger('catchlog').info("This log message won't be shown")
677 logging.getLogger('catchlog').warning("This log message will be shown")
678 print('PASSED')
679 """
680 )
681
682 log_file = str(pytester.path.joinpath("pytest.log"))
683
684 with open(log_file, mode="w", encoding="utf-8") as wfh:
685 wfh.write("A custom header\n")
686
687 result = pytester.runpytest(
688 "-s",
689 f"--log-file={log_file}",
690 "--log-file-mode=a",
691 "--log-file-level=WARNING",
692 )
693
694 # fnmatch_lines does an assertion internally
695 result.stdout.fnmatch_lines(["test_log_file_mode_cli.py PASSED"])
696
697 # make sure that we get a '0' exit code for the testsuite
698 assert result.ret == 0
699 assert os.path.isfile(log_file)
700 with open(log_file, encoding="utf-8") as rfh:
701 contents = rfh.read()
702 assert "A custom header" in contents
703 assert "This log message will be shown" in contents
704 assert "This log message won't be shown" not in contents
705
706
707 def test_log_file_mode_cli_invalid(pytester: Pytester) -> None:
708 # Default log file level
709 pytester.makepyfile(
710 """
711 import pytest
712 import logging
713 def test_log_file(request):
714 plugin = request.config.pluginmanager.getplugin('logging-plugin')
715 assert plugin.log_file_handler.level == logging.WARNING
716 logging.getLogger('catchlog').info("This log message won't be shown")
717 logging.getLogger('catchlog').warning("This log message will be shown")
718 """
719 )
720
721 log_file = str(pytester.path.joinpath("pytest.log"))
722
723 result = pytester.runpytest(
724 "-s",
725 f"--log-file={log_file}",
726 "--log-file-mode=b",
727 "--log-file-level=WARNING",
728 )
729
730 # make sure that we get a '4' exit code for the testsuite
731 assert result.ret == ExitCode.USAGE_ERROR
732
733
734 def test_log_file_cli_level(pytester: Pytester) -> None:
735 # Default log file level
736 pytester.makepyfile(
737 """
738 import pytest
739 import logging
740 def test_log_file(request):
741 plugin = request.config.pluginmanager.getplugin('logging-plugin')
742 assert plugin.log_file_handler.level == logging.INFO
743 logging.getLogger('catchlog').debug("This log message won't be shown")
744 logging.getLogger('catchlog').info("This log message will be shown")
745 print('PASSED')
746 """
747 )
748
749 log_file = str(pytester.path.joinpath("pytest.log"))
750
751 result = pytester.runpytest("-s", f"--log-file={log_file}", "--log-file-level=INFO")
752
753 # fnmatch_lines does an assertion internally
754 result.stdout.fnmatch_lines(["test_log_file_cli_level.py PASSED"])
755
756 # make sure that we get a '0' exit code for the testsuite
757 assert result.ret == 0
758 assert os.path.isfile(log_file)
759 with open(log_file, encoding="utf-8") as rfh:
760 contents = rfh.read()
761 assert "This log message will be shown" in contents
762 assert "This log message won't be shown" not in contents
763
764
765 def test_log_level_not_changed_by_default(pytester: Pytester) -> None:
766 pytester.makepyfile(
767 """
768 import logging
769 def test_log_file():
770 assert logging.getLogger().level == logging.WARNING
771 """
772 )
773 result = pytester.runpytest("-s")
774 result.stdout.fnmatch_lines(["* 1 passed in *"])
775
776
777 def test_log_file_ini(pytester: Pytester) -> None:
778 log_file = str(pytester.path.joinpath("pytest.log"))
779
780 pytester.makeini(
781 f"""
782 [pytest]
783 log_file={log_file}
784 log_file_level=WARNING
785 """
786 )
787 pytester.makepyfile(
788 """
789 import pytest
790 import logging
791 def test_log_file(request):
792 plugin = request.config.pluginmanager.getplugin('logging-plugin')
793 assert plugin.log_file_handler.level == logging.WARNING
794 logging.getLogger('catchlog').info("This log message won't be shown")
795 logging.getLogger('catchlog').warning("This log message will be shown")
796 print('PASSED')
797 """
798 )
799
800 result = pytester.runpytest("-s")
801
802 # fnmatch_lines does an assertion internally
803 result.stdout.fnmatch_lines(["test_log_file_ini.py PASSED"])
804
805 # make sure that we get a '0' exit code for the testsuite
806 assert result.ret == 0
807 assert os.path.isfile(log_file)
808 with open(log_file, encoding="utf-8") as rfh:
809 contents = rfh.read()
810 assert "This log message will be shown" in contents
811 assert "This log message won't be shown" not in contents
812
813
814 def test_log_file_mode_ini(pytester: Pytester) -> None:
815 log_file = str(pytester.path.joinpath("pytest.log"))
816
817 pytester.makeini(
818 f"""
819 [pytest]
820 log_file={log_file}
821 log_file_mode=a
822 log_file_level=WARNING
823 """
824 )
825 pytester.makepyfile(
826 """
827 import pytest
828 import logging
829 def test_log_file(request):
830 plugin = request.config.pluginmanager.getplugin('logging-plugin')
831 assert plugin.log_file_handler.level == logging.WARNING
832 logging.getLogger('catchlog').info("This log message won't be shown")
833 logging.getLogger('catchlog').warning("This log message will be shown")
834 print('PASSED')
835 """
836 )
837
838 with open(log_file, mode="w", encoding="utf-8") as wfh:
839 wfh.write("A custom header\n")
840
841 result = pytester.runpytest("-s")
842
843 # fnmatch_lines does an assertion internally
844 result.stdout.fnmatch_lines(["test_log_file_mode_ini.py PASSED"])
845
846 assert result.ret == ExitCode.OK
847 assert os.path.isfile(log_file)
848 with open(log_file, encoding="utf-8") as rfh:
849 contents = rfh.read()
850 assert "A custom header" in contents
851 assert "This log message will be shown" in contents
852 assert "This log message won't be shown" not in contents
853
854
855 def test_log_file_ini_level(pytester: Pytester) -> None:
856 log_file = str(pytester.path.joinpath("pytest.log"))
857
858 pytester.makeini(
859 f"""
860 [pytest]
861 log_file={log_file}
862 log_file_level = INFO
863 """
864 )
865 pytester.makepyfile(
866 """
867 import pytest
868 import logging
869 def test_log_file(request):
870 plugin = request.config.pluginmanager.getplugin('logging-plugin')
871 assert plugin.log_file_handler.level == logging.INFO
872 logging.getLogger('catchlog').debug("This log message won't be shown")
873 logging.getLogger('catchlog').info("This log message will be shown")
874 print('PASSED')
875 """
876 )
877
878 result = pytester.runpytest("-s")
879
880 # fnmatch_lines does an assertion internally
881 result.stdout.fnmatch_lines(["test_log_file_ini_level.py PASSED"])
882
883 # make sure that we get a '0' exit code for the testsuite
884 assert result.ret == 0
885 assert os.path.isfile(log_file)
886 with open(log_file, encoding="utf-8") as rfh:
887 contents = rfh.read()
888 assert "This log message will be shown" in contents
889 assert "This log message won't be shown" not in contents
890
891
892 def test_log_file_unicode(pytester: Pytester) -> None:
893 log_file = str(pytester.path.joinpath("pytest.log"))
894
895 pytester.makeini(
896 f"""
897 [pytest]
898 log_file={log_file}
899 log_file_level = INFO
900 """
901 )
902 pytester.makepyfile(
903 """\
904 import logging
905
906 def test_log_file():
907 logging.getLogger('catchlog').info("Normal message")
908 logging.getLogger('catchlog').info("├")
909 logging.getLogger('catchlog').info("Another normal message")
910 """
911 )
912
913 result = pytester.runpytest()
914
915 # make sure that we get a '0' exit code for the testsuite
916 assert result.ret == 0
917 assert os.path.isfile(log_file)
918 with open(log_file, encoding="utf-8") as rfh:
919 contents = rfh.read()
920 assert "Normal message" in contents
921 assert "├" in contents
922 assert "Another normal message" in contents
923
924
925 @pytest.mark.parametrize("has_capture_manager", [True, False])
926 def test_live_logging_suspends_capture(
927 has_capture_manager: bool, request: FixtureRequest
928 ) -> None:
929 """Test that capture manager is suspended when we emitting messages for live logging.
930
931 This tests the implementation calls instead of behavior because it is difficult/impossible to do it using
932 ``pytester`` facilities because they do their own capturing.
933
934 We parametrize the test to also make sure _LiveLoggingStreamHandler works correctly if no capture manager plugin
935 is installed.
936 """
937 import contextlib
938 from functools import partial
939 import logging
940
941 from _pytest.logging import _LiveLoggingStreamHandler
942
943 class MockCaptureManager:
944 calls = []
945
946 @contextlib.contextmanager
947 def global_and_fixture_disabled(self):
948 self.calls.append("enter disabled")
949 yield
950 self.calls.append("exit disabled")
951
952 class DummyTerminal(io.StringIO):
953 def section(self, *args, **kwargs):
954 pass
955
956 out_file = cast(TerminalReporter, DummyTerminal())
957 capture_manager = (
958 cast(CaptureManager, MockCaptureManager()) if has_capture_manager else None
959 )
960 handler = _LiveLoggingStreamHandler(out_file, capture_manager)
961 handler.set_when("call")
962
963 logger = logging.getLogger(__name__ + ".test_live_logging_suspends_capture")
964 logger.addHandler(handler)
965 request.addfinalizer(partial(logger.removeHandler, handler))
966
967 logger.critical("some message")
968 if has_capture_manager:
969 assert MockCaptureManager.calls == ["enter disabled", "exit disabled"]
970 else:
971 assert MockCaptureManager.calls == []
972 assert cast(io.StringIO, out_file).getvalue() == "\nsome message\n"
973
974
975 def test_collection_live_logging(pytester: Pytester) -> None:
976 pytester.makepyfile(
977 """
978 import logging
979
980 logging.getLogger().info("Normal message")
981 """
982 )
983
984 result = pytester.runpytest("--log-cli-level=INFO")
985 result.stdout.fnmatch_lines(
986 ["*--- live log collection ---*", "*Normal message*", "collected 0 items"]
987 )
988
989
990 @pytest.mark.parametrize("verbose", ["", "-q", "-qq"])
991 def test_collection_collect_only_live_logging(pytester: Pytester, verbose: str) -> None:
992 pytester.makepyfile(
993 """
994 def test_simple():
995 pass
996 """
997 )
998
999 result = pytester.runpytest("--collect-only", "--log-cli-level=INFO", verbose)
1000
1001 expected_lines = []
1002
1003 if not verbose:
1004 expected_lines.extend(
1005 [
1006 "*collected 1 item*",
1007 "*<Module test_collection_collect_only_live_logging.py>*",
1008 "*1 test collected*",
1009 ]
1010 )
1011 elif verbose == "-q":
1012 result.stdout.no_fnmatch_line("*collected 1 item**")
1013 expected_lines.extend(
1014 [
1015 "*test_collection_collect_only_live_logging.py::test_simple*",
1016 "1 test collected in [0-9].[0-9][0-9]s",
1017 ]
1018 )
1019 elif verbose == "-qq":
1020 result.stdout.no_fnmatch_line("*collected 1 item**")
1021 expected_lines.extend(["*test_collection_collect_only_live_logging.py: 1*"])
1022
1023 result.stdout.fnmatch_lines(expected_lines)
1024
1025
1026 def test_collection_logging_to_file(pytester: Pytester) -> None:
1027 log_file = str(pytester.path.joinpath("pytest.log"))
1028
1029 pytester.makeini(
1030 f"""
1031 [pytest]
1032 log_file={log_file}
1033 log_file_level = INFO
1034 """
1035 )
1036
1037 pytester.makepyfile(
1038 """
1039 import logging
1040
1041 logging.getLogger().info("Normal message")
1042
1043 def test_simple():
1044 logging.getLogger().debug("debug message in test_simple")
1045 logging.getLogger().info("info message in test_simple")
1046 """
1047 )
1048
1049 result = pytester.runpytest()
1050
1051 result.stdout.no_fnmatch_line("*--- live log collection ---*")
1052
1053 assert result.ret == 0
1054 assert os.path.isfile(log_file)
1055 with open(log_file, encoding="utf-8") as rfh:
1056 contents = rfh.read()
1057 assert "Normal message" in contents
1058 assert "debug message in test_simple" not in contents
1059 assert "info message in test_simple" in contents
1060
1061
1062 def test_log_in_hooks(pytester: Pytester) -> None:
1063 log_file = str(pytester.path.joinpath("pytest.log"))
1064
1065 pytester.makeini(
1066 f"""
1067 [pytest]
1068 log_file={log_file}
1069 log_file_level = INFO
1070 log_cli=true
1071 """
1072 )
1073 pytester.makeconftest(
1074 """
1075 import logging
1076
1077 def pytest_runtestloop(session):
1078 logging.info('runtestloop')
1079
1080 def pytest_sessionstart(session):
1081 logging.info('sessionstart')
1082
1083 def pytest_sessionfinish(session, exitstatus):
1084 logging.info('sessionfinish')
1085 """
1086 )
1087 result = pytester.runpytest()
1088 result.stdout.fnmatch_lines(["*sessionstart*", "*runtestloop*", "*sessionfinish*"])
1089 with open(log_file, encoding="utf-8") as rfh:
1090 contents = rfh.read()
1091 assert "sessionstart" in contents
1092 assert "runtestloop" in contents
1093 assert "sessionfinish" in contents
1094
1095
1096 def test_log_in_runtest_logreport(pytester: Pytester) -> None:
1097 log_file = str(pytester.path.joinpath("pytest.log"))
1098
1099 pytester.makeini(
1100 f"""
1101 [pytest]
1102 log_file={log_file}
1103 log_file_level = INFO
1104 log_cli=true
1105 """
1106 )
1107 pytester.makeconftest(
1108 """
1109 import logging
1110 logger = logging.getLogger(__name__)
1111
1112 def pytest_runtest_logreport(report):
1113 logger.info("logreport")
1114 """
1115 )
1116 pytester.makepyfile(
1117 """
1118 def test_first():
1119 assert True
1120 """
1121 )
1122 pytester.runpytest()
1123 with open(log_file, encoding="utf-8") as rfh:
1124 contents = rfh.read()
1125 assert contents.count("logreport") == 3
1126
1127
1128 def test_log_set_path(pytester: Pytester) -> None:
1129 report_dir_base = str(pytester.path)
1130
1131 pytester.makeini(
1132 """
1133 [pytest]
1134 log_file_level = DEBUG
1135 log_cli=true
1136 """
1137 )
1138 pytester.makeconftest(
1139 f"""
1140 import os
1141 import pytest
1142 @pytest.hookimpl(wrapper=True, tryfirst=True)
1143 def pytest_runtest_setup(item):
1144 config = item.config
1145 logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
1146 report_file = os.path.join({report_dir_base!r}, item._request.node.name)
1147 logging_plugin.set_log_path(report_file)
1148 return (yield)
1149 """
1150 )
1151 pytester.makepyfile(
1152 """
1153 import logging
1154 logger = logging.getLogger("testcase-logger")
1155 def test_first():
1156 logger.info("message from test 1")
1157 assert True
1158
1159 def test_second():
1160 logger.debug("message from test 2")
1161 assert True
1162 """
1163 )
1164 pytester.runpytest()
1165 with open(os.path.join(report_dir_base, "test_first"), encoding="utf-8") as rfh:
1166 content = rfh.read()
1167 assert "message from test 1" in content
1168
1169 with open(os.path.join(report_dir_base, "test_second"), encoding="utf-8") as rfh:
1170 content = rfh.read()
1171 assert "message from test 2" in content
1172
1173
1174 def test_log_set_path_with_log_file_mode(pytester: Pytester) -> None:
1175 report_dir_base = str(pytester.path)
1176
1177 pytester.makeini(
1178 """
1179 [pytest]
1180 log_file_level = DEBUG
1181 log_cli=true
1182 log_file_mode=a
1183 """
1184 )
1185 pytester.makeconftest(
1186 f"""
1187 import os
1188 import pytest
1189 @pytest.hookimpl(wrapper=True, tryfirst=True)
1190 def pytest_runtest_setup(item):
1191 config = item.config
1192 logging_plugin = config.pluginmanager.get_plugin("logging-plugin")
1193 report_file = os.path.join({report_dir_base!r}, item._request.node.name)
1194 logging_plugin.set_log_path(report_file)
1195 return (yield)
1196 """
1197 )
1198 pytester.makepyfile(
1199 """
1200 import logging
1201 logger = logging.getLogger("testcase-logger")
1202 def test_first():
1203 logger.info("message from test 1")
1204 assert True
1205
1206 def test_second():
1207 logger.debug("message from test 2")
1208 assert True
1209 """
1210 )
1211
1212 test_first_log_file = os.path.join(report_dir_base, "test_first")
1213 test_second_log_file = os.path.join(report_dir_base, "test_second")
1214 with open(test_first_log_file, mode="w", encoding="utf-8") as wfh:
1215 wfh.write("A custom header for test 1\n")
1216
1217 with open(test_second_log_file, mode="w", encoding="utf-8") as wfh:
1218 wfh.write("A custom header for test 2\n")
1219
1220 result = pytester.runpytest()
1221 assert result.ret == ExitCode.OK
1222
1223 with open(test_first_log_file, encoding="utf-8") as rfh:
1224 content = rfh.read()
1225 assert "A custom header for test 1" in content
1226 assert "message from test 1" in content
1227
1228 with open(test_second_log_file, encoding="utf-8") as rfh:
1229 content = rfh.read()
1230 assert "A custom header for test 2" in content
1231 assert "message from test 2" in content
1232
1233
1234 def test_colored_captured_log(pytester: Pytester) -> None:
1235 """Test that the level names of captured log messages of a failing test
1236 are colored."""
1237 pytester.makepyfile(
1238 """
1239 import logging
1240
1241 logger = logging.getLogger(__name__)
1242
1243 def test_foo():
1244 logger.info('text going to logger from call')
1245 assert False
1246 """
1247 )
1248 result = pytester.runpytest("--log-level=INFO", "--color=yes")
1249 assert result.ret == 1
1250 result.stdout.fnmatch_lines(
1251 [
1252 "*-- Captured log call --*",
1253 "\x1b[32mINFO \x1b[0m*text going to logger from call",
1254 ]
1255 )
1256
1257
1258 def test_log_propagation_false(pytester: Pytester) -> None:
1259 pytester.makepyfile(
1260 """
1261 import pytest
1262 import logging
1263
1264 logging.getLogger('foo').propagate = False
1265
1266 def test_log_file():
1267 logging.getLogger().warning("log goes to root logger")
1268 logging.getLogger('foo').warning("log goes to initially non-propagating logger")
1269 logging.getLogger('foo.bar').warning("log goes to initially non-propagating nested logger")
1270 assert False, "intentionally fail to trigger report logging output"
1271 """
1272 )
1273
1274 reprec = pytester.inline_run()
1275 reports = reprec.getfailures()
1276 assert len(reports) == 1
1277 report = reports[0]
1278 sections = list(report.get_sections("Captured log call"))
1279 assert len(sections) == 1
1280 assert sections[0][1] == "\n".join(
1281 [
1282 "WARNING root:test_log_propagation_false.py:7 log goes to root logger",
1283 "WARNING foo:test_log_propagation_false.py:8 log goes to initially non-propagating logger",
1284 "WARNING foo.bar:test_log_propagation_false.py:9 log goes to initially non-propagating nested logger",
1285 ]
1286 )
1287 assert not list(report.get_sections("Captured stderr call"))
1288
1289
1290 def test_colored_ansi_esc_caplogtext(pytester: Pytester) -> None:
1291 """Make sure that caplog.text does not contain ANSI escape sequences."""
1292 pytester.makepyfile(
1293 """
1294 import logging
1295
1296 logger = logging.getLogger(__name__)
1297
1298 def test_foo(caplog):
1299 logger.info('text going to logger from call')
1300 assert '\x1b' not in caplog.text
1301 """
1302 )
1303 result = pytester.runpytest("--log-level=INFO", "--color=yes")
1304 assert result.ret == 0
1305
1306
1307 def test_logging_emit_error(pytester: Pytester) -> None:
1308 """An exception raised during emit() should fail the test.
1309
1310 The default behavior of logging is to print "Logging error"
1311 to stderr with the call stack and some extra details.
1312
1313 pytest overrides this behavior to propagate the exception.
1314 """
1315 pytester.makepyfile(
1316 """
1317 import logging
1318
1319 def test_bad_log():
1320 logging.warning('oops', 'first', 2)
1321 """
1322 )
1323 result = pytester.runpytest()
1324 result.assert_outcomes(failed=1)
1325 result.stdout.fnmatch_lines(
1326 [
1327 "====* FAILURES *====",
1328 "*not all arguments converted during string formatting*",
1329 ]
1330 )
1331
1332
1333 def test_logging_emit_error_supressed(pytester: Pytester) -> None:
1334 """If logging is configured to silently ignore errors, pytest
1335 doesn't propagate errors either."""
1336 pytester.makepyfile(
1337 """
1338 import logging
1339
1340 def test_bad_log(monkeypatch):
1341 monkeypatch.setattr(logging, 'raiseExceptions', False)
1342 logging.warning('oops', 'first', 2)
1343 """
1344 )
1345 result = pytester.runpytest()
1346 result.assert_outcomes(passed=1)
1347
1348
1349 def test_log_file_cli_subdirectories_are_successfully_created(
1350 pytester: Pytester,
1351 ) -> None:
1352 path = pytester.makepyfile(""" def test_logger(): pass """)
1353 expected = os.path.join(os.path.dirname(str(path)), "foo", "bar")
1354 result = pytester.runpytest("--log-file=foo/bar/logf.log")
1355 assert "logf.log" in os.listdir(expected)
1356 assert result.ret == ExitCode.OK
1357
1358
1359 def test_disable_loggers(pytester: Pytester) -> None:
1360 pytester.makepyfile(
1361 """
1362 import logging
1363 import os
1364 disabled_log = logging.getLogger('disabled')
1365 test_log = logging.getLogger('test')
1366 def test_logger_propagation(caplog):
1367 with caplog.at_level(logging.DEBUG):
1368 disabled_log.warning("no log; no stderr")
1369 test_log.debug("Visible text!")
1370 assert caplog.record_tuples == [('test', 10, 'Visible text!')]
1371 """
1372 )
1373 result = pytester.runpytest("--log-disable=disabled", "-s")
1374 assert result.ret == ExitCode.OK
1375 assert not result.stderr.lines
1376
1377
1378 def test_disable_loggers_does_not_propagate(pytester: Pytester) -> None:
1379 pytester.makepyfile(
1380 """
1381 import logging
1382 import os
1383
1384 parent_logger = logging.getLogger("parent")
1385 child_logger = parent_logger.getChild("child")
1386
1387 def test_logger_propagation_to_parent(caplog):
1388 with caplog.at_level(logging.DEBUG):
1389 parent_logger.warning("some parent logger message")
1390 child_logger.warning("some child logger message")
1391 assert len(caplog.record_tuples) == 1
1392 assert caplog.record_tuples[0][0] == "parent"
1393 assert caplog.record_tuples[0][2] == "some parent logger message"
1394 """
1395 )
1396
1397 result = pytester.runpytest("--log-disable=parent.child", "-s")
1398 assert result.ret == ExitCode.OK
1399 assert not result.stderr.lines
1400
1401
1402 def test_log_disabling_works_with_log_cli(pytester: Pytester) -> None:
1403 pytester.makepyfile(
1404 """
1405 import logging
1406 disabled_log = logging.getLogger('disabled')
1407 test_log = logging.getLogger('test')
1408
1409 def test_log_cli_works(caplog):
1410 test_log.info("Visible text!")
1411 disabled_log.warning("This string will be suppressed.")
1412 """
1413 )
1414 result = pytester.runpytest(
1415 "--log-cli-level=DEBUG",
1416 "--log-disable=disabled",
1417 )
1418 assert result.ret == ExitCode.OK
1419 result.stdout.fnmatch_lines(
1420 "INFO test:test_log_disabling_works_with_log_cli.py:6 Visible text!"
1421 )
1422 result.stdout.no_fnmatch_line(
1423 "WARNING disabled:test_log_disabling_works_with_log_cli.py:7 This string will be suppressed."
1424 )
1425 assert not result.stderr.lines
1426
1427
1428 def test_without_date_format_log(pytester: Pytester) -> None:
1429 """Check that date is not printed by default."""
1430 pytester.makepyfile(
1431 """
1432 import logging
1433
1434 logger = logging.getLogger(__name__)
1435
1436 def test_foo():
1437 logger.warning('text')
1438 assert False
1439 """
1440 )
1441 result = pytester.runpytest()
1442 assert result.ret == 1
1443 result.stdout.fnmatch_lines(
1444 ["WARNING test_without_date_format_log:test_without_date_format_log.py:6 text"]
1445 )
1446
1447
1448 def test_date_format_log(pytester: Pytester) -> None:
1449 """Check that log_date_format affects output."""
1450 pytester.makepyfile(
1451 """
1452 import logging
1453
1454 logger = logging.getLogger(__name__)
1455
1456 def test_foo():
1457 logger.warning('text')
1458 assert False
1459 """
1460 )
1461 pytester.makeini(
1462 """
1463 [pytest]
1464 log_format=%(asctime)s; %(levelname)s; %(message)s
1465 log_date_format=%Y-%m-%d %H:%M:%S
1466 """
1467 )
1468 result = pytester.runpytest()
1469 assert result.ret == 1
1470 result.stdout.re_match_lines([r"^[0-9-]{10} [0-9:]{8}; WARNING; text"])
1471
1472
1473 def test_date_format_percentf_log(pytester: Pytester) -> None:
1474 """Make sure that microseconds are printed in log."""
1475 pytester.makepyfile(
1476 """
1477 import logging
1478
1479 logger = logging.getLogger(__name__)
1480
1481 def test_foo():
1482 logger.warning('text')
1483 assert False
1484 """
1485 )
1486 pytester.makeini(
1487 """
1488 [pytest]
1489 log_format=%(asctime)s; %(levelname)s; %(message)s
1490 log_date_format=%Y-%m-%d %H:%M:%S.%f
1491 """
1492 )
1493 result = pytester.runpytest()
1494 assert result.ret == 1
1495 result.stdout.re_match_lines([r"^[0-9-]{10} [0-9:]{8}.[0-9]{6}; WARNING; text"])
1496
1497
1498 def test_date_format_percentf_tz_log(pytester: Pytester) -> None:
1499 """Make sure that timezone and microseconds are properly formatted together."""
1500 pytester.makepyfile(
1501 """
1502 import logging
1503
1504 logger = logging.getLogger(__name__)
1505
1506 def test_foo():
1507 logger.warning('text')
1508 assert False
1509 """
1510 )
1511 pytester.makeini(
1512 """
1513 [pytest]
1514 log_format=%(asctime)s; %(levelname)s; %(message)s
1515 log_date_format=%Y-%m-%d %H:%M:%S.%f%z
1516 """
1517 )
1518 result = pytester.runpytest()
1519 assert result.ret == 1
1520 result.stdout.re_match_lines(
1521 [r"^[0-9-]{10} [0-9:]{8}.[0-9]{6}[+-][0-9\.]+; WARNING; text"]
1522 )
1523
1524
1525 def test_log_file_cli_fallback_options(pytester: Pytester) -> None:
1526 """Make sure that fallback values for log-file formats and level works."""
1527 pytester.makepyfile(
1528 """
1529 import logging
1530 logger = logging.getLogger()
1531
1532 def test_foo():
1533 logger.info('info text going to logger')
1534 logger.warning('warning text going to logger')
1535 logger.error('error text going to logger')
1536
1537 assert 0
1538 """
1539 )
1540 log_file = str(pytester.path.joinpath("pytest.log"))
1541 result = pytester.runpytest(
1542 "--log-level=ERROR",
1543 "--log-format=%(asctime)s %(message)s",
1544 "--log-date-format=%H:%M",
1545 "--log-file=pytest.log",
1546 )
1547 assert result.ret == 1
1548
1549 # The log file should only contain the error log messages
1550 # not the warning or info ones and the format and date format
1551 # should match the formats provided using --log-format and --log-date-format
1552 assert os.path.isfile(log_file)
1553 with open(log_file, encoding="utf-8") as rfh:
1554 contents = rfh.read()
1555 assert re.match(r"[0-9]{2}:[0-9]{2} error text going to logger\s*", contents)
1556 assert "info text going to logger" not in contents
1557 assert "warning text going to logger" not in contents
1558 assert "error text going to logger" in contents
1559
1560 # Try with a different format and date format to make sure that the formats
1561 # are being used
1562 result = pytester.runpytest(
1563 "--log-level=ERROR",
1564 "--log-format=%(asctime)s : %(message)s",
1565 "--log-date-format=%H:%M:%S",
1566 "--log-file=pytest.log",
1567 )
1568 assert result.ret == 1
1569
1570 # The log file should only contain the error log messages
1571 # not the warning or info ones and the format and date format
1572 # should match the formats provided using --log-format and --log-date-format
1573 assert os.path.isfile(log_file)
1574 with open(log_file, encoding="utf-8") as rfh:
1575 contents = rfh.read()
1576 assert re.match(
1577 r"[0-9]{2}:[0-9]{2}:[0-9]{2} : error text going to logger\s*", contents
1578 )
1579 assert "info text going to logger" not in contents
1580 assert "warning text going to logger" not in contents
1581 assert "error text going to logger" in contents