Debian Codegraph @

testing/test_unittest.py

raw
1 # mypy: allow-untyped-defs
2 from __future__ import annotations
3
4 import sys
5
6 from _pytest.config import ExitCode
7 from _pytest.monkeypatch import MonkeyPatch
8 from _pytest.pytester import Pytester
9 import pytest
10
11
12 def test_simple_unittest(pytester: Pytester) -> None:
13 testpath = pytester.makepyfile(
14 """
15 import unittest
16 class MyTestCase(unittest.TestCase):
17 def testpassing(self):
18 self.assertEqual('foo', 'foo')
19 def test_failing(self):
20 self.assertEqual('foo', 'bar')
21 """
22 )
23 reprec = pytester.inline_run(testpath)
24 assert reprec.matchreport("testpassing").passed
25 assert reprec.matchreport("test_failing").failed
26
27
28 def test_runTest_method(pytester: Pytester) -> None:
29 pytester.makepyfile(
30 """
31 import unittest
32 class MyTestCaseWithRunTest(unittest.TestCase):
33 def runTest(self):
34 self.assertEqual('foo', 'foo')
35 class MyTestCaseWithoutRunTest(unittest.TestCase):
36 def runTest(self):
37 self.assertEqual('foo', 'foo')
38 def test_something(self):
39 pass
40 """
41 )
42 result = pytester.runpytest("-v")
43 result.stdout.fnmatch_lines(
44 """
45 *MyTestCaseWithRunTest::runTest*
46 *MyTestCaseWithoutRunTest::test_something*
47 *2 passed*
48 """
49 )
50
51
52 def test_isclasscheck_issue53(pytester: Pytester) -> None:
53 testpath = pytester.makepyfile(
54 """
55 import unittest
56 class _E(object):
57 def __getattr__(self, tag):
58 pass
59 E = _E()
60 """
61 )
62 result = pytester.runpytest(testpath)
63 assert result.ret == ExitCode.NO_TESTS_COLLECTED
64
65
66 def test_setup(pytester: Pytester) -> None:
67 testpath = pytester.makepyfile(
68 """
69 import unittest
70 class MyTestCase(unittest.TestCase):
71 def setUp(self):
72 self.foo = 1
73 def setup_method(self, method):
74 self.foo2 = 1
75 def test_both(self):
76 self.assertEqual(1, self.foo)
77 assert self.foo2 == 1
78 def teardown_method(self, method):
79 assert 0, "42"
80
81 """
82 )
83 reprec = pytester.inline_run("-s", testpath)
84 assert reprec.matchreport("test_both", when="call").passed
85 rep = reprec.matchreport("test_both", when="teardown")
86 assert rep.failed and "42" in str(rep.longrepr)
87
88
89 def test_setUpModule(pytester: Pytester) -> None:
90 testpath = pytester.makepyfile(
91 """
92 values = []
93
94 def setUpModule():
95 values.append(1)
96
97 def tearDownModule():
98 del values[0]
99
100 def test_hello():
101 assert values == [1]
102
103 def test_world():
104 assert values == [1]
105 """
106 )
107 result = pytester.runpytest(testpath)
108 result.stdout.fnmatch_lines(["*2 passed*"])
109
110
111 def test_setUpModule_failing_no_teardown(pytester: Pytester) -> None:
112 testpath = pytester.makepyfile(
113 """
114 values = []
115
116 def setUpModule():
117 0/0
118
119 def tearDownModule():
120 values.append(1)
121
122 def test_hello():
123 pass
124 """
125 )
126 reprec = pytester.inline_run(testpath)
127 reprec.assertoutcome(passed=0, failed=1)
128 call = reprec.getcalls("pytest_runtest_setup")[0]
129 assert not call.item.module.values
130
131
132 def test_new_instances(pytester: Pytester) -> None:
133 testpath = pytester.makepyfile(
134 """
135 import unittest
136 class MyTestCase(unittest.TestCase):
137 def test_func1(self):
138 self.x = 2
139 def test_func2(self):
140 assert not hasattr(self, 'x')
141 """
142 )
143 reprec = pytester.inline_run(testpath)
144 reprec.assertoutcome(passed=2)
145
146
147 def test_function_item_obj_is_instance(pytester: Pytester) -> None:
148 """item.obj should be a bound method on unittest.TestCase function items (#5390)."""
149 pytester.makeconftest(
150 """
151 def pytest_runtest_makereport(item, call):
152 if call.when == 'call':
153 class_ = item.parent.obj
154 assert isinstance(item.obj.__self__, class_)
155 """
156 )
157 pytester.makepyfile(
158 """
159 import unittest
160
161 class Test(unittest.TestCase):
162 def test_foo(self):
163 pass
164 """
165 )
166 result = pytester.runpytest_inprocess()
167 result.stdout.fnmatch_lines(["* 1 passed in*"])
168
169
170 def test_teardown(pytester: Pytester) -> None:
171 testpath = pytester.makepyfile(
172 """
173 import unittest
174 class MyTestCase(unittest.TestCase):
175 values = []
176 def test_one(self):
177 pass
178 def tearDown(self):
179 self.values.append(None)
180 class Second(unittest.TestCase):
181 def test_check(self):
182 self.assertEqual(MyTestCase.values, [None])
183 """
184 )
185 reprec = pytester.inline_run(testpath)
186 passed, skipped, failed = reprec.countoutcomes()
187 assert failed == 0, failed
188 assert passed == 2
189 assert passed + skipped + failed == 2
190
191
192 def test_teardown_issue1649(pytester: Pytester) -> None:
193 """
194 Are TestCase objects cleaned up? Often unittest TestCase objects set
195 attributes that are large and expensive during test run or setUp.
196
197 The TestCase will not be cleaned up if the test fails, because it
198 would then exist in the stackframe.
199
200 Regression test for #1649 (see also #12367).
201 """
202 pytester.makepyfile(
203 """
204 import unittest
205 import gc
206
207 class TestCaseObjectsShouldBeCleanedUp(unittest.TestCase):
208 def test_expensive(self):
209 self.an_expensive_obj = object()
210
211 def test_is_it_still_alive(self):
212 gc.collect()
213 for obj in gc.get_objects():
214 if type(obj).__name__ == "TestCaseObjectsShouldBeCleanedUp":
215 assert not hasattr(obj, "an_expensive_obj")
216 break
217 else:
218 assert False, "Could not find TestCaseObjectsShouldBeCleanedUp instance"
219 """
220 )
221
222 result = pytester.runpytest()
223 assert result.ret == ExitCode.OK
224
225
226 def test_unittest_skip_issue148(pytester: Pytester) -> None:
227 testpath = pytester.makepyfile(
228 """
229 import unittest
230
231 @unittest.skip("hello")
232 class MyTestCase(unittest.TestCase):
233 @classmethod
234 def setUpClass(self):
235 xxx
236 def test_one(self):
237 pass
238 @classmethod
239 def tearDownClass(self):
240 xxx
241 """
242 )
243 reprec = pytester.inline_run(testpath)
244 reprec.assertoutcome(skipped=1)
245
246
247 def test_unittest_skip_with_autouse_fixture(pytester: Pytester) -> None:
248 """Autouse fixtures inside a @unittest.skipIf class should not run (#13885)."""
249 pytester.makepyfile(
250 """
251 import unittest
252 import pytest
253
254 @unittest.skipIf(True, "skip reason")
255 class TestSkipped(unittest.TestCase):
256 @pytest.fixture(autouse=True)
257 def my_fixture(self):
258 raise RuntimeError("fixture should not run")
259
260 def test_one(self):
261 pass
262 """
263 )
264 reprec = pytester.inline_run()
265 reprec.assertoutcome(skipped=1)
266
267
268 def test_method_and_teardown_failing_reporting(pytester: Pytester) -> None:
269 pytester.makepyfile(
270 """
271 import unittest
272 class TC(unittest.TestCase):
273 def tearDown(self):
274 assert 0, "down1"
275 def test_method(self):
276 assert False, "down2"
277 """
278 )
279 result = pytester.runpytest("-s")
280 assert result.ret == 1
281 result.stdout.fnmatch_lines(
282 [
283 "*tearDown*",
284 "*assert 0*",
285 "*test_method*",
286 "*assert False*",
287 "*1 failed*1 error*",
288 ]
289 )
290
291
292 def test_setup_failure_is_shown(pytester: Pytester) -> None:
293 pytester.makepyfile(
294 """
295 import unittest
296 import pytest
297 class TC(unittest.TestCase):
298 def setUp(self):
299 assert 0, "down1"
300 def test_method(self):
301 print("never42")
302 xyz
303 """
304 )
305 result = pytester.runpytest("-s")
306 assert result.ret == 1
307 result.stdout.fnmatch_lines(["*setUp*", "*assert 0*down1*", "*1 failed*"])
308 result.stdout.no_fnmatch_line("*never42*")
309
310
311 def test_setup_setUpClass(pytester: Pytester) -> None:
312 testpath = pytester.makepyfile(
313 """
314 import unittest
315 import pytest
316 class MyTestCase(unittest.TestCase):
317 x = 0
318 @classmethod
319 def setUpClass(cls):
320 cls.x += 1
321 def test_func1(self):
322 assert self.x == 1
323 def test_func2(self):
324 assert self.x == 1
325 @classmethod
326 def tearDownClass(cls):
327 cls.x -= 1
328 def test_torn_down():
329 assert MyTestCase.x == 0
330 """
331 )
332 reprec = pytester.inline_run(testpath)
333 reprec.assertoutcome(passed=3)
334
335
336 def test_fixtures_setup_setUpClass_issue8394(pytester: Pytester) -> None:
337 pytester.makepyfile(
338 """
339 import unittest
340 class MyTestCase(unittest.TestCase):
341 @classmethod
342 def setUpClass(cls):
343 pass
344 def test_func1(self):
345 pass
346 @classmethod
347 def tearDownClass(cls):
348 pass
349 """
350 )
351 result = pytester.runpytest("--fixtures")
352 assert result.ret == 0
353 result.stdout.no_fnmatch_line("*no docstring available*")
354
355 result = pytester.runpytest("--fixtures", "-v")
356 assert result.ret == 0
357 result.stdout.fnmatch_lines(["*no docstring available*"])
358
359
360 def test_setup_class(pytester: Pytester) -> None:
361 testpath = pytester.makepyfile(
362 """
363 import unittest
364 import pytest
365 class MyTestCase(unittest.TestCase):
366 x = 0
367 def setup_class(cls):
368 cls.x += 1
369 def test_func1(self):
370 assert self.x == 1
371 def test_func2(self):
372 assert self.x == 1
373 def teardown_class(cls):
374 cls.x -= 1
375 def test_torn_down():
376 assert MyTestCase.x == 0
377 """
378 )
379 reprec = pytester.inline_run(testpath)
380 reprec.assertoutcome(passed=3)
381
382
383 @pytest.mark.parametrize("type", ["Error", "Failure"])
384 def test_testcase_adderrorandfailure_defers(pytester: Pytester, type: str) -> None:
385 pytester.makepyfile(
386 f"""
387 from unittest import TestCase
388 import pytest
389 class MyTestCase(TestCase):
390 def run(self, result):
391 excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)
392 try:
393 result.add{type}(self, excinfo._excinfo)
394 except KeyboardInterrupt:
395 raise
396 except:
397 pytest.fail("add{type} should not raise")
398 def test_hello(self):
399 pass
400 """
401 )
402 result = pytester.runpytest()
403 result.stdout.no_fnmatch_line("*should not raise*")
404
405
406 @pytest.mark.parametrize("type", ["Error", "Failure"])
407 def test_testcase_custom_exception_info(pytester: Pytester, type: str) -> None:
408 pytester.makepyfile(
409 f"""
410 from typing import Generic, TypeVar
411 from unittest import TestCase
412 import pytest, _pytest._code
413
414 class MyTestCase(TestCase):
415 def run(self, result):
416 excinfo = pytest.raises(ZeroDivisionError, lambda: 0/0)
417 # We fake an incompatible exception info.
418 class FakeExceptionInfo(Generic[TypeVar("E")]):
419 def __init__(self, *args, **kwargs):
420 mp.undo()
421 raise TypeError()
422 @classmethod
423 def from_current(cls):
424 return cls()
425 @classmethod
426 def from_exc_info(cls, *args, **kwargs):
427 return cls()
428 mp = pytest.MonkeyPatch()
429 mp.setattr(_pytest._code, 'ExceptionInfo', FakeExceptionInfo)
430 try:
431 excinfo = excinfo._excinfo
432 result.add{type}(self, excinfo)
433 finally:
434 mp.undo()
435
436 def test_hello(self):
437 pass
438 """
439 )
440 result = pytester.runpytest()
441 result.stdout.fnmatch_lines(
442 [
443 "NOTE: Incompatible Exception Representation*",
444 "*ZeroDivisionError*",
445 "*1 failed*",
446 ]
447 )
448
449
450 def test_testcase_totally_incompatible_exception_info(pytester: Pytester) -> None:
451 import _pytest.unittest
452
453 (item,) = pytester.getitems(
454 """
455 from unittest import TestCase
456 class MyTestCase(TestCase):
457 def test_hello(self):
458 pass
459 """
460 )
461 assert isinstance(item, _pytest.unittest.TestCaseFunction)
462 item.addError(None, 42) # type: ignore[arg-type]
463 excinfo = item._excinfo
464 assert excinfo is not None
465 assert "ERROR: Unknown Incompatible" in str(excinfo.pop(0).getrepr())
466
467
468 def test_module_level_pytestmark(pytester: Pytester) -> None:
469 testpath = pytester.makepyfile(
470 """
471 import unittest
472 import pytest
473 pytestmark = pytest.mark.xfail
474 class MyTestCase(unittest.TestCase):
475 def test_func1(self):
476 assert 0
477 """
478 )
479 reprec = pytester.inline_run(testpath, "-s")
480 reprec.assertoutcome(skipped=1)
481
482
483 class TestTrialUnittest:
484 def setup_class(cls):
485 cls.ut = pytest.importorskip("twisted.trial.unittest")
486 # on windows trial uses a socket for a reactor and apparently doesn't close it properly
487 # https://twistedmatrix.com/trac/ticket/9227
488 cls.ignore_unclosed_socket_warning = ("-W", "always")
489
490 def test_trial_testcase_runtest_not_collected(self, pytester: Pytester) -> None:
491 pytester.makepyfile(
492 """
493 from twisted.trial.unittest import TestCase
494
495 class TC(TestCase):
496 def test_hello(self):
497 pass
498 """
499 )
500 reprec = pytester.inline_run(*self.ignore_unclosed_socket_warning)
501 reprec.assertoutcome(passed=1)
502 pytester.makepyfile(
503 """
504 from twisted.trial.unittest import TestCase
505
506 class TC(TestCase):
507 def runTest(self):
508 pass
509 """
510 )
511 reprec = pytester.inline_run(*self.ignore_unclosed_socket_warning)
512 reprec.assertoutcome(passed=1)
513
514 def test_trial_exceptions_with_skips(self, pytester: Pytester) -> None:
515 pytester.makepyfile(
516 """
517 from twisted.trial import unittest
518 import pytest
519 class TC(unittest.TestCase):
520 def test_hello(self):
521 pytest.skip("skip_in_method")
522 @pytest.mark.skipif("sys.version_info != 1")
523 def test_hello2(self):
524 pass
525 @pytest.mark.xfail(reason="iwanto")
526 def test_hello3(self):
527 assert 0
528 def test_hello4(self):
529 pytest.xfail("i2wanto")
530 def test_trial_skip(self):
531 pass
532 test_trial_skip.skip = "trialselfskip"
533
534 def test_trial_todo(self):
535 assert 0
536 test_trial_todo.todo = "mytodo"
537
538 def test_trial_todo_success(self):
539 pass
540 test_trial_todo_success.todo = "mytodo"
541
542 class TC2(unittest.TestCase):
543 def setup_class(cls):
544 pytest.skip("skip_in_setup_class")
545 def test_method(self):
546 pass
547 """
548 )
549 result = pytester.runpytest("-rxs", *self.ignore_unclosed_socket_warning)
550 result.stdout.fnmatch_lines_random(
551 [
552 "*XFAIL*test_trial_todo*",
553 "*trialselfskip*",
554 "*skip_in_setup_class*",
555 "*iwanto*",
556 "*i2wanto*",
557 "*sys.version_info*",
558 "*skip_in_method*",
559 "*1 failed*4 skipped*3 xfailed*",
560 ]
561 )
562 assert result.ret == 1
563
564 def test_trial_error(self, pytester: Pytester) -> None:
565 pytester.makepyfile(
566 """
567 from twisted.trial.unittest import TestCase
568 from twisted.internet.defer import Deferred
569 from twisted.internet import reactor
570
571 class TC(TestCase):
572 def test_one(self):
573 crash
574
575 def test_two(self):
576 def f(_):
577 crash
578
579 d = Deferred()
580 d.addCallback(f)
581 reactor.callLater(0.3, d.callback, None)
582 return d
583
584 def test_three(self):
585 def f():
586 pass # will never get called
587 reactor.callLater(0.3, f)
588 # will crash at teardown
589
590 def test_four(self):
591 def f(_):
592 reactor.callLater(0.3, f)
593 crash
594
595 d = Deferred()
596 d.addCallback(f)
597 reactor.callLater(0.3, d.callback, None)
598 return d
599 # will crash both at test time and at teardown
600 """
601 )
602 result = pytester.runpytest(
603 "-vv", "-oconsole_output_style=classic", "-W", "ignore::DeprecationWarning"
604 )
605 result.stdout.fnmatch_lines(
606 [
607 "test_trial_error.py::TC::test_four FAILED",
608 "test_trial_error.py::TC::test_four ERROR",
609 "test_trial_error.py::TC::test_one FAILED",
610 "test_trial_error.py::TC::test_three FAILED",
611 "test_trial_error.py::TC::test_two FAILED",
612 "*ERRORS*",
613 "*_ ERROR at teardown of TC.test_four _*",
614 "*DelayedCalls*",
615 "*= FAILURES =*",
616 "*_ TC.test_four _*",
617 "*NameError*crash*",
618 "*_ TC.test_one _*",
619 "*NameError*crash*",
620 "*_ TC.test_three _*",
621 "*DelayedCalls*",
622 "*_ TC.test_two _*",
623 "*NameError*crash*",
624 "*= 4 failed, 1 error in *",
625 ]
626 )
627
628 def test_trial_pdb(self, pytester: Pytester) -> None:
629 p = pytester.makepyfile(
630 """
631 from twisted.trial import unittest
632 import pytest
633 class TC(unittest.TestCase):
634 def test_hello(self):
635 assert 0, "hellopdb"
636 """
637 )
638 child = pytester.spawn_pytest(str(p))
639 child.expect("hellopdb")
640 child.sendeof()
641
642 def test_trial_testcase_skip_property(self, pytester: Pytester) -> None:
643 testpath = pytester.makepyfile(
644 """
645 from twisted.trial import unittest
646 class MyTestCase(unittest.TestCase):
647 skip = 'dont run'
648 def test_func(self):
649 pass
650 """
651 )
652 reprec = pytester.inline_run(testpath, "-s")
653 reprec.assertoutcome(skipped=1)
654
655 def test_trial_testfunction_skip_property(self, pytester: Pytester) -> None:
656 testpath = pytester.makepyfile(
657 """
658 from twisted.trial import unittest
659 class MyTestCase(unittest.TestCase):
660 def test_func(self):
661 pass
662 test_func.skip = 'dont run'
663 """
664 )
665 reprec = pytester.inline_run(testpath, "-s")
666 reprec.assertoutcome(skipped=1)
667
668 def test_trial_testcase_todo_property(self, pytester: Pytester) -> None:
669 testpath = pytester.makepyfile(
670 """
671 from twisted.trial import unittest
672 class MyTestCase(unittest.TestCase):
673 todo = 'dont run'
674 def test_func(self):
675 assert 0
676 """
677 )
678 reprec = pytester.inline_run(testpath, "-s")
679 reprec.assertoutcome(skipped=1)
680
681 def test_trial_testfunction_todo_property(self, pytester: Pytester) -> None:
682 testpath = pytester.makepyfile(
683 """
684 from twisted.trial import unittest
685 class MyTestCase(unittest.TestCase):
686 def test_func(self):
687 assert 0
688 test_func.todo = 'dont run'
689 """
690 )
691 reprec = pytester.inline_run(
692 testpath, "-s", *self.ignore_unclosed_socket_warning
693 )
694 reprec.assertoutcome(skipped=1)
695
696
697 def test_djangolike_testcase(pytester: Pytester) -> None:
698 # contributed from Morten Breekevold
699 pytester.makepyfile(
700 """
701 from unittest import TestCase, main
702
703 class DjangoLikeTestCase(TestCase):
704
705 def setUp(self):
706 print("setUp()")
707
708 def test_presetup_has_been_run(self):
709 print("test_thing()")
710 self.assertTrue(hasattr(self, 'was_presetup'))
711
712 def tearDown(self):
713 print("tearDown()")
714
715 def __call__(self, result=None):
716 try:
717 self._pre_setup()
718 except (KeyboardInterrupt, SystemExit):
719 raise
720 except Exception:
721 import sys
722 result.addError(self, sys.exc_info())
723 return
724 super(DjangoLikeTestCase, self).__call__(result)
725 try:
726 self._post_teardown()
727 except (KeyboardInterrupt, SystemExit):
728 raise
729 except Exception:
730 import sys
731 result.addError(self, sys.exc_info())
732 return
733
734 def _pre_setup(self):
735 print("_pre_setup()")
736 self.was_presetup = True
737
738 def _post_teardown(self):
739 print("_post_teardown()")
740 """
741 )
742 result = pytester.runpytest("-s")
743 assert result.ret == 0
744 result.stdout.fnmatch_lines(
745 [
746 "*_pre_setup()*",
747 "*setUp()*",
748 "*test_thing()*",
749 "*tearDown()*",
750 "*_post_teardown()*",
751 ]
752 )
753
754
755 def test_unittest_not_shown_in_traceback(pytester: Pytester) -> None:
756 pytester.makepyfile(
757 """
758 import unittest
759 class t(unittest.TestCase):
760 def test_hello(self):
761 x = 3
762 self.assertEqual(x, 4)
763 """
764 )
765 res = pytester.runpytest()
766 res.stdout.no_fnmatch_line("*failUnlessEqual*")
767
768
769 def test_unorderable_types(pytester: Pytester) -> None:
770 pytester.makepyfile(
771 """
772 import unittest
773 class TestJoinEmpty(unittest.TestCase):
774 pass
775
776 def make_test():
777 class Test(unittest.TestCase):
778 pass
779 Test.__name__ = "TestFoo"
780 return Test
781 TestFoo = make_test()
782 """
783 )
784 result = pytester.runpytest()
785 result.stdout.no_fnmatch_line("*TypeError*")
786 assert result.ret == ExitCode.NO_TESTS_COLLECTED
787
788
789 def test_unittest_typerror_traceback(pytester: Pytester) -> None:
790 pytester.makepyfile(
791 """
792 import unittest
793 class TestJoinEmpty(unittest.TestCase):
794 def test_hello(self, arg1):
795 pass
796 """
797 )
798 result = pytester.runpytest()
799 assert "TypeError" in result.stdout.str()
800 assert result.ret == 1
801
802
803 @pytest.mark.parametrize("runner", ["pytest", "unittest"])
804 def test_unittest_expected_failure_for_failing_test_is_xfail(
805 pytester: Pytester, runner
806 ) -> None:
807 script = pytester.makepyfile(
808 """
809 import unittest
810 class MyTestCase(unittest.TestCase):
811 @unittest.expectedFailure
812 def test_failing_test_is_xfail(self):
813 assert False
814 if __name__ == '__main__':
815 unittest.main()
816 """
817 )
818 if runner == "pytest":
819 result = pytester.runpytest("-rxX")
820 result.stdout.fnmatch_lines(
821 ["*XFAIL*MyTestCase*test_failing_test_is_xfail*", "*1 xfailed*"]
822 )
823 else:
824 result = pytester.runpython(script)
825 result.stderr.fnmatch_lines(["*1 test in*", "*OK*(expected failures=1)*"])
826 assert result.ret == 0
827
828
829 @pytest.mark.parametrize("runner", ["pytest", "unittest"])
830 def test_unittest_expected_failure_for_passing_test_is_fail(
831 pytester: Pytester,
832 runner: str,
833 ) -> None:
834 script = pytester.makepyfile(
835 """
836 import unittest
837 class MyTestCase(unittest.TestCase):
838 @unittest.expectedFailure
839 def test_passing_test_is_fail(self):
840 assert True
841 if __name__ == '__main__':
842 unittest.main()
843 """
844 )
845
846 if runner == "pytest":
847 result = pytester.runpytest("-rxX")
848 result.stdout.fnmatch_lines(
849 [
850 "*MyTestCase*test_passing_test_is_fail*",
851 "Unexpected success",
852 "*1 failed*",
853 ]
854 )
855 else:
856 result = pytester.runpython(script)
857 result.stderr.fnmatch_lines(["*1 test in*", "*(unexpected successes=1)*"])
858
859 assert result.ret == 1
860
861
862 @pytest.mark.parametrize("stmt", ["return", "yield"])
863 def test_unittest_setup_interaction(pytester: Pytester, stmt: str) -> None:
864 pytester.makepyfile(
865 f"""
866 import unittest
867 import pytest
868 class MyTestCase(unittest.TestCase):
869 @pytest.fixture(scope="class", autouse=True)
870 @classmethod
871 def perclass(cls, request):
872 request.cls.hello = "world"
873 {stmt}
874
875 @pytest.fixture(scope="function", autouse=True)
876 def perfunction(self, request):
877 request.instance.funcname = request.function.__name__
878 {stmt}
879
880 def test_method1(self):
881 assert self.funcname == "test_method1"
882 assert self.hello == "world"
883
884 def test_method2(self):
885 assert self.funcname == "test_method2"
886
887 def test_classattr(self):
888 assert self.__class__.hello == "world"
889 """
890 )
891 result = pytester.runpytest()
892 result.stdout.fnmatch_lines(["*3 passed*"])
893
894
895 def test_non_unittest_no_setupclass_support(pytester: Pytester) -> None:
896 testpath = pytester.makepyfile(
897 """
898 class TestFoo(object):
899 x = 0
900
901 @classmethod
902 def setUpClass(cls):
903 cls.x = 1
904
905 def test_method1(self):
906 assert self.x == 0
907
908 @classmethod
909 def tearDownClass(cls):
910 cls.x = 1
911
912 def test_not_torn_down():
913 assert TestFoo.x == 0
914
915 """
916 )
917 reprec = pytester.inline_run(testpath)
918 reprec.assertoutcome(passed=2)
919
920
921 def test_no_teardown_if_setupclass_failed(pytester: Pytester) -> None:
922 testpath = pytester.makepyfile(
923 """
924 import unittest
925
926 class MyTestCase(unittest.TestCase):
927 x = 0
928
929 @classmethod
930 def setUpClass(cls):
931 cls.x = 1
932 assert False
933
934 def test_func1(self):
935 cls.x = 10
936
937 @classmethod
938 def tearDownClass(cls):
939 cls.x = 100
940
941 def test_notTornDown():
942 assert MyTestCase.x == 1
943 """
944 )
945 reprec = pytester.inline_run(testpath)
946 reprec.assertoutcome(passed=1, failed=1)
947
948
949 def test_cleanup_functions(pytester: Pytester) -> None:
950 """Ensure functions added with addCleanup are always called after each test ends (#6947)"""
951 pytester.makepyfile(
952 """
953 import unittest
954
955 cleanups = []
956
957 class Test(unittest.TestCase):
958
959 def test_func_1(self):
960 self.addCleanup(cleanups.append, "test_func_1")
961
962 def test_func_2(self):
963 self.addCleanup(cleanups.append, "test_func_2")
964 assert 0
965
966 def test_func_3_check_cleanups(self):
967 assert cleanups == ["test_func_1", "test_func_2"]
968 """
969 )
970 result = pytester.runpytest("-v")
971 result.stdout.fnmatch_lines(
972 [
973 "*::test_func_1 PASSED *",
974 "*::test_func_2 FAILED *",
975 "*::test_func_3_check_cleanups PASSED *",
976 ]
977 )
978
979
980 def test_issue333_result_clearing(pytester: Pytester) -> None:
981 pytester.makeconftest(
982 """
983 import pytest
984 @pytest.hookimpl(wrapper=True)
985 def pytest_runtest_call(item):
986 yield
987 assert 0
988 """
989 )
990 pytester.makepyfile(
991 """
992 import unittest
993 class TestIt(unittest.TestCase):
994 def test_func(self):
995 0/0
996 """
997 )
998
999 reprec = pytester.inline_run()
1000 reprec.assertoutcome(failed=1)
1001
1002
1003 def test_unittest_raise_skip_issue748(pytester: Pytester) -> None:
1004 pytester.makepyfile(
1005 test_foo="""
1006 import unittest
1007
1008 class MyTestCase(unittest.TestCase):
1009 def test_one(self):
1010 raise unittest.SkipTest('skipping due to reasons')
1011 """
1012 )
1013 result = pytester.runpytest("-v", "-rs")
1014 result.stdout.fnmatch_lines(
1015 """
1016 *SKIP*[1]*test_foo.py*skipping due to reasons*
1017 *1 skipped*
1018 """
1019 )
1020
1021
1022 def test_unittest_skip_issue1169(pytester: Pytester) -> None:
1023 pytester.makepyfile(
1024 test_foo="""
1025 import unittest
1026
1027 class MyTestCase(unittest.TestCase):
1028 @unittest.skip("skipping due to reasons")
1029 def test_skip(self):
1030 self.fail()
1031 """
1032 )
1033 result = pytester.runpytest("-v", "-rs")
1034 result.stdout.fnmatch_lines(
1035 """
1036 *SKIP*[1]*skipping due to reasons*
1037 *1 skipped*
1038 """
1039 )
1040
1041
1042 def test_class_method_containing_test_issue1558(pytester: Pytester) -> None:
1043 pytester.makepyfile(
1044 test_foo="""
1045 import unittest
1046
1047 class MyTestCase(unittest.TestCase):
1048 def test_should_run(self):
1049 pass
1050 def test_should_not_run(self):
1051 pass
1052 test_should_not_run.__test__ = False
1053 """
1054 )
1055 reprec = pytester.inline_run()
1056 reprec.assertoutcome(passed=1)
1057
1058
1059 @pytest.mark.parametrize("base", ["builtins.object", "unittest.TestCase"])
1060 def test_usefixtures_marker_on_unittest(base, pytester: Pytester) -> None:
1061 """#3498"""
1062 module = base.rsplit(".", 1)[0]
1063 pytest.importorskip(module)
1064 pytester.makepyfile(
1065 conftest="""
1066 import pytest
1067
1068 @pytest.fixture(scope='function')
1069 def fixture1(request, monkeypatch):
1070 monkeypatch.setattr(request.instance, 'fixture1', True )
1071
1072
1073 @pytest.fixture(scope='function')
1074 def fixture2(request, monkeypatch):
1075 monkeypatch.setattr(request.instance, 'fixture2', True )
1076
1077 def node_and_marks(item):
1078 print(item.nodeid)
1079 for mark in item.iter_markers():
1080 print(" ", mark)
1081
1082 @pytest.fixture(autouse=True)
1083 def my_marks(request):
1084 node_and_marks(request.node)
1085
1086 def pytest_collection_modifyitems(items):
1087 for item in items:
1088 node_and_marks(item)
1089
1090 """
1091 )
1092
1093 pytester.makepyfile(
1094 f"""
1095 import pytest
1096 import {module}
1097
1098 class Tests({base}):
1099 fixture1 = False
1100 fixture2 = False
1101
1102 @pytest.mark.usefixtures("fixture1")
1103 def test_one(self):
1104 assert self.fixture1
1105 assert not self.fixture2
1106
1107 @pytest.mark.usefixtures("fixture1", "fixture2")
1108 def test_two(self):
1109 assert self.fixture1
1110 assert self.fixture2
1111
1112
1113 """
1114 )
1115
1116 result = pytester.runpytest("-s")
1117 result.assert_outcomes(passed=2)
1118
1119
1120 def test_skip_setup_class(pytester: Pytester) -> None:
1121 """Skipping tests in a class by raising unittest.SkipTest in `setUpClass` (#13985)."""
1122 pytester.makepyfile(
1123 """
1124 import unittest
1125
1126 class Test(unittest.TestCase):
1127
1128 @classmethod
1129 def setUpClass(cls):
1130 raise unittest.SkipTest('Skipping setupclass')
1131
1132 def test_foo(self):
1133 assert False
1134
1135 def test_bar(self):
1136 assert False
1137 """
1138 )
1139 result = pytester.runpytest()
1140 result.assert_outcomes(skipped=2)
1141
1142
1143 def test_unittest_skip_function(pytester: Pytester) -> None:
1144 """
1145 Ensure raising an explicit unittest.SkipTest skips standard pytest functions.
1146
1147 Support for this is debatable -- technically we only support unittest.SkipTest in TestCase subclasses,
1148 but stating this support here in this test because users currently expect this to work,
1149 so if we ever break it we at least know we are breaking this use case (#13985).
1150 """
1151 pytester.makepyfile(
1152 """
1153 import unittest
1154
1155 def test_foo():
1156 raise unittest.SkipTest('Skipping test_foo')
1157 """
1158 )
1159 result = pytester.runpytest()
1160 result.assert_outcomes(skipped=1)
1161
1162
1163 def test_testcase_handles_init_exceptions(pytester: Pytester) -> None:
1164 """
1165 Regression test to make sure exceptions in the __init__ method are bubbled up correctly.
1166 See https://github.com/pytest-dev/pytest/issues/3788
1167 """
1168 pytester.makepyfile(
1169 """
1170 from unittest import TestCase
1171 import pytest
1172 class MyTestCase(TestCase):
1173 def __init__(self, *args, **kwargs):
1174 raise Exception("should raise this exception")
1175 def test_hello(self):
1176 pass
1177 """
1178 )
1179 result = pytester.runpytest()
1180 assert "should raise this exception" in result.stdout.str()
1181 result.stdout.no_fnmatch_line("*ERROR at teardown of MyTestCase.test_hello*")
1182
1183
1184 def test_error_message_with_parametrized_fixtures(pytester: Pytester) -> None:
1185 pytester.copy_example("unittest/test_parametrized_fixture_error_message.py")
1186 result = pytester.runpytest()
1187 result.stdout.fnmatch_lines(
1188 [
1189 "*test_two does not support fixtures*",
1190 "*TestSomethingElse::test_two",
1191 "*Function type: TestCaseFunction",
1192 ]
1193 )
1194
1195
1196 @pytest.mark.parametrize(
1197 "test_name, expected_outcome",
1198 [
1199 ("test_setup_skip.py", "1 skipped"),
1200 ("test_setup_skip_class.py", "1 skipped"),
1201 ("test_setup_skip_module.py", "1 error"),
1202 ],
1203 )
1204 def test_setup_inheritance_skipping(
1205 pytester: Pytester, test_name, expected_outcome
1206 ) -> None:
1207 """Issue #4700"""
1208 pytester.copy_example(f"unittest/{test_name}")
1209 result = pytester.runpytest()
1210 result.stdout.fnmatch_lines([f"* {expected_outcome} in *"])
1211
1212
1213 def test_BdbQuit(pytester: Pytester) -> None:
1214 pytester.makepyfile(
1215 test_foo="""
1216 import unittest
1217
1218 class MyTestCase(unittest.TestCase):
1219 def test_bdbquit(self):
1220 import bdb
1221 raise bdb.BdbQuit()
1222
1223 def test_should_not_run(self):
1224 pass
1225 """
1226 )
1227 reprec = pytester.inline_run()
1228 reprec.assertoutcome(failed=1, passed=1)
1229
1230
1231 def test_exit_outcome(pytester: Pytester) -> None:
1232 pytester.makepyfile(
1233 test_foo="""
1234 import pytest
1235 import unittest
1236
1237 class MyTestCase(unittest.TestCase):
1238 def test_exit_outcome(self):
1239 pytest.exit("pytest_exit called")
1240
1241 def test_should_not_run(self):
1242 pass
1243 """
1244 )
1245 result = pytester.runpytest()
1246 result.stdout.fnmatch_lines(["*Exit: pytest_exit called*", "*= no tests ran in *"])
1247
1248
1249 def test_trace(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
1250 calls = []
1251
1252 def check_call(*args, **kwargs):
1253 calls.append((args, kwargs))
1254 assert args == ("runcall",)
1255
1256 class _pdb:
1257 def runcall(*args, **kwargs):
1258 calls.append((args, kwargs))
1259
1260 return _pdb
1261
1262 monkeypatch.setattr("_pytest.debugging.pytestPDB._init_pdb", check_call)
1263
1264 p1 = pytester.makepyfile(
1265 """
1266 import unittest
1267
1268 class MyTestCase(unittest.TestCase):
1269 def test(self):
1270 self.assertEqual('foo', 'foo')
1271 """
1272 )
1273 result = pytester.runpytest("--trace", str(p1))
1274 assert len(calls) == 2
1275 assert result.ret == 0
1276
1277
1278 def test_pdb_teardown_called(pytester: Pytester, monkeypatch: MonkeyPatch) -> None:
1279 """Ensure tearDown() is always called when --pdb is given in the command-line.
1280
1281 We delay the normal tearDown() calls when --pdb is given, so this ensures we are calling
1282 tearDown() eventually to avoid memory leaks when using --pdb.
1283 """
1284 teardowns: list[str] = []
1285 monkeypatch.setattr(
1286 pytest, "test_pdb_teardown_called_teardowns", teardowns, raising=False
1287 )
1288
1289 pytester.makepyfile(
1290 """
1291 import unittest
1292 import pytest
1293
1294 class MyTestCase(unittest.TestCase):
1295
1296 def tearDown(self):
1297 pytest.test_pdb_teardown_called_teardowns.append(self.id())
1298
1299 def test_1(self):
1300 pass
1301 def test_2(self):
1302 pass
1303 """
1304 )
1305 result = pytester.runpytest_inprocess("--pdb")
1306 result.stdout.fnmatch_lines("* 2 passed in *")
1307 assert teardowns == [
1308 "test_pdb_teardown_called.MyTestCase.test_1",
1309 "test_pdb_teardown_called.MyTestCase.test_2",
1310 ]
1311
1312
1313 @pytest.mark.parametrize("mark", ["@unittest.skip", "@pytest.mark.skip"])
1314 def test_pdb_teardown_skipped_for_functions(
1315 pytester: Pytester, monkeypatch: MonkeyPatch, mark: str
1316 ) -> None:
1317 """
1318 With --pdb, setUp and tearDown should not be called for tests skipped
1319 via a decorator (#7215).
1320 """
1321 tracked: list[str] = []
1322 monkeypatch.setattr(pytest, "track_pdb_teardown_skipped", tracked, raising=False)
1323
1324 pytester.makepyfile(
1325 f"""
1326 import unittest
1327 import pytest
1328
1329 class MyTestCase(unittest.TestCase):
1330
1331 def setUp(self):
1332 pytest.track_pdb_teardown_skipped.append("setUp:" + self.id())
1333
1334 def tearDown(self):
1335 pytest.track_pdb_teardown_skipped.append("tearDown:" + self.id())
1336
1337 {mark}("skipped for reasons")
1338 def test_1(self):
1339 pass
1340
1341 """
1342 )
1343 result = pytester.runpytest_inprocess("--pdb")
1344 result.stdout.fnmatch_lines("* 1 skipped in *")
1345 assert tracked == []
1346
1347
1348 @pytest.mark.parametrize("mark", ["@unittest.skip", "@pytest.mark.skip"])
1349 def test_pdb_teardown_skipped_for_classes(
1350 pytester: Pytester, monkeypatch: MonkeyPatch, mark: str
1351 ) -> None:
1352 """
1353 With --pdb, setUp and tearDown should not be called for tests skipped
1354 via a decorator on the class (#10060).
1355 """
1356 tracked: list[str] = []
1357 monkeypatch.setattr(pytest, "track_pdb_teardown_skipped", tracked, raising=False)
1358
1359 pytester.makepyfile(
1360 f"""
1361 import unittest
1362 import pytest
1363
1364 {mark}("skipped for reasons")
1365 class MyTestCase(unittest.TestCase):
1366
1367 def setUp(self):
1368 pytest.track_pdb_teardown_skipped.append("setUp:" + self.id())
1369
1370 def tearDown(self):
1371 pytest.track_pdb_teardown_skipped.append("tearDown:" + self.id())
1372
1373 def test_1(self):
1374 pass
1375
1376 """
1377 )
1378 result = pytester.runpytest_inprocess("--pdb")
1379 result.stdout.fnmatch_lines("* 1 skipped in *")
1380 assert tracked == []
1381
1382
1383 def test_async_support(pytester: Pytester) -> None:
1384 pytest.importorskip("unittest.async_case")
1385
1386 pytester.copy_example("unittest/test_unittest_asyncio.py")
1387 reprec = pytester.inline_run()
1388 reprec.assertoutcome(failed=1, passed=2)
1389
1390
1391 @pytest.mark.skipif(
1392 sys.version_info >= (3, 11), reason="asynctest is not compatible with Python 3.11+"
1393 )
1394 def test_asynctest_support(pytester: Pytester) -> None:
1395 """Check asynctest support (#7110)"""
1396 pytest.importorskip("asynctest")
1397 pytester.copy_example("unittest/test_unittest_asynctest.py")
1398 reprec = pytester.inline_run()
1399 reprec.assertoutcome(failed=1, passed=2)
1400
1401
1402 def test_plain_unittest_does_not_support_async(pytester: Pytester) -> None:
1403 """Async functions in plain unittest.TestCase subclasses are not supported without plugins.
1404
1405 This test exists here to avoid introducing this support by accident, leading users
1406 to expect that it works, rather than doing so intentionally as a feature.
1407
1408 See https://github.com/pytest-dev/pytest-asyncio/issues/180 for more context.
1409 """
1410 pytester.copy_example("unittest/test_unittest_plain_async.py")
1411 result = pytester.runpytest_subprocess()
1412 if hasattr(sys, "pypy_version_info"):
1413 # in PyPy we can't reliable get the warning about the coroutine not being awaited,
1414 # because it depends on the coroutine being garbage collected; given that
1415 # we are running in a subprocess, that's difficult to enforce
1416 expected_lines = ["*1 passed*"]
1417 else:
1418 expected_lines = [
1419 "*RuntimeWarning: coroutine * was never awaited",
1420 "*1 passed*",
1421 ]
1422 result.stdout.fnmatch_lines(expected_lines)
1423
1424
1425 def test_do_class_cleanups_on_success(pytester: Pytester) -> None:
1426 testpath = pytester.makepyfile(
1427 """
1428 import unittest
1429 class MyTestCase(unittest.TestCase):
1430 values = []
1431 @classmethod
1432 def setUpClass(cls):
1433 def cleanup():
1434 cls.values.append(1)
1435 cls.addClassCleanup(cleanup)
1436 def test_one(self):
1437 pass
1438 def test_two(self):
1439 pass
1440 def test_cleanup_called_exactly_once():
1441 assert MyTestCase.values == [1]
1442 """
1443 )
1444 reprec = pytester.inline_run(testpath)
1445 passed, _skipped, failed = reprec.countoutcomes()
1446 assert failed == 0
1447 assert passed == 3
1448
1449
1450 def test_do_class_cleanups_on_setupclass_failure(pytester: Pytester) -> None:
1451 testpath = pytester.makepyfile(
1452 """
1453 import unittest
1454 class MyTestCase(unittest.TestCase):
1455 values = []
1456 @classmethod
1457 def setUpClass(cls):
1458 def cleanup():
1459 cls.values.append(1)
1460 cls.addClassCleanup(cleanup)
1461 assert False
1462 def test_one(self):
1463 pass
1464 def test_cleanup_called_exactly_once():
1465 assert MyTestCase.values == [1]
1466 """
1467 )
1468 reprec = pytester.inline_run(testpath)
1469 passed, _skipped, failed = reprec.countoutcomes()
1470 assert failed == 1
1471 assert passed == 1
1472
1473
1474 def test_do_class_cleanups_on_teardownclass_failure(pytester: Pytester) -> None:
1475 testpath = pytester.makepyfile(
1476 """
1477 import unittest
1478 class MyTestCase(unittest.TestCase):
1479 values = []
1480 @classmethod
1481 def setUpClass(cls):
1482 def cleanup():
1483 cls.values.append(1)
1484 cls.addClassCleanup(cleanup)
1485 @classmethod
1486 def tearDownClass(cls):
1487 assert False
1488 def test_one(self):
1489 pass
1490 def test_two(self):
1491 pass
1492 def test_cleanup_called_exactly_once():
1493 assert MyTestCase.values == [1]
1494 """
1495 )
1496 reprec = pytester.inline_run(testpath)
1497 passed, _skipped, _failed = reprec.countoutcomes()
1498 assert passed == 3
1499
1500
1501 def test_do_cleanups_on_success(pytester: Pytester) -> None:
1502 testpath = pytester.makepyfile(
1503 """
1504 import unittest
1505 class MyTestCase(unittest.TestCase):
1506 values = []
1507 def setUp(self):
1508 def cleanup():
1509 self.values.append(1)
1510 self.addCleanup(cleanup)
1511 def test_one(self):
1512 pass
1513 def test_two(self):
1514 pass
1515 def test_cleanup_called_the_right_number_of_times():
1516 assert MyTestCase.values == [1, 1]
1517 """
1518 )
1519 reprec = pytester.inline_run(testpath)
1520 passed, _skipped, failed = reprec.countoutcomes()
1521 assert failed == 0
1522 assert passed == 3
1523
1524
1525 def test_do_cleanups_on_setup_failure(pytester: Pytester) -> None:
1526 testpath = pytester.makepyfile(
1527 """
1528 import unittest
1529 class MyTestCase(unittest.TestCase):
1530 values = []
1531 def setUp(self):
1532 def cleanup():
1533 self.values.append(1)
1534 self.addCleanup(cleanup)
1535 assert False
1536 def test_one(self):
1537 pass
1538 def test_two(self):
1539 pass
1540 def test_cleanup_called_the_right_number_of_times():
1541 assert MyTestCase.values == [1, 1]
1542 """
1543 )
1544 reprec = pytester.inline_run(testpath)
1545 passed, _skipped, failed = reprec.countoutcomes()
1546 assert failed == 2
1547 assert passed == 1
1548
1549
1550 def test_do_cleanups_on_teardown_failure(pytester: Pytester) -> None:
1551 testpath = pytester.makepyfile(
1552 """
1553 import unittest
1554 class MyTestCase(unittest.TestCase):
1555 values = []
1556 def setUp(self):
1557 def cleanup():
1558 self.values.append(1)
1559 self.addCleanup(cleanup)
1560 def tearDown(self):
1561 assert False
1562 def test_one(self):
1563 pass
1564 def test_two(self):
1565 pass
1566 def test_cleanup_called_the_right_number_of_times():
1567 assert MyTestCase.values == [1, 1]
1568 """
1569 )
1570 reprec = pytester.inline_run(testpath)
1571 passed, _skipped, failed = reprec.countoutcomes()
1572 assert failed == 2
1573 assert passed == 1
1574
1575
1576 class TestClassCleanupErrors:
1577 """
1578 Make sure to show exceptions raised during class cleanup function (those registered
1579 via addClassCleanup()).
1580
1581 See #11728.
1582 """
1583
1584 def test_class_cleanups_failure_in_setup(self, pytester: Pytester) -> None:
1585 testpath = pytester.makepyfile(
1586 """
1587 import unittest
1588 class MyTestCase(unittest.TestCase):
1589 @classmethod
1590 def setUpClass(cls):
1591 def cleanup(n):
1592 raise Exception(f"fail {n}")
1593 cls.addClassCleanup(cleanup, 2)
1594 cls.addClassCleanup(cleanup, 1)
1595 raise Exception("fail 0")
1596 def test(self):
1597 pass
1598 """
1599 )
1600 result = pytester.runpytest("-s", testpath)
1601 result.assert_outcomes(passed=0, errors=1)
1602 result.stdout.fnmatch_lines(
1603 [
1604 "*Unittest class cleanup errors *2 sub-exceptions*",
1605 "*Exception: fail 1",
1606 "*Exception: fail 2",
1607 ]
1608 )
1609 result.stdout.fnmatch_lines(
1610 [
1611 "* ERROR at setup of MyTestCase.test *",
1612 "E * Exception: fail 0",
1613 ]
1614 )
1615
1616 def test_class_cleanups_failure_in_teardown(self, pytester: Pytester) -> None:
1617 testpath = pytester.makepyfile(
1618 """
1619 import unittest
1620 class MyTestCase(unittest.TestCase):
1621 @classmethod
1622 def setUpClass(cls):
1623 def cleanup(n):
1624 raise Exception(f"fail {n}")
1625 cls.addClassCleanup(cleanup, 2)
1626 cls.addClassCleanup(cleanup, 1)
1627 def test(self):
1628 pass
1629 """
1630 )
1631 result = pytester.runpytest("-s", testpath)
1632 result.assert_outcomes(passed=1, errors=1)
1633 result.stdout.fnmatch_lines(
1634 [
1635 "*Unittest class cleanup errors *2 sub-exceptions*",
1636 "*Exception: fail 1",
1637 "*Exception: fail 2",
1638 ]
1639 )
1640
1641 def test_class_cleanup_1_failure_in_teardown(self, pytester: Pytester) -> None:
1642 testpath = pytester.makepyfile(
1643 """
1644 import unittest
1645 class MyTestCase(unittest.TestCase):
1646 @classmethod
1647 def setUpClass(cls):
1648 def cleanup(n):
1649 raise Exception(f"fail {n}")
1650 cls.addClassCleanup(cleanup, 1)
1651 def test(self):
1652 pass
1653 """
1654 )
1655 result = pytester.runpytest("-s", testpath)
1656 result.assert_outcomes(passed=1, errors=1)
1657 result.stdout.fnmatch_lines(
1658 [
1659 "*ERROR at teardown of MyTestCase.test*",
1660 "*Exception: fail 1",
1661 ]
1662 )
1663
1664
1665 def test_traceback_pruning(pytester: Pytester) -> None:
1666 """Regression test for #9610 - doesn't crash during traceback pruning."""
1667 pytester.makepyfile(
1668 """
1669 import unittest
1670
1671 class MyTestCase(unittest.TestCase):
1672 def __init__(self, test_method):
1673 unittest.TestCase.__init__(self, test_method)
1674
1675 class TestIt(MyTestCase):
1676 @classmethod
1677 def tearDownClass(cls) -> None:
1678 assert False
1679
1680 def test_it(self):
1681 pass
1682 """
1683 )
1684 reprec = pytester.inline_run()
1685 passed, _skipped, failed = reprec.countoutcomes()
1686 assert passed == 1
1687 assert failed == 1
1688 assert reprec.ret == 1
1689
1690
1691 def test_raising_unittest_skiptest_during_collection(
1692 pytester: Pytester,
1693 ) -> None:
1694 pytester.makepyfile(
1695 """
1696 import unittest
1697
1698 class TestIt(unittest.TestCase):
1699 def test_it(self): pass
1700 def test_it2(self): pass
1701
1702 raise unittest.SkipTest()
1703
1704 class TestIt2(unittest.TestCase):
1705 def test_it(self): pass
1706 def test_it2(self): pass
1707 """
1708 )
1709 reprec = pytester.inline_run()
1710 passed, skipped, failed = reprec.countoutcomes()
1711 assert passed == 0
1712 # Unittest reports one fake test for a skipped module.
1713 assert skipped == 1
1714 assert failed == 0
1715 assert reprec.ret == ExitCode.NO_TESTS_COLLECTED
1716
1717
1718 def test_abstract_testcase_is_not_collected(pytester: Pytester) -> None:
1719 """Regression test for #12275."""
1720 pytester.makepyfile(
1721 """
1722 import abc
1723 import unittest
1724
1725 class TestBase(unittest.TestCase, abc.ABC):
1726 @abc.abstractmethod
1727 def abstract1(self): pass
1728
1729 @abc.abstractmethod
1730 def abstract2(self): pass
1731
1732 def test_it(self): pass
1733
1734 class TestPartial(TestBase):
1735 def abstract1(self): pass
1736
1737 class TestConcrete(TestPartial):
1738 def abstract2(self): pass
1739 """
1740 )
1741 result = pytester.runpytest()
1742 assert result.ret == ExitCode.OK
1743 result.assert_outcomes(passed=1)