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 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
|
# mypy: allow-untyped-defs
from __future__ import annotations
from collections.abc import Iterator
from collections.abc import Sequence
import dataclasses
import itertools
import re
import sys
import textwrap
from typing import Any
from typing import cast
import hypothesis
from hypothesis import strategies
from _pytest import fixtures
from _pytest import python
from _pytest.compat import getfuncargnames
from _pytest.compat import NOTSET
from _pytest.outcomes import fail
from _pytest.outcomes import Failed
from _pytest.pytester import Pytester
from _pytest.python import Function
from _pytest.python import IdMaker
from _pytest.scope import Scope
import pytest
class TestMetafunc:
def Metafunc(self, func, config=None) -> python.Metafunc:
# The unit tests of this class check if things work correctly
# on the funcarg level, so we don't need a full blown
# initialization.
class FuncFixtureInfoMock:
name2fixturedefs: dict[str, list[fixtures.FixtureDef[object]]] = {}
def __init__(self, names):
self.names_closure = names
@dataclasses.dataclass
class FixtureManagerMock:
config: Any
@dataclasses.dataclass
class SessionMock:
_fixturemanager: FixtureManagerMock
@dataclasses.dataclass
class DefinitionMock(python.FunctionDefinition):
_nodeid: str
obj: object
names = getfuncargnames(func)
fixtureinfo: Any = FuncFixtureInfoMock(names)
definition: Any = DefinitionMock._create(obj=func, _nodeid="mock::nodeid")
definition._fixtureinfo = fixtureinfo
definition.session = SessionMock(FixtureManagerMock({}))
return python.Metafunc(definition, fixtureinfo, config, _ispytest=True)
def test_no_funcargs(self) -> None:
def function():
pass
metafunc = self.Metafunc(function)
assert not metafunc.fixturenames
repr(metafunc._calls)
def test_function_basic(self) -> None:
def func(arg1, arg2="qwe"):
pass
metafunc = self.Metafunc(func)
assert len(metafunc.fixturenames) == 1
assert "arg1" in metafunc.fixturenames
assert metafunc.function is func
assert metafunc.cls is None
def test_parametrize_error(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2])
with pytest.raises(pytest.Collector.CollectError):
metafunc.parametrize("x", [5, 6])
with pytest.raises(pytest.Collector.CollectError):
metafunc.parametrize("x", [5, 6])
metafunc.parametrize("y", [1, 2])
with pytest.raises(pytest.Collector.CollectError):
metafunc.parametrize("y", [5, 6])
with pytest.raises(pytest.Collector.CollectError):
metafunc.parametrize("y", [5, 6])
with pytest.raises(TypeError, match=r"^ids must be a callable or an iterable$"):
metafunc.parametrize("y", [5, 6], ids=42) # type: ignore[arg-type]
def test_parametrize_error_iterator(self) -> None:
def func(x):
raise NotImplementedError()
class Exc(Exception):
def __repr__(self):
return "Exc(from_gen)"
def gen() -> Iterator[int | None | Exc]:
yield 0
yield None
yield Exc()
metafunc = self.Metafunc(func)
# When the input is an iterator, only len(args) are taken,
# so the bad Exc isn't reached.
metafunc.parametrize("x", [1, 2], ids=gen())
assert [(x.params, x.id) for x in metafunc._calls] == [
({"x": 1}, "0"),
({"x": 2}, "2"),
]
with pytest.raises(
fail.Exception,
match=(
r"In func: ids contains unsupported value Exc\(from_gen\) \(type: <class .*Exc'>\) at index 2. "
r"Supported types are: .*"
),
):
metafunc.parametrize("x", [1, 2, 3], ids=gen())
def test_parametrize_bad_scope(self) -> None:
def func(x):
pass
metafunc = self.Metafunc(func)
with pytest.raises(
fail.Exception,
match=r"parametrize\(\) call in func got an unexpected scope value 'doggy'",
):
metafunc.parametrize("x", [1], scope="doggy") # type: ignore[arg-type]
def test_parametrize_request_name(self, pytester: Pytester) -> None:
"""Show proper error when 'request' is used as a parameter name in parametrize (#6183)"""
def func(request):
raise NotImplementedError()
metafunc = self.Metafunc(func)
with pytest.raises(
fail.Exception,
match=r"'request' is a reserved name and cannot be used in @pytest.mark.parametrize",
):
metafunc.parametrize("request", [1])
def test_find_parametrized_scope(self) -> None:
"""Unit test for _find_parametrized_scope (#3941)."""
from _pytest.python import _find_parametrized_scope
@dataclasses.dataclass
class DummyFixtureDef:
_scope: Scope
fixtures_defs = cast(
dict[str, Sequence[fixtures.FixtureDef[object]]],
dict(
session_fix=[DummyFixtureDef(Scope.Session)],
package_fix=[DummyFixtureDef(Scope.Package)],
module_fix=[DummyFixtureDef(Scope.Module)],
class_fix=[DummyFixtureDef(Scope.Class)],
func_fix=[DummyFixtureDef(Scope.Function)],
mixed_fix=[DummyFixtureDef(Scope.Module), DummyFixtureDef(Scope.Class)],
),
)
# use arguments to determine narrow scope; the cause of the bug is that it would look on all
# fixture defs given to the method
def find_scope(argnames, indirect):
return _find_parametrized_scope(argnames, fixtures_defs, indirect=indirect)
assert find_scope(["func_fix"], indirect=True) == Scope.Function
assert find_scope(["class_fix"], indirect=True) == Scope.Class
assert find_scope(["module_fix"], indirect=True) == Scope.Module
assert find_scope(["package_fix"], indirect=True) == Scope.Package
assert find_scope(["session_fix"], indirect=True) == Scope.Session
assert find_scope(["class_fix", "func_fix"], indirect=True) == Scope.Function
assert find_scope(["func_fix", "session_fix"], indirect=True) == Scope.Function
assert find_scope(["session_fix", "class_fix"], indirect=True) == Scope.Class
assert (
find_scope(["package_fix", "session_fix"], indirect=True) == Scope.Package
)
assert find_scope(["module_fix", "session_fix"], indirect=True) == Scope.Module
# when indirect is False or is not for all scopes, always use function
assert (
find_scope(["session_fix", "module_fix"], indirect=False) == Scope.Function
)
assert (
find_scope(["session_fix", "module_fix"], indirect=["module_fix"])
== Scope.Function
)
assert (
find_scope(
["session_fix", "module_fix"], indirect=["session_fix", "module_fix"]
)
== Scope.Module
)
assert find_scope(["mixed_fix"], indirect=True) == Scope.Class
def test_parametrize_and_id(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=["basic", "advanced"])
metafunc.parametrize("y", ["abc", "def"])
ids = [x.id for x in metafunc._calls]
assert ids == ["basic-abc", "basic-def", "advanced-abc", "advanced-def"]
def test_parametrize_and_id_unicode(self) -> None:
"""Allow unicode strings for "ids" parameter in Python 2 (##1905)"""
def func(x):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=["basic", "advanced"])
ids = [x.id for x in metafunc._calls]
assert ids == ["basic", "advanced"]
def test_parametrize_with_wrong_number_of_ids(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
with pytest.raises(fail.Exception):
metafunc.parametrize("x", [1, 2], ids=["basic"])
with pytest.raises(fail.Exception):
metafunc.parametrize(
("x", "y"), [("abc", "def"), ("ghi", "jkl")], ids=["one"]
)
def test_parametrize_ids_iterator_without_mark(self) -> None:
def func(x, y):
pass
it = itertools.count()
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=it)
metafunc.parametrize("y", [3, 4], ids=it)
ids = [x.id for x in metafunc._calls]
assert ids == ["0-2", "0-3", "1-2", "1-3"]
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1, 2], ids=it)
metafunc.parametrize("y", [3, 4], ids=it)
ids = [x.id for x in metafunc._calls]
assert ids == ["4-6", "4-7", "5-6", "5-7"]
def test_parametrize_empty_list(self) -> None:
"""#510"""
def func(y):
pass
class MockConfig:
def getini(self, name):
return ""
@property
def hook(self):
return self
def pytest_make_parametrize_id(self, **kw):
pass
metafunc = self.Metafunc(func, MockConfig())
metafunc.parametrize("y", [])
assert "skip" == metafunc._calls[0].marks[0].name
def test_parametrize_with_userobjects(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
class A:
pass
metafunc.parametrize("x", [A(), A()])
metafunc.parametrize("y", list("ab"))
assert metafunc._calls[0].id == "x0-a"
assert metafunc._calls[1].id == "x0-b"
assert metafunc._calls[2].id == "x1-a"
assert metafunc._calls[3].id == "x1-b"
@hypothesis.given(strategies.text() | strategies.binary())
@hypothesis.settings(
deadline=400.0
) # very close to std deadline and CI boxes are not reliable in CPU power
def test_idval_hypothesis(self, value) -> None:
escaped = IdMaker([], [], None, None, None, None, None)._idval(value, "a", 6)
assert isinstance(escaped, str)
escaped.encode("ascii")
def test_unicode_idval(self) -> None:
"""Test that Unicode strings outside the ASCII character set get
escaped, using byte escapes if they're in that range or unicode
escapes if they're not.
"""
values = [
("", r""),
("ascii", r"ascii"),
("ação", r"a\xe7\xe3o"),
("josé@blah.com", r"jos\xe9@blah.com"),
(
r"δοκ.ιμή@παράδειγμα.δοκιμή",
r"\u03b4\u03bf\u03ba.\u03b9\u03bc\u03ae@\u03c0\u03b1\u03c1\u03ac\u03b4\u03b5\u03b9\u03b3"
r"\u03bc\u03b1.\u03b4\u03bf\u03ba\u03b9\u03bc\u03ae",
),
]
for val, expected in values:
assert (
IdMaker([], [], None, None, None, None, None)._idval(val, "a", 6)
== expected
)
def test_unicode_idval_with_config(self) -> None:
"""Unit test for expected behavior to obtain ids with
disable_test_id_escaping_and_forfeit_all_rights_to_community_support
option (#5294)."""
class MockConfig:
def __init__(self, config):
self.config = config
@property
def hook(self):
return self
def pytest_make_parametrize_id(self, **kw):
pass
def getini(self, name):
return self.config[name]
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values: list[tuple[str, Any, str]] = [
("ação", MockConfig({option: True}), "ação"),
("ação", MockConfig({option: False}), "a\\xe7\\xe3o"),
]
for val, config, expected in values:
actual = IdMaker([], [], None, None, config, None, None)._idval(val, "a", 6)
assert actual == expected
def test_bytes_idval(self) -> None:
"""Unit test for the expected behavior to obtain ids for parametrized
bytes values: bytes objects are always escaped using "binary escape"."""
values = [
(b"", r""),
(b"\xc3\xb4\xff\xe4", r"\xc3\xb4\xff\xe4"),
(b"ascii", r"ascii"),
("αρά".encode(), r"\xce\xb1\xcf\x81\xce\xac"),
]
for val, expected in values:
assert (
IdMaker([], [], None, None, None, None, None)._idval(val, "a", 6)
== expected
)
def test_class_or_function_idval(self) -> None:
"""Unit test for the expected behavior to obtain ids for parametrized
values that are classes or functions: their __name__."""
class TestClass:
pass
def test_function():
pass
values = [(TestClass, "TestClass"), (test_function, "test_function")]
for val, expected in values:
assert (
IdMaker([], [], None, None, None, None, None)._idval(val, "a", 6)
== expected
)
def test_notset_idval(self) -> None:
"""Test that a NOTSET value (used by an empty parameterset) generates
a proper ID.
Regression test for #7686.
"""
assert (
IdMaker([], [], None, None, None, None, None)._idval(NOTSET, "a", 0) == "a0"
)
def test_idmaker_autoname(self) -> None:
"""#250"""
result = IdMaker(
("a", "b"),
[pytest.param("string", 1.0), pytest.param("st-ring", 2.0)],
None,
None,
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["string-1.0", "st-ring-2.0"]
result = IdMaker(
("a", "b"),
[pytest.param(object(), 1.0), pytest.param(object(), object())],
None,
None,
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["a0-1.0", "a1-b1"]
# unicode mixing, issue250
result = IdMaker(
("a", "b"), [pytest.param({}, b"\xc3\xb4")], None, None, None, None, None
).make_unique_parameterset_ids()
assert result == ["a0-\\xc3\\xb4"]
def test_idmaker_with_bytes_regex(self) -> None:
result = IdMaker(
("a"), [pytest.param(re.compile(b"foo"))], None, None, None, None, None
).make_unique_parameterset_ids()
assert result == ["foo"]
def test_idmaker_native_strings(self) -> None:
result = IdMaker(
("a", "b"),
[
pytest.param(1.0, -1.1),
pytest.param(2, -202),
pytest.param("three", "three hundred"),
pytest.param(True, False),
pytest.param(None, None),
pytest.param(re.compile("foo"), re.compile("bar")),
pytest.param(str, int),
pytest.param(list("six"), [66, 66]),
pytest.param({7}, set("seven")),
pytest.param(tuple("eight"), (8, -8, 8)),
pytest.param(b"\xc3\xb4", b"name"),
pytest.param(b"\xc3\xb4", "other"),
pytest.param(1.0j, -2.0j),
],
None,
None,
None,
None,
None,
).make_unique_parameterset_ids()
assert result == [
"1.0--1.1",
"2--202",
"three-three hundred",
"True-False",
"None-None",
"foo-bar",
"str-int",
"a7-b7",
"a8-b8",
"a9-b9",
"\\xc3\\xb4-name",
"\\xc3\\xb4-other",
"1j-(-0-2j)",
]
def test_idmaker_non_printable_characters(self) -> None:
result = IdMaker(
("s", "n"),
[
pytest.param("\x00", 1),
pytest.param("\x05", 2),
pytest.param(b"\x00", 3),
pytest.param(b"\x05", 4),
pytest.param("\t", 5),
pytest.param(b"\t", 6),
],
None,
None,
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["\\x00-1", "\\x05-2", "\\x00-3", "\\x05-4", "\\t-5", "\\t-6"]
def test_idmaker_manual_ids_must_be_printable(self) -> None:
result = IdMaker(
("s",),
[
pytest.param("x00", id="hello \x00"),
pytest.param("x05", id="hello \x05"),
],
None,
None,
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["hello \\x00", "hello \\x05"]
def test_idmaker_enum(self) -> None:
enum = pytest.importorskip("enum")
e = enum.Enum("Foo", "one, two")
result = IdMaker(
("a", "b"), [pytest.param(e.one, e.two)], None, None, None, None, None
).make_unique_parameterset_ids()
assert result == ["Foo.one-Foo.two"]
def test_idmaker_idfn(self) -> None:
"""#351"""
def ids(val: object) -> str | None:
if isinstance(val, Exception):
return repr(val)
return None
result = IdMaker(
("a", "b"),
[
pytest.param(10.0, IndexError()),
pytest.param(20, KeyError()),
pytest.param("three", [1, 2, 3]),
],
ids,
None,
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["10.0-IndexError()", "20-KeyError()", "three-b2"]
def test_idmaker_idfn_unique_names(self) -> None:
"""#351"""
def ids(val: object) -> str:
return "a"
result = IdMaker(
("a", "b"),
[
pytest.param(10.0, IndexError()),
pytest.param(20, KeyError()),
pytest.param("three", [1, 2, 3]),
],
ids,
None,
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["a-a0", "a-a1", "a-a2"]
def test_idmaker_with_idfn_and_config(self) -> None:
"""Unit test for expected behavior to create ids with idfn and
disable_test_id_escaping_and_forfeit_all_rights_to_community_support
option (#5294).
"""
class MockConfig:
def __init__(self, config):
self.config = config
@property
def hook(self):
return self
def pytest_make_parametrize_id(self, **kw):
pass
def getini(self, name):
return self.config[name]
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values: list[tuple[Any, str]] = [
(MockConfig({option: True}), "ação"),
(MockConfig({option: False}), "a\\xe7\\xe3o"),
]
for config, expected in values:
result = IdMaker(
("a",),
[pytest.param("string")],
lambda _: "ação",
None,
config,
None,
None,
).make_unique_parameterset_ids()
assert result == [expected]
def test_idmaker_with_ids_and_config(self) -> None:
"""Unit test for expected behavior to create ids with ids and
disable_test_id_escaping_and_forfeit_all_rights_to_community_support
option (#5294).
"""
class MockConfig:
def __init__(self, config):
self.config = config
@property
def hook(self):
return self
def pytest_make_parametrize_id(self, **kw):
pass
def getini(self, name):
return self.config[name]
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values: list[tuple[Any, str]] = [
(MockConfig({option: True}), "ação"),
(MockConfig({option: False}), "a\\xe7\\xe3o"),
]
for config, expected in values:
result = IdMaker(
("a",), [pytest.param("string")], None, ["ação"], config, None, None
).make_unique_parameterset_ids()
assert result == [expected]
def test_idmaker_with_param_id_and_config(self) -> None:
"""Unit test for expected behavior to create ids with pytest.param(id=...) and
disable_test_id_escaping_and_forfeit_all_rights_to_community_support
option (#9037).
"""
class MockConfig:
def __init__(self, config):
self.config = config
def getini(self, name):
return self.config[name]
option = "disable_test_id_escaping_and_forfeit_all_rights_to_community_support"
values: list[tuple[Any, str]] = [
(MockConfig({option: True}), "ação"),
(MockConfig({option: False}), "a\\xe7\\xe3o"),
]
for config, expected in values:
result = IdMaker(
("a",),
[pytest.param("string", id="ação")],
None,
None,
config,
None,
None,
).make_unique_parameterset_ids()
assert result == [expected]
def test_idmaker_duplicated_empty_str(self) -> None:
"""Regression test for empty strings parametrized more than once (#11563)."""
result = IdMaker(
("a",), [pytest.param(""), pytest.param("")], None, None, None, None, None
).make_unique_parameterset_ids()
assert result == ["0", "1"]
def test_parametrize_ids_exception(self, pytester: Pytester) -> None:
"""
:param pytester: the instance of Pytester class, a temporary
test directory.
"""
pytester.makepyfile(
"""
import pytest
def ids(arg):
raise Exception("bad ids")
@pytest.mark.parametrize("arg", ["a", "b"], ids=ids)
def test_foo(arg):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"*Exception: bad ids",
"*test_foo: error raised while trying to determine id of parameter 'arg' at position 0",
]
)
def test_parametrize_ids_returns_non_string(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""\
import pytest
def ids(d):
return d
@pytest.mark.parametrize("arg", ({1: 2}, {3, 4}), ids=ids)
def test(arg):
assert arg
@pytest.mark.parametrize("arg", (1, 2.0, True), ids=ids)
def test_int(arg):
assert arg
"""
)
result = pytester.runpytest("-vv", "-s")
result.stdout.fnmatch_lines(
[
"test_parametrize_ids_returns_non_string.py::test[arg0] PASSED",
"test_parametrize_ids_returns_non_string.py::test[arg1] PASSED",
"test_parametrize_ids_returns_non_string.py::test_int[1] PASSED",
"test_parametrize_ids_returns_non_string.py::test_int[2.0] PASSED",
"test_parametrize_ids_returns_non_string.py::test_int[True] PASSED",
]
)
def test_idmaker_with_ids(self) -> None:
result = IdMaker(
("a", "b"),
[pytest.param(1, 2), pytest.param(3, 4)],
None,
["a", None],
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["a", "3-4"]
def test_idmaker_with_paramset_id(self) -> None:
result = IdMaker(
("a", "b"),
[pytest.param(1, 2, id="me"), pytest.param(3, 4, id="you")],
None,
["a", None],
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["me", "you"]
def test_idmaker_with_ids_unique_names(self) -> None:
result = IdMaker(
("a"),
list(map(pytest.param, [1, 2, 3, 4, 5])),
None,
["a", "a", "b", "c", "b"],
None,
None,
None,
).make_unique_parameterset_ids()
assert result == ["a0", "a1", "b0", "c", "b1"]
def test_parametrize_indirect(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x", [1], indirect=True)
metafunc.parametrize("y", [2, 3], indirect=True)
assert len(metafunc._calls) == 2
assert metafunc._calls[0].params == dict(x=1, y=2)
assert metafunc._calls[1].params == dict(x=1, y=3)
def test_parametrize_indirect_list(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x, y", [("a", "b")], indirect=["x"])
assert metafunc._calls[0].params == dict(x="a", y="b")
# Since `y` is a direct parameter, its pseudo-fixture would
# be registered.
assert list(metafunc._arg2fixturedefs.keys()) == ["y"]
def test_parametrize_indirect_list_all(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x, y", [("a", "b")], indirect=["x", "y"])
assert metafunc._calls[0].params == dict(x="a", y="b")
assert list(metafunc._arg2fixturedefs.keys()) == []
def test_parametrize_indirect_list_empty(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
metafunc.parametrize("x, y", [("a", "b")], indirect=[])
assert metafunc._calls[0].params == dict(x="a", y="b")
assert list(metafunc._arg2fixturedefs.keys()) == ["x", "y"]
def test_parametrize_indirect_wrong_type(self) -> None:
def func(x, y):
pass
metafunc = self.Metafunc(func)
with pytest.raises(
fail.Exception,
match="In func: expected Sequence or boolean for indirect, got dict",
):
metafunc.parametrize("x, y", [("a", "b")], indirect={}) # type: ignore[arg-type]
def test_parametrize_indirect_list_functional(self, pytester: Pytester) -> None:
"""
#714
Test parametrization with 'indirect' parameter applied on
particular arguments. As y is direct, its value should
be used directly rather than being passed to the fixture y.
:param pytester: the instance of Pytester class, a temporary
test directory.
"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.fixture(scope='function')
def y(request):
return request.param * 2
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
def test_simple(x,y):
assert len(x) == 3
assert len(y) == 1
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(["*test_simple*a-b*", "*1 passed*"])
def test_parametrize_indirect_list_error(self) -> None:
"""#714"""
def func(x, y):
pass
metafunc = self.Metafunc(func)
with pytest.raises(fail.Exception):
metafunc.parametrize("x, y", [("a", "b")], indirect=["x", "z"])
def test_parametrize_uses_no_fixture_error_indirect_false(
self, pytester: Pytester
) -> None:
"""The 'uses no fixture' error tells the user at collection time
that the parametrize data they've set up doesn't correspond to the
fixtures in their test function, rather than silently ignoring this
and letting the test potentially pass.
#714
"""
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=False)
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no argument 'y'*"])
def test_parametrize_uses_no_fixture_error_indirect_true(
self, pytester: Pytester
) -> None:
"""#714"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.fixture(scope='function')
def y(request):
return request.param * 2
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=True)
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
def test_parametrize_indirect_uses_no_fixture_error_indirect_string(
self, pytester: Pytester
) -> None:
"""#714"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect='y')
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
def test_parametrize_indirect_uses_no_fixture_error_indirect_list(
self, pytester: Pytester
) -> None:
"""#714"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['y'])
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no fixture 'y'*"])
def test_parametrize_argument_not_in_indirect_list(
self, pytester: Pytester
) -> None:
"""#714"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='function')
def x(request):
return request.param * 3
@pytest.mark.parametrize('x, y', [('a', 'b')], indirect=['x'])
def test_simple(x):
assert len(x) == 3
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(["*uses no argument 'y'*"])
def test_parametrize_gives_indicative_error_on_function_with_default_argument(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize('x, y', [('a', 'b')])
def test_simple(x, y=1):
assert len(x) == 1
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(
["*already takes an argument 'y' with a default value"]
)
def test_parametrize_functional(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize('x', [1,2], indirect=True)
metafunc.parametrize('y', [2])
@pytest.fixture
def x(request):
return request.param * 10
def test_simple(x,y):
assert x in (10,20)
assert y == 2
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
["*test_simple*1-2*", "*test_simple*2-2*", "*2 passed*"]
)
def test_parametrize_onearg(self) -> None:
metafunc = self.Metafunc(lambda x: None)
metafunc.parametrize("x", [1, 2])
assert len(metafunc._calls) == 2
assert metafunc._calls[0].params == dict(x=1)
assert metafunc._calls[0].id == "1"
assert metafunc._calls[1].params == dict(x=2)
assert metafunc._calls[1].id == "2"
def test_parametrize_onearg_indirect(self) -> None:
metafunc = self.Metafunc(lambda x: None)
metafunc.parametrize("x", [1, 2], indirect=True)
assert metafunc._calls[0].params == dict(x=1)
assert metafunc._calls[0].id == "1"
assert metafunc._calls[1].params == dict(x=2)
assert metafunc._calls[1].id == "2"
def test_parametrize_twoargs(self) -> None:
metafunc = self.Metafunc(lambda x, y: None)
metafunc.parametrize(("x", "y"), [(1, 2), (3, 4)])
assert len(metafunc._calls) == 2
assert metafunc._calls[0].params == dict(x=1, y=2)
assert metafunc._calls[0].id == "1-2"
assert metafunc._calls[1].params == dict(x=3, y=4)
assert metafunc._calls[1].id == "3-4"
def test_high_scoped_parametrize_reordering(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("arg2", [3, 4])
@pytest.mark.parametrize("arg1", [0, 1, 2], scope='module')
def test1(arg1, arg2):
pass
def test2():
pass
@pytest.mark.parametrize("arg1", [0, 1, 2], scope='module')
def test3(arg1):
pass
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.re_match_lines(
[
r" <Function test1\[0-3\]>",
r" <Function test3\[0\]>",
r" <Function test1\[0-4\]>",
r" <Function test3\[1\]>",
r" <Function test1\[1-3\]>",
r" <Function test3\[2\]>",
r" <Function test1\[1-4\]>",
r" <Function test1\[2-3\]>",
r" <Function test1\[2-4\]>",
r" <Function test2>",
]
)
def test_parametrize_multiple_times(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
pytestmark = pytest.mark.parametrize("x", [1,2])
def test_func(x):
assert 0, x
class TestClass(object):
pytestmark = pytest.mark.parametrize("y", [3,4])
def test_meth(self, x, y):
assert 0, x
"""
)
result = pytester.runpytest()
assert result.ret == 1
result.assert_outcomes(failed=6)
def test_parametrize_CSV(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("x, y,", [(1,2), (2,3)])
def test_func(x, y):
assert x+1 == y
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
def test_parametrize_class_scenarios(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
# same as doc/en/example/parametrize scenario example
def pytest_generate_tests(metafunc):
idlist = []
argvalues = []
for scenario in metafunc.cls.scenarios:
idlist.append(scenario[0])
items = scenario[1].items()
argnames = [x[0] for x in items]
argvalues.append(([x[1] for x in items]))
metafunc.parametrize(argnames, argvalues, ids=idlist, scope="class")
class Test(object):
scenarios = [['1', {'arg': {1: 2}, "arg2": "value2"}],
['2', {'arg':'value2', "arg2": "value2"}]]
def test_1(self, arg, arg2):
pass
def test_2(self, arg2, arg):
pass
def test_3(self, arg, arg2):
pass
"""
)
result = pytester.runpytest("-v")
assert result.ret == 0
result.stdout.fnmatch_lines(
"""
*test_1*1*
*test_2*1*
*test_3*1*
*test_1*2*
*test_2*2*
*test_3*2*
*6 passed*
"""
)
class TestMetafuncFunctional:
def test_attributes(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
# assumes that generate/provide runs in the same process
import sys, pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize('metafunc', [metafunc])
@pytest.fixture
def metafunc(request):
return request.param
def test_function(metafunc, pytestconfig):
assert metafunc.config == pytestconfig
assert metafunc.module.__name__ == __name__
assert metafunc.function == test_function
assert metafunc.cls is None
class TestClass(object):
def test_method(self, metafunc, pytestconfig):
assert metafunc.config == pytestconfig
assert metafunc.module.__name__ == __name__
unbound = TestClass.test_method
assert metafunc.function == unbound
assert metafunc.cls == TestClass
"""
)
result = pytester.runpytest(p, "-v")
result.assert_outcomes(passed=2)
def test_two_functions(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def pytest_generate_tests(metafunc):
metafunc.parametrize('arg1', [10, 20], ids=['0', '1'])
def test_func1(arg1):
assert arg1 == 10
def test_func2(arg1):
assert arg1 in (10, 20)
"""
)
result = pytester.runpytest("-v", p)
result.stdout.fnmatch_lines(
[
"*test_func1*0*PASS*",
"*test_func1*1*FAIL*",
"*test_func2*PASS*",
"*test_func2*PASS*",
"*1 failed, 3 passed*",
]
)
def test_noself_in_method(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def pytest_generate_tests(metafunc):
assert 'xyz' not in metafunc.fixturenames
class TestHello(object):
def test_hello(xyz):
pass
"""
)
result = pytester.runpytest(p)
result.assert_outcomes(passed=1)
def test_generate_tests_in_class(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
class TestClass(object):
def pytest_generate_tests(self, metafunc):
metafunc.parametrize('hello', ['world'], ids=['hellow'])
def test_myfunc(self, hello):
assert hello == "world"
"""
)
result = pytester.runpytest("-v", p)
result.stdout.fnmatch_lines(["*test_myfunc*hello*PASS*", "*1 passed*"])
def test_two_functions_not_same_instance(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def pytest_generate_tests(metafunc):
metafunc.parametrize('arg1', [10, 20], ids=["0", "1"])
class TestClass(object):
def test_func(self, arg1):
assert not hasattr(self, 'x')
self.x = 1
"""
)
result = pytester.runpytest("-v", p)
result.stdout.fnmatch_lines(
["*test_func*0*PASS*", "*test_func*1*PASS*", "*2 pass*"]
)
def test_issue28_setup_method_in_generate_tests(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def pytest_generate_tests(metafunc):
metafunc.parametrize('arg1', [1])
class TestClass(object):
def test_method(self, arg1):
assert arg1 == self.val
def setup_method(self, func):
self.val = 1
"""
)
result = pytester.runpytest(p)
result.assert_outcomes(passed=1)
def test_parametrize_functional2(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
def pytest_generate_tests(metafunc):
metafunc.parametrize("arg1", [1,2])
metafunc.parametrize("arg2", [4,5])
def test_hello(arg1, arg2):
assert 0, (arg1, arg2)
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
["*(1, 4)*", "*(1, 5)*", "*(2, 4)*", "*(2, 5)*", "*4 failed*"]
)
def test_parametrize_and_inner_getfixturevalue(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def pytest_generate_tests(metafunc):
metafunc.parametrize("arg1", [1], indirect=True)
metafunc.parametrize("arg2", [10], indirect=True)
import pytest
@pytest.fixture
def arg1(request):
x = request.getfixturevalue("arg2")
return x + request.param
@pytest.fixture
def arg2(request):
return request.param
def test_func1(arg1, arg2):
assert arg1 == 11
"""
)
result = pytester.runpytest("-v", p)
result.stdout.fnmatch_lines(["*test_func1*1*PASS*", "*1 passed*"])
def test_parametrize_on_setup_arg(self, pytester: Pytester) -> None:
p = pytester.makepyfile(
"""
def pytest_generate_tests(metafunc):
assert "arg1" in metafunc.fixturenames
metafunc.parametrize("arg1", [1], indirect=True)
import pytest
@pytest.fixture
def arg1(request):
return request.param
@pytest.fixture
def arg2(request, arg1):
return 10 * arg1
def test_func(arg2):
assert arg2 == 10
"""
)
result = pytester.runpytest("-v", p)
result.stdout.fnmatch_lines(["*test_func*1*PASS*", "*1 passed*"])
def test_parametrize_with_ids(self, pytester: Pytester) -> None:
pytester.makeini(
"""
[pytest]
console_output_style=classic
"""
)
pytester.makepyfile(
"""
import pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize(("a", "b"), [(1,1), (1,2)],
ids=["basic", "advanced"])
def test_function(a, b):
assert a == b
"""
)
result = pytester.runpytest("-v")
assert result.ret == 1
result.stdout.fnmatch_lines_random(
["*test_function*basic*PASSED", "*test_function*advanced*FAILED"]
)
def test_parametrize_without_ids(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize(("a", "b"),
[(1,object()), (1.3,object())])
def test_function(a, b):
assert 1
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
"""
*test_function*1-b0*
*test_function*1.3-b1*
"""
)
def test_parametrize_with_None_in_ids(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize(("a", "b"), [(1,1), (1,1), (1,2)],
ids=["basic", None, "advanced"])
def test_function(a, b):
assert a == b
"""
)
result = pytester.runpytest("-v")
assert result.ret == 1
result.stdout.fnmatch_lines_random(
[
"*test_function*basic*PASSED*",
"*test_function*1-1*PASSED*",
"*test_function*advanced*FAILED*",
]
)
def test_fixture_parametrized_empty_ids(self, pytester: Pytester) -> None:
"""Fixtures parametrized with empty ids cause an internal error (#1849)."""
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module", ids=[], params=[])
def temp(request):
return request.param
def test_temp(temp):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 1 skipped *"])
def test_parametrized_empty_ids(self, pytester: Pytester) -> None:
"""Tests parametrized with empty ids cause an internal error (#1849)."""
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize('temp', [], ids=list())
def test_temp(temp):
pass
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 1 skipped *"])
def test_parametrized_ids_invalid_type(self, pytester: Pytester) -> None:
"""Test error with non-strings/non-ints, without generator (#1857)."""
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("x, expected", [(1, 2), (3, 4), (5, 6)], ids=(None, 2, OSError()))
def test_ids_numbers(x,expected):
assert x * 2 == expected
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(
[
"In test_ids_numbers: ids contains unsupported value OSError() (type: <class 'OSError'>) at index 2. "
"Supported types are: str, bytes, int, float, complex, bool, enum, regex or anything with a __name__."
]
)
def test_parametrize_with_identical_ids_get_unique_names(
self, pytester: Pytester
) -> None:
pytester.makepyfile(
"""
import pytest
def pytest_generate_tests(metafunc):
metafunc.parametrize(("a", "b"), [(1,1), (1,2)],
ids=["a", "a"])
def test_function(a, b):
assert a == b
"""
)
result = pytester.runpytest("-v")
assert result.ret == 1
result.stdout.fnmatch_lines_random(
["*test_function*a0*PASSED*", "*test_function*a1*FAILED*"]
)
@pytest.mark.parametrize(("scope", "length"), [("module", 2), ("function", 4)])
def test_parametrize_scope_overrides(
self, pytester: Pytester, scope: str, length: int
) -> None:
pytester.makepyfile(
f"""
import pytest
values = []
def pytest_generate_tests(metafunc):
if "arg" in metafunc.fixturenames:
metafunc.parametrize("arg", [1,2], indirect=True,
scope={scope!r})
@pytest.fixture
def arg(request):
values.append(request.param)
return request.param
def test_hello(arg):
assert arg in (1,2)
def test_world(arg):
assert arg in (1,2)
def test_checklength():
assert len(values) == {length}
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=5)
def test_parametrize_issue323(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='module', params=range(966))
def foo(request):
return request.param
def test_it(foo):
pass
def test_it2(foo):
pass
"""
)
reprec = pytester.inline_run("--collect-only")
assert not reprec.getcalls("pytest_internalerror")
def test_usefixtures_seen_in_generate_tests(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def pytest_generate_tests(metafunc):
assert "abc" in metafunc.fixturenames
metafunc.parametrize("abc", [1])
@pytest.mark.usefixtures("abc")
def test_function():
pass
"""
)
reprec = pytester.runpytest()
reprec.assert_outcomes(passed=1)
def test_generate_tests_only_done_in_subdir(self, pytester: Pytester) -> None:
sub1 = pytester.mkpydir("sub1")
sub2 = pytester.mkpydir("sub2")
sub1.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
def pytest_generate_tests(metafunc):
assert metafunc.function.__name__ == "test_1"
"""
),
encoding="utf-8",
)
sub2.joinpath("conftest.py").write_text(
textwrap.dedent(
"""\
def pytest_generate_tests(metafunc):
assert metafunc.function.__name__ == "test_2"
"""
),
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("--keep-duplicates", "-v", "-s", sub1, sub2, sub1)
result.assert_outcomes(passed=3)
def test_generate_same_function_names_issue403(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
def make_tests():
@pytest.mark.parametrize("x", range(2))
def test_foo(x):
pass
return test_foo
test_x = make_tests()
test_y = make_tests()
"""
)
reprec = pytester.runpytest()
reprec.assert_outcomes(passed=4)
def test_parametrize_misspelling(self, pytester: Pytester) -> None:
"""#463"""
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrise("x", range(2))
def test_foo(x):
pass
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(
[
"collected 0 items / 1 error",
"",
"*= ERRORS =*",
"*_ ERROR collecting test_parametrize_misspelling.py _*",
"test_parametrize_misspelling.py:3: in <module>",
' @pytest.mark.parametrise("x", range(2))',
"E Failed: Unknown 'parametrise' mark, did you mean 'parametrize'?",
"*! Interrupted: 1 error during collection !*",
"*= no tests collected, 1 error in *",
]
)
@pytest.mark.parametrize("scope", ["class", "package"])
def test_parametrize_missing_scope_doesnt_crash(
self, pytester: Pytester, scope: str
) -> None:
"""Doesn't crash when parametrize(scope=<scope>) is used without a
corresponding <scope> node."""
pytester.makepyfile(
f"""
import pytest
@pytest.mark.parametrize("x", [0], scope="{scope}")
def test_it(x): pass
"""
)
result = pytester.runpytest()
assert result.ret == 0
def test_parametrize_module_level_test_with_class_scope(
self, pytester: Pytester
) -> None:
"""
Test that a class-scoped parametrization without a corresponding `Class`
gets module scope, i.e. we only create a single FixtureDef for it per module.
"""
module = pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("x", [0, 1], scope="class")
def test_1(x):
pass
@pytest.mark.parametrize("x", [1, 2], scope="module")
def test_2(x):
pass
"""
)
test_1_0, _, test_2_0, _ = pytester.genitems((pytester.getmodulecol(module),))
assert isinstance(test_1_0, Function)
assert test_1_0.name == "test_1[0]"
test_1_fixture_x = test_1_0._fixtureinfo.name2fixturedefs["x"][-1]
assert isinstance(test_2_0, Function)
assert test_2_0.name == "test_2[1]"
test_2_fixture_x = test_2_0._fixtureinfo.name2fixturedefs["x"][-1]
assert test_1_fixture_x is test_2_fixture_x
def test_reordering_with_scopeless_and_just_indirect_parametrization(
self, pytester: Pytester
) -> None:
pytester.makeconftest(
"""
import pytest
@pytest.fixture(scope="package")
def fixture1():
pass
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope="module")
def fixture0():
pass
@pytest.fixture(scope="module")
def fixture1(fixture0):
pass
@pytest.mark.parametrize("fixture1", [0], indirect=True)
def test_0(fixture1):
pass
@pytest.fixture(scope="module")
def fixture():
pass
@pytest.mark.parametrize("fixture", [0], indirect=True)
def test_1(fixture):
pass
def test_2():
pass
class Test:
@pytest.fixture(scope="class")
def fixture(self, fixture):
pass
@pytest.mark.parametrize("fixture", [0], indirect=True)
def test_3(self, fixture):
pass
"""
)
result = pytester.runpytest("-v")
assert result.ret == 0
result.stdout.fnmatch_lines(
[
"*test_0*",
"*test_1*",
"*test_2*",
"*test_3*",
]
)
class TestMetafuncFunctionalAuto:
"""Tests related to automatically find out the correct scope for
parametrized tests (#1832)."""
def test_parametrize_auto_scope(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='session', autouse=True)
def fixture():
return 1
@pytest.mark.parametrize('animal', ["dog", "cat"])
def test_1(animal):
assert animal in ('dog', 'cat')
@pytest.mark.parametrize('animal', ['fish'])
def test_2(animal):
assert animal == 'fish'
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 3 passed *"])
def test_parametrize_auto_scope_indirect(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='session')
def echo(request):
return request.param
@pytest.mark.parametrize('animal, echo', [("dog", 1), ("cat", 2)], indirect=['echo'])
def test_1(animal, echo):
assert animal in ('dog', 'cat')
assert echo in (1, 2, 3)
@pytest.mark.parametrize('animal, echo', [('fish', 3)], indirect=['echo'])
def test_2(animal, echo):
assert animal == 'fish'
assert echo in (1, 2, 3)
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 3 passed *"])
def test_parametrize_auto_scope_override_fixture(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='session', autouse=True)
def animal():
return 'fox'
@pytest.mark.parametrize('animal', ["dog", "cat"])
def test_1(animal):
assert animal in ('dog', 'cat')
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 2 passed *"])
def test_parametrize_all_indirects(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture()
def animal(request):
return request.param
@pytest.fixture(scope='session')
def echo(request):
return request.param
@pytest.mark.parametrize('animal, echo', [("dog", 1), ("cat", 2)], indirect=True)
def test_1(animal, echo):
assert animal in ('dog', 'cat')
assert echo in (1, 2, 3)
@pytest.mark.parametrize('animal, echo', [("fish", 3)], indirect=True)
def test_2(animal, echo):
assert animal == 'fish'
assert echo in (1, 2, 3)
"""
)
result = pytester.runpytest()
result.stdout.fnmatch_lines(["* 3 passed *"])
def test_parametrize_some_arguments_auto_scope(
self, pytester: Pytester, monkeypatch
) -> None:
"""Integration test for (#3941)"""
class_fix_setup: list[object] = []
monkeypatch.setattr(sys, "class_fix_setup", class_fix_setup, raising=False)
func_fix_setup: list[object] = []
monkeypatch.setattr(sys, "func_fix_setup", func_fix_setup, raising=False)
pytester.makepyfile(
"""
import pytest
import sys
@pytest.fixture(scope='class', autouse=True)
def class_fix(request):
sys.class_fix_setup.append(request.param)
@pytest.fixture(autouse=True)
def func_fix():
sys.func_fix_setup.append(True)
@pytest.mark.parametrize('class_fix', [10, 20], indirect=True)
class Test:
def test_foo(self):
pass
def test_bar(self):
pass
"""
)
result = pytester.runpytest_inprocess()
result.stdout.fnmatch_lines(["* 4 passed in *"])
assert func_fix_setup == [True] * 4
assert class_fix_setup == [10, 20]
def test_parametrize_issue634(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.fixture(scope='module')
def foo(request):
print('preparing foo-%d' % request.param)
return 'foo-%d' % request.param
def test_one(foo):
pass
def test_two(foo):
pass
test_two.test_with = (2, 3)
def pytest_generate_tests(metafunc):
params = (1, 2, 3, 4)
if not 'foo' in metafunc.fixturenames:
return
test_with = getattr(metafunc.function, 'test_with', None)
if test_with:
params = test_with
metafunc.parametrize('foo', params, indirect=True)
"""
)
result = pytester.runpytest("-s")
output = result.stdout.str()
assert output.count("preparing foo-2") == 1
assert output.count("preparing foo-3") == 1
class TestMarkersWithParametrization:
"""#308"""
def test_simple_mark(self, pytester: Pytester) -> None:
s = """
import pytest
@pytest.mark.foo
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.param(1, 3, marks=pytest.mark.bar),
(2, 3),
])
def test_increment(n, expected):
assert n + 1 == expected
"""
items = pytester.getitems(s)
assert len(items) == 3
for item in items:
assert "foo" in item.keywords
assert "bar" not in items[0].keywords
assert "bar" in items[1].keywords
assert "bar" not in items[2].keywords
def test_select_based_on_mark(self, pytester: Pytester) -> None:
s = """
import pytest
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.param(2, 3, marks=pytest.mark.foo),
(3, 4),
])
def test_increment(n, expected):
assert n + 1 == expected
"""
pytester.makepyfile(s)
rec = pytester.inline_run("-m", "foo")
passed, skipped, fail = rec.listoutcomes()
assert len(passed) == 1
assert len(skipped) == 0
assert len(fail) == 0
def test_simple_xfail(self, pytester: Pytester) -> None:
s = """
import pytest
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.param(1, 3, marks=pytest.mark.xfail),
(2, 3),
])
def test_increment(n, expected):
assert n + 1 == expected
"""
pytester.makepyfile(s)
reprec = pytester.inline_run()
# xfail is skip??
reprec.assertoutcome(passed=2, skipped=1)
def test_simple_xfail_single_argname(self, pytester: Pytester) -> None:
s = """
import pytest
@pytest.mark.parametrize("n", [
2,
pytest.param(3, marks=pytest.mark.xfail),
4,
])
def test_isEven(n):
assert n % 2 == 0
"""
pytester.makepyfile(s)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2, skipped=1)
def test_xfail_with_arg(self, pytester: Pytester) -> None:
s = """
import pytest
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.param(1, 3, marks=pytest.mark.xfail("True")),
(2, 3),
])
def test_increment(n, expected):
assert n + 1 == expected
"""
pytester.makepyfile(s)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2, skipped=1)
def test_xfail_with_kwarg(self, pytester: Pytester) -> None:
s = """
import pytest
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.param(1, 3, marks=pytest.mark.xfail(reason="some bug")),
(2, 3),
])
def test_increment(n, expected):
assert n + 1 == expected
"""
pytester.makepyfile(s)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2, skipped=1)
def test_xfail_with_arg_and_kwarg(self, pytester: Pytester) -> None:
s = """
import pytest
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.param(1, 3, marks=pytest.mark.xfail("True", reason="some bug")),
(2, 3),
])
def test_increment(n, expected):
assert n + 1 == expected
"""
pytester.makepyfile(s)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2, skipped=1)
@pytest.mark.parametrize("strict", [True, False])
def test_xfail_passing_is_xpass(self, pytester: Pytester, strict: bool) -> None:
s = f"""
import pytest
m = pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict})
@pytest.mark.parametrize(("n", "expected"), [
(1, 2),
pytest.param(2, 3, marks=m),
(3, 4),
])
def test_increment(n, expected):
assert n + 1 == expected
"""
pytester.makepyfile(s)
reprec = pytester.inline_run()
passed, failed = (2, 1) if strict else (3, 0)
reprec.assertoutcome(passed=passed, failed=failed)
def test_parametrize_called_in_generate_tests(self, pytester: Pytester) -> None:
s = """
import pytest
def pytest_generate_tests(metafunc):
passingTestData = [(1, 2),
(2, 3)]
failingTestData = [(1, 3),
(2, 2)]
testData = passingTestData + [pytest.param(*d, marks=pytest.mark.xfail)
for d in failingTestData]
metafunc.parametrize(("n", "expected"), testData)
def test_increment(n, expected):
assert n + 1 == expected
"""
pytester.makepyfile(s)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2, skipped=2)
def test_parametrize_ID_generation_string_int_works(
self, pytester: Pytester
) -> None:
"""#290"""
pytester.makepyfile(
"""
import pytest
@pytest.fixture
def myfixture():
return 'example'
@pytest.mark.parametrize(
'limit', (0, '0'))
def test_limit(limit, myfixture):
return
"""
)
reprec = pytester.inline_run()
reprec.assertoutcome(passed=2)
@pytest.mark.parametrize("strict", [True, False])
def test_parametrize_marked_value(self, pytester: Pytester, strict: bool) -> None:
s = f"""
import pytest
@pytest.mark.parametrize(("n", "expected"), [
pytest.param(
2,3,
marks=pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict}),
),
pytest.param(
2,3,
marks=[pytest.mark.xfail("sys.version_info > (0, 0, 0)", reason="some bug", strict={strict})],
),
])
def test_increment(n, expected):
assert n + 1 == expected
"""
pytester.makepyfile(s)
reprec = pytester.inline_run()
passed, failed = (0, 2) if strict else (2, 0)
reprec.assertoutcome(passed=passed, failed=failed)
def test_pytest_make_parametrize_id(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_make_parametrize_id(config, val):
return str(val * 2)
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("x", range(2))
def test_func(x):
pass
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(["*test_func*0*PASS*", "*test_func*2*PASS*"])
def test_pytest_make_parametrize_id_with_argname(self, pytester: Pytester) -> None:
pytester.makeconftest(
"""
def pytest_make_parametrize_id(config, val, argname):
return str(val * 2 if argname == 'x' else val * 10)
"""
)
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("x", range(2))
def test_func_a(x):
pass
@pytest.mark.parametrize("y", [1])
def test_func_b(y):
pass
"""
)
result = pytester.runpytest("-v")
result.stdout.fnmatch_lines(
["*test_func_a*0*PASS*", "*test_func_a*2*PASS*", "*test_func_b*10*PASS*"]
)
def test_parametrize_positional_args(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize("a", [1], False)
def test_foo(a):
pass
"""
)
result = pytester.runpytest()
result.assert_outcomes(passed=1)
def test_parametrize_iterator(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import itertools
import pytest
id_parametrize = pytest.mark.parametrize(
ids=("param%d" % i for i in itertools.count())
)
@id_parametrize('y', ['a', 'b'])
def test1(y):
pass
@id_parametrize('y', ['a', 'b'])
def test2(y):
pass
@pytest.mark.parametrize("a, b", [(1, 2), (3, 4)], ids=itertools.count())
def test_converted_to_str(a, b):
pass
"""
)
result = pytester.runpytest("-vv", "-s")
result.stdout.fnmatch_lines(
[
"test_parametrize_iterator.py::test1[param0] PASSED",
"test_parametrize_iterator.py::test1[param1] PASSED",
"test_parametrize_iterator.py::test2[param0] PASSED",
"test_parametrize_iterator.py::test2[param1] PASSED",
"test_parametrize_iterator.py::test_converted_to_str[0] PASSED",
"test_parametrize_iterator.py::test_converted_to_str[1] PASSED",
"*= 6 passed in *",
]
)
class TestHiddenParam:
"""Test that pytest.HIDDEN_PARAM works"""
def test_parametrize_ids(self, pytester: Pytester) -> None:
items = pytester.getitems(
"""
import pytest
@pytest.mark.parametrize(
("foo", "bar"),
[
("a", "x"),
("b", "y"),
("c", "z"),
],
ids=["paramset1", pytest.HIDDEN_PARAM, "paramset3"],
)
def test_func(foo, bar):
pass
"""
)
names = [item.name for item in items]
assert names == [
"test_func[paramset1]",
"test_func",
"test_func[paramset3]",
]
def test_param_id(self, pytester: Pytester) -> None:
items = pytester.getitems(
"""
import pytest
@pytest.mark.parametrize(
("foo", "bar"),
[
pytest.param("a", "x", id="paramset1"),
pytest.param("b", "y", id=pytest.HIDDEN_PARAM),
("c", "z"),
],
)
def test_func(foo, bar):
pass
"""
)
names = [item.name for item in items]
assert names == [
"test_func[paramset1]",
"test_func",
"test_func[c-z]",
]
def test_multiple_hidden_param_is_forbidden(self, pytester: Pytester) -> None:
pytester.makepyfile(
"""
import pytest
@pytest.mark.parametrize(
("foo", "bar"),
[
("a", "x"),
("b", "y"),
],
ids=[pytest.HIDDEN_PARAM, pytest.HIDDEN_PARAM],
)
def test_func(foo, bar):
pass
"""
)
result = pytester.runpytest("--collect-only")
result.stdout.fnmatch_lines(
[
"collected 0 items / 1 error",
"",
"*= ERRORS =*",
"*_ ERROR collecting test_multiple_hidden_param_is_forbidden.py _*",
"E Failed: In test_func: multiple instances of HIDDEN_PARAM cannot be used "
"in the same parametrize call, because the tests names need to be unique.",
"*! Interrupted: 1 error during collection !*",
"*= no tests collected, 1 error in *",
]
)
def test_multiple_hidden_param_is_forbidden_idmaker(self) -> None:
id_maker = IdMaker(
("foo", "bar"),
[pytest.param("a", "x"), pytest.param("b", "y")],
None,
[pytest.HIDDEN_PARAM, pytest.HIDDEN_PARAM],
None,
"some_node_id",
None,
)
expected = "In some_node_id: multiple instances of HIDDEN_PARAM"
with pytest.raises(Failed, match=expected):
id_maker.make_unique_parameterset_ids()
def test_multiple_parametrize(self, pytester: Pytester) -> None:
items = pytester.getitems(
"""
import pytest
@pytest.mark.parametrize(
"bar",
["x", "y"],
)
@pytest.mark.parametrize(
"foo",
["a", "b"],
ids=["a", pytest.HIDDEN_PARAM],
)
def test_func(foo, bar):
pass
"""
)
names = [item.name for item in items]
assert names == [
"test_func[a-x]",
"test_func[a-y]",
"test_func[x]",
"test_func[y]",
]
|