Spaces:
Running
Running
File size: 98,519 Bytes
e56d042 | 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 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 | import io
import json
import os
import time
import zipfile
from urllib.parse import urlparse
import pytest
from botocore.exceptions import ClientError
import uuid as _uuid_mod
_endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
_EXECUTE_PORT = urlparse(_endpoint).port or 4566
def _make_zip(code: str) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", code)
return buf.getvalue()
def _make_zip_js(code: str, filename: str = "index.js") -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr(filename, code)
return buf.getvalue()
_LAMBDA_CODE = 'def handler(event, context):\n return {"statusCode": 200, "body": "ok"}\n'
_LAMBDA_CODE_V2 = 'def handler(event, context):\n return {"statusCode": 200, "body": "v2"}\n'
_LAMBDA_ROLE = "arn:aws:iam::000000000000:role/lambda-role"
_NODE_CODE = (
"exports.handler = async (event, context) => {"
" return { statusCode: 200, body: JSON.stringify({ hello: event.name || 'world' }) }; };"
)
def _zip_lambda(code: str) -> bytes:
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", code)
return buf.getvalue()
def test_lambda_create_invoke(lam):
code = b'def handler(event, context):\n return {"statusCode": 200, "body": "Hello!", "event": event}\n'
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", code)
lam.create_function(
FunctionName="test-func-1",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test-role",
Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
)
funcs = lam.list_functions()
assert any(f["FunctionName"] == "test-func-1" for f in funcs["Functions"])
resp = lam.invoke(FunctionName="test-func-1", Payload=json.dumps({"key": "value"}))
payload = json.loads(resp["Payload"].read())
assert payload["statusCode"] == 200
def test_create_function_missing_runtime_raises(lam):
"""Zip deployment without a Runtime should return InvalidParameterValueException."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", "def handler(e, c): return {}")
with pytest.raises(ClientError) as exc:
lam.create_function(
FunctionName="no-runtime-fn",
Role="arn:aws:iam::000000000000:role/role",
Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
)
assert exc.value.response["Error"]["Code"] == "InvalidParameterValueException"
def test_lambda_esm_sqs(lam, sqs):
"""SQS β Lambda event source mapping: messages sent to SQS trigger Lambda."""
import io
import zipfile as zf
# Clean up from previous runs
try:
lam.delete_function(FunctionName="esm-test-func")
except Exception:
pass
# Lambda that records what it received
code = (
b"import json\n"
b"received = []\n"
b"def handler(event, context):\n"
b" received.extend(event.get('Records', []))\n"
b" return {'processed': len(event.get('Records', []))}\n"
)
buf = io.BytesIO()
with zf.ZipFile(buf, "w") as z:
z.writestr("index.py", code)
lam.create_function(
FunctionName="esm-test-func",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test-role",
Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
)
q_url = sqs.create_queue(QueueName="esm-test-queue")["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
# Create event source mapping
resp = lam.create_event_source_mapping(
EventSourceArn=q_arn,
FunctionName="esm-test-func",
BatchSize=5,
Enabled=True,
)
esm_uuid = resp["UUID"]
assert resp["State"] == "Enabled"
# Send a message to SQS
sqs.send_message(QueueUrl=q_url, MessageBody="trigger-lambda")
# Wait for poller to pick it up (max 5s)
import time
for _ in range(10):
time.sleep(0.5)
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1)
if not msgs.get("Messages"):
break # message was consumed by Lambda
# Queue should be empty β Lambda consumed the message
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1)
assert not msgs.get("Messages"), "Message should have been consumed by Lambda via ESM"
# Cleanup
lam.delete_event_source_mapping(UUID=esm_uuid)
def test_lambda_create_function(lam):
resp = lam.create_function(
FunctionName="lam-create-test",
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
assert resp["FunctionName"] == "lam-create-test"
assert resp["Runtime"] == "python3.12"
assert resp["Handler"] == "index.handler"
# AWS: CreateFunction returns State=Pending and transitions to Active
# asynchronously. Terraform's FunctionActive waiter polls GetFunction.
assert resp["State"] in ("Pending", "Active")
assert resp["LastUpdateStatus"] in ("InProgress", "Successful")
assert "FunctionArn" in resp
def test_lambda_create_duplicate(lam):
with pytest.raises(ClientError) as exc:
lam.create_function(
FunctionName="lam-create-test",
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
assert exc.value.response["Error"]["Code"] == "ResourceConflictException"
def test_lambda_get_function(lam):
resp = lam.get_function(FunctionName="lam-create-test")
assert resp["Configuration"]["FunctionName"] == "lam-create-test"
assert "Code" in resp
assert "Tags" in resp
def test_lambda_get_function_not_found(lam):
with pytest.raises(ClientError) as exc:
lam.get_function(FunctionName="nonexistent-func-xyz")
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_lambda_list_functions(lam):
resp = lam.list_functions()
names = [f["FunctionName"] for f in resp["Functions"]]
assert "lam-create-test" in names
def test_lambda_delete_function(lam):
lam.create_function(
FunctionName="lam-to-delete",
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
lam.delete_function(FunctionName="lam-to-delete")
with pytest.raises(ClientError) as exc:
lam.get_function(FunctionName="lam-to-delete")
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_lambda_invoke(lam):
lam.create_function(
FunctionName="lam-invoke-test",
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
resp = lam.invoke(
FunctionName="lam-invoke-test",
Payload=json.dumps({"hello": "world"}),
)
assert resp["StatusCode"] == 200
payload = json.loads(resp["Payload"].read())
assert payload["statusCode"] == 200
assert payload["body"] == "ok"
def test_lambda_invoke_async(lam):
resp = lam.invoke(
FunctionName="lam-invoke-test",
InvocationType="Event",
Payload=json.dumps({"async": True}),
)
assert resp["StatusCode"] == 202
def test_lambda_update_code(lam):
lam.update_function_code(
FunctionName="lam-invoke-test",
ZipFile=_make_zip(_LAMBDA_CODE_V2),
)
resp = lam.invoke(
FunctionName="lam-invoke-test",
Payload=json.dumps({}),
)
payload = json.loads(resp["Payload"].read())
assert payload["body"] == "v2"
def test_lambda_update_config(lam):
lam.update_function_configuration(
FunctionName="lam-invoke-test",
Handler="index.new_handler",
Environment={"Variables": {"MY_VAR": "my_val"}},
)
resp = lam.get_function(FunctionName="lam-invoke-test")
cfg = resp["Configuration"]
assert cfg["Handler"] == "index.new_handler"
assert cfg["Environment"]["Variables"]["MY_VAR"] == "my_val"
lam.update_function_configuration(
FunctionName="lam-invoke-test",
Handler="index.handler",
)
def test_lambda_tags(lam):
arn = lam.get_function(FunctionName="lam-invoke-test")["Configuration"]["FunctionArn"]
lam.tag_resource(Resource=arn, Tags={"env": "test", "team": "backend"})
resp = lam.list_tags(Resource=arn)
assert resp["Tags"]["env"] == "test"
assert resp["Tags"]["team"] == "backend"
lam.untag_resource(Resource=arn, TagKeys=["team"])
resp = lam.list_tags(Resource=arn)
assert "team" not in resp["Tags"]
assert resp["Tags"]["env"] == "test"
def test_lambda_add_permission(lam):
lam.add_permission(
FunctionName="lam-invoke-test",
StatementId="allow-s3",
Action="lambda:InvokeFunction",
Principal="s3.amazonaws.com",
SourceArn="arn:aws:s3:::my-bucket",
)
resp = lam.get_policy(FunctionName="lam-invoke-test")
policy = json.loads(resp["Policy"])
sids = [s["Sid"] for s in policy["Statement"]]
assert "allow-s3" in sids
def test_lambda_list_versions(lam):
resp = lam.list_versions_by_function(FunctionName="lam-invoke-test")
versions = resp["Versions"]
assert any(v["Version"] == "$LATEST" for v in versions)
def test_lambda_publish_version(lam):
resp = lam.publish_version(
FunctionName="lam-invoke-test",
Description="first published version",
)
assert resp["Version"] == "1"
assert resp["Description"] == "first published version"
assert "FunctionArn" in resp
versions = lam.list_versions_by_function(FunctionName="lam-invoke-test")["Versions"]
version_nums = [v["Version"] for v in versions]
assert "$LATEST" in version_nums
assert "1" in version_nums
def test_lambda_esm_sqs_comprehensive(lam, sqs):
try:
lam.delete_function(FunctionName="esm-comp-func")
except ClientError:
pass
code = 'def handler(event, context):\n return {"processed": len(event.get("Records", []))}\n'
lam.create_function(
FunctionName="esm-comp-func",
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
)
q_url = sqs.create_queue(QueueName="esm-comp-queue")["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url,
AttributeNames=["QueueArn"],
)["Attributes"]["QueueArn"]
resp = lam.create_event_source_mapping(
EventSourceArn=q_arn,
FunctionName="esm-comp-func",
BatchSize=5,
Enabled=True,
)
esm_uuid = resp["UUID"]
assert resp["State"] == "Enabled"
assert resp["BatchSize"] == 5
assert resp["EventSourceArn"] == q_arn
got = lam.get_event_source_mapping(UUID=esm_uuid)
assert got["UUID"] == esm_uuid
listed = lam.list_event_source_mappings(FunctionName="esm-comp-func")
assert any(e["UUID"] == esm_uuid for e in listed["EventSourceMappings"])
lam.delete_event_source_mapping(UUID=esm_uuid)
def test_lambda_esm_sqs_failure_respects_visibility_timeout(lam, sqs):
"""On Lambda failure, the message should remain in-flight until VisibilityTimeout expires."""
import io
import zipfile as zf
for fn in ("esm-fail-func",):
try:
lam.delete_function(FunctionName=fn)
except Exception:
pass
code = b"def handler(event, context):\n raise Exception('boom')\n"
buf = io.BytesIO()
with zf.ZipFile(buf, "w") as z:
z.writestr("index.py", code)
lam.create_function(
FunctionName="esm-fail-func",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test-role",
Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
Timeout=3,
)
q_url = sqs.create_queue(
QueueName="esm-fail-queue",
Attributes={"VisibilityTimeout": "30"},
)["QueueUrl"]
q_arn = sqs.get_queue_attributes(QueueUrl=q_url, AttributeNames=["QueueArn"])["Attributes"]["QueueArn"]
resp = lam.create_event_source_mapping(
EventSourceArn=q_arn,
FunctionName="esm-fail-func",
BatchSize=1,
Enabled=True,
)
esm_uuid = resp["UUID"]
sqs.send_message(QueueUrl=q_url, MessageBody="trigger-failure")
# Wait until ESM has actually processed (and failed) the message
for _ in range(40):
time.sleep(0.5)
cur = lam.get_event_source_mapping(UUID=esm_uuid)
if cur.get("LastProcessingResult") == "FAILED":
break
else:
pytest.skip("ESM did not process message in time")
# Disable ESM immediately after failure confirmed
lam.update_event_source_mapping(UUID=esm_uuid, Enabled=False)
# Message should be invisible (VisibilityTimeout=30s, and ESM just received it)
msgs = sqs.receive_message(QueueUrl=q_url, MaxNumberOfMessages=1, WaitTimeSeconds=0)
assert not msgs.get("Messages"), "Message should be invisible during VisibilityTimeout after failed ESM invoke"
lam.delete_event_source_mapping(UUID=esm_uuid)
def test_lambda_esm_sqs_report_batch_item_failures(lam, sqs):
"""ReportBatchItemFailures: failed messages stay on queue and reach DLQ."""
for fn in ("esm-partial-func",):
try:
lam.delete_function(FunctionName=fn)
except Exception:
pass
# Handler reports ALL messages as failed
code = (
"import json\n"
"def handler(event, context):\n"
" failures = []\n"
" for r in event.get('Records', []):\n"
" failures.append({'itemIdentifier': r['messageId']})\n"
" return {'batchItemFailures': failures}\n"
)
lam.create_function(
FunctionName="esm-partial-func",
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
)
# DLQ + main queue with maxReceiveCount=1
dlq_url = sqs.create_queue(QueueName="esm-partial-dlq")["QueueUrl"]
dlq_arn = sqs.get_queue_attributes(
QueueUrl=dlq_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
q_url = sqs.create_queue(
QueueName="esm-partial-queue",
Attributes={
"VisibilityTimeout": "1",
"RedrivePolicy": json.dumps({
"deadLetterTargetArn": dlq_arn,
"maxReceiveCount": "1",
}),
},
)["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
esm = lam.create_event_source_mapping(
EventSourceArn=q_arn,
FunctionName="esm-partial-func",
FunctionResponseTypes=["ReportBatchItemFailures"],
BatchSize=1,
Enabled=True,
)
esm_uuid = esm["UUID"]
assert "ReportBatchItemFailures" in esm["FunctionResponseTypes"]
sqs.send_message(QueueUrl=q_url, MessageBody="partial-fail-test")
# Wait for ESM to process and message to land in DLQ
dlq_count = 0
for _ in range(30):
time.sleep(1)
attrs = sqs.get_queue_attributes(
QueueUrl=dlq_url,
AttributeNames=["ApproximateNumberOfMessages"],
)
dlq_count = int(attrs["Attributes"]["ApproximateNumberOfMessages"])
if dlq_count >= 1:
break
lam.update_event_source_mapping(UUID=esm_uuid, Enabled=False)
lam.delete_event_source_mapping(UUID=esm_uuid)
assert dlq_count >= 1, (
f"Message should have reached DLQ after partial failure, "
f"but DLQ has {dlq_count} messages"
)
def test_lambda_warm_start(lam, apigw):
"""Warm worker via API Gateway execute-api: module-level state persists across invocations."""
import urllib.request as _urlreq
import uuid as _uuid
fname = f"intg-warm-{_uuid.uuid4().hex[:8]}"
code = (
b"import time\n"
b"_boot_time = time.time()\n"
b"def handler(event, context):\n"
b" return {'statusCode': 200, 'body': str(_boot_time)}\n"
)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", code)
lam.create_function(
FunctionName=fname,
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test-role",
Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
)
api_id = apigw.create_api(Name=f"warm-api-{fname}", ProtocolType="HTTP")["ApiId"]
int_id = apigw.create_integration(
ApiId=api_id,
IntegrationType="AWS_PROXY",
IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",
PayloadFormatVersion="2.0",
)["IntegrationId"]
apigw.create_route(ApiId=api_id, RouteKey="GET /ping", Target=f"integrations/{int_id}")
apigw.create_stage(ApiId=api_id, StageName="$default")
def call():
req = _urlreq.Request(
f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/ping",
method="GET",
)
req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
return _urlreq.urlopen(req).read().decode()
t1 = call() # cold start β spawns worker, imports module
t2 = call() # warm β reuses worker, same module state
assert t1 == t2, f"Warm worker should reuse module state: {t1} != {t2}"
apigw.delete_api(ApiId=api_id)
lam.delete_function(FunctionName=fname)
def test_lambda_warm_invoke_with_stderr_logging(lam):
"""Warm invoke should succeed repeatedly even when the worker writes to stderr."""
fname = f"lam-warm-stderr-{_uuid_mod.uuid4().hex[:8]}"
code = (
"import sys\n"
"def handler(event, context):\n"
" print(f'log:{event.get(\"n\", 0)}')\n"
" return {'statusCode': 200, 'value': event.get('n', 0)}\n"
)
lam.create_function(
FunctionName=fname,
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
)
try:
first = lam.invoke(FunctionName=fname, Payload=json.dumps({"n": 1}))
second = lam.invoke(FunctionName=fname, Payload=json.dumps({"n": 2}))
assert first["StatusCode"] == 200
assert second["StatusCode"] == 200
assert json.loads(first["Payload"].read())["value"] == 1
assert json.loads(second["Payload"].read())["value"] == 2
finally:
lam.delete_function(FunctionName=fname)
def test_lambda_nodejs_create_and_invoke(lam):
lam.create_function(
FunctionName="lam-node-basic",
Runtime="nodejs20.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip_js(_NODE_CODE, "index.js")},
)
resp = lam.invoke(
FunctionName="lam-node-basic",
Payload=json.dumps({"name": "ministack"}),
)
assert resp["StatusCode"] == 200
payload = json.loads(resp["Payload"].read())
assert payload["statusCode"] == 200
body = json.loads(payload["body"])
assert body["hello"] == "ministack"
def test_lambda_nodejs22_runtime(lam):
lam.create_function(
FunctionName="lam-node22",
Runtime="nodejs22.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip_js(_NODE_CODE, "index.js")},
)
resp = lam.invoke(FunctionName="lam-node22", Payload=json.dumps({"name": "v22"}))
assert resp["StatusCode"] == 200
payload = json.loads(resp["Payload"].read())
assert payload["statusCode"] == 200
def test_lambda_nodejs_update_code(lam):
v2 = (
"exports.handler = async (event) => {"
" return { statusCode: 200, body: 'v2' }; };"
)
lam.update_function_code(
FunctionName="lam-node-basic",
ZipFile=_make_zip_js(v2, "index.js"),
)
resp = lam.invoke(FunctionName="lam-node-basic", Payload=b"{}")
assert resp["StatusCode"] == 200
payload = json.loads(resp["Payload"].read())
assert payload["body"] == "v2"
def test_lambda_create_from_s3(lam, s3):
bucket = "lambda-code-bucket"
s3.create_bucket(Bucket=bucket)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", "def handler(event, context): return {'s3': True}")
s3.put_object(Bucket=bucket, Key="fn.zip", Body=buf.getvalue())
lam.create_function(
FunctionName="lam-s3-code",
Runtime="python3.11",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"S3Bucket": bucket, "S3Key": "fn.zip"},
)
resp = lam.invoke(FunctionName="lam-s3-code", Payload=b"{}")
assert resp["StatusCode"] == 200
assert json.loads(resp["Payload"].read())["s3"] is True
def test_lambda_update_code_from_s3(lam, s3):
bucket = "lambda-code-bucket"
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", "def handler(event, context): return {'v': 's3v2'}")
s3.put_object(Bucket=bucket, Key="fn-v2.zip", Body=buf.getvalue())
lam.update_function_code(
FunctionName="lam-s3-code",
S3Bucket=bucket,
S3Key="fn-v2.zip",
)
resp = lam.invoke(FunctionName="lam-s3-code", Payload=b"{}")
assert json.loads(resp["Payload"].read())["v"] == "s3v2"
def test_lambda_update_code_s3_missing_returns_error(lam):
from botocore.exceptions import ClientError
with pytest.raises(ClientError) as exc:
lam.update_function_code(
FunctionName="lam-s3-code",
S3Bucket="lambda-code-bucket",
S3Key="does-not-exist.zip",
)
assert exc.value.response["Error"]["Code"] == "InvalidParameterValueException"
def test_lambda_publish_version_with_create(lam):
code = "def handler(event, context): return {'ver': 1}"
try:
lam.get_function(FunctionName="lam-versioned-pub")
except Exception:
lam.create_function(
FunctionName="lam-versioned-pub",
Runtime="python3.11",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
Publish=True,
)
resp = lam.list_versions_by_function(FunctionName="lam-versioned-pub")
versions = [v["Version"] for v in resp["Versions"]]
assert any(v != "$LATEST" for v in versions)
def test_lambda_update_code_publish_version(lam):
# Ensure function exists (may have been cleaned up)
try:
lam.get_function(FunctionName="lam-versioned")
except Exception:
lam.create_function(
FunctionName="lam-versioned",
Runtime="python3.11",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip("def handler(event, context): return {'ver': 1}")},
Publish=True,
)
v2 = "def handler(event, context): return {'ver': 2}"
lam.update_function_code(
FunctionName="lam-versioned",
ZipFile=_make_zip(v2),
Publish=True,
)
resp = lam.list_versions_by_function(FunctionName="lam-versioned")
versions = [v["Version"] for v in resp["Versions"] if v["Version"] != "$LATEST"]
assert len(versions) >= 1
def test_lambda_nodejs_promise_handler(lam):
code = (
"exports.handler = (event) => Promise.resolve({ promise: true, val: event.x });"
)
lam.create_function(
FunctionName="lam-node-promise",
Runtime="nodejs20.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip_js(code, "index.js")},
)
resp = lam.invoke(FunctionName="lam-node-promise", Payload=json.dumps({"x": 42}))
payload = json.loads(resp["Payload"].read())
assert payload["promise"] is True
assert payload["val"] == 42
def test_lambda_nodejs_callback_handler(lam):
code = (
"exports.handler = (event, context, cb) => cb(null, { cb: true, val: event.y });"
)
lam.create_function(
FunctionName="lam-node-cb",
Runtime="nodejs20.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip_js(code, "index.js")},
)
resp = lam.invoke(FunctionName="lam-node-cb", Payload=json.dumps({"y": 7}))
payload = json.loads(resp["Payload"].read())
assert payload["cb"] is True
assert payload["val"] == 7
def test_lambda_nodejs_env_vars_at_spawn(lam):
"""Lambda env vars are available at process startup (NODE_OPTIONS, etc.)."""
code = (
"exports.handler = async (event) => ({"
" myVar: process.env.MY_CUSTOM_VAR,"
" region: process.env.AWS_REGION"
"});"
)
lam.create_function(
FunctionName="lam-node-env-spawn",
Runtime="nodejs20.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip_js(code, "index.js")},
Environment={"Variables": {"MY_CUSTOM_VAR": "from-spawn"}},
)
resp = lam.invoke(FunctionName="lam-node-env-spawn", Payload=b"{}")
payload = json.loads(resp["Payload"].read())
assert payload["myVar"] == "from-spawn"
def test_lambda_python_env_vars_at_spawn(lam):
"""Python Lambda env vars are available at process startup."""
code = (
"import os\n"
"def handler(event, context):\n"
" return {'myVar': os.environ.get('MY_PY_VAR', 'missing')}\n"
)
lam.create_function(
FunctionName="lam-py-env-spawn",
Runtime="python3.11",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
Environment={"Variables": {"MY_PY_VAR": "from-spawn-py"}},
)
resp = lam.invoke(FunctionName="lam-py-env-spawn", Payload=b"{}")
payload = json.loads(resp["Payload"].read())
assert payload["myVar"] == "from-spawn-py"
def test_lambda_endpoint_url_not_overridden_by_function_env(lam):
"""AWS_ENDPOINT_URL from function env vars must not override the
process-level value. When MiniStack runs in Docker, the host-mapped
port (e.g. 4568) is unreachable from inside the container β the
Lambda binary must always use MiniStack's internal endpoint.
This test verifies that the MiniStack server's AWS_ENDPOINT_URL takes
precedence over function-level env vars. It requires the server to
have AWS_ENDPOINT_URL set (as it does when running via docker-compose).
"""
# Verify the MiniStack server has AWS_ENDPOINT_URL set by checking
# a baseline Lambda. If the server doesn't have it, the override
# logic has nothing to restore and this test is not meaningful.
probe_code = (
"import os\n"
"def handler(event, context):\n"
" return {'endpoint': os.environ.get('AWS_ENDPOINT_URL', '')}\n"
)
probe_name = f"lam-endpoint-probe-{_uuid_mod.uuid4().hex[:8]}"
lam.create_function(
FunctionName=probe_name,
Runtime="python3.11",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(probe_code)},
)
resp = lam.invoke(FunctionName=probe_name, Payload=b"{}")
server_endpoint = json.loads(resp["Payload"].read()).get("endpoint", "")
if not server_endpoint:
pytest.skip("MiniStack server does not have AWS_ENDPOINT_URL set "
"(run with docker-compose to test endpoint override)")
# Now test with a function that sets a conflicting AWS_ENDPOINT_URL.
code = (
"import os\n"
"def handler(event, context):\n"
" return {'endpoint': os.environ.get('AWS_ENDPOINT_URL', 'unset')}\n"
)
fname = f"lam-endpoint-override-{_uuid_mod.uuid4().hex[:8]}"
lam.create_function(
FunctionName=fname,
Runtime="python3.11",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
Environment={"Variables": {
"AWS_ENDPOINT_URL": "http://should-be-overridden:9999",
}},
)
resp = lam.invoke(FunctionName=fname, Payload=b"{}")
payload = json.loads(resp["Payload"].read())
# The Lambda must see the server's endpoint, not the function env var.
assert payload["endpoint"] != "http://should-be-overridden:9999", (
"Function-level AWS_ENDPOINT_URL must not override internal endpoint"
)
assert payload["endpoint"] == server_endpoint
def test_lambda_dynamodb_stream_esm(lam, ddb):
# Create table with streams enabled
ddb.create_table(
TableName="stream-test-table",
KeySchema=[{"AttributeName": "pk", "KeyType": "HASH"}],
AttributeDefinitions=[{"AttributeName": "pk", "AttributeType": "S"}],
BillingMode="PAY_PER_REQUEST",
StreamSpecification={"StreamEnabled": True, "StreamViewType": "NEW_AND_OLD_IMAGES"},
)
stream_arn = ddb.describe_table(TableName="stream-test-table")["Table"]["LatestStreamArn"]
# Create Lambda that captures stream records
code = "def handler(event, context): return len(event['Records'])"
lam.create_function(
FunctionName="lam-ddb-stream",
Runtime="python3.11",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
)
esm = lam.create_event_source_mapping(
FunctionName="lam-ddb-stream",
EventSourceArn=stream_arn,
StartingPosition="TRIM_HORIZON",
BatchSize=10,
)
assert esm["EventSourceArn"] == stream_arn
assert esm["FunctionArn"].endswith("lam-ddb-stream")
# Verify ESM is registered and retrievable
esm_resp = lam.get_event_source_mapping(UUID=esm["UUID"])
assert esm_resp["EventSourceArn"] == stream_arn
assert esm_resp["StartingPosition"] == "TRIM_HORIZON"
# Write items β stream should capture them
ddb.put_item(TableName="stream-test-table", Item={"pk": {"S": "k1"}, "val": {"S": "v1"}})
ddb.put_item(TableName="stream-test-table", Item={"pk": {"S": "k2"}, "val": {"S": "v2"}})
ddb.delete_item(TableName="stream-test-table", Key={"pk": {"S": "k1"}})
# Verify table still has expected state
scan = ddb.scan(TableName="stream-test-table")
pks = [item["pk"]["S"] for item in scan["Items"]]
assert "k2" in pks
assert "k1" not in pks
def test_lambda_function_url_config(lam):
"""CreateFunctionUrlConfig / Get / Update / Delete / List lifecycle."""
import uuid as _uuid_mod
fn = f"intg-url-cfg-{_uuid_mod.uuid4().hex[:8]}"
lam.create_function(
FunctionName=fn,
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
# Create
resp = lam.create_function_url_config(FunctionName=fn, AuthType="NONE")
assert resp["AuthType"] == "NONE"
assert "FunctionUrl" in resp
url = resp["FunctionUrl"]
# Get
got = lam.get_function_url_config(FunctionName=fn)
assert got["FunctionUrl"] == url
# Update
updated = lam.update_function_url_config(
FunctionName=fn,
AuthType="AWS_IAM",
Cors={"AllowOrigins": ["*"]},
)
assert updated["AuthType"] == "AWS_IAM"
assert updated["Cors"]["AllowOrigins"] == ["*"]
# List
listed = lam.list_function_url_configs(FunctionName=fn)
assert any(c["FunctionUrl"] == url for c in listed["FunctionUrlConfigs"])
# Delete
lam.delete_function_url_config(FunctionName=fn)
with pytest.raises(ClientError) as exc:
lam.get_function_url_config(FunctionName=fn)
assert exc.value.response["Error"]["Code"] == "ResourceNotFoundException"
def test_lambda_unknown_path_returns_404(lam):
"""Requests to an unrecognised Lambda path must return 404, not 400 InvalidRequest."""
import urllib.error
import urllib.request
endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
req = urllib.request.Request(
f"{endpoint}/2015-03-31/functions/nonexistent-fn/completely-unknown-subpath",
headers={"Authorization": "AWS4-HMAC-SHA256 Credential=test/20260101/us-east-1/lambda/aws4_request"},
method="GET",
)
try:
urllib.request.urlopen(req)
assert False, "Expected an error response"
except urllib.error.HTTPError as e:
assert e.code == 404
def test_lambda_reset_terminates_workers(lam):
"""/_ministack/reset must cleanly terminate warm Lambda workers."""
import urllib.request
fn = f"intg-reset-worker-{__import__('uuid').uuid4().hex[:8]}"
code = "import time\n_boot = time.time()\ndef handler(event, context):\n return {'boot': _boot}\n"
lam.create_function(
FunctionName=fn,
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
)
# Warm the worker
r1 = lam.invoke(FunctionName=fn, Payload=b"{}")
boot1 = json.loads(r1["Payload"].read())["boot"]
# Reset β must terminate worker without error
endpoint = os.environ.get("MINISTACK_ENDPOINT", "http://localhost:4566")
req = urllib.request.Request(f"{endpoint}/_ministack/reset", data=b"", method="POST")
for _attempt in range(3):
try:
urllib.request.urlopen(req, timeout=15)
break
except Exception:
if _attempt == 2:
raise
# Re-create and invoke β new worker means new boot time
lam.create_function(
FunctionName=fn,
Runtime="python3.12",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": _make_zip(code)},
)
r2 = lam.invoke(FunctionName=fn, Payload=b"{}")
boot2 = json.loads(r2["Payload"].read())["boot"]
assert boot2 > boot1, "Worker should have been reset β new boot time expected"
def test_lambda_alias_crud(lam):
"""CreateAlias, GetAlias, UpdateAlias, DeleteAlias."""
code = _zip_lambda("def handler(e,c): return {'v': 1}")
lam.create_function(
FunctionName="qa-lam-alias",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/r",
Handler="index.handler",
Code={"ZipFile": code},
)
lam.publish_version(FunctionName="qa-lam-alias")
lam.create_alias(
FunctionName="qa-lam-alias",
Name="prod",
FunctionVersion="1",
Description="production alias",
)
alias = lam.get_alias(FunctionName="qa-lam-alias", Name="prod")
assert alias["Name"] == "prod"
assert alias["FunctionVersion"] == "1"
lam.update_alias(FunctionName="qa-lam-alias", Name="prod", Description="updated")
alias2 = lam.get_alias(FunctionName="qa-lam-alias", Name="prod")
assert alias2["Description"] == "updated"
aliases = lam.list_aliases(FunctionName="qa-lam-alias")["Aliases"]
assert any(a["Name"] == "prod" for a in aliases)
lam.delete_alias(FunctionName="qa-lam-alias", Name="prod")
aliases2 = lam.list_aliases(FunctionName="qa-lam-alias")["Aliases"]
assert not any(a["Name"] == "prod" for a in aliases2)
def test_lambda_publish_version_snapshot(lam):
"""PublishVersion creates a numbered version snapshot."""
code = _zip_lambda("def handler(e,c): return 'v1'")
lam.create_function(
FunctionName="qa-lam-version",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/r",
Handler="index.handler",
Code={"ZipFile": code},
)
ver = lam.publish_version(FunctionName="qa-lam-version")
assert ver["Version"] == "1"
versions = lam.list_versions_by_function(FunctionName="qa-lam-version")["Versions"]
version_nums = [v["Version"] for v in versions]
assert "1" in version_nums
assert "$LATEST" in version_nums
def test_lambda_function_concurrency(lam):
"""PutFunctionConcurrency / GetFunctionConcurrency / DeleteFunctionConcurrency."""
code = _zip_lambda("def handler(e,c): return {}")
lam.create_function(
FunctionName="qa-lam-concurrency",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/r",
Handler="index.handler",
Code={"ZipFile": code},
)
lam.put_function_concurrency(
FunctionName="qa-lam-concurrency",
ReservedConcurrentExecutions=5,
)
resp = lam.get_function_concurrency(FunctionName="qa-lam-concurrency")
assert resp["ReservedConcurrentExecutions"] == 5
lam.delete_function_concurrency(FunctionName="qa-lam-concurrency")
resp2 = lam.get_function_concurrency(FunctionName="qa-lam-concurrency")
assert resp2.get("ReservedConcurrentExecutions") is None
def test_lambda_add_remove_permission(lam):
"""AddPermission / RemovePermission / GetPolicy."""
code = _zip_lambda("def handler(e,c): return {}")
lam.create_function(
FunctionName="qa-lam-policy",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/r",
Handler="index.handler",
Code={"ZipFile": code},
)
lam.add_permission(
FunctionName="qa-lam-policy",
StatementId="allow-s3",
Action="lambda:InvokeFunction",
Principal="s3.amazonaws.com",
)
policy = json.loads(lam.get_policy(FunctionName="qa-lam-policy")["Policy"])
assert any(s["Sid"] == "allow-s3" for s in policy["Statement"])
lam.remove_permission(FunctionName="qa-lam-policy", StatementId="allow-s3")
policy2 = json.loads(lam.get_policy(FunctionName="qa-lam-policy")["Policy"])
assert not any(s["Sid"] == "allow-s3" for s in policy2["Statement"])
def test_lambda_list_functions_pagination(lam):
"""ListFunctions pagination with Marker works correctly."""
for i in range(5):
code = _zip_lambda("def handler(e,c): return {}")
try:
lam.create_function(
FunctionName=f"qa-lam-page-{i}",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/r",
Handler="index.handler",
Code={"ZipFile": code},
)
except ClientError:
pass
resp1 = lam.list_functions(MaxItems=2)
assert len(resp1["Functions"]) <= 2
if "NextMarker" in resp1:
resp2 = lam.list_functions(MaxItems=2, Marker=resp1["NextMarker"])
names1 = {f["FunctionName"] for f in resp1["Functions"]}
names2 = {f["FunctionName"] for f in resp2["Functions"]}
assert not names1 & names2
def test_lambda_invoke_event_type_returns_202(lam):
"""Invoke with InvocationType=Event returns 202 immediately."""
code = _zip_lambda("def handler(e,c): return {}")
try:
lam.create_function(
FunctionName="qa-lam-event-invoke",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/r",
Handler="index.handler",
Code={"ZipFile": code},
)
except ClientError:
pass
resp = lam.invoke(
FunctionName="qa-lam-event-invoke",
InvocationType="Event",
Payload=json.dumps({}),
)
assert resp["StatusCode"] == 202
def test_lambda_invoke_dry_run_returns_204(lam):
"""Invoke with InvocationType=DryRun returns 204."""
code = _zip_lambda("def handler(e,c): return {}")
try:
lam.create_function(
FunctionName="qa-lam-dryrun",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/r",
Handler="index.handler",
Code={"ZipFile": code},
)
except ClientError:
pass
resp = lam.invoke(
FunctionName="qa-lam-dryrun",
InvocationType="DryRun",
Payload=json.dumps({}),
)
assert resp["StatusCode"] == 204
def test_lambda_layer_publish(lam):
import base64, zipfile, io
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("layer.py", "# layer")
zip_bytes = buf.getvalue()
resp = lam.publish_layer_version(
LayerName="my-test-layer",
Description="Test layer",
Content={"ZipFile": zip_bytes},
CompatibleRuntimes=["python3.12"],
)
assert resp["Version"] == 1
assert "my-test-layer" in resp["LayerVersionArn"]
def test_lambda_layer_publish_from_s3(lam, s3):
"""PublishLayerVersion with S3Bucket/S3Key. Contributed by @Baptiste-Garcin (#356)."""
import zipfile, io
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("s3layer.py", "# layer from s3")
zip_bytes = buf.getvalue()
bucket = "layer-bucket"
key = "layers/my-layer.zip"
s3.create_bucket(Bucket=bucket)
s3.put_object(Bucket=bucket, Key=key, Body=zip_bytes)
resp = lam.publish_layer_version(
LayerName="s3-layer",
Description="Layer from S3",
Content={"S3Bucket": bucket, "S3Key": key},
CompatibleRuntimes=["python3.12"],
)
assert resp["Version"] == 1
assert "s3-layer" in resp["LayerVersionArn"]
assert resp["Content"]["CodeSize"] == len(zip_bytes)
assert resp["Content"]["CodeSha256"]
def test_lambda_layer_get_version(lam):
resp = lam.get_layer_version(LayerName="my-test-layer", VersionNumber=1)
assert resp["Version"] == 1
assert resp["Description"] == "Test layer"
def test_lambda_layer_list_versions(lam):
resp = lam.list_layer_versions(LayerName="my-test-layer")
assert len(resp["LayerVersions"]) >= 1
assert resp["LayerVersions"][0]["Version"] == 1
def test_lambda_layer_list_layers(lam):
resp = lam.list_layers()
names = [l["LayerName"] for l in resp["Layers"]]
assert "my-test-layer" in names
def test_lambda_layer_delete_version(lam):
import base64, zipfile, io
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("tmp.py", "")
lam.publish_layer_version(LayerName="delete-layer-test", Content={"ZipFile": buf.getvalue()})
lam.delete_layer_version(LayerName="delete-layer-test", VersionNumber=1)
resp = lam.list_layer_versions(LayerName="delete-layer-test")
assert len(resp["LayerVersions"]) == 0
def test_lambda_function_with_layer(lam):
# Publish layer
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("layer.py", "")
layer_resp = lam.publish_layer_version(LayerName="fn-layer", Content={"ZipFile": buf.getvalue()})
layer_arn = layer_resp["LayerVersionArn"]
# Create function using the layer
fn_zip = io.BytesIO()
with zipfile.ZipFile(fn_zip, "w") as z:
z.writestr("index.py", "def handler(e, c): return {}")
lam.create_function(
FunctionName="fn-with-layer",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test",
Handler="index.handler",
Code={"ZipFile": fn_zip.getvalue()},
Layers=[layer_arn],
)
fn = lam.get_function(FunctionName="fn-with-layer")
assert layer_arn in fn["Configuration"]["Layers"][0]["Arn"]
def test_lambda_layer_content_location(lam):
"""Content.Location should be a non-empty URL pointing to the layer zip."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("mod.py", "X=1")
resp = lam.publish_layer_version(
LayerName="loc-layer",
Content={"ZipFile": buf.getvalue()},
)
assert resp["Content"]["Location"]
assert "loc-layer" in resp["Content"]["Location"]
# Verify the URL actually serves zip data
import urllib.request
data = urllib.request.urlopen(resp["Content"]["Location"]).read()
assert len(data) == resp["Content"]["CodeSize"]
def test_lambda_layer_pagination(lam):
"""Publish 3 versions, paginate with MaxItems=1."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("p.py", "")
for _ in range(3):
lam.publish_layer_version(LayerName="page-layer", Content={"ZipFile": buf.getvalue()})
# List with MaxItems=1 (newest first)
resp = lam.list_layer_versions(LayerName="page-layer", MaxItems=1)
assert len(resp["LayerVersions"]) == 1
assert "NextMarker" in resp
def test_lambda_layer_list_filter_runtime(lam):
"""Filter list_layer_versions by CompatibleRuntime."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("r.py", "")
lam.publish_layer_version(
LayerName="rt-filter-layer",
Content={"ZipFile": buf.getvalue()},
CompatibleRuntimes=["python3.12"],
)
lam.publish_layer_version(
LayerName="rt-filter-layer",
Content={"ZipFile": buf.getvalue()},
CompatibleRuntimes=["nodejs18.x"],
)
resp = lam.list_layer_versions(
LayerName="rt-filter-layer",
CompatibleRuntime="python3.12",
)
assert all("python3.12" in v["CompatibleRuntimes"] for v in resp["LayerVersions"])
def test_lambda_layer_list_filter_architecture(lam):
"""Filter list_layer_versions by CompatibleArchitecture."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("a.py", "")
lam.publish_layer_version(
LayerName="arch-filter-layer",
Content={"ZipFile": buf.getvalue()},
CompatibleArchitectures=["x86_64"],
)
lam.publish_layer_version(
LayerName="arch-filter-layer",
Content={"ZipFile": buf.getvalue()},
CompatibleArchitectures=["arm64"],
)
resp = lam.list_layer_versions(
LayerName="arch-filter-layer",
CompatibleArchitecture="x86_64",
)
assert all("x86_64" in v["CompatibleArchitectures"] for v in resp["LayerVersions"])
def test_lambda_layer_list_layers_pagination(lam):
"""Multiple layers, paginate ListLayers."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("x.py", "")
for i in range(3):
lam.publish_layer_version(
LayerName=f"ll-page-{i}",
Content={"ZipFile": buf.getvalue()},
)
resp = lam.list_layers(MaxItems=1)
assert len(resp["Layers"]) == 1
assert "NextMarker" in resp
def test_lambda_layer_list_layers_filter_runtime(lam):
"""ListLayers filtered by CompatibleRuntime."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("f.py", "")
lam.publish_layer_version(
LayerName="ll-rt-py",
Content={"ZipFile": buf.getvalue()},
CompatibleRuntimes=["python3.12"],
)
lam.publish_layer_version(
LayerName="ll-rt-node",
Content={"ZipFile": buf.getvalue()},
CompatibleRuntimes=["nodejs18.x"],
)
resp = lam.list_layers(CompatibleRuntime="python3.12")
names = [l["LayerName"] for l in resp["Layers"]]
assert "ll-rt-py" in names
assert "ll-rt-node" not in names
def test_lambda_layer_get_version_not_found(lam):
"""Getting a nonexistent layer should raise 404."""
from botocore.exceptions import ClientError
with pytest.raises(ClientError) as exc:
lam.get_layer_version(LayerName="no-such-layer-xyz", VersionNumber=1)
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
def test_lambda_layer_get_version_by_arn(lam):
"""GetLayerVersionByArn resolves by full ARN."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("ba.py", "")
pub = lam.publish_layer_version(
LayerName="by-arn-layer",
Content={"ZipFile": buf.getvalue()},
)
arn = pub["LayerVersionArn"]
resp = lam.get_layer_version_by_arn(Arn=arn)
assert resp["LayerVersionArn"] == arn
assert resp["Version"] == pub["Version"]
def test_lambda_layer_version_permission_add(lam):
"""Add a layer version permission and verify response."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("perm.py", "")
pub = lam.publish_layer_version(
LayerName="perm-layer",
Content={"ZipFile": buf.getvalue()},
)
resp = lam.add_layer_version_permission(
LayerName="perm-layer",
VersionNumber=pub["Version"],
StatementId="allow-all",
Action="lambda:GetLayerVersion",
Principal="*",
)
assert "Statement" in resp
import json
stmt = json.loads(resp["Statement"])
assert stmt["Sid"] == "allow-all"
assert stmt["Action"] == "lambda:GetLayerVersion"
def test_lambda_layer_version_permission_get_policy(lam):
"""Get policy after adding a permission."""
import json
resp = lam.get_layer_version_policy(LayerName="perm-layer", VersionNumber=1)
policy = json.loads(resp["Policy"])
assert len(policy["Statement"]) >= 1
assert policy["Statement"][0]["Sid"] == "allow-all"
def test_lambda_layer_version_permission_remove(lam):
"""Remove a layer version permission."""
lam.remove_layer_version_permission(
LayerName="perm-layer",
VersionNumber=1,
StatementId="allow-all",
)
from botocore.exceptions import ClientError
with pytest.raises(ClientError) as exc:
lam.get_layer_version_policy(LayerName="perm-layer", VersionNumber=1)
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 404
def test_lambda_layer_version_permission_duplicate_sid(lam):
"""Adding a duplicate StatementId should raise conflict."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("dup.py", "")
pub = lam.publish_layer_version(
LayerName="dup-sid-layer",
Content={"ZipFile": buf.getvalue()},
)
lam.add_layer_version_permission(
LayerName="dup-sid-layer",
VersionNumber=pub["Version"],
StatementId="s1",
Action="lambda:GetLayerVersion",
Principal="*",
)
from botocore.exceptions import ClientError
with pytest.raises(ClientError) as exc:
lam.add_layer_version_permission(
LayerName="dup-sid-layer",
VersionNumber=pub["Version"],
StatementId="s1",
Action="lambda:GetLayerVersion",
Principal="*",
)
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] == 409
def test_lambda_layer_version_permission_invalid_action(lam):
"""Only lambda:GetLayerVersion is a valid action."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("inv.py", "")
pub = lam.publish_layer_version(
LayerName="inv-act-layer",
Content={"ZipFile": buf.getvalue()},
)
from botocore.exceptions import ClientError
with pytest.raises(ClientError) as exc:
lam.add_layer_version_permission(
LayerName="inv-act-layer",
VersionNumber=pub["Version"],
StatementId="s1",
Action="lambda:InvokeFunction",
Principal="*",
)
assert exc.value.response["ResponseMetadata"]["HTTPStatusCode"] in (400, 403)
def test_lambda_layer_delete_idempotent(lam):
"""Deleting a nonexistent version should not error."""
lam.delete_layer_version(LayerName="no-such-layer-del", VersionNumber=999)
def test_lambda_warm_worker_invalidation(lam):
"""Create function with code v1, invoke, update code to v2, invoke again β must see v2."""
import io as _io
import zipfile as _zf
fname = "lambda-worker-invalidation-test"
try:
lam.delete_function(FunctionName=fname)
except Exception:
pass
# v1 code
code_v1 = b'def handler(event, context):\n return {"version": 1}\n'
buf1 = _io.BytesIO()
with _zf.ZipFile(buf1, "w") as z:
z.writestr("index.py", code_v1)
lam.create_function(
FunctionName=fname,
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test-role",
Handler="index.handler",
Code={"ZipFile": buf1.getvalue()},
)
# Invoke v1
resp1 = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
payload1 = json.loads(resp1["Payload"].read())
assert payload1["version"] == 1
# Update to v2
code_v2 = b'def handler(event, context):\n return {"version": 2}\n'
buf2 = _io.BytesIO()
with _zf.ZipFile(buf2, "w") as z:
z.writestr("index.py", code_v2)
lam.update_function_code(FunctionName=fname, ZipFile=buf2.getvalue())
# Invoke v2
resp2 = lam.invoke(FunctionName=fname, Payload=json.dumps({}))
payload2 = json.loads(resp2["Payload"].read())
assert payload2["version"] == 2
def test_lambda_event_invoke_config_crud(lam):
"""Put/Get/Delete EventInvokeConfig lifecycle."""
code = "def handler(e,c): return {}"
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", code)
lam.create_function(
FunctionName="eic-fn", Runtime="python3.11",
Role=_LAMBDA_ROLE, Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
)
lam.put_function_event_invoke_config(
FunctionName="eic-fn",
MaximumRetryAttempts=1,
MaximumEventAgeInSeconds=300,
)
cfg = lam.get_function_event_invoke_config(FunctionName="eic-fn")
assert cfg["MaximumRetryAttempts"] == 1
assert cfg["MaximumEventAgeInSeconds"] == 300
lam.delete_function_event_invoke_config(FunctionName="eic-fn")
from botocore.exceptions import ClientError
with pytest.raises(ClientError):
lam.get_function_event_invoke_config(FunctionName="eic-fn")
lam.delete_function(FunctionName="eic-fn")
def test_lambda_provisioned_concurrency_crud(lam):
"""Put/Get/Delete ProvisionedConcurrencyConfig lifecycle."""
code = "def handler(e,c): return {}"
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("index.py", code)
lam.create_function(
FunctionName="pc-fn", Runtime="python3.11",
Role=_LAMBDA_ROLE, Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
Publish=True,
)
versions = lam.list_versions_by_function(FunctionName="pc-fn")["Versions"]
ver = [v for v in versions if v["Version"] != "$LATEST"][0]["Version"]
lam.put_provisioned_concurrency_config(
FunctionName="pc-fn",
Qualifier=ver,
ProvisionedConcurrentExecutions=5,
)
cfg = lam.get_provisioned_concurrency_config(
FunctionName="pc-fn", Qualifier=ver,
)
assert cfg["RequestedProvisionedConcurrentExecutions"] == 5
lam.delete_provisioned_concurrency_config(
FunctionName="pc-fn", Qualifier=ver,
)
from botocore.exceptions import ClientError
with pytest.raises(ClientError):
lam.get_provisioned_concurrency_config(FunctionName="pc-fn", Qualifier=ver)
lam.delete_function(FunctionName="pc-fn")
def test_lambda_image_create_invoke(lam):
"""CreateFunction with PackageType Image + GetFunction returns ImageUri."""
lam.create_function(
FunctionName="img-test-v39",
PackageType="Image",
Code={"ImageUri": "my-repo/my-image:latest"},
Role="arn:aws:iam::000000000000:role/test",
Timeout=30,
)
desc = lam.get_function(FunctionName="img-test-v39")
assert desc["Configuration"]["PackageType"] == "Image"
assert desc["Code"]["RepositoryType"] == "ECR"
assert desc["Code"]["ImageUri"] == "my-repo/my-image:latest"
lam.delete_function(FunctionName="img-test-v39")
def test_lambda_update_code_image_uri(lam):
"""UpdateFunctionCode with ImageUri updates the image."""
lam.create_function(
FunctionName="img-update-v39",
PackageType="Image",
Code={"ImageUri": "my-repo/my-image:v1"},
Role="arn:aws:iam::000000000000:role/test",
)
lam.update_function_code(FunctionName="img-update-v39", ImageUri="my-repo/my-image:v2")
desc = lam.get_function(FunctionName="img-update-v39")
assert desc["Code"]["ImageUri"] == "my-repo/my-image:v2"
lam.delete_function(FunctionName="img-update-v39")
def test_lambda_provided_runtime_create(lam):
"""CreateFunction with provided.al2023 runtime accepts bootstrap handler."""
import zipfile, io
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
zf.writestr("bootstrap", "#!/bin/sh\necho ok\n")
lam.create_function(
FunctionName="provided-test-v39",
Runtime="provided.al2023",
Handler="bootstrap",
Code={"ZipFile": buf.getvalue()},
Role="arn:aws:iam::000000000000:role/test",
)
desc = lam.get_function_configuration(FunctionName="provided-test-v39")
assert desc["Runtime"] == "provided.al2023"
assert desc["Handler"] == "bootstrap"
lam.delete_function(FunctionName="provided-test-v39")
@pytest.mark.skipif(
os.environ.get("LAMBDA_EXECUTOR", "").lower() != "docker",
reason="requires LAMBDA_EXECUTOR=docker and Docker daemon",
)
def test_lambda_provided_runtime_docker_invoke(lam):
"""Invoke a provided.al2023 Lambda via the Docker executor.
Uses a shell-script bootstrap that implements the Lambda Runtime API
(GET /invocation/next, POST /invocation/{id}/response).
"""
# Shell bootstrap implementing the Lambda Runtime API protocol.
# Must loop: the RIE expects the bootstrap to poll for invocations.
bootstrap_script = (
"#!/bin/sh\n"
'RUNTIME_API="${AWS_LAMBDA_RUNTIME_API}"\n'
"while true; do\n"
' RESP=$(curl -s -D /tmp/headers '
'"http://${RUNTIME_API}/2018-06-01/runtime/invocation/next")\n'
' REQUEST_ID=$(grep -i "Lambda-Runtime-Aws-Request-Id" /tmp/headers '
'| tr -d "\\r" | cut -d" " -f2)\n'
' curl -s -X POST '
'"http://${RUNTIME_API}/2018-06-01/runtime/invocation/${REQUEST_ID}/response" '
"-d '{\"statusCode\":200,\"body\":\"hello from provided\"}'\n"
"done\n"
)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as zf:
info = zipfile.ZipInfo("bootstrap")
info.external_attr = 0o755 << 16 # executable
zf.writestr(info, bootstrap_script)
func_name = f"provided-docker-test-{_uuid_mod.uuid4().hex[:8]}"
lam.create_function(
FunctionName=func_name,
Runtime="provided.al2023",
Handler="bootstrap",
Code={"ZipFile": buf.getvalue()},
Role="arn:aws:iam::000000000000:role/test",
Timeout=30,
)
try:
resp = lam.invoke(FunctionName=func_name, Payload=json.dumps({"key": "value"}))
payload = json.loads(resp["Payload"].read())
assert payload["statusCode"] == 200
assert payload["body"] == "hello from provided"
finally:
lam.delete_function(FunctionName=func_name)
def test_apigwv2_nodejs_lambda_proxy(lam, apigw):
"""API Gateway v2 HTTP API should invoke Node.js Lambda via warm worker, not return mock."""
import urllib.request as _urlreq
import uuid as _uuid
from botocore.exceptions import ClientError
fname = f"apigwv2-node-{_uuid.uuid4().hex[:8]}"
api_id = None
code = (
"exports.handler = async (event) => ({"
" statusCode: 200,"
" body: JSON.stringify({ route: event.routeKey, method: event.requestContext.http.method })"
"});"
)
try:
lam.create_function(
FunctionName=fname,
Runtime="nodejs20.x",
Role="arn:aws:iam::000000000000:role/test-role",
Handler="index.handler",
Code={"ZipFile": _make_zip_js(code, "index.js")},
)
api_id = apigw.create_api(Name=f"v2-node-{fname}", ProtocolType="HTTP")["ApiId"]
int_id = apigw.create_integration(
ApiId=api_id,
IntegrationType="AWS_PROXY",
IntegrationUri=f"arn:aws:lambda:us-east-1:000000000000:function:{fname}",
PayloadFormatVersion="2.0",
)["IntegrationId"]
apigw.create_route(ApiId=api_id, RouteKey="GET /test", Target=f"integrations/{int_id}")
apigw.create_stage(ApiId=api_id, StageName="$default")
req = _urlreq.Request(
f"http://{api_id}.execute-api.localhost:{_EXECUTE_PORT}/$default/test",
method="GET",
)
req.add_header("Host", f"{api_id}.execute-api.localhost:{_EXECUTE_PORT}")
resp = _urlreq.urlopen(req).read().decode()
body = json.loads(resp)
assert body.get("route") == "GET /test", f"Expected handler result, got: {resp}"
assert body.get("method") == "GET"
finally:
if api_id is not None:
try:
apigw.delete_api(ApiId=api_id)
except ClientError:
pass
try:
lam.delete_function(FunctionName=fname)
except ClientError:
pass
def test_lambda_nodejs_esm_mjs_handler(lam):
"""Node.js .mjs (ESM) handlers should be loaded via dynamic import() fallback.
Creates a ZIP with two .mjs files:
- utils.mjs: exports a helper function using ESM `export` syntax
- index.mjs: imports utils.mjs via ESM `import` statement and uses it
This verifies that:
1. .mjs files are loaded via import() instead of require()
2. ESM import/export syntax works between modules
3. The handler's return value is correctly propagated
"""
fname = f"lam-esm-{_uuid_mod.uuid4().hex[:8]}"
utils_code = (
"export function greet(name) {\n"
" return `Hello, ${name} from ESM!`;\n"
"}\n"
"\n"
"export const VERSION = '1.0.0';\n"
)
handler_code = (
"import { greet, VERSION } from './utils.mjs';\n"
"\n"
"export const handler = async (event) => {\n"
" const name = event.name || 'World';\n"
" return {\n"
" statusCode: 200,\n"
" body: JSON.stringify({\n"
" message: greet(name),\n"
" version: VERSION,\n"
" esm: true,\n"
" }),\n"
" };\n"
"};\n"
)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("index.mjs", handler_code)
z.writestr("utils.mjs", utils_code)
lam.create_function(
FunctionName=fname,
Runtime="nodejs20.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
)
try:
resp = lam.invoke(
FunctionName=fname,
Payload=json.dumps({"name": "MiniStack"}),
)
assert resp["StatusCode"] == 200
assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"
payload = json.loads(resp["Payload"].read())
assert payload["statusCode"] == 200
body = json.loads(payload["body"])
assert body["message"] == "Hello, MiniStack from ESM!"
assert body["version"] == "1.0.0"
assert body["esm"] is True
finally:
lam.delete_function(FunctionName=fname)
def test_lambda_warm_worker_uses_layer(lam):
"""Warm worker should extract layers and make their code available to the handler."""
# Create a layer with a Python module
layer_buf = io.BytesIO()
with zipfile.ZipFile(layer_buf, "w") as z:
z.writestr("python/myhelper.py", "LAYER_VALUE = 'from-layer'\n")
layer_resp = lam.publish_layer_version(
LayerName="warm-layer-test",
Content={"ZipFile": layer_buf.getvalue()},
CompatibleRuntimes=["python3.12"],
)
layer_arn = layer_resp["LayerVersionArn"]
# Create a function that imports from the layer
func_code = (
"import myhelper\n"
"def handler(event, context):\n"
" return {'value': myhelper.LAYER_VALUE}\n"
)
func_buf = io.BytesIO()
with zipfile.ZipFile(func_buf, "w") as z:
z.writestr("index.py", func_code)
fname = f"warm-layer-{_uuid_mod.uuid4().hex[:8]}"
lam.create_function(
FunctionName=fname,
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test",
Handler="index.handler",
Code={"ZipFile": func_buf.getvalue()},
Layers=[layer_arn],
)
try:
resp = lam.invoke(FunctionName=fname, Payload=b"{}")
assert resp["StatusCode"] == 200
assert "FunctionError" not in resp, f"Lambda error: {resp.get('FunctionError')}"
payload = json.loads(resp["Payload"].read())
assert payload["value"] == "from-layer"
finally:
lam.delete_function(FunctionName=fname)
def test_lambda_nodejs_esm_type_module(lam):
"""Node.js ESM via package.json type:module should trigger ERR_REQUIRE_ESM fallback."""
fname = f"lam-esm-type-{_uuid_mod.uuid4().hex[:8]}"
handler_code = (
"export const handler = async (event) => ({\n"
" statusCode: 200,\n"
" body: 'type-module-works',\n"
"});\n"
)
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("index.js", handler_code)
z.writestr("package.json", '{"type": "module"}')
lam.create_function(
FunctionName=fname,
Runtime="nodejs20.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": buf.getvalue()},
)
try:
resp = lam.invoke(FunctionName=fname, Payload=b"{}")
assert resp["StatusCode"] == 200
assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"
payload = json.loads(resp["Payload"].read())
assert payload["statusCode"] == 200
assert payload["body"] == "type-module-works"
finally:
lam.delete_function(FunctionName=fname)
def test_lambda_warm_worker_nodejs_uses_layer(lam):
"""Warm worker should extract Node.js layers and make packages available via require()."""
# Create a layer with a Node.js module under nodejs/node_modules/
layer_buf = io.BytesIO()
with zipfile.ZipFile(layer_buf, "w") as z:
z.writestr(
"nodejs/node_modules/layerhelper/index.js",
"module.exports.LAYER_VALUE = 'from-node-layer';\n",
)
layer_resp = lam.publish_layer_version(
LayerName="warm-node-layer-test",
Content={"ZipFile": layer_buf.getvalue()},
CompatibleRuntimes=["nodejs20.x"],
)
layer_arn = layer_resp["LayerVersionArn"]
# Create a Node.js function that requires the layer package
handler_code = (
"const helper = require('layerhelper');\n"
"exports.handler = async (event) => {\n"
" return { value: helper.LAYER_VALUE };\n"
"};\n"
)
func_buf = io.BytesIO()
with zipfile.ZipFile(func_buf, "w") as z:
z.writestr("index.js", handler_code)
fname = f"warm-node-layer-{_uuid_mod.uuid4().hex[:8]}"
lam.create_function(
FunctionName=fname,
Runtime="nodejs20.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": func_buf.getvalue()},
Layers=[layer_arn],
)
try:
resp = lam.invoke(FunctionName=fname, Payload=b"{}")
assert resp["StatusCode"] == 200
assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"
payload = json.loads(resp["Payload"].read())
assert payload["value"] == "from-node-layer"
finally:
lam.delete_function(FunctionName=fname)
def test_lambda_warm_worker_nodejs_esm_uses_layer(lam):
"""ESM .mjs handler must be able to import packages from a Lambda Layer.
This is the combined case of ESM support (PR #238) and Layer extraction
(PR #236). Node.js ESM import() does not use NODE_PATH, so the runtime
symlinks layer packages into code/node_modules/ for ancestor-tree resolution.
"""
# Create a layer with a Node.js package under nodejs/node_modules/
layer_buf = io.BytesIO()
with zipfile.ZipFile(layer_buf, "w") as z:
z.writestr(
"nodejs/node_modules/esmhelper/index.js",
"module.exports.LAYER_VALUE = 'from-esm-layer';\n",
)
layer_resp = lam.publish_layer_version(
LayerName="warm-esm-layer-test",
Content={"ZipFile": layer_buf.getvalue()},
CompatibleRuntimes=["nodejs20.x"],
)
layer_arn = layer_resp["LayerVersionArn"]
# Create an ESM handler that uses native import to load the layer package.
# The layer package exports via CJS but Node.js ESM can import CJS modules.
# Native import does NOT use NODE_PATH β this is the bug we are testing.
handler_code = (
"import helper from 'esmhelper';\n"
"export const handler = async (event) => {\n"
" return { value: helper.LAYER_VALUE, esm: true };\n"
"};\n"
)
func_buf = io.BytesIO()
with zipfile.ZipFile(func_buf, "w") as z:
z.writestr("index.mjs", handler_code)
fname = f"warm-esm-layer-{_uuid_mod.uuid4().hex[:8]}"
lam.create_function(
FunctionName=fname,
Runtime="nodejs20.x",
Role=_LAMBDA_ROLE,
Handler="index.handler",
Code={"ZipFile": func_buf.getvalue()},
Layers=[layer_arn],
)
try:
resp = lam.invoke(FunctionName=fname, Payload=b"{}")
assert resp["StatusCode"] == 200
assert "FunctionError" not in resp, f"Lambda error: {resp['Payload'].read().decode()}"
payload = json.loads(resp["Payload"].read())
assert payload["value"] == "from-esm-layer"
assert payload["esm"] is True
finally:
lam.delete_function(FunctionName=fname)
# ---------------------------------------------------------------------------
# Terraform compatibility tests
# ---------------------------------------------------------------------------
def test_lambda_image_no_default_runtime_handler(lam):
"""Image-based functions must not get default runtime/handler values."""
fname = "tf-compat-image-no-defaults"
try:
lam.delete_function(FunctionName=fname)
except ClientError:
pass
resp = lam.create_function(
FunctionName=fname,
PackageType="Image",
Code={"ImageUri": "my-repo/my-image:latest"},
Role=_LAMBDA_ROLE,
Timeout=30,
)
try:
assert resp["PackageType"] == "Image"
assert resp["Runtime"] == "", f"Expected empty Runtime for Image, got {resp['Runtime']!r}"
assert resp["Handler"] == "", f"Expected empty Handler for Image, got {resp['Handler']!r}"
finally:
lam.delete_function(FunctionName=fname)
def test_lambda_image_preserves_image_config(lam):
"""ImageConfig provided at creation must be preserved in the GetFunction response."""
fname = "tf-compat-image-config"
try:
lam.delete_function(FunctionName=fname)
except ClientError:
pass
lam.create_function(
FunctionName=fname,
PackageType="Image",
Code={"ImageUri": "my-repo/my-image:latest"},
Role=_LAMBDA_ROLE,
ImageConfig={"Command": ["main.lambda_handler"]},
)
try:
get_resp = lam.get_function(FunctionName=fname)
cfg = get_resp["Configuration"]
assert "ImageConfigResponse" in cfg, "ImageConfigResponse missing from get_function response"
assert cfg["ImageConfigResponse"]["ImageConfig"]["Command"] == ["main.lambda_handler"]
finally:
lam.delete_function(FunctionName=fname)
def test_lambda_empty_dead_letter_config(lam):
"""Functions without DeadLetterConfig must return empty dict, not {TargetArn: ''}."""
fname = "tf-compat-no-dlc"
try:
lam.delete_function(FunctionName=fname)
except ClientError:
pass
resp = lam.create_function(
FunctionName=fname,
Runtime="python3.12",
Handler="index.handler",
Role=_LAMBDA_ROLE,
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
try:
dlc = resp.get("DeadLetterConfig", {})
assert dlc == {} or "TargetArn" not in dlc or dlc.get("TargetArn") == "", \
f"Expected empty DeadLetterConfig, got {dlc!r}"
assert dlc.get("TargetArn") is None or dlc == {}, \
f"DeadLetterConfig should not have TargetArn when unconfigured, got {dlc!r}"
finally:
lam.delete_function(FunctionName=fname)
def test_esm_sqs_no_starting_position(lam, sqs):
"""SQS event source mappings must not include StartingPosition."""
fname = "tf-compat-esm-sqs"
try:
lam.delete_function(FunctionName=fname)
except ClientError:
pass
lam.create_function(
FunctionName=fname,
Runtime="python3.12",
Handler="index.handler",
Role=_LAMBDA_ROLE,
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
q_url = sqs.create_queue(QueueName="tf-compat-esm-queue")["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
esm_uuid = None
try:
resp = lam.create_event_source_mapping(
EventSourceArn=q_arn,
FunctionName=fname,
BatchSize=5,
Enabled=True,
)
esm_uuid = resp["UUID"]
assert "StartingPosition" not in resp, \
f"SQS ESM should not have StartingPosition, got {resp.get('StartingPosition')!r}"
get_resp = lam.get_event_source_mapping(UUID=esm_uuid)
assert "StartingPosition" not in get_resp, \
"StartingPosition should not appear in get_event_source_mapping for SQS"
finally:
if esm_uuid:
lam.delete_event_source_mapping(UUID=esm_uuid)
lam.delete_function(FunctionName=fname)
sqs.delete_queue(QueueUrl=q_url)
def test_esm_kinesis_has_starting_position(lam, kin):
"""Kinesis event source mappings must include StartingPosition."""
fname = "tf-compat-esm-kinesis"
stream_name = "tf-compat-esm-stream"
try:
lam.delete_function(FunctionName=fname)
except ClientError:
pass
try:
kin.delete_stream(StreamName=stream_name, EnforceConsumerDeletion=True)
except ClientError:
pass
lam.create_function(
FunctionName=fname,
Runtime="python3.12",
Handler="index.handler",
Role=_LAMBDA_ROLE,
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
kin.create_stream(StreamName=stream_name, ShardCount=1)
stream_arn = kin.describe_stream(
StreamName=stream_name
)["StreamDescription"]["StreamARN"]
esm_uuid = None
try:
resp = lam.create_event_source_mapping(
EventSourceArn=stream_arn,
FunctionName=fname,
StartingPosition="TRIM_HORIZON",
BatchSize=100,
Enabled=True,
)
esm_uuid = resp["UUID"]
assert "StartingPosition" in resp, "Kinesis ESM must include StartingPosition"
assert resp["StartingPosition"] == "TRIM_HORIZON"
finally:
if esm_uuid:
lam.delete_event_source_mapping(UUID=esm_uuid)
lam.delete_function(FunctionName=fname)
try:
kin.delete_stream(StreamName=stream_name, EnforceConsumerDeletion=True)
except ClientError:
pass
def test_esm_response_no_function_name_field(lam, sqs):
"""ESM API responses should contain FunctionArn but not FunctionName (matching AWS)."""
fname = "tf-compat-esm-no-fname"
try:
lam.delete_function(FunctionName=fname)
except ClientError:
pass
lam.create_function(
FunctionName=fname,
Runtime="python3.12",
Handler="index.handler",
Role=_LAMBDA_ROLE,
Code={"ZipFile": _make_zip(_LAMBDA_CODE)},
)
q_url = sqs.create_queue(QueueName="tf-compat-esm-fname-queue")["QueueUrl"]
q_arn = sqs.get_queue_attributes(
QueueUrl=q_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
esm_uuid = None
try:
resp = lam.create_event_source_mapping(
EventSourceArn=q_arn,
FunctionName=fname,
BatchSize=5,
Enabled=True,
)
esm_uuid = resp["UUID"]
assert "FunctionArn" in resp, "ESM response must include FunctionArn"
assert fname in resp["FunctionArn"], "FunctionArn must contain the function name"
finally:
if esm_uuid:
lam.delete_event_source_mapping(UUID=esm_uuid)
lam.delete_function(FunctionName=fname)
sqs.delete_queue(QueueUrl=q_url)
def test_lambda_update_function_configuration_layers(lam):
"""Attaching a layer via update-function-configuration should normalize ARN strings
to {Arn, CodeSize} dicts β regression test for 'str' object has no attribute 'get'."""
buf = io.BytesIO()
with zipfile.ZipFile(buf, "w") as z:
z.writestr("util.py", "# layer code")
layer_resp = lam.publish_layer_version(
LayerName="update-cfg-layer", Content={"ZipFile": buf.getvalue()},
)
layer_arn = layer_resp["LayerVersionArn"]
fn_zip = io.BytesIO()
with zipfile.ZipFile(fn_zip, "w") as z:
z.writestr("index.py", "def handler(e, c): return {}")
lam.create_function(
FunctionName="fn-update-layer-test",
Runtime="python3.12",
Role="arn:aws:iam::000000000000:role/test",
Handler="index.handler",
Code={"ZipFile": fn_zip.getvalue()},
)
resp = lam.update_function_configuration(
FunctionName="fn-update-layer-test",
Layers=[layer_arn],
)
# Response Layers must be dicts with Arn key, not raw strings
assert len(resp["Layers"]) == 1
assert isinstance(resp["Layers"][0], dict)
assert resp["Layers"][0]["Arn"] == layer_arn
# GetFunction must also return normalized layer dicts
fn = lam.get_function(FunctionName="fn-update-layer-test")
assert fn["Configuration"]["Layers"][0]["Arn"] == layer_arn
# ============================================================================
# Unit tests β Lambda warm-container pool, ESM filter, CW Logs emitter,
# event-stream framing, throttle response shape. These mock containers and
# don't hit the live ministack server, so they run even without Docker.
# Originally lived in tests/test_lambda_pool.py β merged here for one-file-per-service.
# ============================================================================
import time
from unittest.mock import MagicMock
import pytest
import ministack.services.lambda_svc as lsvc
from ministack.core.responses import set_request_account_id
@pytest.fixture(autouse=True)
def _clear_pool():
"""Fresh pool before every test; also clear after so later tests don't see residue."""
lsvc._warm_pool.clear()
yield
lsvc._warm_pool.clear()
def _mk_container(running: bool = True):
"""Fake container with a .reload() that sets status, matching docker-py interface."""
c = MagicMock()
c.status = "running" if running else "exited"
def _reload():
# No-op β container.status stays at whatever was set last.
pass
c.reload.side_effect = _reload
return c
# ββββββββββββββββββββββββββββββββ pool key ββββββββββββββββββββββββββββββββββ
def test_pool_key_scopes_by_account():
"""Same function in two accounts β two distinct keys β two distinct pools."""
set_request_account_id("111111111111")
k_a = lsvc._warm_pool_key("fn", {"CodeSha256": "abc"})
set_request_account_id("222222222222")
k_b = lsvc._warm_pool_key("fn", {"CodeSha256": "abc"})
assert k_a != k_b
assert k_a.startswith("111111111111:")
assert k_b.startswith("222222222222:")
def test_pool_key_differs_by_package_type():
set_request_account_id("111111111111")
k_zip = lsvc._warm_pool_key("fn", {"CodeSha256": "abc"})
k_img = lsvc._warm_pool_key("fn", {"PackageType": "Image", "ImageUri": "my/img:v1"})
assert k_zip != k_img
assert ":zip:" in k_zip
assert ":image:" in k_img
def test_pool_key_differs_by_code_sha():
"""Code update β new key β cold start (doesn't accidentally reuse old container)."""
set_request_account_id("111111111111")
k1 = lsvc._warm_pool_key("fn", {"CodeSha256": "sha-v1"})
k2 = lsvc._warm_pool_key("fn", {"CodeSha256": "sha-v2"})
assert k1 != k2
def test_pool_key_differs_by_image_uri():
set_request_account_id("111111111111")
k1 = lsvc._warm_pool_key("fn", {"PackageType": "Image", "ImageUri": "img:v1"})
k2 = lsvc._warm_pool_key("fn", {"PackageType": "Image", "ImageUri": "img:v2"})
assert k1 != k2
# ββββββββββββββββββββββββββββ acquire / spawn / release βββββββββββββββββββββ
def test_acquire_on_empty_pool_signals_spawn():
entry, reason = lsvc._pool_acquire("k", max_concurrency=None)
assert entry is None
assert reason == "spawn"
def test_register_then_reacquire_reuses_same_entry():
c = _mk_container()
entry1 = lsvc._pool_register("k", c, tmpdir=None)
assert entry1["in_use"] is True
# While in_use, next acquire can't reuse it β signals spawn.
entry2, reason = lsvc._pool_acquire("k", max_concurrency=None)
assert entry2 is None
assert reason == "spawn"
# After release, the same container is reused.
lsvc._pool_release(entry1)
assert entry1["in_use"] is False
entry3, reason = lsvc._pool_acquire("k", max_concurrency=None)
assert entry3 is entry1
assert reason == "reused"
assert entry3["in_use"] is True
def test_multiple_concurrent_invocations_get_separate_entries():
"""Two concurrent invocations must land on two distinct pool entries (not the same container)."""
c1 = _mk_container()
c2 = _mk_container()
e1 = lsvc._pool_register("k", c1, tmpdir=None)
# e1 is in_use β next acquire signals spawn, simulating cold start
_, reason = lsvc._pool_acquire("k", max_concurrency=None)
assert reason == "spawn"
e2 = lsvc._pool_register("k", c2, tmpdir=None)
assert e1 is not e2
assert e1["container"] is c1
assert e2["container"] is c2
assert len(lsvc._warm_pool["k"]) == 2
def test_function_concurrency_cap_rejects_when_full():
"""ReservedConcurrentExecutions=2 β 3rd concurrent invocation gets func_cap."""
for _ in range(2):
lsvc._pool_register("k", _mk_container(), tmpdir=None)
entry, reason = lsvc._pool_acquire("k", max_concurrency=2)
assert entry is None
assert reason == "func_cap"
def test_function_concurrency_cap_none_is_unbounded():
"""No ReservedConcurrentExecutions β can always spawn."""
for _ in range(50):
lsvc._pool_register("k", _mk_container(), tmpdir=None)
entry, reason = lsvc._pool_acquire("k", max_concurrency=None)
assert entry is None
assert reason == "spawn"
def test_account_concurrency_cap_rejects(monkeypatch):
"""Global account cap: 3 in-use total β 4th is throttled as acct_cap."""
monkeypatch.setattr(lsvc, "_ACCOUNT_CONCURRENCY_CAP", 3)
# 3 in-use entries across two pool keys
lsvc._pool_register("k1", _mk_container(), tmpdir=None)
lsvc._pool_register("k1", _mk_container(), tmpdir=None)
lsvc._pool_register("k2", _mk_container(), tmpdir=None)
entry, reason = lsvc._pool_acquire("k2", max_concurrency=None)
assert entry is None
assert reason == "acct_cap"
# ββββββββββββββββββββββββββββ lifecycle: dead, remove, evict, clear βββββββββ
def test_dead_containers_are_pruned_on_acquire():
"""Pool must not hand out a dead container on reuse."""
dead = _mk_container(running=False)
alive_entry = lsvc._pool_register("k", _mk_container(running=True), tmpdir=None)
# Release alive so it becomes reusable
lsvc._pool_release(alive_entry)
# Sneak a dead one into the pool directly
lsvc._warm_pool["k"].append({
"container": dead, "tmpdir": None, "in_use": False,
"last_used": time.time(), "created": time.time(),
})
assert len(lsvc._warm_pool["k"]) == 2
# Acquire β dead one pruned, alive one reused
entry, reason = lsvc._pool_acquire("k", max_concurrency=None)
assert reason == "reused"
assert entry["container"] is alive_entry["container"]
assert len(lsvc._warm_pool["k"]) == 1
def test_pool_remove_kills_and_unregisters():
entry = lsvc._pool_register("k", _mk_container(), tmpdir=None)
lsvc._pool_remove(entry)
assert entry not in lsvc._warm_pool.get("k", [])
entry["container"].stop.assert_called()
entry["container"].remove.assert_called()
def test_pool_evict_idle_removes_only_expired_and_not_in_use(monkeypatch):
monkeypatch.setattr(lsvc, "_WARM_CONTAINER_TTL", 60)
busy = lsvc._pool_register("k", _mk_container(), tmpdir=None) # in_use=True
idle_old = lsvc._pool_register("k", _mk_container(), tmpdir=None)
lsvc._pool_release(idle_old)
idle_old["last_used"] = time.time() - 300 # past TTL
idle_fresh = lsvc._pool_register("k", _mk_container(), tmpdir=None)
lsvc._pool_release(idle_fresh) # last_used = now, within TTL
lsvc._pool_evict_idle()
remaining = lsvc._warm_pool.get("k", [])
assert busy in remaining # still in use β must not be evicted
assert idle_fresh in remaining # under TTL β kept
assert idle_old not in remaining
idle_old["container"].stop.assert_called()
def test_pool_clear_all_kills_everything():
for key in ("a", "b", "c"):
lsvc._pool_register(key, _mk_container(), tmpdir=None)
victims = [e for lst in lsvc._warm_pool.values() for e in lst]
assert len(victims) == 3
lsvc._pool_clear_all()
assert lsvc._warm_pool == {}
for v in victims:
v["container"].stop.assert_called()
v["container"].remove.assert_called()
# ββββββββββββββββββββββββββββ multi-tenancy βββββββββββββββββββββββββββββββββ
def test_two_accounts_get_independent_pools():
"""Invocations in account A must not pick up account B's containers."""
set_request_account_id("111111111111")
k_a = lsvc._warm_pool_key("fn", {"CodeSha256": "sha"})
c_a = _mk_container()
e_a = lsvc._pool_register(k_a, c_a, tmpdir=None)
lsvc._pool_release(e_a)
set_request_account_id("222222222222")
k_b = lsvc._warm_pool_key("fn", {"CodeSha256": "sha"})
assert k_a != k_b
entry, reason = lsvc._pool_acquire(k_b, max_concurrency=None)
assert entry is None
assert reason == "spawn" # account B must cold-start; can't reuse A's container
def test_throttle_response_shape_matches_aws():
"""The throttle response body must match the AWS TooManyRequestsException shape."""
r = lsvc._throttle_response(
reason_code="ReservedFunctionConcurrentInvocationLimitExceeded",
msg="Rate Exceeded",
retry_after=1,
)
assert r["throttle"] is True
assert r["error"] is True
body = r["body"]
assert body["__type"] == "TooManyRequestsException"
assert body["Reason"] == "ReservedFunctionConcurrentInvocationLimitExceeded"
assert "retryAfterSeconds" in body
assert "message" in body
# ββββββββββββββββββββ async retry + DLQ routing βββββββββββββββββββββββββββββ
def test_route_async_failure_to_sqs_dlq():
"""Async invoke final failure routes an AWS-shaped envelope to the SQS DLQ."""
import ministack.services.sqs as _sqs
set_request_account_id("000000000000")
# Create a queue directly in the internal state
url = "http://localhost:4566/000000000000/dlq-test"
arn = "arn:aws:sqs:us-east-1:000000000000:dlq-test"
_sqs._queues[url] = {
"messages": [], "attributes": {"QueueArn": arn},
"is_fifo": False, "dedup_cache": {}, "fifo_seq": 0,
}
try:
lsvc._route_async_failure(
target_arn=arn,
func_name="doesnt-matter",
event={"input": "hi"},
result={"error": True, "function_error": "Unhandled",
"body": {"errorType": "Handler", "errorMessage": "boom"}},
)
assert len(_sqs._queues[url]["messages"]) == 1
import json as _json
envelope = _json.loads(_sqs._queues[url]["messages"][0]["body"])
assert envelope["requestPayload"] == {"input": "hi"}
assert envelope["requestContext"]["condition"] == "RetriesExhausted"
assert envelope["responseContext"]["functionError"] == "Unhandled"
assert envelope["responsePayload"]["errorMessage"] == "boom"
finally:
_sqs._queues.pop(url, None)
def test_route_async_failure_to_sns_topic():
"""Async invoke final failure can target an SNS topic (OnFailure destination)."""
import ministack.services.sns as _sns
set_request_account_id("000000000000")
arn = "arn:aws:sns:us-east-1:000000000000:async-fail"
_sns._topics[arn] = {
"arn": arn, "name": "async-fail",
"subscriptions": [], "messages": [], "tags": {}, "attributes": {},
}
try:
# Monkey-patch _fanout to observe the call without needing subscribers
called = {}
real_fanout = _sns._fanout
def _capture(topic_arn, msg_id, message, subject, *args, **kwargs):
called["topic_arn"] = topic_arn
called["message"] = message
called["subject"] = subject
_sns._fanout = _capture
try:
lsvc._route_async_failure(
target_arn=arn,
func_name="doesnt-matter",
event={"k": "v"},
result={"error": True, "function_error": "Handled",
"body": {"errorType": "X"}},
)
assert called.get("topic_arn") == arn
assert "requestPayload" in called.get("message", "")
finally:
_sns._fanout = real_fanout
finally:
_sns._topics.pop(arn, None)
def test_route_async_failure_unknown_target_logs_and_returns():
"""Unknown DLQ ARN must not raise β just logs."""
set_request_account_id("000000000000")
# Should NOT raise
lsvc._route_async_failure(
target_arn="arn:aws:sqs:us-east-1:000000000000:does-not-exist",
func_name="x", event={}, result={"error": True, "body": {}},
)
# ββββββββββββββββββββ RIE result β function_error classification ββββββββββββ
def test_lambda_strict_hard_fails_when_docker_unavailable(monkeypatch):
"""LAMBDA_STRICT=1 + no Docker β Runtime.DockerUnavailable, NO fallback to warm/local."""
monkeypatch.setattr(lsvc, "LAMBDA_STRICT", True)
monkeypatch.setattr(lsvc, "_docker_available", False)
func = {"config": {
"FunctionName": "strict-test",
"Runtime": "python3.12",
"PackageType": "Zip",
"CodeSha256": "abc",
"Timeout": 3,
"MemorySize": 128,
}, "code_zip": b"\x00"}
result = lsvc._execute_function_docker(func, {"k": "v"})
assert result.get("error") is True
assert result["body"]["errorType"] == "Runtime.DockerUnavailable"
def test_lambda_permissive_falls_back_to_warm_without_docker(monkeypatch):
"""Default (LAMBDA_STRICT=False) + no Docker + python runtime β warm fallback."""
monkeypatch.setattr(lsvc, "LAMBDA_STRICT", False)
monkeypatch.setattr(lsvc, "_docker_available", False)
called = {"warm": False}
def _fake_warm(func, event):
called["warm"] = True
return {"body": {"ok": True}}
monkeypatch.setattr(lsvc, "_execute_function_warm", _fake_warm)
func = {"config": {
"FunctionName": "perm-test",
"Runtime": "python3.12",
"PackageType": "Zip",
"CodeSha256": "abc",
"Timeout": 3,
"MemorySize": 128,
}, "code_zip": b"\x00"}
lsvc._execute_function_docker(func, {})
assert called["warm"] is True
def test_emit_lambda_logs_writes_start_end_report_to_cw_logs():
"""Lambda β CW Logs emits AWS-shaped START / body / END / REPORT lines."""
import ministack.services.cloudwatch_logs as _cwl
set_request_account_id("000000000000")
_cwl._log_groups.clear()
func = {"config": {"FunctionName": "emit-test", "Version": "$LATEST", "MemorySize": 128}}
lsvc._emit_lambda_logs(
func, request_id="abc-1234",
log_text="user print line 1\nuser print line 2",
error=False, duration_ms=42,
)
assert "/aws/lambda/emit-test" in _cwl._log_groups
streams = _cwl._log_groups["/aws/lambda/emit-test"]["streams"]
assert len(streams) == 1
stream_name = next(iter(streams))
assert stream_name.startswith(tuple(f"{y:04d}/" for y in range(2024, 2031)))
assert "[$LATEST]" in stream_name
msgs = [e["message"] for e in streams[stream_name]["events"]]
assert any(m.startswith("START RequestId: abc-1234") and "$LATEST" in m for m in msgs)
assert "user print line 1" in msgs
assert "user print line 2" in msgs
assert any(m == "END RequestId: abc-1234" for m in msgs)
assert any(m.startswith("REPORT RequestId: abc-1234") and "Duration: 42 ms" in m for m in msgs)
def test_emit_lambda_logs_autocreate_is_per_function():
"""Each function gets its own /aws/lambda/{name} group."""
import ministack.services.cloudwatch_logs as _cwl
set_request_account_id("000000000000")
_cwl._log_groups.clear()
lsvc._emit_lambda_logs(
{"config": {"FunctionName": "fn-a", "Version": "$LATEST", "MemorySize": 128}},
"r1", "", False, 1,
)
lsvc._emit_lambda_logs(
{"config": {"FunctionName": "fn-b", "Version": "$LATEST", "MemorySize": 128}},
"r2", "", False, 1,
)
assert "/aws/lambda/fn-a" in _cwl._log_groups
assert "/aws/lambda/fn-b" in _cwl._log_groups
def test_emit_lambda_logs_failure_is_best_effort(monkeypatch):
"""A broken CW Logs module must not bubble into the Lambda invocation."""
import ministack.services.cloudwatch_logs as _cwl
# Nuke the target to force a write failure
monkeypatch.setattr(_cwl, "_log_groups", None)
# Must not raise
lsvc._emit_lambda_logs(
{"config": {"FunctionName": "crash", "Version": "$LATEST", "MemorySize": 128}},
"r", "", False, 1,
)
def test_match_esm_filter_equality():
"""Basic equality matching on a nested record."""
rec = {"body": {"orderType": "Premium", "region": "us-east-1"}}
assert lsvc._match_esm_filter(rec, {"body": {"orderType": ["Premium"]}}) is True
assert lsvc._match_esm_filter(rec, {"body": {"orderType": ["Basic"]}}) is False
def test_match_esm_filter_content_prefix_suffix_anything_but():
"""Content-filter dicts: prefix, suffix, anything-but, exists."""
rec = {"body": {"name": "prod-user-42"}}
assert lsvc._match_esm_filter(rec, {"body": {"name": [{"prefix": "prod-"}]}}) is True
assert lsvc._match_esm_filter(rec, {"body": {"name": [{"prefix": "dev-"}]}}) is False
assert lsvc._match_esm_filter(rec, {"body": {"name": [{"suffix": "-42"}]}}) is True
assert lsvc._match_esm_filter(rec, {"body": {"name": [{"anything-but": ["prod-user-42"]}]}}) is False
assert lsvc._match_esm_filter(rec, {"body": {"name": [{"anything-but": ["other"]}]}}) is True
assert lsvc._match_esm_filter(rec, {"body": {"missing": [{"exists": False}]}}) is True
assert lsvc._match_esm_filter(rec, {"body": {"name": [{"exists": True}]}}) is True
def test_match_esm_filter_numeric():
"""Numeric comparison operator."""
rec = {"body": {"count": 7}}
assert lsvc._match_esm_filter(rec, {"body": {"count": [{"numeric": [">", 5]}]}}) is True
assert lsvc._match_esm_filter(rec, {"body": {"count": [{"numeric": [">", 10]}]}}) is False
assert lsvc._match_esm_filter(rec, {"body": {"count": [{"numeric": [">", 5, "<", 10]}]}}) is True
def test_apply_filter_criteria_drops_non_matching_sqs_records():
"""SQS bodies are JSON-parsed before matching, matching AWS behaviour."""
import json as _json
esm = {"FilterCriteria": {"Filters": [
{"Pattern": _json.dumps({"body": {"orderType": ["Premium"]}})},
]}}
records = [
{"messageId": "a", "body": _json.dumps({"orderType": "Premium"})},
{"messageId": "b", "body": _json.dumps({"orderType": "Basic"})},
]
filtered = lsvc._apply_filter_criteria(records, esm)
assert [r["messageId"] for r in filtered] == ["a"]
def test_apply_filter_criteria_no_filters_passes_through():
records = [{"messageId": "x"}, {"messageId": "y"}]
assert lsvc._apply_filter_criteria(records, {}) == records
assert lsvc._apply_filter_criteria(records, {"FilterCriteria": {}}) == records
def test_event_stream_encode_roundtrip():
"""The vnd.amazon.eventstream encoder must produce a valid framed message
that boto3's own EventStream parser can decode."""
from botocore.eventstream import EventStreamBuffer
msg = lsvc._es_encode_message({
":message-type": "event",
":event-type": "PayloadChunk",
":content-type": "application/octet-stream",
}, b"hello-world")
buf = EventStreamBuffer()
buf.add_data(msg)
events = list(buf)
assert len(events) == 1
event = events[0]
# botocore surfaces headers as a dict[str, Any] on the parsed event
assert event.headers[":event-type"] == "PayloadChunk"
assert event.payload == b"hello-world"
def test_invoke_rie_classifies_unhandled_vs_handled():
"""If RIE returns X-Amz-Function-Error header the result carries
function_error='Unhandled'. A handler-returned errorType with no RIE
header should produce 'Handled'."""
# The classification logic lives inside _invoke_rie; unit-test by
# simulating what that branch does via a tiny inline replica.
parsed_error_payload = {"errorType": "E", "errorMessage": "m"}
# Case 1: RIE header present β Unhandled
has_header = True
if has_header or (isinstance(parsed_error_payload, dict) and parsed_error_payload.get("errorType")):
classification = "Unhandled" if has_header else "Handled"
assert classification == "Unhandled"
# Case 2: No RIE header, but body has errorType β Handled
has_header = False
if has_header or (isinstance(parsed_error_payload, dict) and parsed_error_payload.get("errorType")):
classification = "Unhandled" if has_header else "Handled"
assert classification == "Handled"
|