Debian Codegraph @

testing/logging/test_fixture.py

raw
1 # mypy: disable-error-code="attr-defined"
2 # mypy: disallow-untyped-defs
3 from __future__ import annotations
4
5 from collections.abc import Iterator
6 import logging
7
8 from _pytest.logging import caplog_records_key
9 from _pytest.pytester import Pytester
10 import pytest
11
12
13 logger = logging.getLogger(__name__)
14 sublogger = logging.getLogger(__name__ + ".baz")
15
16
17 @pytest.fixture(autouse=True)
18 def cleanup_disabled_logging() -> Iterator[None]:
19 """Simple fixture that ensures that a test doesn't disable logging.
20
21 This is necessary because ``logging.disable()`` is global, so a test disabling logging
22 and not cleaning up after will break every test that runs after it.
23
24 This behavior was moved to a fixture so that logging will be un-disabled even if the test fails an assertion.
25 """
26 yield
27 logging.disable(logging.NOTSET)
28
29
30 def test_fixture_help(pytester: Pytester) -> None:
31 result = pytester.runpytest("--fixtures")
32 result.stdout.fnmatch_lines(["*caplog*"])
33
34
35 def test_change_level(caplog: pytest.LogCaptureFixture) -> None:
36 caplog.set_level(logging.INFO)
37 logger.debug("handler DEBUG level")
38 logger.info("handler INFO level")
39
40 caplog.set_level(logging.CRITICAL, logger=sublogger.name)
41 sublogger.warning("logger WARNING level")
42 sublogger.critical("logger CRITICAL level")
43
44 assert "DEBUG" not in caplog.text
45 assert "INFO" in caplog.text
46 assert "WARNING" not in caplog.text
47 assert "CRITICAL" in caplog.text
48
49
50 def test_change_level_logging_disabled(caplog: pytest.LogCaptureFixture) -> None:
51 logging.disable(logging.CRITICAL)
52 assert logging.root.manager.disable == logging.CRITICAL
53 caplog.set_level(logging.WARNING)
54 logger.info("handler INFO level")
55 logger.warning("handler WARNING level")
56
57 caplog.set_level(logging.CRITICAL, logger=sublogger.name)
58 sublogger.warning("logger SUB_WARNING level")
59 sublogger.critical("logger SUB_CRITICAL level")
60
61 assert "INFO" not in caplog.text
62 assert "WARNING" in caplog.text
63 assert "SUB_WARNING" not in caplog.text
64 assert "SUB_CRITICAL" in caplog.text
65
66
67 def test_change_level_undo(pytester: Pytester) -> None:
68 """Ensure that 'set_level' is undone after the end of the test.
69
70 Tests the logging output themselves (affected both by logger and handler levels).
71 """
72 pytester.makepyfile(
73 """
74 import logging
75
76 def test1(caplog):
77 caplog.set_level(logging.INFO)
78 # using + operator here so fnmatch_lines doesn't match the code in the traceback
79 logging.info('log from ' + 'test1')
80 assert 0
81
82 def test2(caplog):
83 # using + operator here so fnmatch_lines doesn't match the code in the traceback
84 logging.info('log from ' + 'test2')
85 assert 0
86 """
87 )
88 result = pytester.runpytest()
89 result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
90 result.stdout.no_fnmatch_line("*log from test2*")
91
92
93 def test_change_disabled_level_undo(pytester: Pytester) -> None:
94 """Ensure that '_force_enable_logging' in 'set_level' is undone after the end of the test.
95
96 Tests the logging output themselves (affected by disabled logging level).
97 """
98 pytester.makepyfile(
99 """
100 import logging
101
102 def test1(caplog):
103 logging.disable(logging.CRITICAL)
104 caplog.set_level(logging.INFO)
105 # using + operator here so fnmatch_lines doesn't match the code in the traceback
106 logging.info('log from ' + 'test1')
107 assert 0
108
109 def test2(caplog):
110 # using + operator here so fnmatch_lines doesn't match the code in the traceback
111 # use logging.warning because we need a level that will show up if logging.disabled
112 # isn't reset to ``CRITICAL`` after test1.
113 logging.warning('log from ' + 'test2')
114 assert 0
115 """
116 )
117 result = pytester.runpytest()
118 result.stdout.fnmatch_lines(["*log from test1*", "*2 failed in *"])
119 result.stdout.no_fnmatch_line("*log from test2*")
120
121
122 def test_change_level_undoes_handler_level(pytester: Pytester) -> None:
123 """Ensure that 'set_level' is undone after the end of the test (handler).
124
125 Issue #7569. Tests the handler level specifically.
126 """
127 pytester.makepyfile(
128 """
129 import logging
130
131 def test1(caplog):
132 assert caplog.handler.level == 0
133 caplog.set_level(9999)
134 caplog.set_level(41)
135 assert caplog.handler.level == 41
136
137 def test2(caplog):
138 assert caplog.handler.level == 0
139
140 def test3(caplog):
141 assert caplog.handler.level == 0
142 caplog.set_level(43)
143 assert caplog.handler.level == 43
144 """
145 )
146 result = pytester.runpytest()
147 result.assert_outcomes(passed=3)
148
149
150 def test_with_statement_at_level(caplog: pytest.LogCaptureFixture) -> None:
151 with caplog.at_level(logging.INFO):
152 logger.debug("handler DEBUG level")
153 logger.info("handler INFO level")
154
155 with caplog.at_level(logging.CRITICAL, logger=sublogger.name):
156 sublogger.warning("logger WARNING level")
157 sublogger.critical("logger CRITICAL level")
158
159 assert "DEBUG" not in caplog.text
160 assert "INFO" in caplog.text
161 assert "WARNING" not in caplog.text
162 assert "CRITICAL" in caplog.text
163
164
165 def test_with_statement_at_level_logging_disabled(
166 caplog: pytest.LogCaptureFixture,
167 ) -> None:
168 logging.disable(logging.CRITICAL)
169 assert logging.root.manager.disable == logging.CRITICAL
170 with caplog.at_level(logging.WARNING):
171 logger.debug("handler DEBUG level")
172 logger.info("handler INFO level")
173 logger.warning("handler WARNING level")
174 logger.error("handler ERROR level")
175 logger.critical("handler CRITICAL level")
176
177 assert logging.root.manager.disable == logging.INFO
178
179 with caplog.at_level(logging.CRITICAL, logger=sublogger.name):
180 sublogger.warning("logger SUB_WARNING level")
181 sublogger.critical("logger SUB_CRITICAL level")
182
183 assert "DEBUG" not in caplog.text
184 assert "INFO" not in caplog.text
185 assert "WARNING" in caplog.text
186 assert "ERROR" in caplog.text
187 assert " CRITICAL" in caplog.text
188 assert "SUB_WARNING" not in caplog.text
189 assert "SUB_CRITICAL" in caplog.text
190 assert logging.root.manager.disable == logging.CRITICAL
191
192
193 def test_with_statement_filtering(caplog: pytest.LogCaptureFixture) -> None:
194 class TestFilter(logging.Filter):
195 def filter(self, record: logging.LogRecord) -> bool:
196 record.msg = "filtered handler call"
197 return True
198
199 with caplog.at_level(logging.INFO):
200 with caplog.filtering(TestFilter()):
201 logger.info("handler call")
202 logger.info("handler call")
203
204 filtered_tuple, unfiltered_tuple = caplog.record_tuples
205 assert filtered_tuple == ("test_fixture", 20, "filtered handler call")
206 assert unfiltered_tuple == ("test_fixture", 20, "handler call")
207
208
209 @pytest.mark.parametrize(
210 "level_str,expected_disable_level",
211 [
212 ("CRITICAL", logging.ERROR),
213 ("ERROR", logging.WARNING),
214 ("WARNING", logging.INFO),
215 ("INFO", logging.DEBUG),
216 ("DEBUG", logging.NOTSET),
217 ("NOTSET", logging.NOTSET),
218 ("NOTVALIDLEVEL", logging.NOTSET),
219 ],
220 )
221 def test_force_enable_logging_level_string(
222 caplog: pytest.LogCaptureFixture, level_str: str, expected_disable_level: int
223 ) -> None:
224 """Test _force_enable_logging using a level string.
225
226 ``expected_disable_level`` is one level below ``level_str`` because the disabled log level
227 always needs to be *at least* one level lower than the level that caplog is trying to capture.
228 """
229 test_logger = logging.getLogger("test_str_level_force_enable")
230 # Emulate a testing environment where all logging is disabled.
231 logging.disable(logging.CRITICAL)
232 # Make sure all logging is disabled.
233 assert not test_logger.isEnabledFor(logging.CRITICAL)
234 # Un-disable logging for `level_str`.
235 caplog._force_enable_logging(level_str, test_logger)
236 # Make sure that the disabled level is now one below the requested logging level.
237 # We don't use `isEnabledFor` here because that also checks the level set by
238 # `logging.setLevel()` which is irrelevant to `logging.disable()`.
239 assert test_logger.manager.disable == expected_disable_level
240
241
242 def test_log_access(caplog: pytest.LogCaptureFixture) -> None:
243 caplog.set_level(logging.INFO)
244 logger.info("boo %s", "arg")
245 assert caplog.records[0].levelname == "INFO"
246 assert caplog.records[0].msg == "boo %s"
247 assert "boo arg" in caplog.text
248
249
250 def test_messages(caplog: pytest.LogCaptureFixture) -> None:
251 caplog.set_level(logging.INFO)
252 logger.info("boo %s", "arg")
253 logger.info("bar %s\nbaz %s", "arg1", "arg2")
254 assert "boo arg" == caplog.messages[0]
255 assert "bar arg1\nbaz arg2" == caplog.messages[1]
256 assert caplog.text.count("\n") > len(caplog.messages)
257 assert len(caplog.text.splitlines()) > len(caplog.messages)
258
259 try:
260 raise Exception("test")
261 except Exception:
262 logger.exception("oops")
263
264 assert "oops" in caplog.text
265 assert "oops" in caplog.messages[-1]
266 # Tracebacks are stored in the record and not added until the formatter or handler.
267 assert "Exception" in caplog.text
268 assert "Exception" not in caplog.messages[-1]
269
270
271 def test_record_tuples(caplog: pytest.LogCaptureFixture) -> None:
272 caplog.set_level(logging.INFO)
273 logger.info("boo %s", "arg")
274
275 assert caplog.record_tuples == [(__name__, logging.INFO, "boo arg")]
276
277
278 def test_unicode(caplog: pytest.LogCaptureFixture) -> None:
279 caplog.set_level(logging.INFO)
280 logger.info("bū")
281 assert caplog.records[0].levelname == "INFO"
282 assert caplog.records[0].msg == "bū"
283 assert "bū" in caplog.text
284
285
286 def test_clear(caplog: pytest.LogCaptureFixture) -> None:
287 caplog.set_level(logging.INFO)
288 logger.info("bū")
289 assert len(caplog.records)
290 assert caplog.text
291 caplog.clear()
292 assert not len(caplog.records)
293 assert not caplog.text
294
295
296 @pytest.fixture
297 def logging_during_setup_and_teardown(
298 caplog: pytest.LogCaptureFixture,
299 ) -> Iterator[None]:
300 caplog.set_level("INFO")
301 logger.info("a_setup_log")
302 yield
303 logger.info("a_teardown_log")
304 assert [x.message for x in caplog.get_records("teardown")] == ["a_teardown_log"]
305
306
307 def private_assert_caplog_records_is_setup_call(
308 caplog: pytest.LogCaptureFixture,
309 ) -> None:
310 # This reaches into private API, don't use this type of thing in real tests!
311 caplog_records = caplog._item.stash[caplog_records_key]
312 assert set(caplog_records) == {"setup", "call"}
313
314
315 def test_captures_for_all_stages(
316 caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None
317 ) -> None:
318 assert not caplog.records
319 assert not caplog.get_records("call")
320 logger.info("a_call_log")
321 assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
322
323 assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
324
325 private_assert_caplog_records_is_setup_call(caplog)
326
327
328 def test_clear_for_call_stage(
329 caplog: pytest.LogCaptureFixture, logging_during_setup_and_teardown: None
330 ) -> None:
331 logger.info("a_call_log")
332 assert [x.message for x in caplog.get_records("call")] == ["a_call_log"]
333 assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
334 private_assert_caplog_records_is_setup_call(caplog)
335
336 caplog.clear()
337
338 assert caplog.get_records("call") == []
339 assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
340 private_assert_caplog_records_is_setup_call(caplog)
341
342 logging.info("a_call_log_after_clear")
343 assert [x.message for x in caplog.get_records("call")] == ["a_call_log_after_clear"]
344 assert [x.message for x in caplog.get_records("setup")] == ["a_setup_log"]
345 private_assert_caplog_records_is_setup_call(caplog)
346
347
348 def test_ini_controls_global_log_level(pytester: Pytester) -> None:
349 pytester.makepyfile(
350 """
351 import pytest
352 import logging
353 def test_log_level_override(request, caplog):
354 plugin = request.config.pluginmanager.getplugin('logging-plugin')
355 assert plugin.log_level == logging.ERROR
356 logger = logging.getLogger('catchlog')
357 logger.warning("WARNING message won't be shown")
358 logger.error("ERROR message will be shown")
359 assert 'WARNING' not in caplog.text
360 assert 'ERROR' in caplog.text
361 """
362 )
363 pytester.makeini(
364 """
365 [pytest]
366 log_level=ERROR
367 """
368 )
369
370 result = pytester.runpytest()
371 # make sure that we get a '0' exit code for the testsuite
372 assert result.ret == 0
373
374
375 def test_can_override_global_log_level(pytester: Pytester) -> None:
376 pytester.makepyfile(
377 """
378 import pytest
379 import logging
380 def test_log_level_override(request, caplog):
381 logger = logging.getLogger('catchlog')
382 plugin = request.config.pluginmanager.getplugin('logging-plugin')
383 assert plugin.log_level == logging.WARNING
384
385 logger.info("INFO message won't be shown")
386
387 caplog.set_level(logging.INFO, logger.name)
388
389 with caplog.at_level(logging.DEBUG, logger.name):
390 logger.debug("DEBUG message will be shown")
391
392 logger.debug("DEBUG message won't be shown")
393
394 with caplog.at_level(logging.CRITICAL, logger.name):
395 logger.warning("WARNING message won't be shown")
396
397 logger.debug("DEBUG message won't be shown")
398 logger.info("INFO message will be shown")
399
400 assert "message won't be shown" not in caplog.text
401 """
402 )
403 pytester.makeini(
404 """
405 [pytest]
406 log_level=WARNING
407 """
408 )
409
410 result = pytester.runpytest()
411 assert result.ret == 0
412
413
414 def test_can_capture_non_propagating_logger(pytester: Pytester) -> None:
415 """Logs emitted by non-propagating loggers are still captured (#3697)."""
416 pytester.makepyfile(
417 """
418 import logging
419
420 logger = logging.getLogger("catchlog")
421 logger.propagate = False
422 child_logger = logging.getLogger("catchlog.child")
423
424 def test_non_propagating_logger(caplog):
425 caplog.set_level(logging.INFO)
426
427 logger.info("parent logger message")
428 child_logger.info("child logger message")
429
430 assert caplog.record_tuples == [
431 ("catchlog", logging.INFO, "parent logger message"),
432 ("catchlog.child", logging.INFO, "child logger message"),
433 ]
434 """
435 )
436
437 result = pytester.runpytest()
438 result.assert_outcomes(passed=1)
439
440
441 def test_captures_despite_exception(pytester: Pytester) -> None:
442 pytester.makepyfile(
443 """
444 import pytest
445 import logging
446 def test_log_level_override(request, caplog):
447 logger = logging.getLogger('catchlog')
448 plugin = request.config.pluginmanager.getplugin('logging-plugin')
449 assert plugin.log_level == logging.WARNING
450
451 logger.error("ERROR message " + "will be shown")
452
453 with caplog.at_level(logging.DEBUG, logger.name):
454 logger.debug("DEBUG message " + "won't be shown")
455 raise Exception()
456 """
457 )
458 pytester.makeini(
459 """
460 [pytest]
461 log_level=WARNING
462 """
463 )
464
465 result = pytester.runpytest()
466 result.stdout.fnmatch_lines(["*ERROR message will be shown*"])
467 result.stdout.no_fnmatch_line("*DEBUG message won't be shown*")
468 assert result.ret == 1
469
470
471 def test_log_report_captures_according_to_config_option_upon_failure(
472 pytester: Pytester,
473 ) -> None:
474 """Test that upon failure:
475 (1) `caplog` succeeded to capture the DEBUG message and assert on it => No `Exception` is raised.
476 (2) The `DEBUG` message does NOT appear in the `Captured log call` report.
477 (3) The stdout, `INFO`, and `WARNING` messages DO appear in the test reports due to `--log-level=INFO`.
478 """
479 pytester.makepyfile(
480 """
481 import pytest
482 import logging
483
484 def function_that_logs():
485 logging.debug('DEBUG log ' + 'message')
486 logging.info('INFO log ' + 'message')
487 logging.warning('WARNING log ' + 'message')
488 print('Print ' + 'message')
489
490 def test_that_fails(request, caplog):
491 plugin = request.config.pluginmanager.getplugin('logging-plugin')
492 assert plugin.log_level == logging.INFO
493
494 with caplog.at_level(logging.DEBUG):
495 function_that_logs()
496
497 if 'DEBUG log ' + 'message' not in caplog.text:
498 raise Exception('caplog failed to ' + 'capture DEBUG')
499
500 assert False
501 """
502 )
503
504 result = pytester.runpytest("--log-level=INFO")
505 result.stdout.no_fnmatch_line("*Exception: caplog failed to capture DEBUG*")
506 result.stdout.no_fnmatch_line("*DEBUG log message*")
507 result.stdout.fnmatch_lines(
508 ["*Print message*", "*INFO log message*", "*WARNING log message*"]
509 )
510 assert result.ret == 1