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
|
# mypy: allow-untyped-defs
from __future__ import annotations
import os
import sys
import textwrap
from typing import Any
import _pytest._code
from _pytest.config import ExitCode
from _pytest.main import Session
from _pytest.monkeypatch import MonkeyPatch
from _pytest.nodes import Collector
from _pytest.pytester import Pytester
from _pytest.python import Class
from _pytest.python import Function
import pytest
class TestModule:
def test_failing_import(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol("import alksdjalskdjalkjals")
pytest.raises(Collector.CollectError, modcol.collect)
def test_import_duplicate(self, pytester: Pytester) -> None:
a = pytester.mkdir("a")
b = pytester.mkdir("b")
p1 = a.joinpath("test_whatever.py")
p1.touch()
p2 = b.joinpath("test_whatever.py")
p2.touch()
# ensure we don't have it imported already
sys.modules.pop(p1.stem, None)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*import*mismatch*",
"*imported*test_whatever*",
f"*{p1}*",
"*not the same*",
f"*{p2}*",
"*HINT*",
]
)
def test_import_prepend_append(
self, pytester: Pytester, monkeypatch: MonkeyPatch
) -> None:
root1 = pytester.mkdir("root1")
root2 = pytester.mkdir("root2")
root1.joinpath("x456.py").touch()
root2.joinpath("x456.py").touch()
p = root2.joinpath("test_x456.py")
monkeypatch.syspath_prepend(str(root1))
p.write_text(
textwrap.dedent(
f"""\
import x456
def test():
assert x456.__file__.startswith({str(root2)!r})
"""
),
encoding="utf-8",
)
with monkeypatch.context() as mp:
mp.chdir(root2)
reprec = pytester.inline_run("--import-mode=append")
reprec.assertoutcome(passed=0, failed=1)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_syntax_error_in_module(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol("this is a syntax error")
pytest.raises(modcol.CollectError, modcol.collect)
pytest.raises(modcol.CollectError, modcol.collect)
def test_module_considers_pluginmanager_at_import(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol("pytest_plugins='xasdlkj',")
pytest.raises(ImportError, lambda: modcol.obj)
def test_invalid_test_module_name(self, pytester: Pytester) -> None:
a = pytester.mkdir("a")
a.joinpath("test_one.part1.py").touch()
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"ImportError while importing test module*test_one.part1*",
"Hint: make sure your test modules/packages have valid Python names.",
]
)
@pytest.mark.parametrize("verbose", [0, 1, 2])
def test_show_traceback_import_error(
self, pytester: Pytester, verbose: int
) -> None:
"""Import errors when collecting modules should display the traceback (#1976).
With low verbosity we omit pytest and internal modules, otherwise show all traceback entries.
"""
pytester.makepyfile(
foo_traceback_import_error="""
from bar_traceback_import_error import NOT_AVAILABLE
""",
bar_traceback_import_error="",
)
pytester.makepyfile(
"""
import foo_traceback_import_error
"""
)
args = ("-v",) * verbose
result = pytester.runpytest(*args)
result.stdout.fnmatch_lines(
[
"ImportError while importing test module*",
"Traceback:",
"*from bar_traceback_import_error import NOT_AVAILABLE",
"*cannot import name *NOT_AVAILABLE*",
]
)
assert result.ret == 2
stdout = result.stdout.str()
if verbose == 2:
assert "_pytest" in stdout
else:
assert "_pytest" not in stdout
def test_show_traceback_import_error_unicode(self, pytester: Pytester) -> None:
"""Check test modules collected which raise ImportError with unicode messages
are handled properly (#2336).
"""
pytester.makepyfile("raise ImportError('Something bad happened ☺')")
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"ImportError while importing test module*",
"Traceback:",
"*raise ImportError*Something bad happened*",
]
)
assert result.ret == 2
class TestClass:
def test_class_with_init_warning(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
class TestClass1(object):
def __init__(self):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*cannot collect test class 'TestClass1' because it has "
"a __init__ constructor (from: test_class_with_init_warning.py)"
]
)
def test_class_with_new_warning(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
class TestClass1(object):
def __new__(self):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*cannot collect test class 'TestClass1' because it has "
"a __new__ constructor (from: test_class_with_new_warning.py)"
]
)
def test_class_subclassobject(self, pytester: Pytester) -> None:
pytester.getmodulecol(
"""
class test(object):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*collected 0*"])
def test_static_method(self, pytester: Pytester) -> None:
"""Support for collecting staticmethod tests (#2528, #2699)"""
pytester.getmodulecol(
"""
import pytest
class Test(object):
@staticmethod
def test_something():
pass
@pytest.fixture
def fix(self):
return 1
@staticmethod
def test_fix(fix):
assert fix == 1
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*collected 2 items*", "*2 passed in*"])
def test_setup_teardown_class_as_classmethod(self, pytester: Pytester) -> None:
pytester.makepyfile(
test_mod1="""
class TestClassMethod(object):
@classmethod
def setup_class(cls):
pass
def test_1(self):
pass
@classmethod
def teardown_class(cls):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"])
def test_issue1035_obj_has_getattr(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol(
"""
class Chameleon(object):
def __getattr__(self, name):
return True
chameleon = Chameleon()
"""
)
colitems = modcol.collect()
assert len(colitems) == 0
def test_issue1579_namedtuple(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import collections
TestCase = collections.namedtuple('TestCase', ['a'])
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
"*cannot collect test class 'TestCase' "
"because it has a __new__ constructor*"
)
def test_issue2234_property(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
class TestCase(object):
@property
def prop(self):
raise NotImplementedError()
"""
)
result = pytester.runpytest()
assert result.ret == ExitCode.NO_TESTS_COLLECTED
def test_does_not_discover_properties(self, pytester: Pytester) -> None:
"""Regression test for #12446."""
pytester.makepyfile(
"""\
class TestCase:
@property
def oops(self):
raise SystemExit('do not call me!')
"""
)
result = pytester.runpytest()
assert result.ret == ExitCode.NO_TESTS_COLLECTED
def test_does_not_discover_instance_descriptors(self, pytester: Pytester) -> None:
"""Regression test for #12446."""
pytester.makepyfile(
"""\
# not `@property`, but it acts like one
# this should cover the case of things like `@cached_property` / etc.
class MyProperty:
def __init__(self, func):
self._func = func
def __get__(self, inst, owner):
if inst is None:
return self
else:
return self._func.__get__(inst, owner)()
class TestCase:
@MyProperty
def oops(self):
raise SystemExit('do not call me!')
"""
)
result = pytester.runpytest()
assert result.ret == ExitCode.NO_TESTS_COLLECTED
def test_abstract_class_is_not_collected(self, pytester: Pytester) -> None:
"""Regression test for #12275 (non-unittest version)."""
pytester.makepyfile(
"""
import abc
class TestBase(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)
class TestFunction:
def test_getmodulecollector(self, pytester: Pytester) -> None:
item = pytester.getitem("def test_func(): pass")
modcol = item.getparent(pytest.Module)
assert isinstance(modcol, pytest.Module)
assert hasattr(modcol.obj, "test_func")
@pytest.mark.filterwarnings("default")
def test_function_as_object_instance_ignored(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
class A(object):
def __call__(self, tmp_path):
0/0
test_a = A()
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"collected 0 items",
"*test_function_as_object_instance_ignored.py:2: "
"*cannot collect 'test_a' because it is not a function.",
]
)
@staticmethod
def make_function(pytester: Pytester, **kwargs: Any) -> Any:
from _pytest.fixtures import FixtureManager
config = pytester.parseconfigure()
session = Session.from_config(config)
session._fixturemanager = FixtureManager(session)
return pytest.Function.from_parent(parent=session, **kwargs)
def test_function_equality(self, pytester: Pytester) -> None:
def func1():
pass
def func2():
pass
f1 = self.make_function(pytester, name="name", callobj=func1)
assert f1 == f1
f2 = self.make_function(
pytester, name="name", callobj=func2, originalname="foobar"
)
assert f1 != f2
def test_repr_produces_actual_test_id(self, pytester: Pytester) -> None:
f = self.make_function(
pytester, name=r"test[\xe5]", callobj=self.test_repr_produces_actual_test_id
)
assert repr(f) == r"<Function test[\xe5]>"
def test_issue197_parametrize_emptyset(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize('arg', [])
def test_function(arg):
pass
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(skipped=1)
def test_single_tuple_unwraps_values(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize(('arg',), [(1,)])
def test_function(arg):
assert arg == 1
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_issue213_parametrize_value_no_equal(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
class A(object):
def __eq__(self, other):
raise ValueError("not possible")
@pytest.mark.parametrize('arg', [A()])
def test_function(arg):
assert arg.__class__.__name__ == "A"
"""
)
reprec = pytester.inline_run("--fulltrace")
reprec.assertoutcome(passed=1)
def test_parametrize_with_non_hashable_values(self, pytester: Pytester) -> None:
"""Test parametrization with non-hashable values."""
pytester.makepyfile(
"""
archival_mapping = {
'1.0': {'tag': '1.0'},
'1.2.2a1': {'tag': 'release-1.2.2a1'},
}
import pytest
@pytest.mark.parametrize('key value'.split(),
archival_mapping.items())
def test_archival_to_version(key, value):
assert key in archival_mapping
assert value == archival_mapping[key]
"""
)
rec = pytester.inline_run()
rec.assertoutcome(passed=2)
def test_parametrize_with_non_hashable_values_indirect(
self, pytester: Pytester
) -> None:
"""Test parametrization with non-hashable values with indirect parametrization."""
pytester.makepyfile(
"""
archival_mapping = {
'1.0': {'tag': '1.0'},
'1.2.2a1': {'tag': 'release-1.2.2a1'},
}
import pytest
@pytest.fixture
def key(request):
return request.param
@pytest.fixture
def value(request):
return request.param
@pytest.mark.parametrize('key value'.split(),
archival_mapping.items(), indirect=True)
def test_archival_to_version(key, value):
assert key in archival_mapping
assert value == archival_mapping[key]
"""
)
rec = pytester.inline_run()
rec.assertoutcome(passed=2)
def test_parametrize_overrides_fixture(self, pytester: Pytester) -> None:
"""Test parametrization when parameter overrides existing fixture with same name."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def value():
return 'value'
@pytest.mark.parametrize('value',
['overridden'])
def test_overridden_via_param(value):
assert value == 'overridden'
@pytest.mark.parametrize('somevalue', ['overridden'])
def test_not_overridden(value, somevalue):
assert value == 'value'
assert somevalue == 'overridden'
@pytest.mark.parametrize('other,value', [('foo', 'overridden')])
def test_overridden_via_multiparam(other, value):
assert other == 'foo'
assert value == 'overridden'
"""
)
rec = pytester.inline_run()
rec.assertoutcome(passed=3)
def test_parametrize_overrides_parametrized_fixture(
self, pytester: Pytester
) -> None:
"""Test parametrization when parameter overrides existing parametrized fixture with same name."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(params=[1, 2])
def value(request):
return request.param
@pytest.mark.parametrize('value',
['overridden'])
def test_overridden_via_param(value):
assert value == 'overridden'
"""
)
rec = pytester.inline_run()
rec.assertoutcome(passed=1)
def test_parametrize_overrides_indirect_dependency_fixture(
self, pytester: Pytester
) -> None:
"""Test parametrization when parameter overrides a fixture that a test indirectly depends on"""
pytester.makepyfile(
"""
import pytest
fix3_instantiated = False
@pytest.fixture
def fix1(fix2):
return fix2 + '1'
@pytest.fixture
def fix2(fix3):
return fix3 + '2'
@pytest.fixture
def fix3():
global fix3_instantiated
fix3_instantiated = True
return '3'
@pytest.mark.parametrize('fix2', ['2'])
def test_it(fix1):
assert fix1 == '21'
assert not fix3_instantiated
"""
)
rec = pytester.inline_run()
rec.assertoutcome(passed=1)
def test_parametrize_with_mark(self, pytester: Pytester) -> None:
items = pytester.getitems(
"""
import pytest
@pytest.mark.foo
@pytest.mark.parametrize('arg', [
1,
pytest.param(2, marks=[pytest.mark.baz, pytest.mark.bar])
])
def test_function(arg):
pass
"""
)
keywords = [item.keywords for item in items]
assert (
"foo" in keywords[0]
and "bar" not in keywords[0]
and "baz" not in keywords[0]
)
assert "foo" in keywords[1] and "bar" in keywords[1] and "baz" in keywords[1]
def test_parametrize_with_empty_string_arguments(self, pytester: Pytester) -> None:
items = pytester.getitems(
"""\
import pytest
@pytest.mark.parametrize('v', ('', ' '))
@pytest.mark.parametrize('w', ('', ' '))
def test(v, w): ...
"""
)
names = {item.name for item in items}
assert names == {"test[-]", "test[ -]", "test[- ]", "test[ - ]"}
def test_function_equality_with_callspec(self, pytester: Pytester) -> None:
items = pytester.getitems(
"""
import pytest
@pytest.mark.parametrize('arg', [1,2])
def test_function(arg):
pass
"""
)
assert items[0] != items[1]
assert not (items[0] == items[1])
def test_pyfunc_call(self, pytester: Pytester) -> None:
item = pytester.getitem("def test_func(): raise ValueError")
config = item.config
class MyPlugin1:
def pytest_pyfunc_call(self):
raise ValueError
class MyPlugin2:
def pytest_pyfunc_call(self):
return True
config.pluginmanager.register(MyPlugin1())
config.pluginmanager.register(MyPlugin2())
config.hook.pytest_runtest_setup(item=item)
config.hook.pytest_pyfunc_call(pyfuncitem=item)
def test_multiple_parametrize(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol(
"""
import pytest
@pytest.mark.parametrize('x', [0, 1])
@pytest.mark.parametrize('y', [2, 3])
def test1(x, y):
pass
"""
)
colitems = modcol.collect()
assert colitems[0].name == "test1[2-0]"
assert colitems[1].name == "test1[2-1]"
assert colitems[2].name == "test1[3-0]"
assert colitems[3].name == "test1[3-1]"
def test_issue751_multiple_parametrize_with_ids(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol(
"""
import pytest
@pytest.mark.parametrize('x', [0], ids=['c'])
@pytest.mark.parametrize('y', [0, 1], ids=['a', 'b'])
class Test(object):
def test1(self, x, y):
pass
def test2(self, x, y):
pass
"""
)
colitems = modcol.collect()[0].collect()
assert colitems[0].name == "test1[a-c]"
assert colitems[1].name == "test1[b-c]"
assert colitems[2].name == "test2[a-c]"
assert colitems[3].name == "test2[b-c]"
def test_parametrize_skipif(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
m = pytest.mark.skipif('True')
@pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
def test_skip_if(x):
assert x < 2
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 2 passed, 1 skipped in *"])
def test_parametrize_skip(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
m = pytest.mark.skip('')
@pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
def test_skip(x):
assert x < 2
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 2 passed, 1 skipped in *"])
def test_parametrize_skipif_no_skip(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
m = pytest.mark.skipif('False')
@pytest.mark.parametrize('x', [0, 1, m(2)])
def test_skipif_no_skip(x):
assert x < 2
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 1 failed, 2 passed in *"])
def test_parametrize_xfail(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
m = pytest.mark.xfail('True')
@pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
def test_xfail(x):
assert x < 2
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 2 passed, 1 xfailed in *"])
def test_parametrize_passed(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
m = pytest.mark.xfail('True')
@pytest.mark.parametrize('x', [0, 1, pytest.param(2, marks=m)])
def test_xfail(x):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 2 passed, 1 xpassed in *"])
def test_parametrize_xfail_passed(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
m = pytest.mark.xfail('False')
@pytest.mark.parametrize('x', [0, 1, m(2)])
def test_passed(x):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 3 passed in *"])
def test_function_originalname(self, pytester: Pytester) -> None:
items = pytester.getitems(
"""
import pytest
@pytest.mark.parametrize('arg', [1,2])
def test_func(arg):
pass
def test_no_param():
pass
"""
)
originalnames = []
for x in items:
assert isinstance(x, pytest.Function)
originalnames.append(x.originalname)
assert originalnames == [
"test_func",
"test_func",
"test_no_param",
]
def test_function_with_square_brackets(self, pytester: Pytester) -> None:
"""Check that functions with square brackets don't cause trouble."""
p1 = pytester.makepyfile(
"""
locals()["test_foo[name]"] = lambda: None
"""
)
result = pytester.runpytest("-v", str(p1))
result.stdout.fnmatch_lines(
[
"test_function_with_square_brackets.py::test_foo[[]name[]] PASSED *",
"*= 1 passed in *",
]
)
class TestSorting:
def test_check_equality(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol(
"""
def test_pass(): pass
def test_fail(): assert 0
"""
)
fn1 = pytester.collect_by_name(modcol, "test_pass")
assert isinstance(fn1, pytest.Function)
fn2 = pytester.collect_by_name(modcol, "test_pass")
assert isinstance(fn2, pytest.Function)
assert fn1 == fn2
assert fn1 != modcol
assert hash(fn1) == hash(fn2)
fn3 = pytester.collect_by_name(modcol, "test_fail")
assert isinstance(fn3, pytest.Function)
assert not (fn1 == fn3)
assert fn1 != fn3
for fn in fn1, fn2, fn3:
assert fn != 3 # type: ignore[comparison-overlap]
assert fn != modcol
assert fn != [1, 2, 3] # type: ignore[comparison-overlap]
assert [1, 2, 3] != fn # type: ignore[comparison-overlap]
assert modcol != fn
def test_allow_sane_sorting_for_decorators(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol(
"""
def dec(f):
g = lambda: f(2)
g.place_as = f
return g
def test_b(y):
pass
test_b = dec(test_b)
def test_a(y):
pass
test_a = dec(test_a)
"""
)
colitems = modcol.collect()
assert len(colitems) == 2
assert [item.name for item in colitems] == ["test_b", "test_a"]
def test_ordered_by_definition_order(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""\
class Test1:
def test_foo(self): pass
def test_bar(self): pass
class Test2:
def test_foo(self): pass
test_bar = Test1.test_bar
class Test3(Test2):
def test_baz(self): pass
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(
[
"*Class Test1*",
"*Function test_foo*",
"*Function test_bar*",
"*Class Test2*",
# previously the order was flipped due to Test1.test_bar reference
"*Function test_foo*",
"*Function test_bar*",
"*Class Test3*",
"*Function test_foo*",
"*Function test_bar*",
"*Function test_baz*",
]
)
class TestConftestCustomization:
def test_pytest_pycollect_module(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
class MyModule(pytest.Module):
pass
def pytest_pycollect_makemodule(module_path, parent):
if module_path.name == "test_xyz.py":
return MyModule.from_parent(path=module_path, parent=parent)
"""
)
pytester.makepyfile("def test_some(): pass")
pytester.makepyfile(test_xyz="def test_func(): pass")
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*<Module*test_pytest*", "*<MyModule*xyz*"])
def test_customized_pymakemodule_issue205_subdir(self, pytester: Pytester) -> None:
b = pytester.path.joinpath("a", "b")
b.mkdir(parents=True)
b.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.hookimpl(wrapper=True)
def pytest_pycollect_makemodule():
mod = yield
mod.obj.hello = "world"
return mod
"""
),
encoding="utf-8",
)
b.joinpath("test_module.py").write_text(
textwrap.dedent(
"""\
def test_hello():
assert hello == "world"
"""
),
encoding="utf-8",
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_customized_pymakeitem(self, pytester: Pytester) -> None:
b = pytester.path.joinpath("a", "b")
b.mkdir(parents=True)
b.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.hookimpl(wrapper=True)
def pytest_pycollect_makeitem():
result = yield
if result:
for func in result:
func._some123 = "world"
return result
"""
),
encoding="utf-8",
)
b.joinpath("test_module.py").write_text(
textwrap.dedent(
"""\
import pytest
@pytest.fixture()
def obj(request):
return request.node._some123
def test_hello(obj):
assert obj == "world"
"""
),
encoding="utf-8",
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=1)
def test_pytest_pycollect_makeitem(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
class MyFunction(pytest.Function):
pass
def pytest_pycollect_makeitem(collector, name, obj):
if name == "some":
return MyFunction.from_parent(name=name, parent=collector)
"""
)
pytester.makepyfile("def some(): pass")
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*MyFunction*some*"])
def test_issue2369_collect_module_fileext(self, pytester: Pytester) -> None:
"""Ensure we can collect files with weird file extensions as Python
modules (#2369)"""
# Implement a little meta path finder to import files containing
# Python source code whose file extension is ".narf".
pytester.makeconftest(
"""
import sys
import os.path
from importlib.util import spec_from_loader
from importlib.machinery import SourceFileLoader
from _pytest.python import Module
class MetaPathFinder:
def find_spec(self, fullname, path, target=None):
if os.path.exists(fullname + ".narf"):
return spec_from_loader(
fullname,
SourceFileLoader(fullname, fullname + ".narf"),
)
sys.meta_path.append(MetaPathFinder())
def pytest_collect_file(file_path, parent):
if file_path.suffix == ".narf":
return Module.from_parent(path=file_path, parent=parent)
"""
)
pytester.makefile(
".narf",
"""\
def test_something():
assert 1 + 1 == 2""",
)
# Use runpytest_subprocess, since we're futzing with sys.meta_path.
result = pytester.runpytest_subprocess()
result.stdout.fnmatch_lines(["*1 passed*"])
def test_early_ignored_attributes(self, pytester: Pytester) -> None:
"""Builtin attributes should be ignored early on, even if
configuration would otherwise allow them.
This tests a performance optimization, not correctness, really,
although it tests PytestCollectionWarning is not raised, while
it would have been raised otherwise.
"""
pytester.makeini(
"""
[pytest]
python_classes=*
python_functions=*
"""
)
pytester.makepyfile(
"""
class TestEmpty:
pass
test_empty = TestEmpty()
def test_real():
pass
"""
)
items, rec = pytester.inline_genitems()
assert rec.ret == 0
assert len(items) == 1
def test_setup_only_available_in_subdir(pytester: Pytester) -> None:
sub1 = pytester.mkpydir("sub1")
sub2 = pytester.mkpydir("sub2")
sub1.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
def pytest_runtest_setup(item):
assert item.path.stem == "test_in_sub1"
def pytest_runtest_call(item):
assert item.path.stem == "test_in_sub1"
def pytest_runtest_teardown(item):
assert item.path.stem == "test_in_sub1"
"""
),
encoding="utf-8",
)
sub2.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
import pytest
def pytest_runtest_setup(item):
assert item.path.stem == "test_in_sub2"
def pytest_runtest_call(item):
assert item.path.stem == "test_in_sub2"
def pytest_runtest_teardown(item):
assert item.path.stem == "test_in_sub2"
"""
),
encoding="utf-8",
)
sub1.joinpath("test_in_sub1.py").write_text("def test_1(): pass", encoding="utf-8")
sub2.joinpath("test_in_sub2.py").write_text("def test_2(): pass", encoding="utf-8")
result = pytester.runpytest("-v", "-s")
result.assert_outcomes(passed=2)
def test_modulecol_roundtrip(pytester: Pytester) -> None:
modcol = pytester.getmodulecol("pass", withinit=False)
trail = modcol.nodeid
newcol = modcol.session.perform_collect([trail], genitems=0)[0]
assert modcol.name == newcol.name
class TestTracebackCutting:
def test_skip_simple(self):
with pytest.raises(pytest.skip.Exception) as excinfo:
pytest.skip("xxx")
if sys.version_info >= (3, 11):
assert excinfo.traceback[-1].frame.code.raw.co_qualname == "_Skip.__call__"
assert excinfo.traceback[-1].ishidden(excinfo)
assert excinfo.traceback[-2].frame.code.name == "test_skip_simple"
assert not excinfo.traceback[-2].ishidden(excinfo)
def test_traceback_argsetup(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture
def hello(request):
raise ValueError("xyz")
"""
)
p = pytester.makepyfile("def test(hello): pass")
result = pytester.runpytest(p)
assert result.ret != 0
out = result.stdout.str()
assert "xyz" in out
assert "conftest.py:5: ValueError" in out
numentries = out.count("_ _ _") # separator for traceback entries
assert numentries == 0
result = pytester.runpytest("--fulltrace", p)
out = result.stdout.str()
assert "conftest.py:5: ValueError" in out
numentries = out.count("_ _ _ _") # separator for traceback entries
assert numentries > 3
def test_traceback_error_during_import(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
x = 1
x = 2
x = 17
asd
"""
)
result = pytester.runpytest()
assert result.ret != 0
out = result.stdout.str()
assert "x = 1" not in out
assert "x = 2" not in out
result.stdout.fnmatch_lines([" *asd*", "E*NameError*"])
result = pytester.runpytest("--fulltrace")
out = result.stdout.str()
assert "x = 1" in out
assert "x = 2" in out
result.stdout.fnmatch_lines([">*asd*", "E*NameError*"])
def test_traceback_filter_error_during_fixture_collection(
self, pytester: Pytester
) -> None:
"""Integration test for issue #995."""
pytester.makepyfile(
"""
import pytest
def fail_me(func):
ns = {}
exec('def w(): raise ValueError("fail me")', ns)
return ns['w']
@pytest.fixture(scope='class')
@fail_me
def fail_fixture():
pass
def test_failing_fixture(fail_fixture):
pass
"""
)
result = pytester.runpytest()
assert result.ret != 0
out = result.stdout.str()
assert "INTERNALERROR>" not in out
result.stdout.fnmatch_lines(["*ValueError: fail me*", "* 1 error in *"])
def test_filter_traceback_generated_code(self) -> None:
"""Test that filter_traceback() works with the fact that
_pytest._code.code.Code.path attribute might return an str object.
In this case, one of the entries on the traceback was produced by
dynamically generated code.
See: https://bitbucket.org/pytest-dev/py/issues/71
This fixes #995.
"""
from _pytest._code import filter_traceback
tb = None
try:
ns: dict[str, Any] = {}
exec("def foo(): raise ValueError", ns)
ns["foo"]()
except ValueError:
_, _, tb = sys.exc_info()
assert tb is not None
traceback = _pytest._code.Traceback(tb)
assert isinstance(traceback[-1].path, str)
assert not filter_traceback(traceback[-1])
def test_filter_traceback_path_no_longer_valid(self, pytester: Pytester) -> None:
"""Test that filter_traceback() works with the fact that
_pytest._code.code.Code.path attribute might return an str object.
In this case, one of the files in the traceback no longer exists.
This fixes #1133.
"""
from _pytest._code import filter_traceback
pytester.syspathinsert()
pytester.makepyfile(
filter_traceback_entry_as_str="""
def foo():
raise ValueError
"""
)
tb = None
try:
import filter_traceback_entry_as_str
filter_traceback_entry_as_str.foo()
except ValueError:
_, _, tb = sys.exc_info()
assert tb is not None
pytester.path.joinpath("filter_traceback_entry_as_str.py").unlink()
traceback = _pytest._code.Traceback(tb)
assert isinstance(traceback[-1].path, str)
assert filter_traceback(traceback[-1])
class TestReportInfo:
def test_itemreport_reportinfo(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
import pytest
class MyFunction(pytest.Function):
def reportinfo(self):
return "ABCDE", 42, "custom"
def pytest_pycollect_makeitem(collector, name, obj):
if name == "test_func":
return MyFunction.from_parent(name=name, parent=collector)
"""
)
item = pytester.getitem("def test_func(): pass")
item.config.pluginmanager.getplugin("runner")
assert item.location == ("ABCDE", 42, "custom")
def test_func_reportinfo(self, pytester: Pytester) -> None:
item = pytester.getitem("def test_func(): pass")
path, lineno, modpath = item.reportinfo()
assert os.fspath(path) == str(item.path)
assert lineno == 0
assert modpath == "test_func"
def test_class_reportinfo(self, pytester: Pytester) -> None:
modcol = pytester.getmodulecol(
"""
# lineno 0
class TestClass(object):
def test_hello(self): pass
"""
)
classcol = pytester.collect_by_name(modcol, "TestClass")
assert isinstance(classcol, Class)
path, lineno, msg = classcol.reportinfo()
assert os.fspath(path) == str(modcol.path)
assert lineno == 1
assert msg == "TestClass"
@pytest.mark.filterwarnings(
"ignore:usage of Generator.Function is deprecated, please use pytest.Function instead"
)
def test_reportinfo_with_nasty_getattr(self, pytester: Pytester) -> None:
# https://github.com/pytest-dev/pytest/issues/1204
modcol = pytester.getmodulecol(
"""
# lineno 0
class TestClass:
def __getattr__(self, name):
return "this is not an int"
def __class_getattr__(cls, name):
return "this is not an int"
def intest_foo(self):
pass
def test_bar(self):
pass
"""
)
classcol = pytester.collect_by_name(modcol, "TestClass")
assert isinstance(classcol, Class)
_path, _lineno, _msg = classcol.reportinfo()
func = next(iter(classcol.collect()))
assert isinstance(func, Function)
_path, _lineno, _msg = func.reportinfo()
def test_customized_python_discovery(pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
python_files=check_*.py
python_classes=Check
python_functions=check
"""
)
p = pytester.makepyfile(
"""
def check_simple():
pass
class CheckMyApp(object):
def check_meth(self):
pass
"""
)
p2 = p.with_name(p.name.replace("test", "check"))
p.rename(p2)
result = pytester.runpytest("--collect-only", "-s")
result.stdout.fnmatch_lines(
["*check_customized*", "*check_simple*", "*CheckMyApp*", "*check_meth*"]
)
result = pytester.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines(["*2 passed*"])
def test_customized_python_discovery_functions(pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
python_functions=_test
"""
)
pytester.makepyfile(
"""
def _test_underscore():
pass
"""
)
result = pytester.runpytest("--collect-only", "-s")
result.stdout.fnmatch_lines(["*_test_underscore*"])
result = pytester.runpytest()
assert result.ret == 0
result.stdout.fnmatch_lines(["*1 passed*"])
def test_unorderable_types(pytester: Pytester) -> None:
pytester.makepyfile(
"""
class TestJoinEmpty(object):
pass
def make_test():
class Test(object):
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
@pytest.mark.filterwarnings("default::pytest.PytestCollectionWarning")
def test_dont_collect_non_function_callable(pytester: Pytester) -> None:
"""Test for issue https://github.com/pytest-dev/pytest/issues/331
In this case an INTERNALERROR occurred trying to report the failure of
a test like this one because pytest failed to get the source lines.
"""
pytester.makepyfile(
"""
class Oh(object):
def __call__(self):
pass
test_a = Oh()
def test_real():
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*collected 1 item*",
"*test_dont_collect_non_function_callable.py:2: *cannot collect 'test_a' because it is not a function*",
"*1 passed, 1 warning in *",
]
)
def test_class_injection_does_not_break_collection(pytester: Pytester) -> None:
"""Tests whether injection during collection time will terminate testing.
In this case the error should not occur if the TestClass itself
is modified during collection time, and the original method list
is still used for collection.
"""
pytester.makeconftest(
"""
from test_inject import TestClass
def pytest_generate_tests(metafunc):
TestClass.changed_var = {}
"""
)
pytester.makepyfile(
test_inject='''
class TestClass(object):
def test_injection(self):
"""Test being parametrized."""
pass
'''
)
result = pytester.runpytest()
assert (
"RuntimeError: dictionary changed size during iteration"
not in result.stdout.str()
)
result.stdout.fnmatch_lines(["*1 passed*"])
def test_syntax_error_with_non_ascii_chars(pytester: Pytester) -> None:
"""Fix decoding issue while formatting SyntaxErrors during collection (#578)."""
pytester.makepyfile("☃")
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*ERROR collecting*", "*SyntaxError*", "*1 error in*"])
def test_collect_error_with_fulltrace(pytester: Pytester) -> None:
pytester.makepyfile("assert 0")
result = pytester.runpytest("--fulltrace")
result.stdout.fnmatch_lines(
[
"collected 0 items / 1 error",
"",
"*= ERRORS =*",
"*_ ERROR collecting test_collect_error_with_fulltrace.py _*",
"",
"> assert 0",
"E assert 0",
"",
"test_collect_error_with_fulltrace.py:1: AssertionError",
"*! Interrupted: 1 error during collection !*",
]
)
def test_skip_duplicates_by_default(pytester: Pytester) -> None:
"""Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)
Ignore duplicate directories.
"""
a = pytester.mkdir("a")
fh = a.joinpath("test_a.py")
fh.write_text(
textwrap.dedent(
"""\
import pytest
def test_real():
pass
"""
),
encoding="utf-8",
)
result = pytester.runpytest(str(a), str(a))
result.stdout.fnmatch_lines(["*collected 1 item*"])
def test_keep_duplicates(pytester: Pytester) -> None:
"""Test for issue https://github.com/pytest-dev/pytest/issues/1609 (#1609)
Use --keep-duplicates to collect tests from duplicate directories.
"""
a = pytester.mkdir("a")
fh = a.joinpath("test_a.py")
fh.write_text(
textwrap.dedent(
"""\
import pytest
def test_real():
pass
"""
),
encoding="utf-8",
)
result = pytester.runpytest("--keep-duplicates", str(a), str(a))
result.stdout.fnmatch_lines(["*collected 2 item*"])
def test_package_collection_infinite_recursion(pytester: Pytester) -> None:
pytester.copy_example("collect/package_infinite_recursion")
result = pytester.runpytest()
result.stdout.fnmatch_lines(["*1 passed*"])
def test_package_collection_init_given_as_argument(pytester: Pytester) -> None:
"""Regression test for #3749, #8976, #9263, #9313.
Specifying an __init__.py file directly should collect only the __init__.py
Module, not the entire package.
"""
p = pytester.copy_example("collect/package_init_given_as_arg")
items, _hookrecorder = pytester.inline_genitems(p / "pkg" / "__init__.py")
assert len(items) == 1
assert items[0].name == "test_init"
def test_package_with_modules(pytester: Pytester) -> None:
"""
.
└── root
├── __init__.py
├── sub1
│ ├── __init__.py
│ └── sub1_1
│ ├── __init__.py
│ └── test_in_sub1.py
└── sub2
└── test
└── test_in_sub2.py
"""
root = pytester.mkpydir("root")
sub1 = root.joinpath("sub1")
sub1_test = sub1.joinpath("sub1_1")
sub1_test.mkdir(parents=True)
for d in (sub1, sub1_test):
d.joinpath("__init__.py").touch()
sub2 = root.joinpath("sub2")
sub2_test = sub2.joinpath("test")
sub2_test.mkdir(parents=True)
sub1_test.joinpath("test_in_sub1.py").write_text(
"def test_1(): pass", encoding="utf-8"
)
sub2_test.joinpath("test_in_sub2.py").write_text(
"def test_2(): pass", encoding="utf-8"
)
# Execute from .
result = pytester.runpytest("-v", "-s")
result.assert_outcomes(passed=2)
# Execute from . with one argument "root"
result = pytester.runpytest("-v", "-s", "root")
result.assert_outcomes(passed=2)
# Chdir into package's root and execute with no args
os.chdir(root)
result = pytester.runpytest("-v", "-s")
result.assert_outcomes(passed=2)
def test_package_ordering(pytester: Pytester) -> None:
"""
.
└── root
├── Test_root.py
├── __init__.py
├── sub1
│ ├── Test_sub1.py
│ └── __init__.py
└── sub2
└── test
└── test_sub2.py
"""
pytester.makeini(
"""
[pytest]
python_files=*.py
"""
)
root = pytester.mkpydir("root")
sub1 = root.joinpath("sub1")
sub1.mkdir()
sub1.joinpath("__init__.py").touch()
sub2 = root.joinpath("sub2")
sub2_test = sub2.joinpath("test")
sub2_test.mkdir(parents=True)
root.joinpath("Test_root.py").write_text("def test_1(): pass", encoding="utf-8")
sub1.joinpath("Test_sub1.py").write_text("def test_2(): pass", encoding="utf-8")
sub2_test.joinpath("test_sub2.py").write_text(
"def test_3(): pass", encoding="utf-8"
)
# Execute from .
result = pytester.runpytest("-v", "-s")
result.assert_outcomes(passed=3)
def test_collection_hierarchy(pytester: Pytester) -> None:
"""A general test checking that a filesystem hierarchy is collected as
expected in various scenarios.
top/
├── aaa
│ ├── pkg
│ │ ├── __init__.py
│ │ └── test_pkg.py
│ └── test_aaa.py
├── test_a.py
├── test_b
│ ├── __init__.py
│ └── test_b.py
├── test_c.py
└── zzz
├── dir
│ └── test_dir.py
├── __init__.py
└── test_zzz.py
"""
pytester.makepyfile(
**{
"top/aaa/test_aaa.py": "def test_it(): pass",
"top/aaa/pkg/__init__.py": "",
"top/aaa/pkg/test_pkg.py": "def test_it(): pass",
"top/test_a.py": "def test_it(): pass",
"top/test_b/__init__.py": "",
"top/test_b/test_b.py": "def test_it(): pass",
"top/test_c.py": "def test_it(): pass",
"top/zzz/__init__.py": "",
"top/zzz/test_zzz.py": "def test_it(): pass",
"top/zzz/dir/test_dir.py": "def test_it(): pass",
}
)
full = [
"<Dir test_collection_hierarchy*>",
" <Dir top>",
" <Dir aaa>",
" <Package pkg>",
" <Module test_pkg.py>",
" <Function test_it>",
" <Module test_aaa.py>",
" <Function test_it>",
" <Module test_a.py>",
" <Function test_it>",
" <Package test_b>",
" <Module test_b.py>",
" <Function test_it>",
" <Module test_c.py>",
" <Function test_it>",
" <Package zzz>",
" <Dir dir>",
" <Module test_dir.py>",
" <Function test_it>",
" <Module test_zzz.py>",
" <Function test_it>",
]
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(full, consecutive=True)
result = pytester.runpytest("top", "--collect-only")
result.stdout.fnmatch_lines(full, consecutive=True)
result = pytester.runpytest("top", "top", "--collect-only")
result.stdout.fnmatch_lines(full, consecutive=True)
result = pytester.runpytest(
"top/aaa", "top/aaa/pkg", "--collect-only", "--keep-duplicates"
)
result.stdout.fnmatch_lines(
[
"<Dir test_collection_hierarchy*>",
" <Dir top>",
" <Dir aaa>",
" <Package pkg>",
" <Module test_pkg.py>",
" <Function test_it>",
" <Module test_aaa.py>",
" <Function test_it>",
" <Package pkg>",
" <Module test_pkg.py>",
" <Function test_it>",
],
consecutive=True,
)
result = pytester.runpytest(
"top/aaa/pkg", "top/aaa", "--collect-only", "--keep-duplicates"
)
result.stdout.fnmatch_lines(
[
"<Dir test_collection_hierarchy*>",
" <Dir top>",
" <Dir aaa>",
" <Package pkg>",
" <Module test_pkg.py>",
" <Function test_it>",
" <Function test_it>",
" <Module test_aaa.py>",
" <Function test_it>",
],
consecutive=True,
)
|