Debian Codegraph @

testing/test_runner.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 from functools import partial
5 import inspect
6 import os
7 from pathlib import Path
8 import sys
9 import types
10 from typing import cast
11
12 from _pytest import outcomes
13 from _pytest import reports
14 from _pytest import runner
15 from _pytest._code import ExceptionInfo
16 from _pytest._code.code import ExceptionChainRepr
17 from _pytest.config import ExitCode
18 from _pytest.monkeypatch import MonkeyPatch
19 from _pytest.outcomes import OutcomeException
20 from _pytest.pytester import Pytester
21 import pytest
22
23
24 if sys.version_info < (3, 11):
25 from exceptiongroup import ExceptionGroup
26
27
28 class TestSetupState:
29 def test_setup(self, pytester: Pytester) -> None:
30 item = pytester.getitem("def test_func(): pass")
31 ss = item.session._setupstate
32 values = [1]
33 ss.setup(item)
34 ss.addfinalizer(values.pop, item)
35 assert values
36 ss.teardown_exact(None)
37 assert not values
38
39 def test_teardown_exact_stack_empty(self, pytester: Pytester) -> None:
40 item = pytester.getitem("def test_func(): pass")
41 ss = item.session._setupstate
42 ss.setup(item)
43 ss.teardown_exact(None)
44 ss.teardown_exact(None)
45 ss.teardown_exact(None)
46
47 def test_setup_fails_and_failure_is_cached(self, pytester: Pytester) -> None:
48 item = pytester.getitem(
49 """
50 def setup_module(mod):
51 raise ValueError(42)
52 def test_func(): pass
53 """
54 )
55 ss = item.session._setupstate
56 with pytest.raises(ValueError):
57 ss.setup(item)
58 with pytest.raises(ValueError):
59 ss.setup(item)
60
61 def test_teardown_multiple_one_fails(self, pytester: Pytester) -> None:
62 r = []
63
64 def fin1():
65 r.append("fin1")
66
67 def fin2():
68 raise Exception("oops")
69
70 def fin3():
71 r.append("fin3")
72
73 item = pytester.getitem("def test_func(): pass")
74 ss = item.session._setupstate
75 ss.setup(item)
76 ss.addfinalizer(fin1, item)
77 ss.addfinalizer(fin2, item)
78 ss.addfinalizer(fin3, item)
79 with pytest.raises(Exception) as err:
80 ss.teardown_exact(None)
81 assert err.value.args == ("oops",)
82 assert r == ["fin3", "fin1"]
83
84 def test_teardown_multiple_fail(self, pytester: Pytester) -> None:
85 def fin1():
86 raise Exception("oops1")
87
88 def fin2():
89 raise Exception("oops2")
90
91 item = pytester.getitem("def test_func(): pass")
92 ss = item.session._setupstate
93 ss.setup(item)
94 ss.addfinalizer(fin1, item)
95 ss.addfinalizer(fin2, item)
96 with pytest.raises(ExceptionGroup) as err:
97 ss.teardown_exact(None)
98
99 # Note that finalizers are run LIFO, but because FIFO is more intuitive for
100 # users we reverse the order of messages, and see the error from fin1 first.
101 err1, err2 = err.value.exceptions
102 assert err1.args == ("oops1",)
103 assert err2.args == ("oops2",)
104
105 def test_teardown_multiple_scopes_one_fails(self, pytester: Pytester) -> None:
106 module_teardown = []
107
108 def fin_func():
109 raise Exception("oops1")
110
111 def fin_module():
112 module_teardown.append("fin_module")
113
114 item = pytester.getitem("def test_func(): pass")
115 mod = item.listchain()[-2]
116 ss = item.session._setupstate
117 ss.setup(item)
118 ss.addfinalizer(fin_module, mod)
119 ss.addfinalizer(fin_func, item)
120 with pytest.raises(Exception, match="oops1"):
121 ss.teardown_exact(None)
122 assert module_teardown == ["fin_module"]
123
124 def test_teardown_multiple_scopes_several_fail(self, pytester) -> None:
125 def raiser(exc):
126 raise exc
127
128 item = pytester.getitem("def test_func(): pass")
129 mod = item.listchain()[-2]
130 ss = item.session._setupstate
131 ss.setup(item)
132 ss.addfinalizer(partial(raiser, KeyError("from module scope")), mod)
133 ss.addfinalizer(partial(raiser, TypeError("from function scope 1")), item)
134 ss.addfinalizer(partial(raiser, ValueError("from function scope 2")), item)
135
136 with pytest.raises(ExceptionGroup, match="errors during test teardown") as e:
137 ss.teardown_exact(None)
138 mod, func = e.value.exceptions
139 assert isinstance(mod, KeyError)
140 assert isinstance(func.exceptions[0], TypeError)
141 assert isinstance(func.exceptions[1], ValueError)
142
143 def test_cached_exception_doesnt_get_longer(self, pytester: Pytester) -> None:
144 """Regression test for #12204 (the "BTW" case)."""
145 pytester.makepyfile(test="")
146 # If the collector.setup() raises, all collected items error with this
147 # exception.
148 pytester.makeconftest(
149 """
150 import pytest
151
152 class MyItem(pytest.Item):
153 def runtest(self) -> None: pass
154
155 class MyBadCollector(pytest.Collector):
156 def collect(self):
157 return [
158 MyItem.from_parent(self, name="one"),
159 MyItem.from_parent(self, name="two"),
160 MyItem.from_parent(self, name="three"),
161 ]
162
163 def setup(self):
164 1 / 0
165
166 def pytest_collect_file(file_path, parent):
167 if file_path.name == "test.py":
168 return MyBadCollector.from_parent(parent, name='bad')
169 """
170 )
171
172 result = pytester.runpytest_inprocess("--tb=native")
173 assert result.ret == ExitCode.TESTS_FAILED
174 failures = result.reprec.getfailures() # type: ignore[attr-defined]
175 assert len(failures) == 3
176 lines1 = failures[1].longrepr.reprtraceback.reprentries[0].lines
177 lines2 = failures[2].longrepr.reprtraceback.reprentries[0].lines
178 assert len(lines1) == len(lines2)
179
180
181 class BaseFunctionalTests:
182 def test_passfunction(self, pytester: Pytester) -> None:
183 reports = pytester.runitem(
184 """
185 def test_func():
186 pass
187 """
188 )
189 rep = reports[1]
190 assert rep.passed
191 assert not rep.failed
192 assert rep.outcome == "passed"
193 assert not rep.longrepr
194
195 def test_failfunction(self, pytester: Pytester) -> None:
196 reports = pytester.runitem(
197 """
198 def test_func():
199 assert 0
200 """
201 )
202 rep = reports[1]
203 assert not rep.passed
204 assert not rep.skipped
205 assert rep.failed
206 assert rep.when == "call"
207 assert rep.outcome == "failed"
208 # assert isinstance(rep.longrepr, ReprExceptionInfo)
209
210 def test_skipfunction(self, pytester: Pytester) -> None:
211 reports = pytester.runitem(
212 """
213 import pytest
214 def test_func():
215 pytest.skip("hello")
216 """
217 )
218 rep = reports[1]
219 assert not rep.failed
220 assert not rep.passed
221 assert rep.skipped
222 assert rep.outcome == "skipped"
223 # assert rep.skipped.when == "call"
224 # assert rep.skipped.when == "call"
225 # assert rep.skipped == "%sreason == "hello"
226 # assert rep.skipped.location.lineno == 3
227 # assert rep.skipped.location.path
228 # assert not rep.skipped.failurerepr
229
230 def test_skip_in_setup_function(self, pytester: Pytester) -> None:
231 reports = pytester.runitem(
232 """
233 import pytest
234 def setup_function(func):
235 pytest.skip("hello")
236 def test_func():
237 pass
238 """
239 )
240 print(reports)
241 rep = reports[0]
242 assert not rep.failed
243 assert not rep.passed
244 assert rep.skipped
245 # assert rep.skipped.reason == "hello"
246 # assert rep.skipped.location.lineno == 3
247 # assert rep.skipped.location.lineno == 3
248 assert len(reports) == 2
249 assert reports[1].passed # teardown
250
251 def test_failure_in_setup_function(self, pytester: Pytester) -> None:
252 reports = pytester.runitem(
253 """
254 import pytest
255 def setup_function(func):
256 raise ValueError(42)
257 def test_func():
258 pass
259 """
260 )
261 rep = reports[0]
262 assert not rep.skipped
263 assert not rep.passed
264 assert rep.failed
265 assert rep.when == "setup"
266 assert len(reports) == 2
267
268 def test_failure_in_teardown_function(self, pytester: Pytester) -> None:
269 reports = pytester.runitem(
270 """
271 import pytest
272 def teardown_function(func):
273 raise ValueError(42)
274 def test_func():
275 pass
276 """
277 )
278 print(reports)
279 assert len(reports) == 3
280 rep = reports[2]
281 assert not rep.skipped
282 assert not rep.passed
283 assert rep.failed
284 assert rep.when == "teardown"
285 # assert rep.longrepr.reprcrash.lineno == 3
286 # assert rep.longrepr.reprtraceback.reprentries
287
288 def test_custom_failure_repr(self, pytester: Pytester) -> None:
289 pytester.makepyfile(
290 conftest="""
291 import pytest
292 class Function(pytest.Function):
293 def repr_failure(self, excinfo):
294 return "hello"
295 """
296 )
297 reports = pytester.runitem(
298 """
299 import pytest
300 def test_func():
301 assert 0
302 """
303 )
304 rep = reports[1]
305 assert not rep.skipped
306 assert not rep.passed
307 assert rep.failed
308 # assert rep.outcome.when == "call"
309 # assert rep.failed.where.lineno == 3
310 # assert rep.failed.where.path.basename == "test_func.py"
311 # assert rep.failed.failurerepr == "hello"
312
313 def test_teardown_final_returncode(self, pytester: Pytester) -> None:
314 rec = pytester.inline_runsource(
315 """
316 def test_func():
317 pass
318 def teardown_function(func):
319 raise ValueError(42)
320 """
321 )
322 assert rec.ret == 1
323
324 def test_logstart_logfinish_hooks(self, pytester: Pytester) -> None:
325 rec = pytester.inline_runsource(
326 """
327 import pytest
328 def test_func():
329 pass
330 """
331 )
332 reps = rec.getcalls("pytest_runtest_logstart pytest_runtest_logfinish")
333 assert [x._name for x in reps] == [
334 "pytest_runtest_logstart",
335 "pytest_runtest_logfinish",
336 ]
337 for rep in reps:
338 assert rep.nodeid == "test_logstart_logfinish_hooks.py::test_func"
339 assert rep.location == ("test_logstart_logfinish_hooks.py", 1, "test_func")
340
341 def test_exact_teardown_issue90(self, pytester: Pytester) -> None:
342 rec = pytester.inline_runsource(
343 """
344 import pytest
345
346 class TestClass(object):
347 def test_method(self):
348 pass
349 def teardown_class(cls):
350 raise Exception()
351
352 def test_func():
353 import sys
354 # on python2 exc_info is kept till a function exits
355 # so we would end up calling test functions while
356 # sys.exc_info would return the indexerror
357 # from guessing the lastitem
358 excinfo = sys.exc_info()
359 import traceback
360 assert excinfo[0] is None, \
361 traceback.format_exception(*excinfo)
362 def teardown_function(func):
363 raise ValueError(42)
364 """
365 )
366 reps = rec.getreports("pytest_runtest_logreport")
367 print(reps)
368 for i in range(2):
369 assert reps[i].nodeid.endswith("test_method")
370 assert reps[i].passed
371 assert reps[2].when == "teardown"
372 assert reps[2].failed
373 assert len(reps) == 6
374 for i in range(3, 5):
375 assert reps[i].nodeid.endswith("test_func")
376 assert reps[i].passed
377 assert reps[5].when == "teardown"
378 assert reps[5].nodeid.endswith("test_func")
379 assert reps[5].failed
380
381 def test_exact_teardown_issue1206(self, pytester: Pytester) -> None:
382 """Issue shadowing error with wrong number of arguments on teardown_method."""
383 rec = pytester.inline_runsource(
384 """
385 import pytest
386
387 class TestClass(object):
388 def teardown_method(self, x, y, z):
389 pass
390
391 def test_method(self):
392 assert True
393 """
394 )
395 reps = rec.getreports("pytest_runtest_logreport")
396 print(reps)
397 assert len(reps) == 3
398 #
399 assert reps[0].nodeid.endswith("test_method")
400 assert reps[0].passed
401 assert reps[0].when == "setup"
402 #
403 assert reps[1].nodeid.endswith("test_method")
404 assert reps[1].passed
405 assert reps[1].when == "call"
406 #
407 assert reps[2].nodeid.endswith("test_method")
408 assert reps[2].failed
409 assert reps[2].when == "teardown"
410 longrepr = reps[2].longrepr
411 assert isinstance(longrepr, ExceptionChainRepr)
412 assert longrepr.reprcrash
413 assert longrepr.reprcrash.message in (
414 "TypeError: teardown_method() missing 2 required positional arguments: 'y' and 'z'",
415 # Python >= 3.10
416 "TypeError: TestClass.teardown_method() missing 2 required positional arguments: 'y' and 'z'",
417 )
418
419 def test_failure_in_setup_function_ignores_custom_repr(
420 self, pytester: Pytester
421 ) -> None:
422 pytester.makepyfile(
423 conftest="""
424 import pytest
425 class Function(pytest.Function):
426 def repr_failure(self, excinfo):
427 assert 0
428 """
429 )
430 reports = pytester.runitem(
431 """
432 def setup_function(func):
433 raise ValueError(42)
434 def test_func():
435 pass
436 """
437 )
438 assert len(reports) == 2
439 rep = reports[0]
440 print(rep)
441 assert not rep.skipped
442 assert not rep.passed
443 assert rep.failed
444 # assert rep.outcome.when == "setup"
445 # assert rep.outcome.where.lineno == 3
446 # assert rep.outcome.where.path.basename == "test_func.py"
447 # assert isinstance(rep.failed.failurerepr, PythonFailureRepr)
448
449 def test_systemexit_does_not_bail_out(self, pytester: Pytester) -> None:
450 try:
451 reports = pytester.runitem(
452 """
453 def test_func():
454 raise SystemExit(42)
455 """
456 )
457 except SystemExit:
458 assert False, "runner did not catch SystemExit"
459 rep = reports[1]
460 assert rep.failed
461 assert rep.when == "call"
462
463 def test_exit_propagates(self, pytester: Pytester) -> None:
464 try:
465 pytester.runitem(
466 """
467 import pytest
468 def test_func():
469 raise pytest.exit.Exception()
470 """
471 )
472 except pytest.exit.Exception:
473 pass
474 else:
475 assert False, "did not raise"
476
477
478 class TestExecutionNonForked(BaseFunctionalTests):
479 def getrunner(self):
480 def f(item):
481 return runner.runtestprotocol(item, log=False)
482
483 return f
484
485 def test_keyboardinterrupt_propagates(self, pytester: Pytester) -> None:
486 try:
487 pytester.runitem(
488 """
489 def test_func():
490 raise KeyboardInterrupt("fake")
491 """
492 )
493 except KeyboardInterrupt:
494 pass
495 else:
496 assert False, "did not raise"
497
498 def test_keyboardinterrupt_clears_request_and_funcargs(
499 self, pytester: Pytester
500 ) -> None:
501 """Ensure that an item's fixtures are cleared quickly even if exiting
502 early due to a keyboard interrupt (#13626)."""
503 item = pytester.getitem(
504 """
505 import pytest
506
507 @pytest.fixture
508 def resource():
509 return object()
510
511 def test_func(resource):
512 raise KeyboardInterrupt("fake")
513 """
514 )
515 assert isinstance(item, pytest.Function)
516 assert item._request
517 assert item.funcargs == {}
518
519 try:
520 runner.runtestprotocol(item, log=False)
521 except KeyboardInterrupt:
522 pass
523 else:
524 assert False, "did not raise"
525
526 assert not cast(object, item._request)
527 assert not item.funcargs
528
529
530 class TestSessionReports:
531 def test_collect_result(self, pytester: Pytester) -> None:
532 col = pytester.getmodulecol(
533 """
534 def test_func1():
535 pass
536 class TestClass(object):
537 pass
538 """
539 )
540 rep = runner.collect_one_node(col)
541 assert not rep.failed
542 assert not rep.skipped
543 assert rep.passed
544 locinfo = rep.location
545 assert locinfo is not None
546 assert locinfo[0] == col.path.name
547 assert not locinfo[1]
548 assert locinfo[2] == col.path.name
549 res = rep.result
550 assert len(res) == 2
551 assert res[0].name == "test_func1"
552 assert res[1].name == "TestClass"
553
554
555 reporttypes: list[type[reports.BaseReport]] = [
556 reports.BaseReport,
557 reports.TestReport,
558 reports.CollectReport,
559 ]
560
561
562 @pytest.mark.parametrize(
563 "reporttype", reporttypes, ids=[x.__name__ for x in reporttypes]
564 )
565 def test_report_extra_parameters(reporttype: type[reports.BaseReport]) -> None:
566 args = list(inspect.signature(reporttype.__init__).parameters.keys())[1:]
567 basekw: dict[str, list[object]] = {arg: [] for arg in args}
568 report = reporttype(newthing=1, **basekw)
569 assert report.newthing == 1
570
571
572 def test_callinfo() -> None:
573 ci = runner.CallInfo.from_call(lambda: 0, "collect")
574 assert ci.when == "collect"
575 assert ci.result == 0
576 assert "result" in repr(ci)
577 assert repr(ci) == "<CallInfo when='collect' result: 0>"
578 assert str(ci) == "<CallInfo when='collect' result: 0>"
579
580 ci2 = runner.CallInfo.from_call(lambda: 0 / 0, "collect")
581 assert ci2.when == "collect"
582 assert not hasattr(ci2, "result")
583 assert repr(ci2) == f"<CallInfo when='collect' excinfo={ci2.excinfo!r}>"
584 assert str(ci2) == repr(ci2)
585 assert ci2.excinfo
586
587 # Newlines are escaped.
588 def raise_assertion():
589 assert 0, "assert_msg"
590
591 ci3 = runner.CallInfo.from_call(raise_assertion, "call")
592 assert repr(ci3) == f"<CallInfo when='call' excinfo={ci3.excinfo!r}>"
593 assert "\n" not in repr(ci3)
594
595
596 # design question: do we want general hooks in python files?
597 # then something like the following functional tests makes sense
598
599
600 @pytest.mark.xfail
601 def test_runtest_in_module_ordering(pytester: Pytester) -> None:
602 p1 = pytester.makepyfile(
603 """
604 import pytest
605 def pytest_runtest_setup(item): # runs after class-level!
606 item.function.mylist.append("module")
607 class TestClass(object):
608 def pytest_runtest_setup(self, item):
609 assert not hasattr(item.function, 'mylist')
610 item.function.mylist = ['class']
611 @pytest.fixture
612 def mylist(self, request):
613 return request.function.mylist
614 @pytest.hookimpl(wrapper=True)
615 def pytest_runtest_call(self, item):
616 try:
617 yield
618 except ValueError:
619 pass
620 def test_hello1(self, mylist):
621 assert mylist == ['class', 'module'], mylist
622 raise ValueError()
623 def test_hello2(self, mylist):
624 assert mylist == ['class', 'module'], mylist
625 def pytest_runtest_teardown(item):
626 del item.function.mylist
627 """
628 )
629 result = pytester.runpytest(p1)
630 result.stdout.fnmatch_lines(["*2 passed*"])
631
632
633 def test_outcomeexception_exceptionattributes() -> None:
634 outcome = outcomes.OutcomeException("test")
635 assert outcome.args[0] == outcome.msg
636
637
638 def test_outcomeexception_passes_except_Exception() -> None:
639 with pytest.raises(outcomes.OutcomeException):
640 try:
641 raise outcomes.OutcomeException("test")
642 except Exception as e:
643 raise NotImplementedError from e
644
645
646 def test_pytest_exit() -> None:
647 with pytest.raises(pytest.exit.Exception) as excinfo:
648 pytest.exit("hello")
649 assert excinfo.errisinstance(pytest.exit.Exception)
650
651
652 def test_pytest_fail() -> None:
653 with pytest.raises(pytest.fail.Exception) as excinfo:
654 pytest.fail("hello")
655 s = excinfo.exconly(tryshort=True)
656 assert s.startswith("Failed")
657
658
659 def test_pytest_exit_msg(pytester: Pytester) -> None:
660 pytester.makeconftest(
661 """
662 import pytest
663
664 def pytest_configure(config):
665 pytest.exit('oh noes')
666 """
667 )
668 result = pytester.runpytest()
669 result.stderr.fnmatch_lines(["Exit: oh noes"])
670
671
672 def _strip_resource_warnings(lines):
673 # Assert no output on stderr, except for unreliable ResourceWarnings.
674 # (https://github.com/pytest-dev/pytest/issues/5088)
675 return [
676 x
677 for x in lines
678 if not x.startswith(("Exception ignored in:", "ResourceWarning"))
679 ]
680
681
682 def test_pytest_exit_returncode(pytester: Pytester) -> None:
683 pytester.makepyfile(
684 """\
685 import pytest
686 def test_foo():
687 pytest.exit("some exit msg", 99)
688 """
689 )
690 result = pytester.runpytest()
691 result.stdout.fnmatch_lines(["*! *Exit: some exit msg !*"])
692
693 assert _strip_resource_warnings(result.stderr.lines) == []
694 assert result.ret == 99
695
696 # It prints to stderr also in case of exit during pytest_sessionstart.
697 pytester.makeconftest(
698 """\
699 import pytest
700
701 def pytest_sessionstart():
702 pytest.exit("during_sessionstart", 98)
703 """
704 )
705 result = pytester.runpytest()
706 result.stdout.fnmatch_lines(["*! *Exit: during_sessionstart !*"])
707 assert _strip_resource_warnings(result.stderr.lines) == [
708 "Exit: during_sessionstart"
709 ]
710 assert result.ret == 98
711
712
713 def test_pytest_fail_notrace_runtest(pytester: Pytester) -> None:
714 """Test pytest.fail(..., pytrace=False) does not show tracebacks during test run."""
715 pytester.makepyfile(
716 """
717 import pytest
718 def test_hello():
719 pytest.fail("hello", pytrace=False)
720 def teardown_function(function):
721 pytest.fail("world", pytrace=False)
722 """
723 )
724 result = pytester.runpytest()
725 result.stdout.fnmatch_lines(["world", "hello"])
726 result.stdout.no_fnmatch_line("*def teardown_function*")
727
728
729 def test_pytest_fail_notrace_collection(pytester: Pytester) -> None:
730 """Test pytest.fail(..., pytrace=False) does not show tracebacks during collection."""
731 pytester.makepyfile(
732 """
733 import pytest
734 def some_internal_function():
735 pytest.fail("hello", pytrace=False)
736 some_internal_function()
737 """
738 )
739 result = pytester.runpytest()
740 result.stdout.fnmatch_lines(["hello"])
741 result.stdout.no_fnmatch_line("*def some_internal_function()*")
742
743
744 def test_pytest_fail_notrace_non_ascii(pytester: Pytester) -> None:
745 """Fix pytest.fail with pytrace=False with non-ascii characters (#1178).
746
747 This tests with native and unicode strings containing non-ascii chars.
748 """
749 pytester.makepyfile(
750 """\
751 import pytest
752
753 def test_hello():
754 pytest.fail('oh oh: โ˜บ', pytrace=False)
755 """
756 )
757 result = pytester.runpytest()
758 result.stdout.fnmatch_lines(["*test_hello*", "oh oh: โ˜บ"])
759 result.stdout.no_fnmatch_line("*def test_hello*")
760
761
762 def test_pytest_no_tests_collected_exit_status(pytester: Pytester) -> None:
763 result = pytester.runpytest()
764 result.stdout.fnmatch_lines(["*collected 0 items*"])
765 assert result.ret == ExitCode.NO_TESTS_COLLECTED
766
767 pytester.makepyfile(
768 test_foo="""
769 def test_foo():
770 assert 1
771 """
772 )
773 result = pytester.runpytest()
774 result.stdout.fnmatch_lines(["*collected 1 item*"])
775 result.stdout.fnmatch_lines(["*1 passed*"])
776 assert result.ret == ExitCode.OK
777
778 result = pytester.runpytest("-k nonmatch")
779 result.stdout.fnmatch_lines(["*collected 1 item*"])
780 result.stdout.fnmatch_lines(["*1 deselected*"])
781 assert result.ret == ExitCode.NO_TESTS_COLLECTED
782
783
784 def test_exception_printing_skip() -> None:
785 assert pytest.skip.Exception == pytest.skip.Exception
786 try:
787 pytest.skip("hello")
788 except pytest.skip.Exception:
789 excinfo = ExceptionInfo.from_current()
790 s = excinfo.exconly(tryshort=True)
791 assert s.startswith("Skipped")
792
793
794 def test_importorskip(monkeypatch) -> None:
795 importorskip = pytest.importorskip
796
797 def f():
798 importorskip("asdlkj")
799
800 try:
801 sysmod = importorskip("sys")
802 assert sysmod is sys
803 # path = pytest.importorskip("os.path")
804 # assert path == os.path
805 excinfo = pytest.raises(pytest.skip.Exception, f)
806 assert excinfo is not None
807 excrepr = excinfo.getrepr()
808 assert excrepr is not None
809 assert excrepr.reprcrash is not None
810 path = Path(excrepr.reprcrash.path)
811 # check that importorskip reports the actual call
812 # in this test the test_runner.py file
813 assert path.stem == "test_runner"
814 with pytest.raises(SyntaxError):
815 pytest.importorskip("x y z")
816 with pytest.raises(SyntaxError):
817 pytest.importorskip("x=y")
818 mod = types.ModuleType("hello123")
819 mod.__version__ = "1.3" # type: ignore
820 monkeypatch.setitem(sys.modules, "hello123", mod)
821 with pytest.raises(pytest.skip.Exception):
822 pytest.importorskip("hello123", minversion="1.3.1")
823 mod2 = pytest.importorskip("hello123", minversion="1.3")
824 assert mod2 == mod
825 except pytest.skip.Exception: # pragma: no cover
826 assert False, f"spurious skip: {ExceptionInfo.from_current()}"
827
828
829 def test_importorskip_imports_last_module_part() -> None:
830 ospath = pytest.importorskip("os.path")
831 assert os.path == ospath
832
833
834 class TestImportOrSkipExcType:
835 """Tests for importorskip's exc_type behavior."""
836
837 def test_module_not_found_skips_by_default(self) -> None:
838 with pytest.raises(pytest.skip.Exception):
839 pytest.importorskip(
840 "TestImportOrSkipExcType_test_module_not_found_skips_without_warning"
841 )
842
843 def test_import_error_is_propagated_by_default(self, pytester: Pytester) -> None:
844 fn = pytester.makepyfile("raise ImportError('some specific problem')")
845 pytester.syspathinsert()
846
847 with pytest.raises(ImportError, match="some specific problem"):
848 pytest.importorskip(fn.stem)
849
850 def test_import_error_can_be_captured_explicitly(self, pytester: Pytester) -> None:
851 fn = pytester.makepyfile("raise ImportError('some specific problem')")
852 pytester.syspathinsert()
853
854 with pytest.raises(pytest.skip.Exception):
855 pytest.importorskip(fn.stem, exc_type=ImportError)
856
857 def test_import_error_integration(self, pytester: Pytester) -> None:
858 pytester.makepyfile(
859 """
860 import pytest
861 def test_foo():
862 pytest.importorskip("warning_integration_module")
863 """
864 )
865 pytester.makepyfile(
866 warning_integration_module="""
867 raise ImportError("required library foobar not compiled properly")
868 """
869 )
870 result = pytester.runpytest()
871 result.stdout.fnmatch_lines(
872 ["*ImportError: required library foobar not compiled properly*"]
873 )
874 result.assert_outcomes(failed=1)
875
876
877 def test_importorskip_dev_module(monkeypatch) -> None:
878 try:
879 mod = types.ModuleType("mockmodule")
880 mod.__version__ = "0.13.0.dev-43290" # type: ignore
881 monkeypatch.setitem(sys.modules, "mockmodule", mod)
882 mod2 = pytest.importorskip("mockmodule", minversion="0.12.0")
883 assert mod2 == mod
884 with pytest.raises(pytest.skip.Exception):
885 pytest.importorskip("mockmodule1", minversion="0.14.0")
886 except pytest.skip.Exception: # pragma: no cover
887 assert False, f"spurious skip: {ExceptionInfo.from_current()}"
888
889
890 def test_importorskip_module_level(pytester: Pytester) -> None:
891 """`importorskip` must be able to skip entire modules when used at module level."""
892 pytester.makepyfile(
893 """
894 import pytest
895 foobarbaz = pytest.importorskip("foobarbaz")
896
897 def test_foo():
898 pass
899 """
900 )
901 result = pytester.runpytest()
902 result.stdout.fnmatch_lines(["*collected 0 items / 1 skipped*"])
903
904
905 def test_importorskip_custom_reason(pytester: Pytester) -> None:
906 """Make sure custom reasons are used."""
907 pytester.makepyfile(
908 """
909 import pytest
910 foobarbaz = pytest.importorskip("foobarbaz2", reason="just because")
911
912 def test_foo():
913 pass
914 """
915 )
916 result = pytester.runpytest("-ra")
917 result.stdout.fnmatch_lines(["*just because*"])
918 result.stdout.fnmatch_lines(["*collected 0 items / 1 skipped*"])
919
920
921 def test_pytest_cmdline_main(pytester: Pytester) -> None:
922 p = pytester.makepyfile(
923 """
924 import pytest
925 def test_hello():
926 assert 1
927 if __name__ == '__main__':
928 pytest.cmdline.main([__file__])
929 """
930 )
931 import subprocess
932
933 popen = subprocess.Popen([sys.executable, str(p)], stdout=subprocess.PIPE)
934 popen.communicate()
935 ret = popen.wait()
936 assert ret == 0
937
938
939 def test_unicode_in_longrepr(pytester: Pytester) -> None:
940 pytester.makeconftest(
941 """\
942 import pytest
943 @pytest.hookimpl(wrapper=True)
944 def pytest_runtest_makereport():
945 rep = yield
946 if rep.when == "call":
947 rep.longrepr = 'รค'
948 return rep
949 """
950 )
951 pytester.makepyfile(
952 """
953 def test_out():
954 assert 0
955 """
956 )
957 result = pytester.runpytest()
958 assert result.ret == 1
959 assert "UnicodeEncodeError" not in result.stderr.str()
960
961
962 def test_failure_in_setup(pytester: Pytester) -> None:
963 pytester.makepyfile(
964 """
965 def setup_module():
966 0/0
967 def test_func():
968 pass
969 """
970 )
971 result = pytester.runpytest("--tb=line")
972 result.stdout.no_fnmatch_line("*def setup_module*")
973
974
975 def test_makereport_getsource(pytester: Pytester) -> None:
976 pytester.makepyfile(
977 """
978 def test_foo():
979 if False: pass
980 else: assert False
981 """
982 )
983 result = pytester.runpytest()
984 result.stdout.no_fnmatch_line("*INTERNALERROR*")
985 result.stdout.fnmatch_lines(["*else: assert False*"])
986
987
988 def test_makereport_getsource_dynamic_code(
989 pytester: Pytester, monkeypatch: MonkeyPatch
990 ) -> None:
991 """Test that exception in dynamically generated code doesn't break getting the source line."""
992 import inspect
993
994 original_findsource = inspect.findsource
995
996 def findsource(obj):
997 # Can be triggered by dynamically created functions
998 if obj.__name__ == "foo":
999 raise IndexError()
1000 return original_findsource(obj)
1001
1002 monkeypatch.setattr(inspect, "findsource", findsource)
1003
1004 pytester.makepyfile(
1005 """
1006 import pytest
1007
1008 @pytest.fixture
1009 def foo(missing):
1010 pass
1011
1012 def test_fix(foo):
1013 assert False
1014 """
1015 )
1016 result = pytester.runpytest("-vv")
1017 result.stdout.no_fnmatch_line("*INTERNALERROR*")
1018 result.stdout.fnmatch_lines(["*test_fix*", "*fixture*'missing'*not found*"])
1019
1020
1021 def test_store_except_info_on_error() -> None:
1022 """Test that upon test failure, the exception info is stored on
1023 sys.last_traceback and friends."""
1024
1025 # Simulate item that might raise a specific exception, depending on `raise_error` class var
1026 class ItemMightRaise:
1027 nodeid = "item_that_raises"
1028 raise_error = True
1029
1030 def runtest(self):
1031 if self.raise_error:
1032 raise IndexError("TEST")
1033
1034 try:
1035 runner.pytest_runtest_call(ItemMightRaise()) # type: ignore[arg-type]
1036 except IndexError:
1037 pass
1038 # Check that exception info is stored on sys
1039 assert sys.last_type is IndexError
1040 assert isinstance(sys.last_value, IndexError)
1041 if sys.version_info >= (3, 12, 0):
1042 assert isinstance(sys.last_exc, IndexError) # type:ignore[attr-defined]
1043
1044 assert sys.last_value.args[0] == "TEST"
1045 assert sys.last_traceback
1046
1047 # The next run should clear the exception info stored by the previous run
1048 ItemMightRaise.raise_error = False
1049 runner.pytest_runtest_call(ItemMightRaise()) # type: ignore[arg-type]
1050 assert not hasattr(sys, "last_type")
1051 assert not hasattr(sys, "last_value")
1052 if sys.version_info >= (3, 12, 0):
1053 assert not hasattr(sys, "last_exc")
1054 assert not hasattr(sys, "last_traceback")
1055
1056
1057 def test_current_test_env_var(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
1058 pytest_current_test_vars: list[tuple[str, str]] = []
1059 monkeypatch.setattr(
1060 sys, "pytest_current_test_vars", pytest_current_test_vars, raising=False
1061 )
1062 pytester.makepyfile(
1063 """
1064 import pytest
1065 import sys
1066 import os
1067
1068 @pytest.fixture
1069 def fix():
1070 sys.pytest_current_test_vars.append(('setup', os.environ['PYTEST_CURRENT_TEST']))
1071 yield
1072 sys.pytest_current_test_vars.append(('teardown', os.environ['PYTEST_CURRENT_TEST']))
1073
1074 def test(fix):
1075 sys.pytest_current_test_vars.append(('call', os.environ['PYTEST_CURRENT_TEST']))
1076 """
1077 )
1078 result = pytester.runpytest_inprocess()
1079 assert result.ret == 0
1080 test_id = "test_current_test_env_var.py::test"
1081 assert pytest_current_test_vars == [
1082 ("setup", test_id + " (setup)"),
1083 ("call", test_id + " (call)"),
1084 ("teardown", test_id + " (teardown)"),
1085 ]
1086 assert "PYTEST_CURRENT_TEST" not in os.environ
1087
1088
1089 class TestReportContents:
1090 """Test user-level API of ``TestReport`` objects."""
1091
1092 def getrunner(self):
1093 return lambda item: runner.runtestprotocol(item, log=False)
1094
1095 def test_longreprtext_pass(self, pytester: Pytester) -> None:
1096 reports = pytester.runitem(
1097 """
1098 def test_func():
1099 pass
1100 """
1101 )
1102 rep = reports[1]
1103 assert rep.longreprtext == ""
1104
1105 def test_longreprtext_skip(self, pytester: Pytester) -> None:
1106 """TestReport.longreprtext can handle non-str ``longrepr`` attributes (#7559)"""
1107 reports = pytester.runitem(
1108 """
1109 import pytest
1110 def test_func():
1111 pytest.skip()
1112 """
1113 )
1114 _, call_rep, _ = reports
1115 assert isinstance(call_rep.longrepr, tuple)
1116 assert "Skipped" in call_rep.longreprtext
1117
1118 def test_longreprtext_collect_skip(self, pytester: Pytester) -> None:
1119 """CollectReport.longreprtext can handle non-str ``longrepr`` attributes (#7559)"""
1120 pytester.makepyfile(
1121 """
1122 import pytest
1123 pytest.skip(allow_module_level=True)
1124 """
1125 )
1126 rec = pytester.inline_run()
1127 calls = rec.getcalls("pytest_collectreport")
1128 _, call, _ = calls
1129 assert isinstance(call.report.longrepr, tuple)
1130 assert "Skipped" in call.report.longreprtext
1131
1132 def test_longreprtext_failure(self, pytester: Pytester) -> None:
1133 reports = pytester.runitem(
1134 """
1135 def test_func():
1136 x = 1
1137 assert x == 4
1138 """
1139 )
1140 rep = reports[1]
1141 assert "assert 1 == 4" in rep.longreprtext
1142
1143 def test_captured_text(self, pytester: Pytester) -> None:
1144 reports = pytester.runitem(
1145 """
1146 import pytest
1147 import sys
1148
1149 @pytest.fixture
1150 def fix():
1151 sys.stdout.write('setup: stdout\\n')
1152 sys.stderr.write('setup: stderr\\n')
1153 yield
1154 sys.stdout.write('teardown: stdout\\n')
1155 sys.stderr.write('teardown: stderr\\n')
1156 assert 0
1157
1158 def test_func(fix):
1159 sys.stdout.write('call: stdout\\n')
1160 sys.stderr.write('call: stderr\\n')
1161 assert 0
1162 """
1163 )
1164 setup, call, teardown = reports
1165 assert setup.capstdout == "setup: stdout\n"
1166 assert call.capstdout == "setup: stdout\ncall: stdout\n"
1167 assert teardown.capstdout == "setup: stdout\ncall: stdout\nteardown: stdout\n"
1168
1169 assert setup.capstderr == "setup: stderr\n"
1170 assert call.capstderr == "setup: stderr\ncall: stderr\n"
1171 assert teardown.capstderr == "setup: stderr\ncall: stderr\nteardown: stderr\n"
1172
1173 def test_no_captured_text(self, pytester: Pytester) -> None:
1174 reports = pytester.runitem(
1175 """
1176 def test_func():
1177 pass
1178 """
1179 )
1180 rep = reports[1]
1181 assert rep.capstdout == ""
1182 assert rep.capstderr == ""
1183
1184 def test_longrepr_type(self, pytester: Pytester) -> None:
1185 reports = pytester.runitem(
1186 """
1187 import pytest
1188 def test_func():
1189 pytest.fail(pytrace=False)
1190 """
1191 )
1192 rep = reports[1]
1193 assert isinstance(rep.longrepr, ExceptionChainRepr)
1194
1195
1196 def test_outcome_exception_bad_msg() -> None:
1197 """Check that OutcomeExceptions validate their input to prevent confusing errors (#5578)"""
1198
1199 def func() -> None:
1200 raise NotImplementedError()
1201
1202 expected = (
1203 "OutcomeException expected string as 'msg' parameter, got 'function' instead.\n"
1204 "Perhaps you meant to use a mark?"
1205 )
1206 with pytest.raises(TypeError) as excinfo:
1207 OutcomeException(func) # type: ignore
1208 assert str(excinfo.value) == expected
1209
1210
1211 def test_pytest_version_env_var(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
1212 monkeypatch.setenv("PYTEST_VERSION", "old version")
1213 pytester.makepyfile(
1214 """
1215 import pytest
1216 import os
1217
1218
1219 def test():
1220 assert os.environ.get("PYTEST_VERSION") == pytest.__version__
1221 """
1222 )
1223 result = pytester.runpytest_inprocess()
1224 assert result.ret == ExitCode.OK
1225 assert os.environ["PYTEST_VERSION"] == "old version"
1226
1227
1228 def test_teardown_session_failed(pytester: Pytester) -> None:
1229 """Test that higher-scoped fixture teardowns run in the context of the last
1230 item after the test session bails early due to --maxfail.
1231
1232 Regression test for #11706.
1233 """
1234 pytester.makepyfile(
1235 """
1236 import pytest
1237
1238 @pytest.fixture(scope="module")
1239 def baz():
1240 yield
1241 pytest.fail("This is a failing teardown")
1242
1243 def test_foo(baz):
1244 pytest.fail("This is a failing test")
1245
1246 def test_bar(): pass
1247 """
1248 )
1249 result = pytester.runpytest("--maxfail=1")
1250 result.assert_outcomes(failed=1, errors=1)
1251
1252
1253 def test_teardown_session_stopped(pytester: Pytester) -> None:
1254 """Test that higher-scoped fixture teardowns run in the context of the last
1255 item after the test session bails early due to --stepwise.
1256
1257 Regression test for #11706.
1258 """
1259 pytester.makepyfile(
1260 """
1261 import pytest
1262
1263 @pytest.fixture(scope="module")
1264 def baz():
1265 yield
1266 pytest.fail("This is a failing teardown")
1267
1268 def test_foo(baz):
1269 pytest.fail("This is a failing test")
1270
1271 def test_bar(): pass
1272 """
1273 )
1274 result = pytester.runpytest("--stepwise")
1275 result.assert_outcomes(failed=1, errors=1)