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