Debian Codegraph @

testing/test_warnings.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import os
5 import sys
6 import warnings
7
8 from _pytest.config import ExitCode
9 from _pytest.fixtures import FixtureRequest
10 from _pytest.pytester import Pytester
11 import pytest
12
13
14 WARNINGS_SUMMARY_HEADER = "warnings summary"
15
16
17 @pytest.fixture
18 def pyfile_with_warnings(pytester: Pytester, request: FixtureRequest) -> str:
19 """Create a test file which calls a function in a module which generates warnings."""
20 pytester.syspathinsert()
21 module_name = request.function.__name__[len("test_") :] + "_module"
22 test_file = pytester.makepyfile(
23 f"""
24 import {module_name}
25 def test_func():
26 assert {module_name}.foo() == 1
27 """,
28 **{
29 module_name: """
30 import warnings
31 def foo():
32 warnings.warn(UserWarning("user warning"))
33 warnings.warn(RuntimeWarning("runtime warning"))
34 return 1
35 """,
36 },
37 )
38 return str(test_file)
39
40
41 @pytest.mark.filterwarnings("default::UserWarning", "default::RuntimeWarning")
42 def test_normal_flow(pytester: Pytester, pyfile_with_warnings) -> None:
43 """Check that the warnings section is displayed."""
44 result = pytester.runpytest(pyfile_with_warnings)
45 result.stdout.fnmatch_lines(
46 [
47 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
48 "test_normal_flow.py::test_func",
49 "*normal_flow_module.py:3: UserWarning: user warning",
50 '* warnings.warn(UserWarning("user warning"))',
51 "*normal_flow_module.py:4: RuntimeWarning: runtime warning",
52 '* warnings.warn(RuntimeWarning("runtime warning"))',
53 "* 1 passed, 2 warnings*",
54 ]
55 )
56
57
58 @pytest.mark.filterwarnings("always::UserWarning")
59 def test_setup_teardown_warnings(pytester: Pytester) -> None:
60 pytester.makepyfile(
61 """
62 import warnings
63 import pytest
64
65 @pytest.fixture
66 def fix():
67 warnings.warn(UserWarning("warning during setup"))
68 yield
69 warnings.warn(UserWarning("warning during teardown"))
70
71 def test_func(fix):
72 pass
73 """
74 )
75 result = pytester.runpytest()
76 result.stdout.fnmatch_lines(
77 [
78 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
79 "*test_setup_teardown_warnings.py:6: UserWarning: warning during setup",
80 '*warnings.warn(UserWarning("warning during setup"))',
81 "*test_setup_teardown_warnings.py:8: UserWarning: warning during teardown",
82 '*warnings.warn(UserWarning("warning during teardown"))',
83 "* 1 passed, 2 warnings*",
84 ]
85 )
86
87
88 @pytest.mark.parametrize("method", ["cmdline", "ini"])
89 def test_as_errors(pytester: Pytester, pyfile_with_warnings, method) -> None:
90 args = ("-W", "error") if method == "cmdline" else ()
91 if method == "ini":
92 pytester.makeini(
93 """
94 [pytest]
95 filterwarnings=error
96 """
97 )
98 # Use a subprocess, since changing logging level affects other threads
99 # (xdist).
100 result = pytester.runpytest_subprocess(*args, pyfile_with_warnings)
101 result.stdout.fnmatch_lines(
102 [
103 "E UserWarning: user warning",
104 "as_errors_module.py:3: UserWarning",
105 "* 1 failed in *",
106 ]
107 )
108
109
110 @pytest.mark.parametrize("method", ["cmdline", "ini"])
111 def test_ignore(pytester: Pytester, pyfile_with_warnings, method) -> None:
112 args = ("-W", "ignore") if method == "cmdline" else ()
113 if method == "ini":
114 pytester.makeini(
115 """
116 [pytest]
117 filterwarnings= ignore
118 """
119 )
120
121 result = pytester.runpytest(*args, pyfile_with_warnings)
122 result.stdout.fnmatch_lines(["* 1 passed in *"])
123 assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
124
125
126 @pytest.mark.filterwarnings("always::UserWarning")
127 def test_unicode(pytester: Pytester) -> None:
128 pytester.makepyfile(
129 """
130 import warnings
131 import pytest
132
133
134 @pytest.fixture
135 def fix():
136 warnings.warn("测试")
137 yield
138
139 def test_func(fix):
140 pass
141 """
142 )
143 result = pytester.runpytest()
144 result.stdout.fnmatch_lines(
145 [
146 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
147 "*test_unicode.py:7: UserWarning: \u6d4b\u8bd5*",
148 "* 1 passed, 1 warning*",
149 ]
150 )
151
152
153 @pytest.mark.skip("issue #13485")
154 def test_works_with_filterwarnings(pytester: Pytester) -> None:
155 """Ensure our warnings capture does not mess with pre-installed filters (#2430)."""
156 pytester.makepyfile(
157 """
158 import warnings
159
160 class MyWarning(Warning):
161 pass
162
163 warnings.filterwarnings("error", category=MyWarning)
164
165 class TestWarnings(object):
166 def test_my_warning(self):
167 try:
168 warnings.warn(MyWarning("warn!"))
169 assert False
170 except MyWarning:
171 assert True
172 """
173 )
174 result = pytester.runpytest()
175 result.stdout.fnmatch_lines(["*== 1 passed in *"])
176
177
178 @pytest.mark.parametrize("default_config", ["ini", "cmdline"])
179 def test_filterwarnings_mark(pytester: Pytester, default_config) -> None:
180 """Test ``filterwarnings`` mark works and takes precedence over command
181 line and ini options."""
182 if default_config == "ini":
183 pytester.makeini(
184 """
185 [pytest]
186 filterwarnings = always::RuntimeWarning
187 """
188 )
189 pytester.makepyfile(
190 """
191 import warnings
192 import pytest
193
194 @pytest.mark.filterwarnings('ignore::RuntimeWarning')
195 def test_ignore_runtime_warning():
196 warnings.warn(RuntimeWarning())
197
198 @pytest.mark.filterwarnings('error')
199 def test_warning_error():
200 warnings.warn(RuntimeWarning())
201
202 def test_show_warning():
203 warnings.warn(RuntimeWarning())
204 """
205 )
206 result = pytester.runpytest(
207 "-W always::RuntimeWarning" if default_config == "cmdline" else ""
208 )
209 result.stdout.fnmatch_lines(["*= 1 failed, 2 passed, 1 warning in *"])
210
211
212 def test_non_string_warning_argument(pytester: Pytester) -> None:
213 """Non-str argument passed to warning breaks pytest (#2956)"""
214 pytester.makepyfile(
215 """\
216 import warnings
217 import pytest
218
219 def test():
220 warnings.warn(UserWarning(1, 'foo'))
221 """
222 )
223 result = pytester.runpytest("-W", "always::UserWarning")
224 result.stdout.fnmatch_lines(["*= 1 passed, 1 warning in *"])
225
226
227 def test_filterwarnings_mark_registration(pytester: Pytester) -> None:
228 """Ensure filterwarnings mark is registered"""
229 pytester.makepyfile(
230 """
231 import pytest
232
233 @pytest.mark.filterwarnings('error')
234 def test_func():
235 pass
236 """
237 )
238 result = pytester.runpytest("--strict-markers")
239 assert result.ret == 0
240
241
242 @pytest.mark.filterwarnings("always::UserWarning")
243 def test_warning_recorded_hook(pytester: Pytester) -> None:
244 pytester.makeconftest(
245 """
246 def pytest_configure(config):
247 config.issue_config_time_warning(UserWarning("config warning"), stacklevel=2)
248 """
249 )
250 pytester.makepyfile(
251 """
252 import pytest, warnings
253
254 warnings.warn(UserWarning("collect warning"))
255
256 @pytest.fixture
257 def fix():
258 warnings.warn(UserWarning("setup warning"))
259 yield 1
260 warnings.warn(UserWarning("teardown warning"))
261
262 def test_func(fix):
263 warnings.warn(UserWarning("call warning"))
264 assert fix == 1
265 """
266 )
267
268 collected = []
269
270 class WarningCollector:
271 def pytest_warning_recorded(self, warning_message, when, nodeid, location):
272 collected.append((str(warning_message.message), when, nodeid, location))
273
274 result = pytester.runpytest(plugins=[WarningCollector()])
275 result.stdout.fnmatch_lines(["*1 passed*"])
276
277 expected = [
278 ("config warning", "config", ""),
279 ("collect warning", "collect", ""),
280 ("setup warning", "runtest", "test_warning_recorded_hook.py::test_func"),
281 ("call warning", "runtest", "test_warning_recorded_hook.py::test_func"),
282 ("teardown warning", "runtest", "test_warning_recorded_hook.py::test_func"),
283 ]
284 for collected_result, expected_result in zip(collected, expected, strict=True):
285 assert collected_result[0] == expected_result[0], str(collected)
286 assert collected_result[1] == expected_result[1], str(collected)
287 assert collected_result[2] == expected_result[2], str(collected)
288
289 # NOTE: collected_result[3] is location, which differs based on the platform you are on
290 # thus, the best we can do here is assert the types of the parameters match what we expect
291 # and not try and preload it in the expected array
292 if collected_result[3] is not None:
293 assert type(collected_result[3][0]) is str, str(collected)
294 assert type(collected_result[3][1]) is int, str(collected)
295 assert type(collected_result[3][2]) is str, str(collected)
296 else:
297 assert collected_result[3] is None, str(collected)
298
299
300 @pytest.mark.filterwarnings("always::UserWarning")
301 def test_collection_warnings(pytester: Pytester) -> None:
302 """Check that we also capture warnings issued during test collection (#3251)."""
303 pytester.makepyfile(
304 """
305 import warnings
306
307 warnings.warn(UserWarning("collection warning"))
308
309 def test_foo():
310 pass
311 """
312 )
313 result = pytester.runpytest()
314 result.stdout.fnmatch_lines(
315 [
316 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
317 " *collection_warnings.py:3: UserWarning: collection warning",
318 ' warnings.warn(UserWarning("collection warning"))',
319 "* 1 passed, 1 warning*",
320 ]
321 )
322
323
324 @pytest.mark.filterwarnings("always::UserWarning")
325 def test_mark_regex_escape(pytester: Pytester) -> None:
326 """@pytest.mark.filterwarnings should not try to escape regex characters (#3936)"""
327 pytester.makepyfile(
328 r"""
329 import pytest, warnings
330
331 @pytest.mark.filterwarnings(r"ignore:some \(warning\)")
332 def test_foo():
333 warnings.warn(UserWarning("some (warning)"))
334 """
335 )
336 result = pytester.runpytest()
337 assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
338
339
340 @pytest.mark.filterwarnings("default::pytest.PytestWarning")
341 @pytest.mark.parametrize("ignore_pytest_warnings", ["no", "ini", "cmdline"])
342 def test_hide_pytest_internal_warnings(
343 pytester: Pytester, ignore_pytest_warnings
344 ) -> None:
345 """Make sure we can ignore internal pytest warnings using a warnings filter."""
346 pytester.makepyfile(
347 """
348 import pytest
349 import warnings
350
351 warnings.warn(pytest.PytestWarning("some internal warning"))
352
353 def test_bar():
354 pass
355 """
356 )
357 if ignore_pytest_warnings == "ini":
358 pytester.makeini(
359 """
360 [pytest]
361 filterwarnings = ignore::pytest.PytestWarning
362 """
363 )
364 args = (
365 ["-W", "ignore::pytest.PytestWarning"]
366 if ignore_pytest_warnings == "cmdline"
367 else []
368 )
369 result = pytester.runpytest(*args)
370 if ignore_pytest_warnings != "no":
371 assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
372 else:
373 result.stdout.fnmatch_lines(
374 [
375 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
376 "*test_hide_pytest_internal_warnings.py:4: PytestWarning: some internal warning",
377 "* 1 passed, 1 warning *",
378 ]
379 )
380
381
382 @pytest.mark.parametrize("ignore_on_cmdline", [True, False])
383 def test_option_precedence_cmdline_over_ini(
384 pytester: Pytester, ignore_on_cmdline
385 ) -> None:
386 """Filters defined in the command-line should take precedence over filters in config files (#3946)."""
387 pytester.makeini(
388 """
389 [pytest]
390 filterwarnings = error::UserWarning
391 """
392 )
393 pytester.makepyfile(
394 """
395 import warnings
396 def test():
397 warnings.warn(UserWarning('hello'))
398 """
399 )
400 args = ["-W", "ignore"] if ignore_on_cmdline else []
401 result = pytester.runpytest(*args)
402 if ignore_on_cmdline:
403 result.stdout.fnmatch_lines(["* 1 passed in*"])
404 else:
405 result.stdout.fnmatch_lines(["* 1 failed in*"])
406
407
408 def test_option_precedence_mark(pytester: Pytester) -> None:
409 """Filters defined by marks should always take precedence (#3946)."""
410 pytester.makeini(
411 """
412 [pytest]
413 filterwarnings = ignore
414 """
415 )
416 pytester.makepyfile(
417 """
418 import pytest, warnings
419 @pytest.mark.filterwarnings('error')
420 def test():
421 warnings.warn(UserWarning('hello'))
422 """
423 )
424 result = pytester.runpytest("-W", "ignore")
425 result.stdout.fnmatch_lines(["* 1 failed in*"])
426
427
428 def test_accept_unknown_category(pytester: Pytester) -> None:
429 """Category types that can't be imported don't cause failure (#13732)."""
430 pytester.makeini(
431 """
432 [pytest]
433 filterwarnings =
434 always:Failed to import filter module.*:pytest.PytestConfigWarning
435 ignore::foobar.Foobar
436 """
437 )
438 pytester.makepyfile(
439 """
440 def test():
441 pass
442 """
443 )
444 result = pytester.runpytest_subprocess("-W", "ignore::bizbaz.Bizbaz")
445 result.stdout.fnmatch_lines(
446 [
447 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
448 "*PytestConfigWarning: Failed to import filter module 'foobar': ignore::foobar.Foobar",
449 "*PytestConfigWarning: Failed to import filter module 'bizbaz': ignore::bizbaz.Bizbaz",
450 "* 1 passed, * warning*",
451 ]
452 )
453
454
455 class TestDeprecationWarningsByDefault:
456 """
457 Note: all pytest runs are executed in a subprocess so we don't inherit warning filters
458 from pytest's own test suite
459 """
460
461 def create_file(self, pytester: Pytester, mark="") -> None:
462 pytester.makepyfile(
463 f"""
464 import pytest, warnings
465
466 warnings.warn(DeprecationWarning("collection"))
467
468 {mark}
469 def test_foo():
470 warnings.warn(PendingDeprecationWarning("test run"))
471 """
472 )
473
474 @pytest.mark.parametrize("customize_filters", [True, False])
475 def test_shown_by_default(self, pytester: Pytester, customize_filters) -> None:
476 """Show deprecation warnings by default, even if user has customized the warnings filters (#4013)."""
477 self.create_file(pytester)
478 if customize_filters:
479 pytester.makeini(
480 """
481 [pytest]
482 filterwarnings =
483 once::UserWarning
484 """
485 )
486 result = pytester.runpytest_subprocess()
487 result.stdout.fnmatch_lines(
488 [
489 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
490 "*test_shown_by_default.py:3: DeprecationWarning: collection",
491 "*test_shown_by_default.py:7: PendingDeprecationWarning: test run",
492 "* 1 passed, 2 warnings*",
493 ]
494 )
495
496 def test_hidden_by_ini(self, pytester: Pytester) -> None:
497 self.create_file(pytester)
498 pytester.makeini(
499 """
500 [pytest]
501 filterwarnings =
502 ignore::DeprecationWarning
503 ignore::PendingDeprecationWarning
504 """
505 )
506 result = pytester.runpytest_subprocess()
507 assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
508
509 def test_hidden_by_mark(self, pytester: Pytester) -> None:
510 """Should hide the deprecation warning from the function, but the warning during collection should
511 be displayed normally.
512 """
513 self.create_file(
514 pytester,
515 mark='@pytest.mark.filterwarnings("ignore::PendingDeprecationWarning")',
516 )
517 result = pytester.runpytest_subprocess()
518 result.stdout.fnmatch_lines(
519 [
520 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
521 "*test_hidden_by_mark.py:3: DeprecationWarning: collection",
522 "* 1 passed, 1 warning*",
523 ]
524 )
525
526 def test_hidden_by_cmdline(self, pytester: Pytester) -> None:
527 self.create_file(pytester)
528 result = pytester.runpytest_subprocess(
529 "-W",
530 "ignore::DeprecationWarning",
531 "-W",
532 "ignore::PendingDeprecationWarning",
533 )
534 assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
535
536 def test_hidden_by_system(self, pytester: Pytester, monkeypatch) -> None:
537 self.create_file(pytester)
538 monkeypatch.setenv("PYTHONWARNINGS", "once::UserWarning")
539 result = pytester.runpytest_subprocess()
540 assert WARNINGS_SUMMARY_HEADER not in result.stdout.str()
541
542 def test_invalid_regex_in_filterwarning(self, pytester: Pytester) -> None:
543 self.create_file(pytester)
544 pytester.makeini(
545 """
546 [pytest]
547 filterwarnings =
548 ignore::DeprecationWarning:*
549 """
550 )
551 result = pytester.runpytest_subprocess()
552 assert result.ret == pytest.ExitCode.USAGE_ERROR
553 result.stderr.fnmatch_lines(
554 [
555 "ERROR: while parsing the following warning configuration:",
556 "",
557 " ignore::DeprecationWarning:[*]",
558 "",
559 "This error occurred:",
560 "",
561 "Invalid regex '[*]': nothing to repeat at position 0",
562 ]
563 )
564
565
566 @pytest.mark.skip("not relevant until pytest 10.0")
567 @pytest.mark.parametrize("change_default", [None, "ini", "cmdline"])
568 def test_removed_in_x_warning_as_error(pytester: Pytester, change_default) -> None:
569 """This ensures that PytestRemovedInXWarnings raised by pytest are turned into errors.
570
571 This test should be enabled as part of each major release, and skipped again afterwards
572 to ensure our deprecations are turning into warnings as expected.
573 """
574 pytester.makepyfile(
575 """
576 import warnings, pytest
577 def test():
578 warnings.warn(pytest.PytestRemovedIn10Warning("some warning"))
579 """
580 )
581 if change_default == "ini":
582 pytester.makeini(
583 """
584 [pytest]
585 filterwarnings =
586 ignore::pytest.PytestRemovedIn10Warning
587 """
588 )
589
590 args = (
591 ("-Wignore::pytest.PytestRemovedIn10Warning",)
592 if change_default == "cmdline"
593 else ()
594 )
595 result = pytester.runpytest(*args)
596 if change_default is None:
597 result.stdout.fnmatch_lines(["* 1 failed in *"])
598 else:
599 assert change_default in ("ini", "cmdline")
600 result.stdout.fnmatch_lines(["* 1 passed in *"])
601
602
603 class TestAssertionWarnings:
604 @staticmethod
605 def assert_result_warns(result, msg) -> None:
606 result.stdout.fnmatch_lines([f"*PytestAssertRewriteWarning: {msg}*"])
607
608 def test_tuple_warning(self, pytester: Pytester) -> None:
609 pytester.makepyfile(
610 """\
611 def test_foo():
612 assert (1,2)
613 """
614 )
615 result = pytester.runpytest()
616 self.assert_result_warns(
617 result, "assertion is always true, perhaps remove parentheses?"
618 )
619
620
621 def test_warnings_checker_twice() -> None:
622 """Issue #4617"""
623 expectation = pytest.warns(UserWarning)
624 with expectation:
625 warnings.warn("Message A", UserWarning)
626 with expectation:
627 warnings.warn("Message B", UserWarning)
628
629
630 @pytest.mark.filterwarnings("always::UserWarning")
631 def test_group_warnings_by_message(pytester: Pytester) -> None:
632 pytester.copy_example("warnings/test_group_warnings_by_message.py")
633 result = pytester.runpytest()
634 result.stdout.fnmatch_lines(
635 [
636 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
637 "test_group_warnings_by_message.py::test_foo[[]0[]]",
638 "test_group_warnings_by_message.py::test_foo[[]1[]]",
639 "test_group_warnings_by_message.py::test_foo[[]2[]]",
640 "test_group_warnings_by_message.py::test_foo[[]3[]]",
641 "test_group_warnings_by_message.py::test_foo[[]4[]]",
642 "test_group_warnings_by_message.py::test_foo_1",
643 " */test_group_warnings_by_message.py:*: UserWarning: foo",
644 " warnings.warn(UserWarning(msg))",
645 "",
646 "test_group_warnings_by_message.py::test_bar[[]0[]]",
647 "test_group_warnings_by_message.py::test_bar[[]1[]]",
648 "test_group_warnings_by_message.py::test_bar[[]2[]]",
649 "test_group_warnings_by_message.py::test_bar[[]3[]]",
650 "test_group_warnings_by_message.py::test_bar[[]4[]]",
651 " */test_group_warnings_by_message.py:*: UserWarning: bar",
652 " warnings.warn(UserWarning(msg))",
653 "",
654 "-- Docs: *",
655 "*= 11 passed, 11 warnings *",
656 ],
657 consecutive=True,
658 )
659
660
661 @pytest.mark.filterwarnings("always::UserWarning")
662 def test_group_warnings_by_message_summary(pytester: Pytester) -> None:
663 pytester.copy_example("warnings/test_group_warnings_by_message_summary")
664 pytester.syspathinsert()
665 result = pytester.runpytest()
666 result.stdout.fnmatch_lines(
667 [
668 f"*== {WARNINGS_SUMMARY_HEADER} ==*",
669 "test_1.py: 21 warnings",
670 "test_2.py: 1 warning",
671 " */test_1.py:10: UserWarning: foo",
672 " warnings.warn(UserWarning(msg))",
673 "",
674 "test_1.py: 20 warnings",
675 " */test_1.py:10: UserWarning: bar",
676 " warnings.warn(UserWarning(msg))",
677 "",
678 "-- Docs: *",
679 "*= 42 passed, 42 warnings *",
680 ],
681 consecutive=True,
682 )
683
684
685 def test_pytest_configure_warning(pytester: Pytester, recwarn) -> None:
686 """Issue 5115."""
687 pytester.makeconftest(
688 """
689 def pytest_configure():
690 import warnings
691
692 warnings.warn("from pytest_configure")
693 """
694 )
695
696 result = pytester.runpytest()
697 assert result.ret == 5
698 assert "INTERNALERROR" not in result.stderr.str()
699 warning = recwarn.pop()
700 assert str(warning.message) == "from pytest_configure"
701
702
703 class TestStackLevel:
704 @pytest.fixture
705 def capwarn(self, pytester: Pytester):
706 class CapturedWarnings:
707 captured: list[
708 tuple[warnings.WarningMessage, tuple[str, int, str] | None]
709 ] = []
710
711 @classmethod
712 def pytest_warning_recorded(cls, warning_message, when, nodeid, location):
713 cls.captured.append((warning_message, location))
714
715 pytester.plugins = [CapturedWarnings()]
716
717 return CapturedWarnings
718
719 def test_issue4445_rewrite(self, pytester: Pytester, capwarn) -> None:
720 """#4445: Make sure the warning points to a reasonable location
721 See origin of _issue_warning_captured at: _pytest.assertion.rewrite.py:241
722 """
723 pytester.makepyfile(some_mod="")
724 conftest = pytester.makeconftest(
725 """
726 import some_mod
727 import pytest
728
729 pytest.register_assert_rewrite("some_mod")
730 """
731 )
732 pytester.parseconfig()
733
734 # with stacklevel=5 the warning originates from register_assert_rewrite
735 # function in the created conftest.py
736 assert len(capwarn.captured) == 1
737 warning, location = capwarn.captured.pop()
738 file, lineno, func = location
739
740 assert "Module already imported" in str(warning.message)
741 assert file == str(conftest)
742 assert func == "<module>" # the above conftest.py
743 assert lineno == 4
744
745 def test_issue4445_initial_conftest(self, pytester: Pytester, capwarn) -> None:
746 """#4445: Make sure the warning points to a reasonable location."""
747 pytester.makeconftest(
748 """
749 import nothing
750 """
751 )
752 pytester.parseconfig("--help")
753
754 # with stacklevel=2 the warning should originate from config._preparse and is
755 # thrown by an erroneous conftest.py
756 assert len(capwarn.captured) == 1
757 warning, location = capwarn.captured.pop()
758 file, _, func = location
759
760 assert "could not load initial conftests" in str(warning.message)
761 assert f"config{os.sep}__init__.py" in file
762 assert func == "parse"
763
764 @pytest.mark.filterwarnings("default")
765 def test_conftest_warning_captured(self, pytester: Pytester) -> None:
766 """Warnings raised during importing of conftest.py files is captured (#2891)."""
767 pytester.makeconftest(
768 """
769 import warnings
770 warnings.warn(UserWarning("my custom warning"))
771 """
772 )
773 result = pytester.runpytest()
774 result.stdout.fnmatch_lines(
775 ["conftest.py:2", "*UserWarning: my custom warning*"]
776 )
777
778 def test_issue4445_import_plugin(self, pytester: Pytester, capwarn) -> None:
779 """#4445: Make sure the warning points to a reasonable location"""
780 pytester.makepyfile(
781 some_plugin="""
782 import pytest
783 pytest.skip("thing", allow_module_level=True)
784 """
785 )
786 pytester.syspathinsert()
787 pytester.parseconfig("-p", "some_plugin")
788
789 # with stacklevel=2 the warning should originate from
790 # config.PytestPluginManager.import_plugin is thrown by a skipped plugin
791
792 assert len(capwarn.captured) == 1
793 warning, location = capwarn.captured.pop()
794 file, _, func = location
795
796 assert "skipped plugin 'some_plugin': thing" in str(warning.message)
797 assert f"config{os.sep}__init__.py" in file
798 assert func == "_warn_about_skipped_plugins"
799
800 def test_issue4445_issue5928_mark_generator(self, pytester: Pytester) -> None:
801 """#4445 and #5928: Make sure the warning from an unknown mark points to
802 the test file where this mark is used.
803 """
804 testfile = pytester.makepyfile(
805 """
806 import pytest
807
808 @pytest.mark.unknown
809 def test_it():
810 pass
811 """
812 )
813 result = pytester.runpytest_subprocess()
814 # with stacklevel=2 the warning should originate from the above created test file
815 result.stdout.fnmatch_lines_random(
816 [
817 f"*{testfile}:3*",
818 "*Unknown pytest.mark.unknown*",
819 ]
820 )
821
822
823 def test_warning_on_testpaths_not_found(pytester: Pytester) -> None:
824 # Check for warning when testpaths set, but not found by glob
825 pytester.makeini(
826 """
827 [pytest]
828 testpaths = absent
829 """
830 )
831 result = pytester.runpytest()
832 result.stdout.fnmatch_lines(
833 ["*ConfigWarning: No files were found in testpaths*", "*1 warning*"]
834 )
835
836
837 def test_resource_warning(pytester: Pytester, monkeypatch: pytest.MonkeyPatch) -> None:
838 # Some platforms (notably PyPy) don't have tracemalloc.
839 # We choose to explicitly not skip this in case tracemalloc is not
840 # available, using `importorskip("tracemalloc")` for example,
841 # because we want to ensure the same code path does not break in those platforms.
842 try:
843 import tracemalloc # noqa: F401
844
845 has_tracemalloc = True
846 except ImportError:
847 has_tracemalloc = False
848
849 # Explicitly disable PYTHONTRACEMALLOC in case pytest's test suite is running
850 # with it enabled.
851 monkeypatch.delenv("PYTHONTRACEMALLOC", raising=False)
852
853 pytester.makepyfile(
854 """
855 def open_file(p):
856 f = p.open("r", encoding="utf-8")
857 assert p.read_text() == "hello"
858
859 def test_resource_warning(tmp_path):
860 p = tmp_path.joinpath("foo.txt")
861 p.write_text("hello", encoding="utf-8")
862 open_file(p)
863 """
864 )
865 result = pytester.run(sys.executable, "-Xdev", "-m", "pytest")
866 expected_extra = (
867 [
868 "*ResourceWarning* unclosed file*",
869 "*Enable tracemalloc to get traceback where the object was allocated*",
870 "*See https* for more info.",
871 ]
872 if has_tracemalloc
873 else []
874 )
875 result.stdout.fnmatch_lines([*expected_extra, "*1 passed*"])
876
877 monkeypatch.setenv("PYTHONTRACEMALLOC", "20")
878
879 result = pytester.run(sys.executable, "-Xdev", "-m", "pytest")
880 expected_extra = (
881 [
882 "*ResourceWarning* unclosed file*",
883 "*Object allocated at*",
884 ]
885 if has_tracemalloc
886 else []
887 )
888 result.stdout.fnmatch_lines([*expected_extra, "*1 passed*"])
889
890
891 class TestMaxWarnings:
892 """Tests for the --max-warnings feature."""
893
894 PYFILE = """
895 import warnings
896 def test_one():
897 warnings.warn(UserWarning("warning one"))
898 def test_two():
899 warnings.warn(UserWarning("warning two"))
900 """
901
902 @pytest.mark.filterwarnings("default::UserWarning")
903 def test_max_warnings_not_set(self, pytester: Pytester) -> None:
904 """Without --max-warnings, warnings don't affect exit code."""
905 pytester.makepyfile(self.PYFILE)
906 result = pytester.runpytest()
907 result.assert_outcomes(passed=2, warnings=2)
908 assert result.ret == ExitCode.OK
909
910 @pytest.mark.filterwarnings("default::UserWarning")
911 def test_max_warnings_not_exceeded(self, pytester: Pytester) -> None:
912 """When warning count is below the threshold, exit code is OK."""
913 pytester.makepyfile(self.PYFILE)
914 result = pytester.runpytest("--max-warnings", "10")
915 result.assert_outcomes(passed=2, warnings=2)
916 assert result.ret == ExitCode.OK
917
918 @pytest.mark.filterwarnings("default::UserWarning")
919 def test_max_warnings_exceeded(self, pytester: Pytester) -> None:
920 """When warning count exceeds threshold, exit code is MAX_WARNINGS_ERROR."""
921 pytester.makepyfile(self.PYFILE)
922 result = pytester.runpytest("--max-warnings", "1")
923 assert result.ret == ExitCode.MAX_WARNINGS_ERROR
924
925 @pytest.mark.filterwarnings("default::UserWarning")
926 def test_max_warnings_equal_to_count(self, pytester: Pytester) -> None:
927 """When warning count equals threshold exactly, exit code is OK."""
928 pytester.makepyfile(self.PYFILE)
929 result = pytester.runpytest("--max-warnings", "2")
930 result.assert_outcomes(passed=2, warnings=2)
931 assert result.ret == ExitCode.OK
932
933 @pytest.mark.filterwarnings("default::UserWarning")
934 def test_max_warnings_zero(self, pytester: Pytester) -> None:
935 """--max-warnings 0 means no warnings are allowed."""
936 pytester.makepyfile(self.PYFILE)
937 result = pytester.runpytest("--max-warnings", "0")
938 assert result.ret == ExitCode.MAX_WARNINGS_ERROR
939
940 @pytest.mark.filterwarnings("default::UserWarning")
941 def test_max_warnings_exceeded_message(self, pytester: Pytester) -> None:
942 """Verify the output message when max warnings is exceeded."""
943 pytester.makepyfile(self.PYFILE)
944 result = pytester.runpytest("--max-warnings", "1")
945 result.stdout.fnmatch_lines(
946 ["*Tests pass, but maximum allowed warnings exceeded: 2 > 1*"]
947 )
948
949 @pytest.mark.filterwarnings("default::UserWarning")
950 def test_max_warnings_ini_option(self, pytester: Pytester) -> None:
951 """max_warnings can be set via INI configuration."""
952 pytester.makeini(
953 """
954 [pytest]
955 max_warnings = 1
956 """
957 )
958 pytester.makepyfile(self.PYFILE)
959 result = pytester.runpytest()
960 assert result.ret == ExitCode.MAX_WARNINGS_ERROR
961
962 @pytest.mark.filterwarnings("default::UserWarning")
963 def test_max_warnings_with_test_failure(self, pytester: Pytester) -> None:
964 """When tests fail AND warnings exceed max, TESTS_FAILED takes priority."""
965 pytester.makepyfile(
966 """
967 import warnings
968 def test_fail():
969 warnings.warn(UserWarning("a warning"))
970 assert False
971 """
972 )
973 result = pytester.runpytest("--max-warnings", "0")
974 assert result.ret == ExitCode.TESTS_FAILED
975
976 @pytest.mark.filterwarnings("default::UserWarning")
977 def test_max_warnings_with_filterwarnings_ignore(self, pytester: Pytester) -> None:
978 """Filtered (ignored) warnings don't count toward max_warnings."""
979 pytester.makepyfile(
980 """
981 import warnings
982 def test_one():
983 warnings.warn(UserWarning("counted"))
984 warnings.warn(RuntimeWarning("ignored"))
985 """
986 )
987 result = pytester.runpytest(
988 "--max-warnings",
989 "1",
990 "-W",
991 "ignore::RuntimeWarning",
992 )
993 result.assert_outcomes(passed=1, warnings=1)
994 assert result.ret == ExitCode.OK
995
996 @pytest.mark.filterwarnings("default::UserWarning")
997 def test_max_warnings_with_filterwarnings_error(self, pytester: Pytester) -> None:
998 """Warnings turned into errors via filterwarnings don't count as warnings."""
999 pytester.makepyfile(
1000 """
1001 import warnings
1002 def test_one():
1003 warnings.warn(UserWarning("still a warning"))
1004 def test_two():
1005 warnings.warn(RuntimeWarning("becomes an error"))
1006 """
1007 )
1008 result = pytester.runpytest(
1009 "--max-warnings",
1010 "0",
1011 "-W",
1012 "error::RuntimeWarning",
1013 )
1014 # The RuntimeWarning becomes a test error, so TESTS_FAILED takes priority.
1015 assert result.ret == ExitCode.TESTS_FAILED
1016
1017 @pytest.mark.filterwarnings("default::UserWarning")
1018 def test_max_warnings_with_filterwarnings_ini_ignore(
1019 self, pytester: Pytester
1020 ) -> None:
1021 """Warnings ignored via ini filterwarnings don't count toward max_warnings."""
1022 pytester.makeini(
1023 """
1024 [pytest]
1025 filterwarnings =
1026 ignore::RuntimeWarning
1027 max_warnings = 1
1028 """
1029 )
1030 pytester.makepyfile(
1031 """
1032 import warnings
1033 def test_one():
1034 warnings.warn(UserWarning("counted"))
1035 warnings.warn(RuntimeWarning("ignored by ini"))
1036 """
1037 )
1038 result = pytester.runpytest()
1039 result.assert_outcomes(passed=1, warnings=1)
1040 assert result.ret == ExitCode.OK
1041
1042
1043 def test_pythonwarnings_not_duplicated(pytester: Pytester) -> None:
1044 """Regression test for #13484: -W values should not be duplicated in
1045 known_args_namespace due to the arg parser being called multiple times."""
1046 config = pytester.parseconfig("-W", "error")
1047 warnings_list = config.known_args_namespace.pythonwarnings
1048 assert warnings_list is not None
1049 assert warnings_list == ["error"]